@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 397 lines 15.5 KB
Raw
1 import * as iam from "@distilled.cloud/gcp/unstable/iam_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts";
12 import { waitForOperation } from "../Operation.ts";
13 import type { Providers } from "../Providers.ts";
14 import { encodeOwnedDescription, parseOwnedDescription } from "./internal.ts";
15
16 const PROVIDER_ID_MAX = 32;
17
18 export type WorkloadIdentityProviderOidc = {
19 /** Issuer URL (HTTPS), e.g. `https://token.actions.githubusercontent.com`. */
20 issuerUri: string;
21 /**
22 * Accepted `aud` values. When empty, the token audience must be the
23 * provider's full resource name.
24 */
25 allowedAudiences?: string[];
26 /** Inline JWKS (JSON). When omitted, keys are fetched from the issuer. */
27 jwksJson?: string;
28 };
29
30 export type WorkloadIdentityProviderProps = {
31 /** Project that owns the pool. Defaults to the current GCP project. */
32 project?: string;
33 /** Id of the pool the provider belongs to. Changing it replaces the provider. */
34 workloadIdentityPoolId: string;
35 /**
36 * Provider id: 4-32 lowercase letters, digits, or hyphens (the `gcp-`
37 * prefix is reserved). If omitted, a unique id is generated. Changing it
38 * replaces the provider. Deleted providers keep their id for 30 days;
39 * redeploying the same id in that window restores the provider.
40 */
41 workloadIdentityPoolProviderId?: string;
42 /** Display name (maximum 32 characters). */
43 displayName?: string;
44 /**
45 * Description. Providers have no labels, so Alchemy stamps ownership into a
46 * `[alchemy …]` prefix and strips it from the `description` attribute.
47 */
48 description?: string;
49 /**
50 * Disable the provider. Tokens from its issuer cannot be exchanged while it
51 * is disabled.
52 * @default false
53 */
54 disabled?: boolean;
55 /**
56 * Maps issuer token claims to Google attributes, e.g.
57 * `{ "google.subject": "assertion.sub" }`. When omitted, the existing
58 * mapping is left as is.
59 */
60 attributeMapping?: Record<string, string>;
61 /**
62 * CEL expression a token must satisfy, e.g.
63 * `assertion.repository == "my-org/my-repo"`. When omitted, the existing
64 * condition is left as is.
65 */
66 attributeCondition?: string;
67 /** OpenID Connect issuer. Set exactly one of `oidc`, `aws`, or `saml`. */
68 oidc?: WorkloadIdentityProviderOidc;
69 /** AWS account whose identities may federate. */
70 aws?: { accountId: string };
71 /** SAML 2.0 identity provider metadata (XML). */
72 saml?: { idpMetadataXml: string };
73 };
74
75 export type WorkloadIdentityProvider = Resource<
76 "GCP.IAM.WorkloadIdentityProvider",
77 WorkloadIdentityProviderProps,
78 {
79 /**
80 * Full resource name as GCP returns it, with the project number:
81 * `projects/{projectNumber}/locations/global/workloadIdentityPools/{pool}/providers/{id}`.
82 */
83 name: string;
84 /** Project that owns the pool. */
85 project: string;
86 /** Pool id. */
87 workloadIdentityPoolId: string;
88 /** Provider id. */
89 workloadIdentityPoolProviderId: string;
90 /** Display name. */
91 displayName: string | undefined;
92 /** User description (Alchemy ownership marker stripped). */
93 description: string | undefined;
94 /** Whether the provider is disabled. */
95 disabled: boolean;
96 /** Attribute mapping. */
97 attributeMapping: Record<string, string> | undefined;
98 /** Attribute condition. */
99 attributeCondition: string | undefined;
100 /** OpenID Connect issuer settings. */
101 oidc: WorkloadIdentityProviderOidc | undefined;
102 /** AWS settings. */
103 aws: { accountId: string } | undefined;
104 /** Provider state (`ACTIVE` or `DELETED`). */
105 state: string | undefined;
106 },
107 never,
108 Providers
109 >;
110
111 /**
112 * An issuer in a Google Cloud IAM workload identity pool (a "workload
113 * identity pool provider"). Tokens from the issuer that pass the attribute
114 * condition can be exchanged for short-lived Google credentials.
115 *
116 * ### GitHub Actions
117 * **Example:** Trust one repository and let its `main` branch deploy
118 * ```typescript
119 * const pool = yield* GCP.IAM.WorkloadIdentityPool("GitHub", {
120 * workloadIdentityPoolId: "github-actions",
121 * });
122 * yield* GCP.IAM.WorkloadIdentityProvider("GitHubOidc", {
123 * workloadIdentityPoolId: pool.workloadIdentityPoolId,
124 * workloadIdentityPoolProviderId: "github",
125 * attributeMapping: {
126 * "google.subject": "assertion.sub",
127 * "attribute.repository": "assertion.repository",
128 * },
129 * attributeCondition: `assertion.repository == "my-org/my-repo"`,
130 * oidc: { issuerUri: "https://token.actions.githubusercontent.com" },
131 * });
132 * ```
133 *
134 * ### AWS
135 * **Example:** Trust roles in one AWS account
136 * ```typescript
137 * yield* GCP.IAM.WorkloadIdentityProvider("Aws", {
138 * workloadIdentityPoolId: pool.workloadIdentityPoolId,
139 * attributeMapping: {
140 * "google.subject": "assertion.arn",
141 * "attribute.aws_role": "assertion.arn.extract('assumed-role/{role}/')",
142 * },
143 * aws: { accountId: "123456789012" },
144 * });
145 * ```
146 *
147 * ### Replacing and restoring <!-- api-prose -->
148 * Changing `workloadIdentityPoolId` or `workloadIdentityPoolProviderId`
149 * replaces the provider. GCP keeps a deleted provider for 30 days and
150 * reserves its id; deploying that id again restores it and re-applies the
151 * declared settings.
152 *
153 * @resource
154 * @category IAM
155 */
156 export const WorkloadIdentityProvider = Resource<WorkloadIdentityProvider>(
157 "GCP.IAM.WorkloadIdentityProvider",
158 );
159
160 export class WorkloadIdentityProviderNotResolved extends Data.TaggedError(
161 "GCP.IAM.WorkloadIdentityProviderNotResolved",
162 )<{ resourceName: string }> {}
163
164 const providerName = (project: string, poolId: string, providerId: string) =>
165 `projects/${project}/locations/global/workloadIdentityPools/${poolId}/providers/${providerId}`;
166
167 const toOidc = (oidc: iam.Oidc | undefined): WorkloadIdentityProviderOidc | undefined =>
168 oidc?.issuerUri === undefined
169 ? undefined
170 : {
171 issuerUri: oidc.issuerUri,
172 ...(oidc.allowedAudiences?.length ? { allowedAudiences: [...oidc.allowedAudiences] } : {}),
173 ...(oidc.jwksJson ? { jwksJson: oidc.jwksJson } : {}),
174 };
175
176 const toMap = (map: iam.StringMap | undefined): Record<string, string> | undefined =>
177 map === undefined
178 ? undefined
179 : Object.fromEntries(
180 Object.entries(map).filter((entry): entry is [string, string] => entry[1] !== undefined),
181 );
182
183 const toAttrs = (
184 provider: iam.WorkloadIdentityPoolProvider,
185 project: string,
186 poolId: string,
187 providerId: string,
188 ): WorkloadIdentityProvider["Attributes"] => ({
189 name: provider.name ?? providerName(project, poolId, providerId),
190 project,
191 workloadIdentityPoolId: poolId,
192 workloadIdentityPoolProviderId: providerId,
193 displayName: provider.displayName || undefined,
194 description: parseOwnedDescription(provider.description).description,
195 disabled: provider.disabled === true,
196 attributeMapping: toMap(provider.attributeMapping),
197 attributeCondition: provider.attributeCondition || undefined,
198 oidc: toOidc(provider.oidc),
199 aws: provider.aws?.accountId ? { accountId: provider.aws.accountId } : undefined,
200 state: provider.state,
201 });
202
203 const getProvider = (name: string) =>
204 iam
205 .getProjectsLocationsWorkloadIdentityPoolsProviders({ name })
206 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
207
208 const waitForProviderOperation = (operation: iam.Operation) =>
209 waitForOperation(operation, (name) =>
210 iam.getProjectsLocationsWorkloadIdentityPoolsProvidersOperations({ name }),
211 );
212
213 const toProviderId = (id: string, explicit: string | undefined, existing: string | undefined) =>
214 Effect.gen(function* () {
215 if (explicit !== undefined) return explicit;
216 if (existing !== undefined) return existing;
217 return yield* createPhysicalName({
218 id,
219 prefix: `alchemy-${id}-`,
220 maxLength: PROVIDER_ID_MAX,
221 lowercase: true,
222 forbiddenPrefixes: ["gcp-"],
223 });
224 });
225
226 const sameMap = (a: Record<string, string> | undefined, b: Record<string, string> | undefined) => {
227 const left = Object.entries(a ?? {}).sort(([x], [y]) => x.localeCompare(y));
228 const right = Object.entries(b ?? {}).sort(([x], [y]) => x.localeCompare(y));
229 return JSON.stringify(left) === JSON.stringify(right);
230 };
231
232 const sameOidc = (current: iam.Oidc | undefined, desired: WorkloadIdentityProviderOidc) =>
233 (current?.issuerUri ?? "") === desired.issuerUri &&
234 JSON.stringify([...(current?.allowedAudiences ?? [])].sort()) ===
235 JSON.stringify([...(desired.allowedAudiences ?? [])].sort()) &&
236 (current?.jwksJson ?? "") === (desired.jwksJson ?? "");
237
238 export const WorkloadIdentityProviderProvider = () =>
239 Provider.succeed(WorkloadIdentityProvider, {
240 stables: ["name", "project", "workloadIdentityPoolId", "workloadIdentityPoolProviderId"],
241
242 diff: Effect.fn(function* ({ news, olds, output }) {
243 if (!isResolved(news)) return undefined;
244 const env = yield* GcpEnvironment.current;
245 const previousProject = olds?.project ?? output?.project ?? env.project;
246 const previousPoolId = olds?.workloadIdentityPoolId ?? output?.workloadIdentityPoolId;
247 const previousProviderId =
248 olds?.workloadIdentityPoolProviderId ?? output?.workloadIdentityPoolProviderId;
249 if (
250 (news.project !== undefined && news.project !== previousProject) ||
251 (previousPoolId !== undefined && news.workloadIdentityPoolId !== previousPoolId) ||
252 (news.workloadIdentityPoolProviderId !== undefined &&
253 news.workloadIdentityPoolProviderId !== previousProviderId)
254 ) {
255 return { action: "replace" as const, deleteFirst: false };
256 }
257 return undefined;
258 }),
259
260 read: Effect.fn(function* ({ id, olds, output }) {
261 const env = yield* GcpEnvironment.current;
262 const project = olds?.project ?? output?.project ?? env.project;
263 const poolId = olds?.workloadIdentityPoolId ?? output?.workloadIdentityPoolId;
264 if (poolId === undefined) return undefined;
265 const providerId = yield* toProviderId(
266 id,
267 olds?.workloadIdentityPoolProviderId,
268 output?.workloadIdentityPoolProviderId,
269 );
270 const existing = yield* getProvider(providerName(project, poolId, providerId));
271 if (existing === undefined || existing.state === "DELETED") return undefined;
272 const attrs = toAttrs(existing, project, poolId, providerId);
273 const { labels } = parseOwnedDescription(existing.description);
274 return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs);
275 }),
276
277 reconcile: Effect.fn(function* ({ id, news, output }) {
278 const env = yield* GcpEnvironment.current;
279 const project = news.project ?? output?.project ?? env.project;
280 const poolId = news.workloadIdentityPoolId;
281 const providerId = yield* toProviderId(
282 id,
283 news.workloadIdentityPoolProviderId,
284 output?.workloadIdentityPoolProviderId,
285 );
286 const name = providerName(project, poolId, providerId);
287 const internal = yield* createInternalLabels(id);
288 const desiredDescription = encodeOwnedDescription(internal, news.description);
289 const desiredDisabled = news.disabled === true;
290
291 // Observe
292 let current = yield* getProvider(name);
293
294 // Ensure — the id stays reserved for 30 days after delete, so a
295 // soft-deleted provider is restored rather than re-created.
296 if (current === undefined) {
297 const operation = yield* iam.createProjectsLocationsWorkloadIdentityPoolsProviders({
298 parent: `projects/${project}/locations/global/workloadIdentityPools/${poolId}`,
299 workloadIdentityPoolProviderId: providerId,
300 body: {
301 displayName: news.displayName,
302 description: desiredDescription,
303 disabled: desiredDisabled,
304 attributeMapping: news.attributeMapping,
305 attributeCondition: news.attributeCondition,
306 oidc: news.oidc,
307 aws: news.aws,
308 saml: news.saml,
309 },
310 });
311 yield* waitForProviderOperation(operation);
312 } else if (current.state === "DELETED") {
313 const operation = yield* iam.undeleteProjectsLocationsWorkloadIdentityPoolsProviders({
314 name,
315 body: {},
316 });
317 yield* waitForProviderOperation(operation);
318 }
319 current = yield* getProvider(name).pipe(
320 Effect.flatMap((provider) =>
321 provider === undefined || provider.state !== "ACTIVE"
322 ? Effect.fail(new WorkloadIdentityProviderNotResolved({ resourceName: name }))
323 : Effect.succeed(provider),
324 ),
325 Effect.retry({
326 while: (error) => error._tag === "GCP.IAM.WorkloadIdentityProviderNotResolved",
327 schedule: Schedule.exponential("500 millis"),
328 times: 8,
329 }),
330 );
331
332 // Sync against observed state. Mapping, condition, and issuer settings
333 // are only managed when declared.
334 const body: iam.WorkloadIdentityPoolProvider = {};
335 const updateMask: string[] = [];
336 if ((current.displayName ?? "") !== (news.displayName ?? "")) {
337 updateMask.push("displayName");
338 body.displayName = news.displayName ?? "";
339 }
340 if ((current.description ?? "") !== desiredDescription) {
341 updateMask.push("description");
342 body.description = desiredDescription;
343 }
344 if ((current.disabled === true) !== desiredDisabled) {
345 updateMask.push("disabled");
346 body.disabled = desiredDisabled;
347 }
348 if (
349 news.attributeMapping !== undefined &&
350 !sameMap(toMap(current.attributeMapping), news.attributeMapping)
351 ) {
352 updateMask.push("attributeMapping");
353 body.attributeMapping = news.attributeMapping;
354 }
355 if (
356 news.attributeCondition !== undefined &&
357 (current.attributeCondition ?? "") !== news.attributeCondition
358 ) {
359 updateMask.push("attributeCondition");
360 body.attributeCondition = news.attributeCondition;
361 }
362 if (news.oidc !== undefined && !sameOidc(current.oidc, news.oidc)) {
363 updateMask.push("oidc");
364 body.oidc = news.oidc;
365 }
366 if (news.aws !== undefined && current.aws?.accountId !== news.aws.accountId) {
367 updateMask.push("aws");
368 body.aws = news.aws;
369 }
370 if (news.saml !== undefined && current.saml?.idpMetadataXml !== news.saml.idpMetadataXml) {
371 updateMask.push("saml");
372 body.saml = news.saml;
373 }
374 if (updateMask.length > 0) {
375 const operation = yield* iam.patchProjectsLocationsWorkloadIdentityPoolsProviders({
376 name,
377 updateMask: updateMask.join(","),
378 body,
379 });
380 yield* waitForProviderOperation(operation);
381 current = { ...current, ...body };
382 }
383 return toAttrs(current, project, poolId, providerId);
384 }),
385
386 // Soft delete: the provider is recoverable (and its id reserved) for 30 days.
387 delete: Effect.fn(function* ({ output }) {
388 // Reads lag behind create, so a NotFound here is not proof the
389 // resource is gone; only an observed DELETED state skips the call.
390 const current = yield* getProvider(output.name);
391 if (current?.state === "DELETED") return;
392 const operation = yield* iam
393 .deleteProjectsLocationsWorkloadIdentityPoolsProviders({ name: output.name })
394 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
395 if (operation !== undefined) yield* waitForProviderOperation(operation);
396 }),
397 });