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
| 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 * as Stream from "effect/Stream"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 13 | import { waitForOperation } from "../Operation.ts"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | import { encodeOwnedDescription, hasOwnedDescription, parseOwnedDescription } from "./internal.ts"; |
| 16 | |
| 17 | const POOL_ID_MAX = 32; |
| 18 | |
| 19 | export type WorkloadIdentityPoolProps = { |
| 20 | /** Project that owns the pool. Defaults to the current GCP project. */ |
| 21 | project?: string; |
| 22 | /** |
| 23 | * Pool id: 4-32 lowercase letters, digits, or hyphens (the `gcp-` prefix is |
| 24 | * reserved). If omitted, a unique id is generated. Changing it replaces the |
| 25 | * pool. Deleted pools keep their id for 30 days; redeploying the same id in |
| 26 | * that window restores the pool instead of creating a new one. |
| 27 | */ |
| 28 | workloadIdentityPoolId?: string; |
| 29 | /** Display name (maximum 32 characters). */ |
| 30 | displayName?: string; |
| 31 | /** |
| 32 | * Description. Pools have no labels, so Alchemy stamps ownership into a |
| 33 | * `[alchemy …]` prefix and strips it from the `description` attribute. The |
| 34 | * marker and this text share the API's 256-character limit; overflow is |
| 35 | * truncated. |
| 36 | */ |
| 37 | description?: string; |
| 38 | /** |
| 39 | * Disable the pool. Tokens cannot be exchanged while it is disabled, and |
| 40 | * existing tokens grant access again once it is re-enabled. |
| 41 | * @default false |
| 42 | */ |
| 43 | disabled?: boolean; |
| 44 | }; |
| 45 | |
| 46 | export type WorkloadIdentityPool = Resource< |
| 47 | "GCP.IAM.WorkloadIdentityPool", |
| 48 | WorkloadIdentityPoolProps, |
| 49 | { |
| 50 | /** |
| 51 | * Full resource name as GCP returns it, with the project number: |
| 52 | * `projects/{projectNumber}/locations/global/workloadIdentityPools/{id}`. |
| 53 | * Prefix it with `principalSet://iam.googleapis.com/` to grant roles to |
| 54 | * federated identities. |
| 55 | */ |
| 56 | name: string; |
| 57 | /** Project that owns the pool. */ |
| 58 | project: string; |
| 59 | /** Pool id. */ |
| 60 | workloadIdentityPoolId: string; |
| 61 | /** Display name. */ |
| 62 | displayName: string | undefined; |
| 63 | /** User description (Alchemy ownership marker stripped). */ |
| 64 | description: string | undefined; |
| 65 | /** Whether the pool is disabled. */ |
| 66 | disabled: boolean; |
| 67 | /** Pool state (`ACTIVE` or `DELETED`). */ |
| 68 | state: string | undefined; |
| 69 | }, |
| 70 | never, |
| 71 | Providers |
| 72 | >; |
| 73 | |
| 74 | /** |
| 75 | * A Google Cloud IAM workload identity pool: a trust boundary that lets |
| 76 | * external identities (GitHub Actions, AWS, any OIDC or SAML issuer) exchange |
| 77 | * their tokens for short-lived Google credentials without service-account keys. |
| 78 | * |
| 79 | * Add an issuer with `GCP.IAM.WorkloadIdentityProvider`, then let the |
| 80 | * federated principals impersonate a service account with `GCP.IAM.Member` |
| 81 | * (`roles/iam.workloadIdentityUser`). |
| 82 | * |
| 83 | * ### Creating a Pool |
| 84 | * **Example:** Pool for GitHub Actions |
| 85 | * ```typescript |
| 86 | * const pool = yield* GCP.IAM.WorkloadIdentityPool("GitHub", { |
| 87 | * workloadIdentityPoolId: "github-actions", |
| 88 | * displayName: "GitHub Actions", |
| 89 | * }); |
| 90 | * ``` |
| 91 | * |
| 92 | * ### Impersonating a Service Account |
| 93 | * **Example:** Let one repository deploy as a service account |
| 94 | * ```typescript |
| 95 | * const deployer = yield* GCP.IAM.ServiceAccount("Deployer", {}); |
| 96 | * yield* GCP.IAM.Member("GitHubDeployer", { |
| 97 | * kind: "iam.serviceAccount", |
| 98 | * name: deployer.name, |
| 99 | * role: "roles/iam.workloadIdentityUser", |
| 100 | * member: Output.interpolate`principalSet://iam.googleapis.com/${pool.name}/attribute.repository/my-org/my-repo`, |
| 101 | * }); |
| 102 | * ``` |
| 103 | * |
| 104 | * @resource |
| 105 | * @category IAM |
| 106 | */ |
| 107 | export const WorkloadIdentityPool = Resource<WorkloadIdentityPool>("GCP.IAM.WorkloadIdentityPool"); |
| 108 | |
| 109 | export class WorkloadIdentityPoolNotResolved extends Data.TaggedError( |
| 110 | "GCP.IAM.WorkloadIdentityPoolNotResolved", |
| 111 | )<{ resourceName: string }> {} |
| 112 | |
| 113 | const poolName = (project: string, poolId: string) => |
| 114 | `projects/${project}/locations/global/workloadIdentityPools/${poolId}`; |
| 115 | |
| 116 | const lastSegment = (name: string) => name.split("/").pop() ?? name; |
| 117 | |
| 118 | const toAttrs = ( |
| 119 | pool: iam.WorkloadIdentityPool, |
| 120 | project: string, |
| 121 | poolId: string, |
| 122 | ): WorkloadIdentityPool["Attributes"] => ({ |
| 123 | // GCP returns the name with the project number, which `principalSet://` |
| 124 | // members require. |
| 125 | name: pool.name ?? poolName(project, poolId), |
| 126 | project, |
| 127 | workloadIdentityPoolId: poolId, |
| 128 | displayName: pool.displayName || undefined, |
| 129 | description: parseOwnedDescription(pool.description).description, |
| 130 | disabled: pool.disabled === true, |
| 131 | state: pool.state, |
| 132 | }); |
| 133 | |
| 134 | const getPool = (name: string) => |
| 135 | iam |
| 136 | .getProjectsLocationsWorkloadIdentityPools({ name }) |
| 137 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 138 | |
| 139 | const waitForPoolOperation = (operation: iam.Operation) => |
| 140 | waitForOperation(operation, (name) => |
| 141 | iam.getProjectsLocationsWorkloadIdentityPoolsOperations({ name }), |
| 142 | ); |
| 143 | |
| 144 | const toPoolId = (id: string, explicit: string | undefined, existing: string | undefined) => |
| 145 | Effect.gen(function* () { |
| 146 | if (explicit !== undefined) return explicit; |
| 147 | if (existing !== undefined) return existing; |
| 148 | return yield* createPhysicalName({ |
| 149 | id, |
| 150 | prefix: `alchemy-${id}-`, |
| 151 | maxLength: POOL_ID_MAX, |
| 152 | lowercase: true, |
| 153 | forbiddenPrefixes: ["gcp-"], |
| 154 | }); |
| 155 | }); |
| 156 | |
| 157 | export const WorkloadIdentityPoolProvider = () => |
| 158 | Provider.succeed(WorkloadIdentityPool, { |
| 159 | stables: ["name", "project", "workloadIdentityPoolId"], |
| 160 | |
| 161 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 162 | if (!isResolved(news)) return undefined; |
| 163 | const env = yield* GcpEnvironment.current; |
| 164 | const previousProject = olds?.project ?? output?.project ?? env.project; |
| 165 | const previousPoolId = olds?.workloadIdentityPoolId ?? output?.workloadIdentityPoolId; |
| 166 | if ( |
| 167 | (news.project !== undefined && news.project !== previousProject) || |
| 168 | (news.workloadIdentityPoolId !== undefined && |
| 169 | news.workloadIdentityPoolId !== previousPoolId) |
| 170 | ) { |
| 171 | return { action: "replace" as const, deleteFirst: false }; |
| 172 | } |
| 173 | return undefined; |
| 174 | }), |
| 175 | |
| 176 | read: Effect.fn(function* ({ id, olds, output }) { |
| 177 | const env = yield* GcpEnvironment.current; |
| 178 | const project = olds?.project ?? output?.project ?? env.project; |
| 179 | const poolId = yield* toPoolId( |
| 180 | id, |
| 181 | olds?.workloadIdentityPoolId, |
| 182 | output?.workloadIdentityPoolId, |
| 183 | ); |
| 184 | const existing = yield* getPool(poolName(project, poolId)); |
| 185 | // A deleted pool is recoverable for 30 days but is not a live resource. |
| 186 | if (existing === undefined || existing.state === "DELETED") return undefined; |
| 187 | const attrs = toAttrs(existing, project, poolId); |
| 188 | const { labels } = parseOwnedDescription(existing.description); |
| 189 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 190 | }), |
| 191 | |
| 192 | list: () => |
| 193 | Effect.gen(function* () { |
| 194 | const env = yield* GcpEnvironment.current; |
| 195 | return yield* iam.listProjectsLocationsWorkloadIdentityPools |
| 196 | .pages({ |
| 197 | parent: `projects/${env.project}/locations/global`, |
| 198 | pageSize: 100, |
| 199 | }) |
| 200 | .pipe( |
| 201 | Stream.flatMap((page) => Stream.fromIterable(page.workloadIdentityPools ?? [])), |
| 202 | Stream.filter( |
| 203 | (pool) => pool.state !== "DELETED" && hasOwnedDescription(pool.description), |
| 204 | ), |
| 205 | Stream.map((pool) => toAttrs(pool, env.project, lastSegment(pool.name ?? ""))), |
| 206 | Stream.runCollect, |
| 207 | Effect.map((chunk) => Array.from(chunk)), |
| 208 | Effect.catchTag("NotFound", () => |
| 209 | Effect.succeed([] as WorkloadIdentityPool["Attributes"][]), |
| 210 | ), |
| 211 | ); |
| 212 | }), |
| 213 | |
| 214 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 215 | const env = yield* GcpEnvironment.current; |
| 216 | const project = news.project ?? output?.project ?? env.project; |
| 217 | const poolId = yield* toPoolId( |
| 218 | id, |
| 219 | news.workloadIdentityPoolId, |
| 220 | output?.workloadIdentityPoolId, |
| 221 | ); |
| 222 | const name = poolName(project, poolId); |
| 223 | const internal = yield* createInternalLabels(id); |
| 224 | const desiredDescription = encodeOwnedDescription(internal, news.description); |
| 225 | const desiredDisabled = news.disabled === true; |
| 226 | |
| 227 | // Observe |
| 228 | let current = yield* getPool(name); |
| 229 | |
| 230 | // Ensure — the id stays reserved for 30 days after delete, so a |
| 231 | // soft-deleted pool is restored rather than re-created. |
| 232 | if (current === undefined) { |
| 233 | const operation = yield* iam.createProjectsLocationsWorkloadIdentityPools({ |
| 234 | parent: `projects/${project}/locations/global`, |
| 235 | workloadIdentityPoolId: poolId, |
| 236 | body: { |
| 237 | displayName: news.displayName, |
| 238 | description: desiredDescription, |
| 239 | disabled: desiredDisabled, |
| 240 | }, |
| 241 | }); |
| 242 | yield* waitForPoolOperation(operation); |
| 243 | } else if (current.state === "DELETED") { |
| 244 | const operation = yield* iam.undeleteProjectsLocationsWorkloadIdentityPools({ |
| 245 | name, |
| 246 | body: {}, |
| 247 | }); |
| 248 | yield* waitForPoolOperation(operation); |
| 249 | } |
| 250 | current = yield* getPool(name).pipe( |
| 251 | Effect.flatMap((pool) => |
| 252 | pool === undefined || pool.state !== "ACTIVE" |
| 253 | ? Effect.fail(new WorkloadIdentityPoolNotResolved({ resourceName: name })) |
| 254 | : Effect.succeed(pool), |
| 255 | ), |
| 256 | Effect.retry({ |
| 257 | while: (error) => error._tag === "GCP.IAM.WorkloadIdentityPoolNotResolved", |
| 258 | schedule: Schedule.exponential("500 millis"), |
| 259 | times: 8, |
| 260 | }), |
| 261 | ); |
| 262 | |
| 263 | // Sync display name, description, and disabled against observed state. |
| 264 | const updateMask = [ |
| 265 | (current.displayName ?? "") !== (news.displayName ?? "") ? "displayName" : undefined, |
| 266 | (current.description ?? "") !== desiredDescription ? "description" : undefined, |
| 267 | (current.disabled === true) !== desiredDisabled ? "disabled" : undefined, |
| 268 | ].filter((field): field is string => field !== undefined); |
| 269 | if (updateMask.length > 0) { |
| 270 | const operation = yield* iam.patchProjectsLocationsWorkloadIdentityPools({ |
| 271 | name, |
| 272 | updateMask: updateMask.join(","), |
| 273 | body: { |
| 274 | displayName: news.displayName ?? "", |
| 275 | description: desiredDescription, |
| 276 | disabled: desiredDisabled, |
| 277 | }, |
| 278 | }); |
| 279 | yield* waitForPoolOperation(operation); |
| 280 | current = { |
| 281 | ...current, |
| 282 | displayName: news.displayName, |
| 283 | description: desiredDescription, |
| 284 | disabled: desiredDisabled, |
| 285 | }; |
| 286 | } |
| 287 | return toAttrs(current, project, poolId); |
| 288 | }), |
| 289 | |
| 290 | // Soft delete: the pool is recoverable (and its id reserved) for 30 days. |
| 291 | delete: Effect.fn(function* ({ output }) { |
| 292 | // Reads lag behind create, so a NotFound here is not proof the |
| 293 | // resource is gone; only an observed DELETED state skips the call. |
| 294 | const current = yield* getPool(output.name); |
| 295 | if (current?.state === "DELETED") return; |
| 296 | const operation = yield* iam |
| 297 | .deleteProjectsLocationsWorkloadIdentityPools({ name: output.name }) |
| 298 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 299 | if (operation !== undefined) yield* waitForPoolOperation(operation); |
| 300 | }), |
| 301 | }); |