@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

main
ts 544 lines 17.1 KB
Raw
1 import * as orgpolicy from "@distilled.cloud/gcp/orgpolicy_v2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Schedule from "effect/Schedule";
8 import { GcpEnvironment } from "../Environment.ts";
9 import type { Providers } from "../Providers.ts";
10
11 export type PolicyParentKind = "projects" | "folders" | "organizations";
12
13 export type PolicyRuleValues = {
14 /**
15 * Values allowed at this resource. List constraints only.
16 */
17 allowedValues?: string[];
18 /**
19 * Values denied at this resource. List constraints only.
20 */
21 deniedValues?: string[];
22 };
23
24 export type PolicyRuleCondition = {
25 /**
26 * CEL expression. Must use `resource.matchTag`, `resource.matchTagId`,
27 * `resource.hasTagKey`, or `resource.hasTagKeyId`.
28 */
29 expression?: string;
30 /**
31 * Short title shown in UIs.
32 */
33 title?: string;
34 /**
35 * Longer description of the condition.
36 */
37 description?: string;
38 /**
39 * Location string for error reporting.
40 */
41 location?: string;
42 };
43
44 export type PolicyRule = {
45 /**
46 * Allow every value. List constraints only.
47 */
48 allowAll?: boolean;
49 /**
50 * Deny every value. List constraints only.
51 */
52 denyAll?: boolean;
53 /**
54 * When true, the boolean/managed constraint is enforced. When false,
55 * any configuration is acceptable. Boolean constraints only.
56 */
57 enforce?: boolean;
58 /**
59 * Allowed and denied values. List constraints only.
60 */
61 values?: PolicyRuleValues;
62 /**
63 * Tag-based CEL condition that selects when this rule applies.
64 */
65 condition?: PolicyRuleCondition;
66 /**
67 * Parameter values for managed constraints.
68 */
69 parameters?: Record<string, unknown>;
70 };
71
72 export type PolicySpec = {
73 /**
74 * When true, list-constraint rules from ancestors are inherited.
75 * List constraints only.
76 */
77 inheritFromParent?: boolean;
78 /**
79 * Restore the constraint default at this resource. When true, `rules`
80 * must be empty and `inheritFromParent` must be false.
81 */
82 reset?: boolean;
83 /**
84 * Policy rules. Boolean constraints must have exactly one rule with no
85 * condition.
86 */
87 rules?: PolicyRule[];
88 };
89
90 export type PolicyProps = {
91 /**
92 * Constraint this policy configures, e.g. `compute.disableSerialPortAccess`
93 * or `constraints/compute.disableSerialPortAccess`. The `constraints/`
94 * prefix is stripped. Immutable — changing it replaces the policy.
95 */
96 constraint: string;
97 /**
98 * Parent resource: `projects/{project}`, `folders/{folder}`, or
99 * `organizations/{organization}`. Defaults to the stack's GCP project.
100 * Immutable — changing it replaces the policy. Responses may rewrite a
101 * project id to the equivalent project number.
102 */
103 parent?: string;
104 /**
105 * Enforcement spec. Omitted on a later update leaves the live spec
106 * unchanged.
107 */
108 spec?: PolicySpec;
109 /**
110 * Dry-run (audit-only) spec. Omitted on a later update leaves the live
111 * dry-run spec unchanged.
112 */
113 dryRunSpec?: PolicySpec;
114 };
115
116 export type Policy = Resource<
117 "GCP.OrgPolicy.Policy",
118 PolicyProps,
119 {
120 /** Full resource name `projects/{project}/policies/{constraint}`. */
121 name: string;
122 /** Constraint id (no `constraints/` prefix). */
123 constraint: string;
124 /** Parent `projects/{project}`, `folders/{folder}`, or `organizations/{organization}`. */
125 parent: string;
126 /** Project id of the deploying stack. */
127 project: string;
128 /** Server etag for optimistic concurrency. */
129 etag: string | undefined;
130 /** Live enforcement spec (`etag` / `updateTime` stripped). */
131 spec: PolicySpec | undefined;
132 /** Live dry-run spec (`etag` / `updateTime` stripped). */
133 dryRunSpec: PolicySpec | undefined;
134 /** RFC3339 last-update timestamp from the live spec. */
135 updateTime: string | undefined;
136 },
137 never,
138 Providers
139 >;
140
141 /**
142 * A Google Cloud Organization Policy on a project, folder, or organization.
143 *
144 * Identity is `(parent, constraint)` — the constraint must already exist
145 * (built-in or custom). Organization policies have no labels or description
146 * field; Alchemy treats existence at the computed name as ownership, and
147 * `list` returns every policy set on the current project so `pnpm nuke:gcp`
148 * can clean leaks.
149 *
150 * `constraint` and `parent` are immutable. `spec` and `dryRunSpec` update
151 * in place.
152 *
153 * ### Creating a Policy
154 * **Example:** Enforce a boolean constraint on the current project
155 * ```typescript
156 * const serial = yield* GCP.OrgPolicy.Policy("SerialPort", {
157 * constraint: "compute.disableSerialPortAccess",
158 * spec: {
159 * rules: [{ enforce: true }],
160 * },
161 * });
162 * ```
163 *
164 * **Example:** List constraint that allows every value
165 * ```typescript
166 * const locations = yield* GCP.OrgPolicy.Policy("Locations", {
167 * constraint: "gcp.resourceLocations",
168 * spec: {
169 * inheritFromParent: false,
170 * rules: [{ allowAll: true }],
171 * },
172 * });
173 * ```
174 *
175 * ### Dry-run
176 * **Example:** Audit-only dry-run spec
177 * ```typescript
178 * const serial = yield* GCP.OrgPolicy.Policy("SerialPort", {
179 * constraint: "compute.disableSerialPortAccess",
180 * spec: {
181 * rules: [{ enforce: true }],
182 * },
183 * dryRunSpec: {
184 * rules: [{ enforce: true }],
185 * },
186 * });
187 * ```
188 *
189 * ### Updating a Policy
190 * **Example:** Relax enforcement
191 * ```typescript
192 * const serial = yield* GCP.OrgPolicy.Policy("SerialPort", {
193 * constraint: "compute.disableSerialPortAccess",
194 * spec: {
195 * rules: [{ enforce: false }],
196 * },
197 * });
198 * ```
199 *
200 * @resource
201 * @category OrgPolicy
202 */
203 export const Policy = Resource<Policy>("GCP.OrgPolicy.Policy");
204
205 export class PolicyNotResolved extends Data.TaggedError("GCP.OrgPolicy.PolicyNotResolved")<{
206 resourceName: string;
207 }> {}
208
209 const CONSTRAINTS_PREFIX = "constraints/";
210 const POLICIES_SEGMENT = "/policies/";
211
212 const lastSegment = (value: string) => {
213 const trimmed = value.replace(/\/+$/, "");
214 const parts = trimmed.split("/");
215 return parts[parts.length - 1] || trimmed;
216 };
217
218 const normalizeConstraint = (constraint: string | undefined) => {
219 const raw = (constraint ?? "").trim();
220 return raw.startsWith(CONSTRAINTS_PREFIX) ? raw.slice(CONSTRAINTS_PREFIX.length) : raw;
221 };
222
223 const parentKindOf = (resource: string): PolicyParentKind => {
224 if (resource.startsWith("folders/")) return "folders";
225 if (resource.startsWith("organizations/")) return "organizations";
226 return "projects";
227 };
228
229 const defaultParent = (project: string) => `projects/${project}`;
230
231 const parsePolicyName = (name: string) => {
232 const at = name.indexOf(POLICIES_SEGMENT);
233 if (at < 0) {
234 return { parent: "", constraint: normalizeConstraint(name) };
235 }
236 return {
237 parent: name.slice(0, at),
238 constraint: normalizeConstraint(name.slice(at + POLICIES_SEGMENT.length)),
239 };
240 };
241
242 const resourceName = (parent: string, constraint: string) =>
243 `${parent}${POLICIES_SEGMENT}${constraint}`;
244
245 const sameParent = (desired: string, observed: string, project: string) => {
246 if (desired === observed) return true;
247 if (parentKindOf(desired) !== parentKindOf(observed)) return false;
248 if (lastSegment(desired) === lastSegment(observed)) return true;
249 return parentKindOf(desired) === "projects" && lastSegment(desired) === project;
250 };
251
252 const toRule = (
253 rule: orgpolicy.GoogleCloudOrgpolicyV2PolicySpecPolicyRule | PolicyRule,
254 ): PolicyRule => ({
255 allowAll: rule.allowAll,
256 denyAll: rule.denyAll,
257 enforce: rule.enforce,
258 values: rule.values
259 ? {
260 allowedValues: rule.values.allowedValues,
261 deniedValues: rule.values.deniedValues,
262 }
263 : undefined,
264 condition: rule.condition
265 ? {
266 expression: rule.condition.expression,
267 title: rule.condition.title,
268 description: rule.condition.description,
269 location: rule.condition.location,
270 }
271 : undefined,
272 parameters: rule.parameters as Record<string, unknown> | undefined,
273 });
274
275 const toSpec = (
276 spec: orgpolicy.GoogleCloudOrgpolicyV2PolicySpec | PolicySpec | undefined,
277 ): PolicySpec | undefined => {
278 if (spec === undefined) return undefined;
279 const rules = (spec.rules ?? []).map(toRule);
280 const next: PolicySpec = {
281 inheritFromParent: spec.inheritFromParent,
282 reset: spec.reset,
283 rules: rules.length > 0 ? rules : undefined,
284 };
285 if (
286 next.inheritFromParent === undefined &&
287 next.reset === undefined &&
288 next.rules === undefined
289 ) {
290 return undefined;
291 }
292 return next;
293 };
294
295 const toApiSpec = (
296 spec: PolicySpec | undefined,
297 ): orgpolicy.GoogleCloudOrgpolicyV2PolicySpec | undefined => {
298 if (spec === undefined) return undefined;
299 return {
300 inheritFromParent: spec.inheritFromParent,
301 reset: spec.reset,
302 rules: spec.rules?.map((rule) => ({
303 allowAll: rule.allowAll,
304 denyAll: rule.denyAll,
305 enforce: rule.enforce,
306 values: rule.values
307 ? {
308 allowedValues: rule.values.allowedValues,
309 deniedValues: rule.values.deniedValues,
310 }
311 : undefined,
312 condition: rule.condition,
313 parameters: rule.parameters,
314 })),
315 };
316 };
317
318 const canonicalizeRule = (rule: PolicyRule) => ({
319 allowAll: rule.allowAll === true,
320 denyAll: rule.denyAll === true,
321 enforce: rule.enforce,
322 values: rule.values
323 ? {
324 allowedValues: [...(rule.values.allowedValues ?? [])].sort(),
325 deniedValues: [...(rule.values.deniedValues ?? [])].sort(),
326 }
327 : undefined,
328 condition: rule.condition
329 ? {
330 expression: rule.condition.expression ?? "",
331 title: rule.condition.title ?? "",
332 description: rule.condition.description ?? "",
333 location: rule.condition.location ?? "",
334 }
335 : undefined,
336 parameters:
337 rule.parameters && Object.keys(rule.parameters).length > 0 ? rule.parameters : undefined,
338 });
339
340 const canonicalizeSpec = (spec: PolicySpec | undefined) => ({
341 inheritFromParent: spec?.inheritFromParent === true,
342 reset: spec?.reset === true,
343 rules: (spec?.rules ?? []).map(canonicalizeRule),
344 });
345
346 const specsEqual = (left: PolicySpec | undefined, right: PolicySpec | undefined) =>
347 JSON.stringify(canonicalizeSpec(left)) === JSON.stringify(canonicalizeSpec(right));
348
349 const toAttrs = (policy: orgpolicy.GoogleCloudOrgpolicyV2Policy, project: string) => {
350 const name = policy.name ?? "";
351 const parsed = parsePolicyName(name);
352 return {
353 name,
354 constraint: parsed.constraint,
355 parent: parsed.parent,
356 project,
357 etag: policy.etag,
358 spec: toSpec(policy.spec),
359 dryRunSpec: toSpec(policy.dryRunSpec),
360 updateTime: policy.spec?.updateTime,
361 };
362 };
363
364 const getByName = (name: string) => {
365 const kind = parentKindOf(name);
366 const request = { name };
367 const get =
368 kind === "folders"
369 ? orgpolicy.getFoldersPolicies(request)
370 : kind === "organizations"
371 ? orgpolicy.getOrganizationsPolicies(request)
372 : orgpolicy.getProjectsPolicies(request);
373 return get.pipe(Effect.catchTag("NotFound", () => Effect.undefined));
374 };
375
376 const createPolicy = (parent: string, body: orgpolicy.GoogleCloudOrgpolicyV2Policy) => {
377 const kind = parentKindOf(parent);
378 const request = { parent, body };
379 return kind === "folders"
380 ? orgpolicy.createFoldersPolicies(request)
381 : kind === "organizations"
382 ? orgpolicy.createOrganizationsPolicies(request)
383 : orgpolicy.createProjectsPolicies(request);
384 };
385
386 const patchPolicy = (
387 name: string,
388 body: orgpolicy.GoogleCloudOrgpolicyV2Policy,
389 updateMask: string,
390 ) => {
391 const kind = parentKindOf(name);
392 const request = { name, body, updateMask };
393 return kind === "folders"
394 ? orgpolicy.patchFoldersPolicies(request)
395 : kind === "organizations"
396 ? orgpolicy.patchOrganizationsPolicies(request)
397 : orgpolicy.patchProjectsPolicies(request);
398 };
399
400 const deletePolicy = (name: string) => {
401 const kind = parentKindOf(name);
402 const request = { name };
403 const del =
404 kind === "folders"
405 ? orgpolicy.deleteFoldersPolicies(request)
406 : kind === "organizations"
407 ? orgpolicy.deleteOrganizationsPolicies(request)
408 : orgpolicy.deleteProjectsPolicies(request);
409 return del.pipe(Effect.catchTag("NotFound", () => Effect.void));
410 };
411
412 const listPolicies = (parent: string) =>
413 Effect.gen(function* () {
414 const kind = parentKindOf(parent);
415 const found: orgpolicy.GoogleCloudOrgpolicyV2Policy[] = [];
416 let pageToken: string | undefined;
417 do {
418 const request = { parent, pageSize: 1000, pageToken };
419 const response =
420 kind === "folders"
421 ? yield* orgpolicy.listFoldersPolicies(request)
422 : kind === "organizations"
423 ? yield* orgpolicy.listOrganizationsPolicies(request)
424 : yield* orgpolicy.listProjectsPolicies(request);
425 found.push(...(response.policies ?? []));
426 pageToken = response.nextPageToken;
427 } while (pageToken !== undefined && pageToken !== "");
428 return found;
429 }).pipe(
430 Effect.catchTag("NotFound", () =>
431 Effect.succeed([] as orgpolicy.GoogleCloudOrgpolicyV2Policy[]),
432 ),
433 );
434
435 export const PolicyProvider = () =>
436 Provider.succeed(Policy, {
437 stables: ["name", "constraint", "parent", "project"],
438
439 diff: Effect.fn(function* ({ news, olds, output }) {
440 if (!isResolved(news)) return undefined;
441 const env = yield* GcpEnvironment.current;
442 const previousConstraint = normalizeConstraint(olds?.constraint ?? output?.constraint);
443 const nextConstraint = normalizeConstraint(news.constraint ?? previousConstraint);
444 const constraintChanged =
445 previousConstraint.length > 0 &&
446 nextConstraint.length > 0 &&
447 previousConstraint !== nextConstraint;
448
449 const previousParent = olds?.parent ?? output?.parent;
450 const nextParent = news.parent ?? previousParent;
451 const parentChanged =
452 previousParent !== undefined &&
453 nextParent !== undefined &&
454 !sameParent(nextParent, previousParent, env.project);
455
456 if (constraintChanged || parentChanged) {
457 return { action: "replace" as const, deleteFirst: false };
458 }
459 return undefined;
460 }),
461
462 read: Effect.fn(function* ({ olds, output }) {
463 const env = yield* GcpEnvironment.current;
464 const constraint = normalizeConstraint(olds?.constraint ?? output?.constraint);
465 if (constraint.length === 0) return undefined;
466 const parent = olds?.parent ?? output?.parent ?? defaultParent(env.project);
467 const name = output?.name ?? resourceName(parent, constraint);
468 const existing = yield* getByName(name);
469 if (existing === undefined) return undefined;
470 // No labels/description — existence at (parent, constraint) is ownership.
471 return toAttrs(existing, env.project);
472 }),
473
474 list: () =>
475 Effect.gen(function* () {
476 const env = yield* GcpEnvironment.current;
477 const policies = yield* listPolicies(defaultParent(env.project));
478 return policies.map((policy) => toAttrs(policy, env.project));
479 }),
480
481 reconcile: Effect.fn(function* ({ news, output }) {
482 const env = yield* GcpEnvironment.current;
483 const constraint = normalizeConstraint(news.constraint ?? output?.constraint);
484 const parent = news.parent ?? output?.parent ?? defaultParent(env.project);
485 const name = output?.name ?? resourceName(parent, constraint);
486 const desiredSpec = toSpec(news.spec);
487 const desiredDryRun = toSpec(news.dryRunSpec);
488
489 let current = yield* getByName(name);
490
491 if (current === undefined) {
492 const created = yield* createPolicy(parent, {
493 name: resourceName(parent, constraint),
494 spec: toApiSpec(desiredSpec),
495 dryRunSpec: toApiSpec(desiredDryRun),
496 }).pipe(Effect.catchTag("Conflict", () => getByName(name)));
497 current = created ?? undefined;
498 }
499
500 if (current === undefined) {
501 return yield* new PolicyNotResolved({ resourceName: name });
502 }
503
504 const specManaged = news.spec !== undefined;
505 const dryRunManaged = news.dryRunSpec !== undefined;
506 const specChanged = specManaged && !specsEqual(toSpec(current.spec), desiredSpec);
507 const dryRunChanged = dryRunManaged && !specsEqual(toSpec(current.dryRunSpec), desiredDryRun);
508
509 if (specChanged || dryRunChanged) {
510 const observed = current;
511 const updateMask = [
512 specChanged ? "spec" : undefined,
513 dryRunChanged ? "dryRunSpec" : undefined,
514 ]
515 .filter((field): field is string => field !== undefined)
516 .join(",");
517 current = yield* Effect.gen(function* () {
518 const latest = (yield* getByName(observed.name ?? name)) ?? observed;
519 return yield* patchPolicy(
520 latest.name ?? name,
521 {
522 name: latest.name ?? name,
523 etag: latest.etag,
524 spec: specManaged ? toApiSpec(desiredSpec) : latest.spec,
525 dryRunSpec: dryRunManaged ? toApiSpec(desiredDryRun) : latest.dryRunSpec,
526 },
527 updateMask,
528 );
529 }).pipe(
530 Effect.retry({
531 while: (error) => error._tag === "Conflict",
532 times: 5,
533 schedule: Schedule.exponential("200 millis"),
534 }),
535 );
536 }
537
538 return toAttrs(current, env.project);
539 }),
540
541 delete: Effect.fn(function* ({ output }) {
542 yield* deletePolicy(output.name);
543 }),
544 });