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, 06:00 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 { revokeHostIam, syncHostIam, type AppliedIamGrant, type GcpIamGrant } from "../Host.ts"; |
| 13 | import { createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 14 | import type { Providers } from "../Providers.ts"; |
| 15 | import { encodeOwnedDescription, hasOwnedDescription, parseOwnedDescription } from "./internal.ts"; |
| 16 | |
| 17 | const ACCOUNT_ID_MAX = 30; |
| 18 | |
| 19 | export type ServiceAccountProps = { |
| 20 | /** Project that owns the account. Defaults to the current GCP project. */ |
| 21 | project?: string; |
| 22 | /** |
| 23 | * Account id used as the email prefix: 6-30 lowercase letters, digits, |
| 24 | * or hyphens. If omitted, a unique id is generated. Changing it |
| 25 | * replaces the account. |
| 26 | */ |
| 27 | accountId?: string; |
| 28 | /** Human-readable display name (maximum 100 UTF-8 bytes). */ |
| 29 | displayName?: string; |
| 30 | /** |
| 31 | * Human-readable description. Service accounts have no labels, so |
| 32 | * Alchemy stamps ownership into a `[alchemy …]` prefix and strips it |
| 33 | * from the `description` attribute. The marker and this text share the |
| 34 | * API's 256-byte limit; overflow is truncated. |
| 35 | */ |
| 36 | description?: string; |
| 37 | }; |
| 38 | |
| 39 | export type ServiceAccount = Resource< |
| 40 | "GCP.IAM.ServiceAccount", |
| 41 | ServiceAccountProps, |
| 42 | { |
| 43 | /** Full resource name `projects/{project}/serviceAccounts/{email}`. */ |
| 44 | name: string; |
| 45 | /** Project that owns the account. */ |
| 46 | project: string; |
| 47 | /** Account id (the email prefix). */ |
| 48 | accountId: string; |
| 49 | /** Service-account email address. */ |
| 50 | email: string; |
| 51 | /** Globally unique numeric id. */ |
| 52 | uniqueId: string | undefined; |
| 53 | /** OAuth 2 client id. */ |
| 54 | oauth2ClientId: string | undefined; |
| 55 | /** Human-readable display name. */ |
| 56 | displayName: string | undefined; |
| 57 | /** User description (Alchemy ownership marker stripped). */ |
| 58 | description: string | undefined; |
| 59 | /** Whether the account is disabled. */ |
| 60 | disabled: boolean | undefined; |
| 61 | /** Roles granted through bindings, revoked once no binding asks for them. */ |
| 62 | iamGrants?: AppliedIamGrant[]; |
| 63 | }, |
| 64 | ServiceAccountBinding, |
| 65 | Providers |
| 66 | >; |
| 67 | |
| 68 | /** What a binding grants a {@link ServiceAccount}. */ |
| 69 | export type ServiceAccountBinding = { |
| 70 | /** Roles to grant the account, each on one resource (or the project). */ |
| 71 | iam?: GcpIamGrant[]; |
| 72 | }; |
| 73 | |
| 74 | /** |
| 75 | * A user-managed Google Cloud IAM service account. |
| 76 | * |
| 77 | * Grant it roles with `GCP.IAM.Member` (`kind: "project"` for project-wide |
| 78 | * roles), and pass its `email` to resources that run as an identity, such |
| 79 | * as GKE node pools or Compute instances. |
| 80 | * |
| 81 | * ### Creating a Service Account |
| 82 | * **Example:** Service account with a generated id |
| 83 | * ```typescript |
| 84 | * const account = yield* GCP.IAM.ServiceAccount("Worker", { |
| 85 | * displayName: "Background worker", |
| 86 | * }); |
| 87 | * ``` |
| 88 | * |
| 89 | * **Example:** Service account with an explicit id |
| 90 | * ```typescript |
| 91 | * const account = yield* GCP.IAM.ServiceAccount("GkeNodes", { |
| 92 | * accountId: "prod-gke-nodes", |
| 93 | * displayName: "Production GKE nodes", |
| 94 | * }); |
| 95 | * ``` |
| 96 | * |
| 97 | * ### Granting Roles |
| 98 | * **Example:** Let the account write logs in the project |
| 99 | * ```typescript |
| 100 | * const account = yield* GCP.IAM.ServiceAccount("Worker", {}); |
| 101 | * yield* GCP.IAM.Member("WorkerLogs", { |
| 102 | * kind: "project", |
| 103 | * name: account.project, |
| 104 | * role: "roles/logging.logWriter", |
| 105 | * member: Output.interpolate`serviceAccount:${account.email}`, |
| 106 | * }); |
| 107 | * ``` |
| 108 | * |
| 109 | * @resource |
| 110 | * @category IAM |
| 111 | */ |
| 112 | export const ServiceAccount = Resource<ServiceAccount>("GCP.IAM.ServiceAccount"); |
| 113 | |
| 114 | export class ServiceAccountNotResolved extends Data.TaggedError( |
| 115 | "GCP.IAM.ServiceAccountNotResolved", |
| 116 | )<{ resourceName: string }> {} |
| 117 | |
| 118 | const accountIdFromEmail = (email: string) => email.split("@")[0] ?? email; |
| 119 | const emailOf = (project: string, accountId: string) => |
| 120 | `${accountId}@${project}.iam.gserviceaccount.com`; |
| 121 | const nameOf = (project: string, accountId: string) => |
| 122 | `projects/${project}/serviceAccounts/${emailOf(project, accountId)}`; |
| 123 | |
| 124 | const toAttrs = (account: iam.ServiceAccount, project: string): ServiceAccount["Attributes"] => { |
| 125 | const email = account.email ?? ""; |
| 126 | const accountId = accountIdFromEmail(email); |
| 127 | return { |
| 128 | name: account.name ?? nameOf(project, accountId), |
| 129 | project: account.projectId ?? project, |
| 130 | accountId, |
| 131 | email, |
| 132 | uniqueId: account.uniqueId, |
| 133 | oauth2ClientId: account.oauth2ClientId, |
| 134 | displayName: account.displayName, |
| 135 | description: parseOwnedDescription(account.description).description, |
| 136 | disabled: account.disabled, |
| 137 | }; |
| 138 | }; |
| 139 | |
| 140 | const getByName = (name: string) => |
| 141 | iam |
| 142 | .getProjectsServiceAccounts({ name }) |
| 143 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 144 | |
| 145 | const toAccountId = (id: string, explicit: string | undefined, existing: string | undefined) => |
| 146 | Effect.gen(function* () { |
| 147 | if (explicit !== undefined) return explicit; |
| 148 | if (existing !== undefined) return existing; |
| 149 | return yield* createPhysicalName({ |
| 150 | id, |
| 151 | prefix: `alchemy-${id}-`, |
| 152 | maxLength: ACCOUNT_ID_MAX, |
| 153 | lowercase: true, |
| 154 | }); |
| 155 | }); |
| 156 | |
| 157 | export const ServiceAccountProvider = () => |
| 158 | Provider.succeed(ServiceAccount, { |
| 159 | stables: ["name", "project", "accountId", "email", "uniqueId"], |
| 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 previousAccountId = olds?.accountId ?? output?.accountId; |
| 166 | if ( |
| 167 | (news.project !== undefined && news.project !== previousProject) || |
| 168 | (news.accountId !== undefined && news.accountId !== previousAccountId) |
| 169 | ) { |
| 170 | return { action: "replace" as const, deleteFirst: false }; |
| 171 | } |
| 172 | return undefined; |
| 173 | }), |
| 174 | |
| 175 | read: Effect.fn(function* ({ id, olds, output }) { |
| 176 | const env = yield* GcpEnvironment.current; |
| 177 | const project = olds?.project ?? output?.project ?? env.project; |
| 178 | const accountId = yield* toAccountId(id, olds?.accountId, output?.accountId); |
| 179 | const existing = yield* getByName(output?.name ?? nameOf(project, accountId)); |
| 180 | if (existing === undefined) return undefined; |
| 181 | const attrs = toAttrs(existing, project); |
| 182 | const { labels } = parseOwnedDescription(existing.description); |
| 183 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 184 | }), |
| 185 | |
| 186 | list: () => |
| 187 | Effect.gen(function* () { |
| 188 | const env = yield* GcpEnvironment.current; |
| 189 | return yield* iam.listProjectsServiceAccounts |
| 190 | .pages({ |
| 191 | name: `projects/${env.project}`, |
| 192 | pageSize: 100, |
| 193 | }) |
| 194 | .pipe( |
| 195 | Stream.flatMap((page) => Stream.fromIterable(page.accounts ?? [])), |
| 196 | Stream.filter((account) => hasOwnedDescription(account.description)), |
| 197 | Stream.map((account) => toAttrs(account, env.project)), |
| 198 | Stream.runCollect, |
| 199 | Effect.map((chunk) => Array.from(chunk)), |
| 200 | Effect.catchTag("NotFound", () => Effect.succeed([] as ServiceAccount["Attributes"][])), |
| 201 | ); |
| 202 | }), |
| 203 | |
| 204 | reconcile: Effect.fn(function* ({ id, news, output, bindings }) { |
| 205 | const env = yield* GcpEnvironment.current; |
| 206 | const project = news.project ?? output?.project ?? env.project; |
| 207 | const accountId = yield* toAccountId(id, news.accountId, output?.accountId); |
| 208 | const name = output?.name ?? nameOf(project, accountId); |
| 209 | const internal = yield* createInternalLabels(id); |
| 210 | const desiredDescription = encodeOwnedDescription(internal, news.description); |
| 211 | |
| 212 | // Observe |
| 213 | let current = yield* getByName(name); |
| 214 | |
| 215 | // Ensure — `Conflict` is a create race; adopt the winner. |
| 216 | if (current === undefined) { |
| 217 | current = yield* iam |
| 218 | .createProjectsServiceAccounts({ |
| 219 | name: `projects/${project}`, |
| 220 | body: { |
| 221 | accountId, |
| 222 | serviceAccount: { |
| 223 | displayName: news.displayName, |
| 224 | description: desiredDescription, |
| 225 | }, |
| 226 | }, |
| 227 | }) |
| 228 | .pipe( |
| 229 | Effect.retry({ |
| 230 | while: (error) => error._tag === "ServiceAccountQuotaExceeded", |
| 231 | times: 6, |
| 232 | schedule: Schedule.exponential("2 seconds"), |
| 233 | }), |
| 234 | Effect.catchTag("Conflict", () => getByName(name)), |
| 235 | ); |
| 236 | } |
| 237 | if (current === undefined) { |
| 238 | return yield* new ServiceAccountNotResolved({ resourceName: name }); |
| 239 | } |
| 240 | // A new account is eventually consistent: reads (and IAM bindings that |
| 241 | // name it) fail with NotFound for a few seconds after create. |
| 242 | current = yield* getByName(current.name ?? name).pipe( |
| 243 | Effect.flatMap((account) => |
| 244 | account === undefined |
| 245 | ? Effect.fail(new ServiceAccountNotResolved({ resourceName: name })) |
| 246 | : Effect.succeed(account), |
| 247 | ), |
| 248 | Effect.retry({ |
| 249 | while: (error) => error._tag === "GCP.IAM.ServiceAccountNotResolved", |
| 250 | schedule: Schedule.exponential("500 millis"), |
| 251 | times: 8, |
| 252 | }), |
| 253 | ); |
| 254 | |
| 255 | // Sync display name and description against observed state. |
| 256 | const updateMask = [ |
| 257 | (current.displayName ?? "") !== (news.displayName ?? "") ? "displayName" : undefined, |
| 258 | (current.description ?? "") !== desiredDescription ? "description" : undefined, |
| 259 | ].filter((field): field is string => field !== undefined); |
| 260 | if (updateMask.length > 0) { |
| 261 | const patched = yield* iam.patchProjectsServiceAccounts({ |
| 262 | name: current.name ?? name, |
| 263 | body: { |
| 264 | updateMask: updateMask.join(","), |
| 265 | serviceAccount: { |
| 266 | displayName: news.displayName ?? "", |
| 267 | description: desiredDescription, |
| 268 | }, |
| 269 | }, |
| 270 | }); |
| 271 | // The patch response only echoes the masked fields, and a re-read can |
| 272 | // still return the previous values, so the patched fields win. |
| 273 | current = { |
| 274 | ...current, |
| 275 | displayName: patched.displayName ?? news.displayName, |
| 276 | description: patched.description ?? desiredDescription, |
| 277 | }; |
| 278 | } |
| 279 | |
| 280 | // Sync the roles bindings grant the account. Roles it holds for other |
| 281 | // reasons (e.g. a `GCP.IAM.Member`) are used but never revoked. |
| 282 | const attrs = toAttrs(current, project); |
| 283 | if (bindings.length === 0 && (output?.iamGrants ?? []).length === 0) return attrs; |
| 284 | const { grants } = yield* syncHostIam({ |
| 285 | project: attrs.project, |
| 286 | serviceAccount: attrs.email, |
| 287 | managed: false, |
| 288 | bindings, |
| 289 | previous: output?.iamGrants, |
| 290 | }); |
| 291 | return { ...attrs, iamGrants: grants }; |
| 292 | }), |
| 293 | |
| 294 | delete: Effect.fn(function* ({ output }) { |
| 295 | // Revoke first, so no `deleted:serviceAccount:` members linger. |
| 296 | yield* revokeHostIam({ serviceAccount: output.email, grants: output.iamGrants ?? [] }); |
| 297 | yield* iam |
| 298 | .deleteProjectsServiceAccounts({ name: output.name }) |
| 299 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 300 | }), |
| 301 | }); |