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

main
ts 418 lines 14.3 KB
Raw
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 DEFAULT_STATE,
16 desiredPolicySets,
17 fieldMask,
18 fingerprint,
19 hasAlchemyAnnotationMap,
20 lastSegment,
21 locationParent,
22 organizationIdOf,
23 organizationParent,
24 parseName,
25 replaceOnIdentity,
26 resolveOrganization,
27 sameText,
28 SecuritypostureNotResolved,
29 toPhysicalId,
30 tryResolveOrganization,
31 userAnnotations,
32 waitForOperation,
33 waitUntilExists,
34 waitUntilGone,
35 } from "./internal.ts";
36
37 export type PostureState = securityposture.PostureStateEnum | (string & {});
38 export type PolicySet = securityposture.PolicySet;
39 export type Policy = securityposture.Policy;
40 export type Constraint = securityposture.Constraint;
41
42 export type PostureProps = {
43 /**
44 * Posture id (the `{posture}` segment of
45 * `organizations/{organization}/locations/global/postures/{posture}`).
46 * If omitted, a unique id is generated from the stack, stage, and
47 * logical id. Letters, digits, hyphens, and underscores; max 63
48 * characters. Immutable — changing it replaces the posture.
49 */
50 postureId?: string;
51 /**
52 * Parent organization (`organizations/{organization}` or the numeric
53 * id). Defaults to `GOOGLE_ORGANIZATION_ID` or the project's Resource
54 * Manager ancestor. Immutable — changing it replaces the posture.
55 */
56 organization?: string;
57 /**
58 * Location. Security postures live in `global`.
59 * @default "global"
60 */
61 location?: string;
62 /**
63 * Posture state. `DRAFT` is not deployable; `ACTIVE` can be deployed;
64 * `DEPRECATED` cannot be deployed until reactivated.
65 * @default "DRAFT"
66 */
67 state?: PostureState;
68 /**
69 * Human-readable description.
70 */
71 description?: string;
72 /**
73 * User annotations. Postures have no labels field — Alchemy ownership
74 * (`alchemy-stack` / `alchemy-stage` / `alchemy-id`) is stored here
75 * so `list` / `pnpm nuke:gcp` can find owned postures. Annotations are
76 * set at create time.
77 */
78 annotations?: Record<string, string>;
79 /**
80 * Policy sets the posture includes. When omitted, a disabled Security
81 * Health Analytics detector is used so the posture is valid.
82 */
83 policySets?: PolicySet[];
84 };
85
86 export type Posture = Resource<
87 "GCP.SecurityPosture.Posture",
88 PostureProps,
89 {
90 /** Full resource name `organizations/{organization}/locations/global/postures/{posture}`. */
91 name: string;
92 /** Posture id (last path segment). */
93 postureId: string;
94 /** Organization resource name. */
95 organization: string;
96 /** Organization id. */
97 organizationId: string;
98 /** Location id (`global`). */
99 location: string;
100 /** Project id of the deploying stack. */
101 project: string;
102 /** Posture state (`DRAFT`, `ACTIVE`, or `DEPRECATED`). */
103 state: string | undefined;
104 /** Opaque eight-character revision id used when deploying. */
105 revisionId: string | undefined;
106 /** User description. */
107 description: string | undefined;
108 /** User annotations (Alchemy ownership keys stripped). */
109 annotations: Record<string, string>;
110 /** Policy sets currently configured. */
111 policySets: PolicySet[];
112 /** Categories assigned by the Security Posture API. */
113 categories: string[] | undefined;
114 /** Whether the posture is being updated. */
115 reconciling: boolean | undefined;
116 /** Server checksum used on update and delete. */
117 etag: string | undefined;
118 /** RFC3339 creation timestamp. */
119 createTime: string | undefined;
120 /** RFC3339 last-update timestamp. */
121 updateTime: string | undefined;
122 },
123 never,
124 Providers
125 >;
126
127 /**
128 * An organization-scoped Security Command Center security posture.
129 *
130 * A posture groups organization-policy constraints and Security Health
131 * Analytics detectors into policy sets that can be deployed to a
132 * project, folder, or organization. Postures live under
133 * `organizations/{organization}/locations/global`. They have no labels
134 * field — Alchemy stamps ownership into `annotations`. `postureId` and
135 * `organization` are identity. Description, policy sets, and state
136 * update in place. State cannot be patched in the same request as other
137 * fields.
138 *
139 * Creating a posture requires the Security Posture API and
140 * organization-level Security Command Center Premium or Enterprise.
141 *
142 * ### Creating a Posture
143 * **Example:** Generated id with the default detector policy set
144 * ```typescript
145 * const posture = yield* GCP.SecurityPosture.Posture("Baseline", {
146 * description: "staging baseline",
147 * });
148 * ```
149 *
150 * **Example:** Named ACTIVE posture with a Security Health Analytics module
151 * ```typescript
152 * const posture = yield* GCP.SecurityPosture.Posture("Baseline", {
153 * organization: "organizations/123456789",
154 * postureId: "staging-baseline",
155 * state: "ACTIVE",
156 * policySets: [
157 * {
158 * policySetId: "sha",
159 * policies: [
160 * {
161 * policyId: "api-key-exists",
162 * constraint: {
163 * securityHealthAnalyticsModule: {
164 * moduleName: "API_KEY_EXISTS",
165 * moduleEnablementState: "DISABLED",
166 * },
167 * },
168 * },
169 * ],
170 * },
171 * ],
172 * });
173 * ```
174 *
175 * @resource
176 * @category SecurityPosture
177 */
178 export const Posture = Resource<Posture>("GCP.SecurityPosture.Posture");
179
180 const resourceName = (organization: string, location: string, postureId: string) =>
181 `${locationParent(organization, location)}/postures/${postureId}`;
182
183 const waitPostureOperation = (operation: securityposture.Operation) => waitForOperation(operation);
184
185 const waitPostureOperationGone = (operation: securityposture.Operation) =>
186 waitForOperation(operation, { notFoundOk: true });
187
188 const toAttrs = (posture: securityposture.Posture, project: string) => {
189 const name = posture.name ?? "";
190 const parsed = parseName(name, "postures");
191 const organization = parsed.organization ? organizationParent(parsed.organization) : "";
192 return {
193 name,
194 postureId: parsed.id || lastSegment(name),
195 organization,
196 organizationId: organizationIdOf(organization),
197 location: parsed.location,
198 project,
199 state: posture.state,
200 revisionId: posture.revisionId,
201 description: posture.description,
202 annotations: userAnnotations(posture.annotations),
203 policySets: posture.policySets ?? [],
204 categories: posture.categories,
205 reconciling: posture.reconciling,
206 etag: posture.etag,
207 createTime: posture.createTime,
208 updateTime: posture.updateTime,
209 };
210 };
211
212 const getByName = (name: string) =>
213 name.length === 0
214 ? Effect.undefined
215 : securityposture
216 .getOrganizationsLocationsPostures({ name })
217 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
218
219 const desiredState = (news: PostureProps) => news.state ?? DEFAULT_STATE;
220
221 const desiredBody = (
222 news: PostureProps,
223 annotations: Record<string, string>,
224 ): securityposture.Posture => ({
225 state: desiredState(news),
226 description: news.description,
227 annotations,
228 policySets: desiredPolicySets(news.policySets),
229 });
230
231 export const PostureProvider = () =>
232 Provider.succeed(Posture, {
233 stables: [
234 "name",
235 "postureId",
236 "organization",
237 "organizationId",
238 "location",
239 "project",
240 "createTime",
241 ],
242
243 diff: Effect.fn(function* ({ news, olds, output }) {
244 if (!isResolved(news)) return undefined;
245 const previousId = olds?.postureId ?? output?.postureId;
246 const nextId = news.postureId ?? previousId;
247 const previousOrg = olds?.organization ?? output?.organization;
248 const nextOrg =
249 news.organization !== undefined ? organizationParent(news.organization) : previousOrg;
250 return replaceOnIdentity(
251 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
252 (previousOrg !== undefined &&
253 nextOrg !== undefined &&
254 organizationParent(previousOrg) !== organizationParent(nextOrg)),
255 false,
256 );
257 }),
258
259 read: Effect.fn(function* ({ id, olds, output }) {
260 const env = yield* GcpEnvironment.current;
261 const postureId = yield* toPhysicalId(id, olds?.postureId, output?.postureId, "posture");
262 const organization = yield* resolveOrganization(
263 olds?.organization ?? output?.organization,
264 output?.organization,
265 ).pipe(
266 Effect.catchTag("GCP.SecurityPosture.OrganizationNotResolved", () =>
267 Effect.succeed(output?.organization ?? ""),
268 ),
269 );
270 const location = lastSegment(olds?.location ?? output?.location ?? DEFAULT_LOCATION);
271 const name =
272 output?.name ??
273 (organization.length > 0 ? resourceName(organization, location, postureId) : "");
274 const existing = yield* getByName(name);
275 if (existing === undefined) return undefined;
276 const attrs = toAttrs(existing, env.project);
277 return (yield* hasAlchemyLabels(id, tagRecord(existing.annotations)))
278 ? attrs
279 : Unowned(attrs);
280 }),
281
282 list: () =>
283 Effect.gen(function* () {
284 const env = yield* GcpEnvironment.current;
285 const organization = yield* tryResolveOrganization();
286 if (organization === undefined) return [];
287 const parent = locationParent(organization, DEFAULT_LOCATION);
288 return yield* securityposture.listOrganizationsLocationsPostures
289 .pages({ parent, pageSize: 1000 })
290 .pipe(
291 Stream.flatMap((page) => Stream.fromIterable(page.postures ?? [])),
292 Stream.filter((posture) => hasAlchemyAnnotationMap(posture.annotations)),
293 Stream.map((posture) => toAttrs(posture, env.project)),
294 Stream.runCollect,
295 Effect.map((chunk) => Array.from(chunk)),
296 Effect.catchTag("NotFound", () => Effect.succeed([])),
297 );
298 }),
299
300 reconcile: Effect.fn(function* ({ id, news, output }) {
301 const env = yield* GcpEnvironment.current;
302 const postureId = yield* toPhysicalId(id, news.postureId, output?.postureId, "posture");
303 const organization = yield* resolveOrganization(
304 news.organization ?? output?.organization,
305 output?.organization,
306 );
307 const location = lastSegment(news.location ?? output?.location ?? DEFAULT_LOCATION);
308 const parent = locationParent(organization, location);
309 const name = resourceName(organization, location, postureId);
310 const desiredAnnotations = {
311 ...toLabels(news.annotations),
312 ...(yield* createInternalLabels(id)),
313 };
314 const desired = desiredBody(news, desiredAnnotations);
315
316 let current = yield* getByName(output?.name ?? name);
317
318 if (current === undefined) {
319 const created = yield* securityposture
320 .createOrganizationsLocationsPostures({
321 parent,
322 postureId,
323 body: desired,
324 })
325 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
326 if (created !== undefined) {
327 yield* waitPostureOperation(created);
328 }
329 current = yield* waitUntilExists(getByName(name), name);
330 current = yield* waitUntilExists(
331 getByName(name).pipe(
332 Effect.map((value) =>
333 value && value.reconciling !== true && (value.revisionId ?? "").length > 0
334 ? value
335 : undefined,
336 ),
337 ),
338 name,
339 );
340 }
341
342 if (current === undefined) {
343 return yield* new SecuritypostureNotResolved({ resourceName: name });
344 }
345
346 const descriptionChanged = !sameText(current.description, desired.description);
347 const policySetsChanged = fingerprint(current.policySets) !== fingerprint(desired.policySets);
348 const stateChanged = !sameText(current.state ?? DEFAULT_STATE, desired.state);
349 const contentMask = fieldMask([
350 descriptionChanged && "description",
351 policySetsChanged && "policy_sets",
352 ]);
353
354 if (contentMask.length > 0) {
355 const operation = yield* securityposture.patchOrganizationsLocationsPostures({
356 name: current.name ?? name,
357 revisionId: current.revisionId,
358 updateMask: contentMask,
359 body: {
360 name: current.name ?? name,
361 description: desired.description,
362 policySets: desired.policySets,
363 etag: current.etag,
364 },
365 });
366 yield* waitPostureOperation(operation);
367 current = yield* waitUntilExists(
368 getByName(current.name ?? name).pipe(
369 Effect.map((value) => (value && value.reconciling !== true ? value : undefined)),
370 ),
371 current.name ?? name,
372 );
373 }
374
375 if (stateChanged) {
376 const operation = yield* securityposture.patchOrganizationsLocationsPostures({
377 name: current.name ?? name,
378 revisionId: current.revisionId,
379 updateMask: "state",
380 body: {
381 name: current.name ?? name,
382 state: desired.state,
383 etag: current.etag,
384 },
385 });
386 yield* waitPostureOperation(operation);
387 current = yield* waitUntilExists(
388 getByName(current.name ?? name).pipe(
389 Effect.map((value) => (value && value.reconciling !== true ? value : undefined)),
390 ),
391 current.name ?? name,
392 );
393 }
394
395 return toAttrs(current, env.project);
396 }),
397
398 delete: Effect.fn(function* ({ output }) {
399 if (!output.name) return;
400 const operation = yield* securityposture
401 .deleteOrganizationsLocationsPostures({
402 name: output.name,
403 etag: output.etag,
404 })
405 .pipe(
406 Effect.retry({
407 while: (error) => error._tag === "Conflict",
408 times: 8,
409 schedule: Schedule.spaced("2 seconds"),
410 }),
411 Effect.catchTag("NotFound", () => Effect.undefined),
412 );
413 if (operation !== undefined) {
414 yield* waitPostureOperationGone(operation);
415 }
416 yield* waitUntilGone(getByName(output.name), output.name);
417 }),
418 });