The best way to control Claude Code, Codex and more from any computer or phone
| 1 | import * as resourcemanager from "@distilled.cloud/gcp/cloudresourcemanager_v3"; |
| 2 | import * as orgpolicy from "@distilled.cloud/gcp/orgpolicy_v2"; |
| 3 | import { Unowned } from "alchemy/AdoptPolicy"; |
| 4 | import { isResolved } from "alchemy/Diff"; |
| 5 | import { createPhysicalName } from "alchemy/PhysicalName"; |
| 6 | import * as Provider from "alchemy/Provider"; |
| 7 | import { Resource } from "alchemy/Resource"; |
| 8 | import * as Data from "effect/Data"; |
| 9 | import * as Effect from "effect/Effect"; |
| 10 | import * as Schedule from "effect/Schedule"; |
| 11 | import { GcpEnvironment } from "../Environment.ts"; |
| 12 | import { alchemyLabelKeys, createInternalLabels, hasAlchemyLabels } from "../Labels.ts"; |
| 13 | import type { Providers } from "../Providers.ts"; |
| 14 | |
| 15 | const CUSTOM_PREFIX = "custom."; |
| 16 | const COLLECTION = "/customConstraints/"; |
| 17 | const DESCRIPTION_MAX = 2000; |
| 18 | const GENERATED_ID_MAX = 60; |
| 19 | |
| 20 | export type CustomConstraintMethodType = |
| 21 | | "CREATE" |
| 22 | | "UPDATE" |
| 23 | | "DELETE" |
| 24 | | "REMOVE_GRANT" |
| 25 | | "GOVERN_TAGS"; |
| 26 | |
| 27 | export type CustomConstraintActionType = "ALLOW" | "DENY"; |
| 28 | |
| 29 | export type CustomConstraintProps = { |
| 30 | /** |
| 31 | * Constraint id (the `{customConstraint}` segment of |
| 32 | * `organizations/{organization}/customConstraints/{customConstraint}`). |
| 33 | * Must start with `custom.` and contain only letters, digits, and |
| 34 | * periods. If omitted, a unique id is generated from the stack, stage, |
| 35 | * and logical id. Immutable — changing it replaces the constraint. |
| 36 | */ |
| 37 | constraintId?: string; |
| 38 | /** |
| 39 | * Parent organization (`organizations/{organization}` or the numeric |
| 40 | * id). Defaults to the project's Resource Manager ancestor. Immutable — changing it replaces the constraint. |
| 41 | */ |
| 42 | organization?: string; |
| 43 | /** |
| 44 | * Resource types this constraint applies to, e.g. |
| 45 | * `compute.googleapis.com/Instance`. Immutable — changing the set |
| 46 | * replaces the constraint. |
| 47 | */ |
| 48 | resourceTypes: string[]; |
| 49 | /** |
| 50 | * Operations the constraint evaluates (`CREATE`, `UPDATE`, `DELETE`, |
| 51 | * `REMOVE_GRANT`, `GOVERN_TAGS`). |
| 52 | */ |
| 53 | methodTypes: CustomConstraintMethodType[]; |
| 54 | /** |
| 55 | * CEL condition evaluated against the resource. Max 1000 characters. |
| 56 | */ |
| 57 | condition: string; |
| 58 | /** |
| 59 | * Whether matching resources are allowed or denied. |
| 60 | */ |
| 61 | actionType: CustomConstraintActionType; |
| 62 | /** |
| 63 | * One-line display name (max 200 characters). |
| 64 | */ |
| 65 | displayName?: string; |
| 66 | /** |
| 67 | * Human-readable description (max 2000 characters including the |
| 68 | * Alchemy ownership prefix). Custom constraints have no labels, so |
| 69 | * ownership is stored in a `[alchemy …]` prefix and stripped from |
| 70 | * attributes. |
| 71 | */ |
| 72 | description?: string; |
| 73 | }; |
| 74 | |
| 75 | export type CustomConstraint = Resource< |
| 76 | "GCP.OrgPolicy.CustomConstraint", |
| 77 | CustomConstraintProps, |
| 78 | { |
| 79 | /** Full resource name `organizations/{organization}/customConstraints/{id}`. */ |
| 80 | name: string; |
| 81 | /** Constraint id (last path segment, including the `custom.` prefix). */ |
| 82 | constraintId: string; |
| 83 | /** Parent `organizations/{organization}`. */ |
| 84 | organization: string; |
| 85 | /** Numeric organization id. */ |
| 86 | organizationId: string; |
| 87 | /** Project id of the deploying stack. */ |
| 88 | project: string; |
| 89 | /** Resource types this constraint applies to. */ |
| 90 | resourceTypes: string[]; |
| 91 | /** Operations the constraint evaluates. */ |
| 92 | methodTypes: string[]; |
| 93 | /** CEL condition. */ |
| 94 | condition: string; |
| 95 | /** `ALLOW` or `DENY`. */ |
| 96 | actionType: string; |
| 97 | /** One-line display name. */ |
| 98 | displayName: string | undefined; |
| 99 | /** User description with the Alchemy ownership prefix stripped. */ |
| 100 | description: string | undefined; |
| 101 | /** RFC3339 last-update timestamp. */ |
| 102 | updateTime: string | undefined; |
| 103 | }, |
| 104 | never, |
| 105 | Providers |
| 106 | >; |
| 107 | |
| 108 | /** |
| 109 | * A Google Cloud Organization Policy custom constraint. |
| 110 | * |
| 111 | * Custom constraints can only be created on an organization. Creating one |
| 112 | * does not enforce anything — attach a `GCP.OrgPolicy.Policy` that |
| 113 | * references the constraint id to enforce it. |
| 114 | * |
| 115 | * Custom constraints have no labels. Alchemy stamps ownership into the |
| 116 | * description (`[alchemy alchemy-stack=… alchemy-stage=… alchemy-id=…]`) |
| 117 | * so `list` / `pnpm nuke:gcp` can find them. |
| 118 | * |
| 119 | * `constraintId`, `organization`, and `resourceTypes` are immutable — |
| 120 | * changing them replaces the constraint. `methodTypes`, `condition`, |
| 121 | * `actionType`, `displayName`, and `description` update in place. |
| 122 | * |
| 123 | * ### Creating a Custom Constraint |
| 124 | * **Example:** Deny matching Compute instances |
| 125 | * ```typescript |
| 126 | * const constraint = yield* GCP.OrgPolicy.CustomConstraint("NoTestVms", { |
| 127 | * resourceTypes: ["compute.googleapis.com/Instance"], |
| 128 | * methodTypes: ["CREATE"], |
| 129 | * condition: "resource.name.startsWith('test-')", |
| 130 | * actionType: "DENY", |
| 131 | * displayName: "Deny test VMs", |
| 132 | * }); |
| 133 | * ``` |
| 134 | * |
| 135 | * **Example:** Named constraint on an explicit organization |
| 136 | * ```typescript |
| 137 | * const constraint = yield* GCP.OrgPolicy.CustomConstraint("NoTestVms", { |
| 138 | * constraintId: "custom.denyTestVms", |
| 139 | * organization: "organizations/123456789", |
| 140 | * resourceTypes: ["compute.googleapis.com/Instance"], |
| 141 | * methodTypes: ["CREATE", "UPDATE"], |
| 142 | * condition: "resource.name.startsWith('test-')", |
| 143 | * actionType: "DENY", |
| 144 | * displayName: "Deny test VMs", |
| 145 | * description: "blocks test-prefixed instances", |
| 146 | * }); |
| 147 | * ``` |
| 148 | * |
| 149 | * ### Updating a Custom Constraint |
| 150 | * **Example:** Broaden methods and change the condition |
| 151 | * ```typescript |
| 152 | * const constraint = yield* GCP.OrgPolicy.CustomConstraint("NoTestVms", { |
| 153 | * constraintId: "custom.denyTestVms", |
| 154 | * resourceTypes: ["compute.googleapis.com/Instance"], |
| 155 | * methodTypes: ["CREATE", "UPDATE"], |
| 156 | * condition: "resource.name.startsWith('tmp-')", |
| 157 | * actionType: "DENY", |
| 158 | * displayName: "Deny tmp VMs", |
| 159 | * }); |
| 160 | * ``` |
| 161 | * |
| 162 | * @resource |
| 163 | * @category OrgPolicy |
| 164 | */ |
| 165 | export const CustomConstraint = Resource<CustomConstraint>("GCP.OrgPolicy.CustomConstraint"); |
| 166 | |
| 167 | export class CustomConstraintNotResolved extends Data.TaggedError( |
| 168 | "GCP.OrgPolicy.CustomConstraintNotResolved", |
| 169 | )<{ |
| 170 | resourceName: string; |
| 171 | }> {} |
| 172 | |
| 173 | export class OrganizationRequired extends Data.TaggedError("GCP.OrgPolicy.OrganizationRequired")<{ |
| 174 | project: string; |
| 175 | }> {} |
| 176 | |
| 177 | const lastSegment = (value: string) => { |
| 178 | const trimmed = value.replace(/\/+$/, ""); |
| 179 | const parts = trimmed.split("/"); |
| 180 | return parts[parts.length - 1] || trimmed; |
| 181 | }; |
| 182 | |
| 183 | const organizationParent = (value: string) => |
| 184 | value.startsWith("organizations/") ? value : `organizations/${lastSegment(value)}`; |
| 185 | |
| 186 | const constraintIdOf = (value: string) => { |
| 187 | const at = value.indexOf(COLLECTION); |
| 188 | return at >= 0 ? value.slice(at + COLLECTION.length) : lastSegment(value); |
| 189 | }; |
| 190 | |
| 191 | const normalizeConstraintId = (value: string) => { |
| 192 | const id = constraintIdOf(value); |
| 193 | return id.startsWith(CUSTOM_PREFIX) ? id : `${CUSTOM_PREFIX}${id}`; |
| 194 | }; |
| 195 | |
| 196 | const resourceName = (organization: string, constraintId: string) => |
| 197 | `${organization}${COLLECTION}${constraintId}`; |
| 198 | |
| 199 | const parseName = (name: string) => { |
| 200 | const at = name.indexOf(COLLECTION); |
| 201 | if (at < 0) { |
| 202 | return { organization: "", constraintId: normalizeConstraintId(name) }; |
| 203 | } |
| 204 | return { |
| 205 | organization: name.slice(0, at), |
| 206 | constraintId: name.slice(at + COLLECTION.length), |
| 207 | }; |
| 208 | }; |
| 209 | |
| 210 | const sameOrganization = (left: string | undefined, right: string | undefined) => { |
| 211 | if (left === undefined || right === undefined) return left === right; |
| 212 | return organizationParent(left) === organizationParent(right); |
| 213 | }; |
| 214 | |
| 215 | const sorted = (values: readonly string[] | undefined) => [...(values ?? [])].slice().sort(); |
| 216 | |
| 217 | const sameStringList = ( |
| 218 | left: readonly string[] | undefined, |
| 219 | right: readonly string[] | undefined, |
| 220 | ) => JSON.stringify(sorted(left)) === JSON.stringify(sorted(right)); |
| 221 | |
| 222 | const parentOfResource = (name: string) => |
| 223 | name.startsWith("projects/") |
| 224 | ? resourcemanager.getProjects({ name }).pipe( |
| 225 | Effect.map((resource) => resource.parent), |
| 226 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 227 | ) |
| 228 | : name.startsWith("folders/") |
| 229 | ? resourcemanager.getFolders({ name }).pipe( |
| 230 | Effect.map((folder) => folder.parent), |
| 231 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 232 | ) |
| 233 | : Effect.undefined; |
| 234 | |
| 235 | const tryResolveOrganization = (explicit?: string) => |
| 236 | Effect.gen(function* () { |
| 237 | if (explicit !== undefined && explicit.length > 0) { |
| 238 | return organizationParent(explicit); |
| 239 | } |
| 240 | const env = yield* GcpEnvironment.current; |
| 241 | let current: string | undefined = `projects/${env.project}`; |
| 242 | for (let i = 0; i < 8; i++) { |
| 243 | if (current === undefined) return undefined; |
| 244 | if (current.startsWith("organizations/")) return current; |
| 245 | current = yield* parentOfResource(current); |
| 246 | } |
| 247 | return undefined; |
| 248 | }); |
| 249 | |
| 250 | const resolveOrganization = (explicit: string | undefined, existing: string | undefined) => |
| 251 | Effect.gen(function* () { |
| 252 | const resolved = yield* tryResolveOrganization(explicit ?? existing); |
| 253 | if (resolved === undefined) { |
| 254 | const env = yield* GcpEnvironment.current; |
| 255 | return yield* new OrganizationRequired({ project: env.project }); |
| 256 | } |
| 257 | return resolved; |
| 258 | }); |
| 259 | |
| 260 | const toConstraintId = (id: string, explicit: string | undefined, existing: string | undefined) => |
| 261 | Effect.gen(function* () { |
| 262 | if (explicit !== undefined) return normalizeConstraintId(explicit); |
| 263 | if (existing !== undefined) return existing; |
| 264 | const generated = yield* createPhysicalName({ |
| 265 | id, |
| 266 | maxLength: GENERATED_ID_MAX, |
| 267 | lowercase: true, |
| 268 | delimiter: ".", |
| 269 | }); |
| 270 | const body = generated.replace(/[^a-z0-9.]/g, "").replace(/^\.+|\.+$/g, ""); |
| 271 | return `${CUSTOM_PREFIX}${body.length > 0 ? body : "c"}`; |
| 272 | }); |
| 273 | |
| 274 | const encodeDescription = ( |
| 275 | labels: Record<string, string>, |
| 276 | description: string | undefined, |
| 277 | ): string => { |
| 278 | const marker = `[alchemy ${alchemyLabelKeys.stack}=${labels[alchemyLabelKeys.stack]} ${alchemyLabelKeys.stage}=${labels[alchemyLabelKeys.stage]} ${alchemyLabelKeys.id}=${labels[alchemyLabelKeys.id]}]`; |
| 279 | if (!description) return marker.slice(0, DESCRIPTION_MAX); |
| 280 | const sep = "\n"; |
| 281 | const budget = DESCRIPTION_MAX - marker.length - sep.length; |
| 282 | if (budget <= 0) return marker.slice(0, DESCRIPTION_MAX); |
| 283 | return `${marker}${sep}${description.slice(0, budget)}`; |
| 284 | }; |
| 285 | |
| 286 | const parseDescription = ( |
| 287 | description: string | undefined, |
| 288 | ): { |
| 289 | labels: Record<string, string>; |
| 290 | description: string | undefined; |
| 291 | } => { |
| 292 | if (!description?.startsWith("[alchemy ")) { |
| 293 | return { labels: {}, description }; |
| 294 | } |
| 295 | const end = description.indexOf("]"); |
| 296 | if (end < 0) return { labels: {}, description }; |
| 297 | const labels: Record<string, string> = {}; |
| 298 | for (const part of description.slice("[alchemy ".length, end).split(/\s+/)) { |
| 299 | const eq = part.indexOf("="); |
| 300 | if (eq > 0) { |
| 301 | labels[part.slice(0, eq)] = part.slice(eq + 1); |
| 302 | } |
| 303 | } |
| 304 | const rest = description.slice(end + 1).replace(/^\n/, ""); |
| 305 | return { labels, description: rest.length > 0 ? rest : undefined }; |
| 306 | }; |
| 307 | |
| 308 | const hasOwnershipMarker = (description: string | undefined) => |
| 309 | Object.keys(parseDescription(description).labels).some((key) => key.startsWith("alchemy-")); |
| 310 | |
| 311 | const toAttrs = (constraint: orgpolicy.GoogleCloudOrgpolicyV2CustomConstraint, project: string) => { |
| 312 | const name = constraint.name ?? ""; |
| 313 | const parsedName = parseName(name); |
| 314 | const parsed = parseDescription(constraint.description); |
| 315 | return { |
| 316 | name, |
| 317 | constraintId: parsedName.constraintId, |
| 318 | organization: parsedName.organization, |
| 319 | organizationId: lastSegment(parsedName.organization), |
| 320 | project, |
| 321 | resourceTypes: [...(constraint.resourceTypes ?? [])], |
| 322 | methodTypes: [...(constraint.methodTypes ?? [])], |
| 323 | condition: constraint.condition ?? "", |
| 324 | actionType: constraint.actionType ?? "", |
| 325 | displayName: constraint.displayName, |
| 326 | description: parsed.description, |
| 327 | updateTime: constraint.updateTime, |
| 328 | }; |
| 329 | }; |
| 330 | |
| 331 | const getByName = (name: string) => |
| 332 | name.length === 0 |
| 333 | ? Effect.undefined |
| 334 | : orgpolicy |
| 335 | .getOrganizationsCustomConstraints({ name }) |
| 336 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 337 | |
| 338 | const listCustomConstraints = (parent: string) => |
| 339 | Effect.gen(function* () { |
| 340 | const found: orgpolicy.GoogleCloudOrgpolicyV2CustomConstraint[] = []; |
| 341 | let pageToken: string | undefined; |
| 342 | do { |
| 343 | const response = yield* orgpolicy.listOrganizationsCustomConstraints({ |
| 344 | parent, |
| 345 | pageSize: 1000, |
| 346 | pageToken, |
| 347 | }); |
| 348 | found.push(...(response.customConstraints ?? [])); |
| 349 | pageToken = response.nextPageToken; |
| 350 | } while (pageToken !== undefined && pageToken !== ""); |
| 351 | return found; |
| 352 | }).pipe( |
| 353 | Effect.catchTag("NotFound", () => |
| 354 | Effect.succeed([] as orgpolicy.GoogleCloudOrgpolicyV2CustomConstraint[]), |
| 355 | ), |
| 356 | ); |
| 357 | |
| 358 | const toBody = ( |
| 359 | name: string, |
| 360 | news: CustomConstraintProps, |
| 361 | description: string, |
| 362 | resourceTypes: readonly string[], |
| 363 | ): orgpolicy.GoogleCloudOrgpolicyV2CustomConstraint => ({ |
| 364 | name, |
| 365 | resourceTypes: [...resourceTypes], |
| 366 | methodTypes: [...news.methodTypes], |
| 367 | condition: news.condition, |
| 368 | actionType: news.actionType, |
| 369 | displayName: news.displayName, |
| 370 | description, |
| 371 | }); |
| 372 | |
| 373 | export const CustomConstraintProvider = () => |
| 374 | Provider.succeed(CustomConstraint, { |
| 375 | stables: ["name", "constraintId", "organization", "organizationId", "project"], |
| 376 | |
| 377 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 378 | if (!isResolved(news)) return undefined; |
| 379 | const previousId = olds?.constraintId ?? output?.constraintId; |
| 380 | const nextId = |
| 381 | news.constraintId !== undefined ? normalizeConstraintId(news.constraintId) : previousId; |
| 382 | const idChanged = previousId !== undefined && nextId !== undefined && previousId !== nextId; |
| 383 | |
| 384 | const previousOrg = olds?.organization ?? output?.organization; |
| 385 | const orgChanged = |
| 386 | news.organization !== undefined && |
| 387 | previousOrg !== undefined && |
| 388 | !sameOrganization(news.organization, previousOrg); |
| 389 | |
| 390 | const previousTypes = olds?.resourceTypes ?? output?.resourceTypes; |
| 391 | const typesChanged = |
| 392 | news.resourceTypes !== undefined && |
| 393 | previousTypes !== undefined && |
| 394 | !sameStringList(news.resourceTypes, previousTypes); |
| 395 | |
| 396 | if (!idChanged && !orgChanged && !typesChanged) return undefined; |
| 397 | return { |
| 398 | action: "replace" as const, |
| 399 | deleteFirst: !idChanged && !orgChanged, |
| 400 | }; |
| 401 | }), |
| 402 | |
| 403 | read: Effect.fn(function* ({ id, olds, output }) { |
| 404 | const env = yield* GcpEnvironment.current; |
| 405 | const organization = yield* tryResolveOrganization( |
| 406 | olds?.organization ?? output?.organization, |
| 407 | ); |
| 408 | const constraintId = yield* toConstraintId(id, olds?.constraintId, output?.constraintId); |
| 409 | const name = |
| 410 | output?.name ?? |
| 411 | (organization !== undefined ? resourceName(organization, constraintId) : ""); |
| 412 | const existing = yield* getByName(name); |
| 413 | if (existing === undefined) return undefined; |
| 414 | const attrs = toAttrs(existing, env.project); |
| 415 | const { labels } = parseDescription(existing.description); |
| 416 | return (yield* hasAlchemyLabels(id, labels)) ? attrs : Unowned(attrs); |
| 417 | }), |
| 418 | |
| 419 | list: () => |
| 420 | Effect.gen(function* () { |
| 421 | const env = yield* GcpEnvironment.current; |
| 422 | const organization = yield* tryResolveOrganization(); |
| 423 | if (organization === undefined) return []; |
| 424 | const constraints = yield* listCustomConstraints(organization); |
| 425 | return constraints |
| 426 | .filter((constraint) => hasOwnershipMarker(constraint.description)) |
| 427 | .map((constraint) => toAttrs(constraint, env.project)); |
| 428 | }), |
| 429 | |
| 430 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 431 | const env = yield* GcpEnvironment.current; |
| 432 | const organization = yield* resolveOrganization(news.organization, output?.organization); |
| 433 | const constraintId = yield* toConstraintId(id, news.constraintId, output?.constraintId); |
| 434 | const name = output?.name ?? resourceName(organization, constraintId); |
| 435 | const ownership = yield* createInternalLabels(id); |
| 436 | const desiredDescription = encodeDescription(ownership, news.description); |
| 437 | const desiredTypes = [...news.resourceTypes]; |
| 438 | |
| 439 | let current = yield* getByName(name); |
| 440 | |
| 441 | if (current === undefined) { |
| 442 | const created = yield* orgpolicy |
| 443 | .createOrganizationsCustomConstraints({ |
| 444 | parent: organization, |
| 445 | body: toBody( |
| 446 | resourceName(organization, constraintId), |
| 447 | news, |
| 448 | desiredDescription, |
| 449 | desiredTypes, |
| 450 | ), |
| 451 | }) |
| 452 | .pipe(Effect.catchTag("Conflict", () => getByName(name))); |
| 453 | current = created ?? undefined; |
| 454 | } |
| 455 | |
| 456 | if (current === undefined) { |
| 457 | return yield* new CustomConstraintNotResolved({ resourceName: name }); |
| 458 | } |
| 459 | |
| 460 | const methodsChanged = !sameStringList(current.methodTypes, news.methodTypes); |
| 461 | const conditionChanged = (current.condition ?? "") !== news.condition; |
| 462 | const actionChanged = (current.actionType ?? "") !== news.actionType; |
| 463 | const displayChanged = (current.displayName ?? "") !== (news.displayName ?? ""); |
| 464 | const descriptionChanged = (current.description ?? "") !== desiredDescription; |
| 465 | |
| 466 | if ( |
| 467 | methodsChanged || |
| 468 | conditionChanged || |
| 469 | actionChanged || |
| 470 | displayChanged || |
| 471 | descriptionChanged |
| 472 | ) { |
| 473 | current = yield* orgpolicy |
| 474 | .patchOrganizationsCustomConstraints({ |
| 475 | name: current.name ?? name, |
| 476 | body: toBody( |
| 477 | current.name ?? name, |
| 478 | news, |
| 479 | desiredDescription, |
| 480 | current.resourceTypes ?? desiredTypes, |
| 481 | ), |
| 482 | }) |
| 483 | .pipe( |
| 484 | Effect.retry({ |
| 485 | while: (error) => error._tag === "Conflict", |
| 486 | times: 5, |
| 487 | schedule: Schedule.exponential("200 millis"), |
| 488 | }), |
| 489 | ); |
| 490 | } |
| 491 | |
| 492 | return toAttrs(current, env.project); |
| 493 | }), |
| 494 | |
| 495 | delete: Effect.fn(function* ({ output }) { |
| 496 | yield* orgpolicy |
| 497 | .deleteOrganizationsCustomConstraints({ name: output.name }) |
| 498 | .pipe(Effect.catchTag("NotFound", () => Effect.void)); |
| 499 | }), |
| 500 | }); |