The best way to control Claude Code, Codex and more from any computer or phone

main
ts 286 lines 9.58 KB
Raw
1 import * as acm from "@distilled.cloud/gcp/accesscontextmanager_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import { GcpEnvironment } from "../Environment.ts";
9 import { createInternalLabels } from "../Labels.ts";
10 import type { Providers } from "../Providers.ts";
11 import {
12 encodeOwnershipLine,
13 lastSegment,
14 listAccessPolicies,
15 MAX_TITLE_LENGTH,
16 normalizeScopes,
17 ownedByAlchemy,
18 parseOwnership,
19 projectNumberOf,
20 replaceOnIdentity,
21 resolveOrganization,
22 resourceNameFromOperation,
23 sameStringList,
24 tryResolveOrganization,
25 waitForOperation,
26 waitUntilExists,
27 waitUntilGone,
28 } from "./internal.ts";
29
30 export type AccessPolicyProps = {
31 /**
32 * Organization parent (`organizations/{organization}` or the numeric
33 * organization id). If omitted, Alchemy uses `GOOGLE_ORGANIZATION_ID`
34 * or the project's Resource Manager parent. Immutable — changing it
35 * replaces the policy.
36 */
37 parent?: string;
38 /**
39 * Human-readable title. Access policies have no labels or description,
40 * so Alchemy ownership (`alchemy-stack` / `alchemy-stage` /
41 * `alchemy-id`) is stored in a `[alchemy …]` prefix and stripped from
42 * attributes.
43 */
44 title?: string;
45 /**
46 * Policy scopes. Format: `folders/{folder_number}` or
47 * `projects/{project_number}`. At most one scope. Empty or omitted
48 * creates the organization-wide default policy (one per organization).
49 * Immutable — changing scopes replaces the policy.
50 */
51 scopes?: string[];
52 };
53
54 export type AccessPolicy = Resource<
55 "GCP.AccessContextManager.AccessPolicy",
56 AccessPolicyProps,
57 {
58 /** Resource name `accessPolicies/{policy}`. */
59 name: string;
60 /** Policy id (last path segment). */
61 policyId: string;
62 /** Parent `organizations/{organization}`. */
63 parent: string;
64 /** User title with the Alchemy ownership prefix stripped. */
65 title: string | undefined;
66 /** Policy scopes (`projects/{number}` or `folders/{number}`). */
67 scopes: string[];
68 /** Server etag for optimistic concurrency. */
69 etag: string | undefined;
70 },
71 never,
72 Providers
73 >;
74
75 /**
76 * An Access Context Manager access policy.
77 *
78 * An access policy is the container for access levels, service
79 * perimeters, and authorized-orgs descriptors. One unscoped
80 * (organization-wide) policy is allowed per organization; additional
81 * policies must set `scopes` to a folder or project.
82 *
83 * Access policies have no labels. Alchemy stamps ownership into `title`
84 * so `list` / `pnpm nuke:gcp` can find them. `parent` and `scopes` are
85 * immutable — changing them replaces the policy. `title` updates in
86 * place. The policy id is assigned by the API.
87 *
88 * ### Creating an Access Policy
89 * **Example:** Scoped to the current project
90 * ```typescript
91 * const policy = yield* GCP.AccessContextManager.AccessPolicy("Corp", {
92 * title: "corp access policy",
93 * scopes: ["projects/123456789"],
94 * });
95 * ```
96 *
97 * **Example:** Organization-wide default policy
98 * ```typescript
99 * const policy = yield* GCP.AccessContextManager.AccessPolicy("Default", {
100 * parent: "organizations/123456789",
101 * title: "default policy",
102 * });
103 * ```
104 *
105 * ### Updating an Access Policy
106 * **Example:** Change the title
107 * ```typescript
108 * const policy = yield* GCP.AccessContextManager.AccessPolicy("Corp", {
109 * title: "corp access policy (prod)",
110 * scopes: ["projects/123456789"],
111 * });
112 * ```
113 *
114 * @resource
115 * @category AccessContextManager
116 */
117 export const AccessPolicy = Resource<AccessPolicy>("GCP.AccessContextManager.AccessPolicy");
118
119 export class AccessPolicyNotResolved extends Data.TaggedError(
120 "GCP.AccessContextManager.AccessPolicyNotResolved",
121 )<{
122 resourceName: string;
123 }> {}
124
125 const toAttrs = (policy: acm.AccessPolicy): AccessPolicy["Attributes"] => {
126 const name = policy.name ?? "";
127 const parsed = parseOwnership(policy.title);
128 return {
129 name,
130 policyId: lastSegment(name),
131 parent: policy.parent ?? "",
132 title: parsed.text,
133 scopes: policy.scopes ?? [],
134 etag: policy.etag,
135 };
136 };
137
138 const getByName = (name: string) =>
139 acm.getAccessPolicies({ name }).pipe(Effect.catchTag("NotFound", () => Effect.undefined));
140
141 const findOwned = (id: string, organization: string) =>
142 Effect.gen(function* () {
143 const policies = yield* listAccessPolicies(organization);
144 for (const policy of policies) {
145 if (yield* ownedByAlchemy(id, policy.title)) {
146 return policy;
147 }
148 }
149 return undefined;
150 });
151
152 const observe = (id: string, name: string | undefined, organization: string) =>
153 Effect.gen(function* () {
154 if (name !== undefined && name.length > 0) {
155 const byName = yield* getByName(name);
156 if (byName !== undefined) return byName;
157 }
158 return yield* findOwned(id, organization);
159 });
160
161 export const AccessPolicyProvider = () =>
162 Provider.succeed(AccessPolicy, {
163 stables: ["name", "policyId", "parent"],
164
165 diff: Effect.fn(function* ({ news, olds, output }) {
166 if (!isResolved(news)) return undefined;
167 const previousParent = olds?.parent ?? output?.parent;
168 const nextParent = news.parent ?? previousParent;
169 const parentChanged =
170 previousParent !== undefined &&
171 nextParent !== undefined &&
172 lastSegment(previousParent) !== lastSegment(nextParent);
173
174 const previousScopes = olds?.scopes ?? output?.scopes;
175 const scopesChanged =
176 news.scopes !== undefined &&
177 previousScopes !== undefined &&
178 !sameStringList(news.scopes, previousScopes);
179
180 return replaceOnIdentity(parentChanged || scopesChanged);
181 }),
182
183 read: Effect.fn(function* ({ id, olds, output }) {
184 const organization = yield* resolveOrganization(olds?.parent, output?.parent);
185 const existing = yield* observe(id, output?.name, organization);
186 if (existing === undefined) return undefined;
187 const attrs = toAttrs(existing);
188 return (yield* ownedByAlchemy(id, existing.title)) ? attrs : Unowned(attrs);
189 }),
190
191 list: () =>
192 Effect.gen(function* () {
193 const organization = yield* tryResolveOrganization();
194 if (organization === undefined) return [];
195 const policies = yield* listAccessPolicies(organization);
196 return policies
197 .filter((policy) => parseOwnership(policy.title).labels["alchemy-id"])
198 .map(toAttrs);
199 }),
200
201 reconcile: Effect.fn(function* ({ id, news, output }) {
202 const env = yield* GcpEnvironment.current;
203 const organization = yield* resolveOrganization(news.parent, output?.parent);
204 const ownership = yield* createInternalLabels(id);
205 const desiredTitle = encodeOwnershipLine(ownership, news.title, MAX_TITLE_LENGTH);
206 const projectNumber = yield* projectNumberOf(env.project);
207 const desiredScopes =
208 news.scopes !== undefined
209 ? normalizeScopes(news.scopes, projectNumber)
210 : (output?.scopes ?? []);
211
212 let current = yield* observe(id, output?.name, organization);
213
214 if (current === undefined) {
215 const created = yield* acm
216 .createAccessPolicies({
217 body: {
218 title: desiredTitle,
219 parent: organization,
220 scopes: desiredScopes.length > 0 ? desiredScopes : undefined,
221 },
222 })
223 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
224 if (created !== undefined) {
225 // ALREADY_EXISTS (6): a concurrent create won the race.
226 const settled = yield* waitForOperation(created).pipe(
227 Effect.catchTag("GCP.OperationFailed", (error) =>
228 error.code === 6 ? Effect.succeed(created) : Effect.fail(error),
229 ),
230 );
231 const createdName =
232 resourceNameFromOperation(settled, "accessPolicies/") ??
233 resourceNameFromOperation(created, "accessPolicies/");
234 current =
235 createdName !== undefined
236 ? yield* waitUntilExists(getByName(createdName), createdName)
237 : yield* waitUntilExists(findOwned(id, organization), organization);
238 } else {
239 current = yield* waitUntilExists(findOwned(id, organization), organization);
240 }
241 }
242
243 if (current === undefined || current.name === undefined) {
244 return yield* new AccessPolicyNotResolved({
245 resourceName: output?.name ?? organization,
246 });
247 }
248
249 if ((current.title ?? "") !== desiredTitle) {
250 const operation = yield* acm.patchAccessPolicies({
251 name: current.name,
252 updateMask: "title",
253 body: {
254 name: current.name,
255 title: desiredTitle,
256 etag: current.etag,
257 },
258 });
259 yield* waitForOperation(operation);
260 current = yield* waitUntilExists(getByName(current.name), current.name);
261 }
262
263 if (current === undefined) {
264 return yield* new AccessPolicyNotResolved({
265 resourceName: output?.name ?? organization,
266 });
267 }
268
269 return toAttrs(current);
270 }),
271
272 delete: Effect.fn(function* ({ output }) {
273 const operation = yield* acm
274 .deleteAccessPolicies({ name: output.name })
275 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
276 if (operation !== undefined) {
277 // NOT_FOUND (5): already gone.
278 yield* waitForOperation(operation).pipe(
279 Effect.catchTag("GCP.OperationFailed", (error) =>
280 error.code === 5 ? Effect.void : Effect.fail(error),
281 ),
282 );
283 }
284 yield* waitUntilGone(getByName(output.name), output.name);
285 }),
286 });