@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 362 lines 11.4 KB
Raw
1 import * as iam from "@distilled.cloud/gcp/iam_v2";
2 import { unownedUnlessPrevious } 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 Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Stream from "effect/Stream";
10 import { GcpEnvironment } from "../Environment.ts";
11 import { createInternalLabels, diffLabels, stripInternalLabels, toLabels } from "../Labels.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 attachmentPointOf,
15 denypoliciesParent,
16 hasOwnershipAnnotations,
17 ownedByAlchemy,
18 parsePolicyName,
19 policyName,
20 ResourceNotResolved,
21 toPolicyId,
22 waitForDeleteOperation,
23 waitForOperation,
24 } from "./internal.ts";
25
26 export type DenyRuleCondition = {
27 /** CEL expression. Resource-tag functions only. */
28 expression?: string;
29 /** Short title. */
30 title?: string;
31 /** Longer description. */
32 description?: string;
33 /** Location string for error reporting. */
34 location?: string;
35 };
36
37 export type DenyRule = {
38 /**
39 * Permissions denied (`{service_fqdn}/{resource}.{verb}`).
40 */
41 deniedPermissions?: string[];
42 /**
43 * Permissions excluded from `deniedPermissions`.
44 */
45 exceptionPermissions?: string[];
46 /**
47 * Identities denied the permissions.
48 */
49 deniedPrincipals?: string[];
50 /**
51 * Identities excluded from `deniedPrincipals`.
52 */
53 exceptionPrincipals?: string[];
54 /**
55 * CEL condition that selects when this rule applies.
56 */
57 denialCondition?: DenyRuleCondition;
58 };
59
60 export type PolicyRule = {
61 /**
62 * User-specified description (max 256 characters).
63 */
64 description?: string;
65 /**
66 * Deny rule.
67 */
68 denyRule?: DenyRule;
69 };
70
71 export type PolicyProps = {
72 /**
73 * Attachment point, URL-encoded (`cloudresourcemanager.googleapis.com%2Fprojects%2Fmy-project`)
74 * or raw (`cloudresourcemanager.googleapis.com/projects/my-project`).
75 * Defaults to the current GCP project. Immutable — changing it
76 * replaces the policy.
77 */
78 attachmentPoint?: string;
79 /**
80 * Policy id (3-63 chars, lowercase letters, numbers, dashes, periods;
81 * must start with a letter). If omitted, a unique name is generated.
82 * Immutable — changing it replaces the policy.
83 */
84 policyId?: string;
85 /**
86 * Display name (max 63 characters).
87 */
88 displayName?: string;
89 /**
90 * User annotations. Alchemy ownership annotations are merged in
91 * automatically (`alchemy-stack` / `alchemy-stage` / `alchemy-id`).
92 */
93 annotations?: Record<string, string>;
94 /**
95 * Deny rules. Defaults to a no-op deny of a non-existent principal so
96 * create is valid without locking anyone out.
97 */
98 rules?: PolicyRule[];
99 };
100
101 export type Policy = Resource<
102 "GCP.IAM.Policy",
103 PolicyProps,
104 {
105 /** Full resource name `policies/{attachment}/denypolicies/{policy}`. */
106 name: string;
107 /** Policy id. */
108 policyId: string;
109 /** URL-encoded attachment point. */
110 attachmentPoint: string;
111 /** Display name. */
112 displayName: string | undefined;
113 /** User annotations (Alchemy ownership keys stripped). */
114 annotations: Record<string, string>;
115 /** Kind (`DenyPolicy`). */
116 kind: string | undefined;
117 /** Globally unique uid. */
118 uid: string | undefined;
119 /** Etag. */
120 etag: string | undefined;
121 /** Rules. */
122 rules: PolicyRule[] | undefined;
123 /** RFC3339 create time. */
124 createTime: string | undefined;
125 /** RFC3339 update time. */
126 updateTime: string | undefined;
127 /** RFC3339 delete time when deleted. */
128 deleteTime: string | undefined;
129 },
130 never,
131 Providers
132 >;
133
134 /**
135 * An IAM v2 deny policy attached to a project, folder, or organization.
136 *
137 * This is not {@link GCP.OrgPolicy.Policy} (organization policy
138 * constraints). Deny policies use annotations for Alchemy ownership.
139 * Create, update, and delete are long-running operations.
140 *
141 * ### Creating a Deny Policy
142 * **Example:** Generated id on this project
143 * ```typescript
144 * const policy = yield* GCP.IAM.Policy("Probe", {
145 * displayName: "alchemy-probe",
146 * rules: [{
147 * denyRule: {
148 * deniedPermissions: ["iam.googleapis.com/roles.list"],
149 * deniedPrincipals: [
150 * "principal://goog/subject/alchemy-deny-probe@example.invalid",
151 * ],
152 * },
153 * }],
154 * });
155 * ```
156 *
157 * @resource
158 * @category IAM
159 */
160 export const Policy = Resource<Policy>("GCP.IAM.Policy");
161
162 export class PolicyNotResolved extends Data.TaggedError("GCP.IAM.PolicyNotResolved")<{
163 resourceName: string;
164 }> {}
165
166 const DEFAULT_RULE: PolicyRule = {
167 description: "alchemy ownership probe",
168 denyRule: {
169 deniedPermissions: ["iam.googleapis.com/roles.list"],
170 deniedPrincipals: ["principal://goog/subject/alchemy-deny-probe@example.invalid"],
171 },
172 };
173
174 const ruleOf = (rule: iam.GoogleIamV2PolicyRule | PolicyRule): PolicyRule => ({
175 description: rule.description,
176 denyRule: rule.denyRule
177 ? {
178 deniedPermissions: rule.denyRule.deniedPermissions,
179 exceptionPermissions: rule.denyRule.exceptionPermissions,
180 deniedPrincipals: rule.denyRule.deniedPrincipals,
181 exceptionPrincipals: rule.denyRule.exceptionPrincipals,
182 denialCondition: rule.denyRule.denialCondition,
183 }
184 : undefined,
185 });
186
187 const jsonOf = (value: unknown) => JSON.stringify(value ?? null);
188
189 const toAttrs = (policy: iam.GoogleIamV2Policy) => {
190 const name = policy.name ?? "";
191 const parsed = parsePolicyName(name);
192 return {
193 name,
194 policyId: parsed.policyId,
195 attachmentPoint: parsed.attachmentPoint,
196 displayName: policy.displayName,
197 annotations: stripInternalLabels(tagRecord(policy.annotations)),
198 kind: policy.kind,
199 uid: policy.uid,
200 etag: policy.etag,
201 rules: policy.rules?.map(ruleOf),
202 createTime: policy.createTime,
203 updateTime: policy.updateTime,
204 deleteTime: policy.deleteTime,
205 };
206 };
207
208 const getByName = (name: string) =>
209 name.length === 0
210 ? Effect.undefined
211 : iam.getPolicies({ name }).pipe(
212 Effect.map((policy) => (policy.deleteTime ? undefined : policy)),
213 Effect.catchTag("NotFound", () => Effect.undefined),
214 );
215
216 const listAt = (parent: string) =>
217 iam.listPoliciesPolicies.pages({ parent, pageSize: 1000 }).pipe(
218 Stream.flatMap((page) => Stream.fromIterable(page.policies ?? [])),
219 Stream.runCollect,
220 Effect.map((chunk) => Array.from(chunk)),
221 Effect.catchTag("NotFound", () => Effect.succeed([] as iam.GoogleIamV2Policy[])),
222 );
223
224 export const PolicyProvider = () =>
225 Provider.succeed(Policy, {
226 stables: ["name", "policyId", "attachmentPoint", "uid", "createTime"],
227
228 diff: Effect.fn(function* ({ news, olds, output }) {
229 if (!isResolved(news)) return undefined;
230 const previousPoint = olds?.attachmentPoint ?? output?.attachmentPoint;
231 const previousId = olds?.policyId ?? output?.policyId;
232 if (
233 (previousPoint !== undefined &&
234 news.attachmentPoint !== undefined &&
235 attachmentPointOf("x", news.attachmentPoint) !== attachmentPointOf("x", previousPoint)) ||
236 (previousId !== undefined && news.policyId !== undefined && news.policyId !== previousId)
237 ) {
238 return { action: "replace" as const, deleteFirst: true };
239 }
240 return undefined;
241 }),
242
243 read: Effect.fn(function* ({ id, olds, output, previous }) {
244 const env = yield* GcpEnvironment.current;
245 const attachmentPoint = attachmentPointOf(
246 env.project,
247 olds?.attachmentPoint ?? output?.attachmentPoint,
248 );
249 const policyId = yield* toPolicyId(id, olds?.policyId, output?.policyId);
250 const name = output?.name ?? policyName(attachmentPoint, policyId);
251 const existing = yield* getByName(name);
252 if (existing === undefined) return undefined;
253 const attrs = toAttrs(existing);
254 return (yield* ownedByAlchemy(id, existing.annotations))
255 ? attrs
256 : unownedUnlessPrevious(attrs, previous, "name");
257 }),
258
259 list: () =>
260 Effect.gen(function* () {
261 const env = yield* GcpEnvironment.current;
262 const parent = denypoliciesParent(attachmentPointOf(env.project));
263 const policies = yield* listAt(parent);
264 const named = yield* Effect.forEach(
265 policies,
266 (policy) => (policy.name ? getByName(policy.name) : Effect.undefined),
267 { concurrency: 4 },
268 );
269 return named
270 .filter(
271 (policy): policy is iam.GoogleIamV2Policy =>
272 policy !== undefined && hasOwnershipAnnotations(policy.annotations),
273 )
274 .map(toAttrs);
275 }),
276
277 reconcile: Effect.fn(function* ({ id, news, output }) {
278 const env = yield* GcpEnvironment.current;
279 const attachmentPoint = attachmentPointOf(
280 env.project,
281 news.attachmentPoint ?? output?.attachmentPoint,
282 );
283 const policyId = yield* toPolicyId(id, news.policyId, output?.policyId);
284 const name = policyName(attachmentPoint, policyId);
285 const parent = denypoliciesParent(attachmentPoint);
286 const desiredAnnotations = {
287 ...toLabels(news.annotations),
288 ...(yield* createInternalLabels(id)),
289 };
290 const rules = (news.rules ?? [DEFAULT_RULE]).map(ruleOf);
291
292 let current = yield* getByName(output?.name ?? name);
293
294 if (current === undefined) {
295 const created = yield* iam
296 .createPolicyPolicies({
297 parent,
298 policyId,
299 body: {
300 displayName: news.displayName,
301 annotations: desiredAnnotations,
302 rules,
303 },
304 })
305 .pipe(
306 Effect.catchTag("Conflict", () =>
307 getByName(name).pipe(
308 Effect.map((policy) =>
309 policy
310 ? ({
311 done: true,
312 response: { name: policy.name },
313 } satisfies iam.GoogleLongrunningOperation)
314 : undefined,
315 ),
316 ),
317 ),
318 );
319 if (created) {
320 yield* waitForOperation(created);
321 }
322 current = yield* getByName(name);
323 }
324
325 if (current === undefined) {
326 return yield* new ResourceNotResolved({ resourceName: name });
327 }
328
329 const observed = tagRecord(current.annotations);
330 const { upsert, removed } = diffLabels(observed, desiredAnnotations);
331 const annotationsChanged = upsert.length > 0 || removed.length > 0;
332 const displayChanged =
333 news.displayName !== undefined && (current.displayName ?? "") !== news.displayName;
334 const rulesChanged = jsonOf(current.rules?.map(ruleOf)) !== jsonOf(rules);
335
336 if (annotationsChanged || displayChanged || rulesChanged) {
337 const updated = yield* iam.updatePolicies({
338 name: current.name ?? name,
339 body: {
340 etag: current.etag,
341 displayName: news.displayName ?? current.displayName,
342 annotations: desiredAnnotations,
343 rules,
344 },
345 });
346 yield* waitForOperation(updated);
347 current = (yield* getByName(current.name ?? name)) ?? current;
348 }
349
350 return toAttrs(current);
351 }),
352
353 delete: Effect.fn(function* ({ output }) {
354 if (!output.name) return;
355 const operation = yield* iam
356 .deletePolicies({ name: output.name, etag: output.etag })
357 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
358 if (operation) {
359 yield* waitForDeleteOperation(operation);
360 }
361 }),
362 });