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 securityposture from "@distilled.cloud/gcp/securityposture_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 { tagRecord } from "alchemy/Tags"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as Stream from "effect/Stream"; |
| 10 | import { GcpEnvironment } from "../Environment.ts"; |
| 11 | import { createInternalLabels, hasAlchemyLabels, toLabels } from "../Labels.ts"; |
| 12 | import type { Providers } from "../Providers.ts"; |
| 13 | import { |
| 14 | DEFAULT_LOCATION, |
| 15 | defaultTargetResource, |
| 16 | fieldMask, |
| 17 | hasAlchemyAnnotationMap, |
| 18 | lastSegment, |
| 19 | locationParent, |
| 20 | normalizeTargetResource, |
| 21 | organizationIdOf, |
| 22 | organizationParent, |
| 23 | parseName, |
| 24 | replaceOnIdentity, |
| 25 | resolveOrganization, |
| 26 | sameText, |
| 27 | SecuritypostureNotResolved, |
| 28 | toPhysicalId, |
| 29 | tryResolveOrganization, |
| 30 | userAnnotations, |
| 31 | waitForOperation, |
| 32 | waitUntilExists, |
| 33 | waitUntilGone, |
| 34 | } from "./internal.ts"; |
| 35 | |
| 36 | export type PostureDeploymentState = securityposture.PostureDeploymentStateEnum | (string & {}); |
| 37 | |
| 38 | export type PostureDeploymentProps = { |
| 39 | /** |
| 40 | * Posture deployment id (the `{postureDeployment}` segment of |
| 41 | * `organizations/{organization}/locations/global/postureDeployments/{postureDeployment}`). |
| 42 | * If omitted, a unique id is generated from the stack, stage, and |
| 43 | * logical id. Letters, digits, hyphens, and underscores; max 63 |
| 44 | * characters. Immutable — changing it replaces the deployment. |
| 45 | */ |
| 46 | postureDeploymentId?: string; |
| 47 | /** |
| 48 | * Parent organization (`organizations/{organization}` or the numeric |
| 49 | * id). Defaults to `GOOGLE_ORGANIZATION_ID` or the project's Resource |
| 50 | * Manager ancestor. Immutable — changing it replaces the deployment. |
| 51 | */ |
| 52 | organization?: string; |
| 53 | /** |
| 54 | * Location. Posture deployments live in `global`. |
| 55 | * @default "global" |
| 56 | */ |
| 57 | location?: string; |
| 58 | /** |
| 59 | * Organization, folder, or project the posture is applied to |
| 60 | * (`organizations/{number}`, `folders/{number}`, or |
| 61 | * `projects/{number}`). Defaults to the stack project. At most one |
| 62 | * posture can be deployed to each target. Immutable — changing it |
| 63 | * replaces the deployment. |
| 64 | */ |
| 65 | targetResource?: string; |
| 66 | /** |
| 67 | * Posture used in the deployment, as |
| 68 | * `organizations/{organization}/locations/global/postures/{posture}`. |
| 69 | */ |
| 70 | postureId: string; |
| 71 | /** |
| 72 | * Revision id of the posture used in the deployment. |
| 73 | */ |
| 74 | postureRevisionId: string; |
| 75 | /** |
| 76 | * Human-readable description. |
| 77 | */ |
| 78 | description?: string; |
| 79 | /** |
| 80 | * User annotations. Deployments have no labels field — Alchemy |
| 81 | * ownership (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is |
| 82 | * stored here so `list` / `pnpm nuke:gcp` can find owned deployments. |
| 83 | * Annotations are set at create time. |
| 84 | */ |
| 85 | annotations?: Record<string, string>; |
| 86 | }; |
| 87 | |
| 88 | export type PostureDeployment = Resource< |
| 89 | "GCP.SecurityPosture.PostureDeployment", |
| 90 | PostureDeploymentProps, |
| 91 | { |
| 92 | /** Full resource name `organizations/{organization}/locations/global/postureDeployments/{postureDeployment}`. */ |
| 93 | name: string; |
| 94 | /** Posture deployment id (last path segment). */ |
| 95 | postureDeploymentId: string; |
| 96 | /** Organization resource name. */ |
| 97 | organization: string; |
| 98 | /** Organization id. */ |
| 99 | organizationId: string; |
| 100 | /** Location id (`global`). */ |
| 101 | location: string; |
| 102 | /** Project id of the deploying stack. */ |
| 103 | project: string; |
| 104 | /** Target organization, folder, or project. */ |
| 105 | targetResource: string | undefined; |
| 106 | /** Deployed posture resource name. */ |
| 107 | postureId: string | undefined; |
| 108 | /** Deployed posture revision id. */ |
| 109 | postureRevisionId: string | undefined; |
| 110 | /** User description. */ |
| 111 | description: string | undefined; |
| 112 | /** User annotations (Alchemy ownership keys stripped). */ |
| 113 | annotations: Record<string, string>; |
| 114 | /** Deployment state (`CREATING`, `ACTIVE`, `CREATE_FAILED`, …). */ |
| 115 | state: string | undefined; |
| 116 | /** Failure message when the deployment is in a failed state. */ |
| 117 | failureMessage: string | undefined; |
| 118 | /** Categories assigned by the Security Posture API. */ |
| 119 | categories: string[] | undefined; |
| 120 | /** Whether the deployment is being updated. */ |
| 121 | reconciling: boolean | undefined; |
| 122 | /** Server checksum used on update and delete. */ |
| 123 | etag: string | undefined; |
| 124 | /** RFC3339 creation timestamp. */ |
| 125 | createTime: string | undefined; |
| 126 | /** RFC3339 last-update timestamp. */ |
| 127 | updateTime: string | undefined; |
| 128 | }, |
| 129 | never, |
| 130 | Providers |
| 131 | >; |
| 132 | |
| 133 | /** |
| 134 | * A Security Command Center posture deployment. |
| 135 | * |
| 136 | * Deployments apply a posture revision to one organization, folder, or |
| 137 | * project. The parent is always the organization, even when the target |
| 138 | * is a folder or project. At most one posture can be deployed to each |
| 139 | * target. Deployments have no labels field — Alchemy stamps ownership |
| 140 | * into `annotations`. `postureDeploymentId`, `organization`, and |
| 141 | * `targetResource` are identity. `postureId` and `postureRevisionId` |
| 142 | * update in place. |
| 143 | * |
| 144 | * The posture must be `ACTIVE`. Creating a deployment requires the |
| 145 | * Security Posture API and organization-level Security Command Center |
| 146 | * Premium or Enterprise. |
| 147 | * |
| 148 | * ### Creating a Posture Deployment |
| 149 | * **Example:** Deploy a posture to the stack project |
| 150 | * ```typescript |
| 151 | * const posture = yield* GCP.SecurityPosture.Posture("Baseline", { |
| 152 | * state: "ACTIVE", |
| 153 | * }); |
| 154 | * const deployment = yield* GCP.SecurityPosture.PostureDeployment( |
| 155 | * "Staging", |
| 156 | * { |
| 157 | * postureId: posture.name, |
| 158 | * postureRevisionId: posture.revisionId, |
| 159 | * }, |
| 160 | * ); |
| 161 | * ``` |
| 162 | * |
| 163 | * **Example:** Deploy to an explicit project |
| 164 | * ```typescript |
| 165 | * const deployment = yield* GCP.SecurityPosture.PostureDeployment( |
| 166 | * "Staging", |
| 167 | * { |
| 168 | * organization: "organizations/123456789", |
| 169 | * targetResource: "projects/987654321", |
| 170 | * postureId: |
| 171 | * "organizations/123456789/locations/global/postures/staging-baseline", |
| 172 | * postureRevisionId: "abcdefgh", |
| 173 | * description: "staging deployment", |
| 174 | * }, |
| 175 | * ); |
| 176 | * ``` |
| 177 | * |
| 178 | * @resource |
| 179 | * @category SecurityPosture |
| 180 | */ |
| 181 | export const PostureDeployment = Resource<PostureDeployment>( |
| 182 | "GCP.SecurityPosture.PostureDeployment", |
| 183 | ); |
| 184 | |
| 185 | const resourceName = (organization: string, location: string, postureDeploymentId: string) => |
| 186 | `${locationParent(organization, location)}/postureDeployments/${postureDeploymentId}`; |
| 187 | |
| 188 | const waitDeploymentOperation = (operation: securityposture.Operation) => |
| 189 | waitForOperation(operation); |
| 190 | |
| 191 | const waitDeploymentOperationGone = (operation: securityposture.Operation) => |
| 192 | waitForOperation(operation, { notFoundOk: true }); |
| 193 | |
| 194 | const toAttrs = (deployment: securityposture.PostureDeployment, project: string) => { |
| 195 | const name = deployment.name ?? ""; |
| 196 | const parsed = parseName(name, "postureDeployments"); |
| 197 | const organization = parsed.organization ? organizationParent(parsed.organization) : ""; |
| 198 | return { |
| 199 | name, |
| 200 | postureDeploymentId: parsed.id || lastSegment(name), |
| 201 | organization, |
| 202 | organizationId: organizationIdOf(organization), |
| 203 | location: parsed.location, |
| 204 | project, |
| 205 | targetResource: deployment.targetResource, |
| 206 | postureId: deployment.postureId, |
| 207 | postureRevisionId: deployment.postureRevisionId, |
| 208 | description: deployment.description, |
| 209 | annotations: userAnnotations(deployment.annotations), |
| 210 | state: deployment.state, |
| 211 | failureMessage: deployment.failureMessage, |
| 212 | categories: deployment.categories, |
| 213 | reconciling: deployment.reconciling, |
| 214 | etag: deployment.etag, |
| 215 | createTime: deployment.createTime, |
| 216 | updateTime: deployment.updateTime, |
| 217 | }; |
| 218 | }; |
| 219 | |
| 220 | const getByName = (name: string) => |
| 221 | name.length === 0 |
| 222 | ? Effect.undefined |
| 223 | : securityposture |
| 224 | .getOrganizationsLocationsPostureDeployments({ name }) |
| 225 | .pipe(Effect.catchTag("NotFound", () => Effect.undefined)); |
| 226 | |
| 227 | const isBusy = (deployment: securityposture.PostureDeployment) => |
| 228 | deployment.reconciling === true || |
| 229 | deployment.state === "CREATING" || |
| 230 | deployment.state === "UPDATING" || |
| 231 | deployment.state === "DELETING"; |
| 232 | |
| 233 | const waitUntilSettled = (name: string) => |
| 234 | getByName(name).pipe( |
| 235 | Effect.flatMap((current) => { |
| 236 | if (current === undefined) { |
| 237 | return Effect.fail(new SecuritypostureNotResolved({ resourceName: name })); |
| 238 | } |
| 239 | if (isBusy(current)) { |
| 240 | return Effect.fail( |
| 241 | new SecuritypostureNotResolved({ resourceName: `${name}:${current.state}` }), |
| 242 | ); |
| 243 | } |
| 244 | return Effect.succeed(current); |
| 245 | }), |
| 246 | Effect.retry({ |
| 247 | while: (error) => error._tag === "GCP.SecurityPosture.NotResolved", |
| 248 | times: 10, |
| 249 | schedule: Schedule.spaced("3 seconds"), |
| 250 | }), |
| 251 | ); |
| 252 | |
| 253 | export const PostureDeploymentProvider = () => |
| 254 | Provider.succeed(PostureDeployment, { |
| 255 | stables: [ |
| 256 | "name", |
| 257 | "postureDeploymentId", |
| 258 | "organization", |
| 259 | "organizationId", |
| 260 | "location", |
| 261 | "project", |
| 262 | "targetResource", |
| 263 | "createTime", |
| 264 | ], |
| 265 | |
| 266 | diff: Effect.fn(function* ({ news, olds, output }) { |
| 267 | if (!isResolved(news)) return undefined; |
| 268 | const previousId = olds?.postureDeploymentId ?? output?.postureDeploymentId; |
| 269 | const nextId = news.postureDeploymentId ?? previousId; |
| 270 | const previousOrg = olds?.organization ?? output?.organization; |
| 271 | const nextOrg = |
| 272 | news.organization !== undefined ? organizationParent(news.organization) : previousOrg; |
| 273 | const previousTarget = olds?.targetResource ?? output?.targetResource; |
| 274 | const nextTarget = news.targetResource ?? previousTarget; |
| 275 | return replaceOnIdentity( |
| 276 | (previousId !== undefined && nextId !== undefined && nextId !== previousId) || |
| 277 | (previousOrg !== undefined && |
| 278 | nextOrg !== undefined && |
| 279 | organizationParent(previousOrg) !== organizationParent(nextOrg)) || |
| 280 | (previousTarget !== undefined && |
| 281 | nextTarget !== undefined && |
| 282 | previousTarget !== nextTarget), |
| 283 | true, |
| 284 | ); |
| 285 | }), |
| 286 | |
| 287 | read: Effect.fn(function* ({ id, olds, output }) { |
| 288 | const env = yield* GcpEnvironment.current; |
| 289 | const postureDeploymentId = yield* toPhysicalId( |
| 290 | id, |
| 291 | olds?.postureDeploymentId, |
| 292 | output?.postureDeploymentId, |
| 293 | "deploy", |
| 294 | ); |
| 295 | const organization = yield* resolveOrganization( |
| 296 | olds?.organization ?? output?.organization, |
| 297 | output?.organization, |
| 298 | ).pipe( |
| 299 | Effect.catchTag("GCP.SecurityPosture.OrganizationNotResolved", () => |
| 300 | Effect.succeed(output?.organization ?? ""), |
| 301 | ), |
| 302 | ); |
| 303 | const location = lastSegment(olds?.location ?? output?.location ?? DEFAULT_LOCATION); |
| 304 | const name = |
| 305 | output?.name ?? |
| 306 | (organization.length > 0 ? resourceName(organization, location, postureDeploymentId) : ""); |
| 307 | const existing = yield* getByName(name); |
| 308 | if (existing === undefined) return undefined; |
| 309 | const attrs = toAttrs(existing, env.project); |
| 310 | return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations))) |
| 311 | ? attrs |
| 312 | : Unowned(attrs); |
| 313 | }), |
| 314 | |
| 315 | list: () => |
| 316 | Effect.gen(function* () { |
| 317 | const env = yield* GcpEnvironment.current; |
| 318 | const organization = yield* tryResolveOrganization(); |
| 319 | if (organization === undefined) return []; |
| 320 | const parent = locationParent(organization, DEFAULT_LOCATION); |
| 321 | return yield* securityposture.listOrganizationsLocationsPostureDeployments |
| 322 | .pages({ parent, pageSize: 1000 }) |
| 323 | .pipe( |
| 324 | Stream.flatMap((page) => Stream.fromIterable(page.postureDeployments ?? [])), |
| 325 | Stream.filter((deployment) => hasAlchemyAnnotationMap(deployment.annotations)), |
| 326 | Stream.map((deployment) => toAttrs(deployment, env.project)), |
| 327 | Stream.runCollect, |
| 328 | Effect.map((chunk) => Array.from(chunk)), |
| 329 | Effect.catchTag("NotFound", () => Effect.succeed([])), |
| 330 | ); |
| 331 | }), |
| 332 | |
| 333 | reconcile: Effect.fn(function* ({ id, news, output }) { |
| 334 | const env = yield* GcpEnvironment.current; |
| 335 | const postureDeploymentId = yield* toPhysicalId( |
| 336 | id, |
| 337 | news.postureDeploymentId, |
| 338 | output?.postureDeploymentId, |
| 339 | "deploy", |
| 340 | ); |
| 341 | const organization = yield* resolveOrganization( |
| 342 | news.organization ?? output?.organization, |
| 343 | output?.organization, |
| 344 | ); |
| 345 | const location = lastSegment(news.location ?? output?.location ?? DEFAULT_LOCATION); |
| 346 | const parent = locationParent(organization, location); |
| 347 | const name = resourceName(organization, location, postureDeploymentId); |
| 348 | const targetResource = yield* news.targetResource !== undefined |
| 349 | ? normalizeTargetResource(news.targetResource) |
| 350 | : output?.targetResource |
| 351 | ? Effect.succeed(output.targetResource) |
| 352 | : defaultTargetResource(); |
| 353 | const desiredAnnotations = { |
| 354 | ...toLabels(news.annotations), |
| 355 | ...(yield* createInternalLabels(id)), |
| 356 | }; |
| 357 | |
| 358 | let current = yield* getByName(output?.name ?? name); |
| 359 | |
| 360 | if (current === undefined) { |
| 361 | const created = yield* securityposture |
| 362 | .createOrganizationsLocationsPostureDeployments({ |
| 363 | parent, |
| 364 | postureDeploymentId, |
| 365 | body: { |
| 366 | targetResource, |
| 367 | postureId: news.postureId, |
| 368 | postureRevisionId: news.postureRevisionId, |
| 369 | description: news.description, |
| 370 | annotations: desiredAnnotations, |
| 371 | }, |
| 372 | }) |
| 373 | .pipe(Effect.catchTag("Conflict", () => Effect.undefined)); |
| 374 | if (created !== undefined) { |
| 375 | yield* waitDeploymentOperation(created); |
| 376 | } |
| 377 | current = yield* waitUntilExists(getByName(name), name); |
| 378 | current = yield* waitUntilSettled(current.name ?? name); |
| 379 | } |
| 380 | |
| 381 | if (current === undefined) { |
| 382 | return yield* new SecuritypostureNotResolved({ resourceName: name }); |
| 383 | } |
| 384 | |
| 385 | const postureChanged = !sameText(current.postureId, news.postureId); |
| 386 | const revisionChanged = !sameText(current.postureRevisionId, news.postureRevisionId); |
| 387 | const descriptionChanged = !sameText(current.description, news.description); |
| 388 | const mask = fieldMask([ |
| 389 | postureChanged && "posture_id", |
| 390 | revisionChanged && "posture_revision_id", |
| 391 | descriptionChanged && "description", |
| 392 | ]); |
| 393 | |
| 394 | if (mask.length > 0) { |
| 395 | const operation = yield* securityposture.patchOrganizationsLocationsPostureDeployments({ |
| 396 | name: current.name ?? name, |
| 397 | updateMask: mask, |
| 398 | body: { |
| 399 | name: current.name ?? name, |
| 400 | postureId: news.postureId, |
| 401 | postureRevisionId: news.postureRevisionId, |
| 402 | description: news.description, |
| 403 | etag: current.etag, |
| 404 | }, |
| 405 | }); |
| 406 | yield* waitDeploymentOperation(operation); |
| 407 | current = yield* waitUntilSettled(current.name ?? name); |
| 408 | } |
| 409 | |
| 410 | return toAttrs(current, env.project); |
| 411 | }), |
| 412 | |
| 413 | delete: Effect.fn(function* ({ output }) { |
| 414 | if (!output.name) return; |
| 415 | const operation = yield* securityposture |
| 416 | .deleteOrganizationsLocationsPostureDeployments({ |
| 417 | name: output.name, |
| 418 | etag: output.etag, |
| 419 | }) |
| 420 | .pipe( |
| 421 | Effect.retry({ |
| 422 | while: (error) => error._tag === "Conflict", |
| 423 | times: 8, |
| 424 | schedule: Schedule.spaced("2 seconds"), |
| 425 | }), |
| 426 | Effect.catchTag("NotFound", () => Effect.undefined), |
| 427 | ); |
| 428 | if (operation !== undefined) { |
| 429 | yield* waitDeploymentOperationGone(operation); |
| 430 | } |
| 431 | yield* waitUntilGone(getByName(output.name), output.name); |
| 432 | }), |
| 433 | }); |