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

main
ts 263 lines 8.23 KB
Raw
1 import * as binaryauthorization from "@distilled.cloud/gcp/binaryauthorization_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 * as Effect from "effect/Effect";
7 import { GcpEnvironment } from "../Environment.ts";
8 import type { Providers } from "../Providers.ts";
9 import {
10 createOwnership,
11 DEFAULT_PLATFORM,
12 encodeDescription,
13 gkePolicyOf,
14 hasOwnershipMarker,
15 listPlatformPolicies,
16 missingGet,
17 ownedBy,
18 parseDescription,
19 parsePolicyName,
20 policyName,
21 replaceOnIdentity,
22 ResourceNotResolved,
23 retryTransient,
24 sameJson,
25 sameText,
26 toPhysicalId,
27 } from "./internal.ts";
28
29 export type GkePolicy = binaryauthorization.GkePolicy;
30
31 export type PlatformsPolicyProps = {
32 /**
33 * Policy id (the `{policy}` segment of
34 * `projects/{project}/platforms/{platform}/policies/{policy}`). If omitted,
35 * a unique RFC1035 id is generated. Immutable — changing it replaces the
36 * policy.
37 */
38 policyId?: string;
39 /**
40 * Platform this policy applies to (`gke` or `cloudRun`). Immutable —
41 * changing it replaces the policy.
42 * @default "gke"
43 */
44 platform?: string;
45 /**
46 * Human-readable comment. Platform policies have no labels field, so
47 * Alchemy stamps ownership into this field for `list` / nuke and strips
48 * the marker from attributes.
49 */
50 description?: string;
51 /**
52 * GKE-specific policy. Empty (the default) allows every image. When
53 * `checkSets` is non-empty the last entry must be an unscoped catch-all.
54 */
55 gkePolicy?: GkePolicy;
56 };
57
58 export type PlatformsPolicy = Resource<
59 "GCP.BinaryAuthorization.PlatformsPolicy",
60 PlatformsPolicyProps,
61 {
62 /** Full name `projects/{project}/platforms/{platform}/policies/{policy}`. */
63 name: string;
64 /** Policy id (last path segment). */
65 policyId: string;
66 /** Platform id (`gke`, `cloudRun`, …). */
67 platform: string;
68 /** Project id. */
69 project: string;
70 /** User description with the Alchemy ownership prefix stripped. */
71 description: string | undefined;
72 /** GKE-specific policy, if set. */
73 gkePolicy: GkePolicy | undefined;
74 /** Server-assigned checksum for optimistic concurrency. */
75 etag: string | undefined;
76 /** RFC3339 last-update timestamp. */
77 updateTime: string | undefined;
78 },
79 never,
80 Providers
81 >;
82
83 /**
84 * A Binary Authorization platform policy. Platform policies apply to a
85 * specific runtime (`gke` by default) and evaluate images independently of
86 * the project-level admission policy.
87 *
88 * Platform policies have no labels field, so Alchemy stamps ownership into
89 * `description` for `list` / nuke. `policyId` and `platform` are identity —
90 * changing either replaces the policy. Description and `gkePolicy` update
91 * in place via replace.
92 *
93 * ### Creating a Platform Policy
94 * **Example:** Allow all images on GKE
95 * ```typescript
96 * const policy = yield* GCP.BinaryAuthorization.PlatformsPolicy(
97 * "Default",
98 * {},
99 * );
100 * ```
101 *
102 * **Example:** Allowlist Google system images
103 * ```typescript
104 * const policy = yield* GCP.BinaryAuthorization.PlatformsPolicy(
105 * "Default",
106 * {
107 * policyId: "gke-default",
108 * description: "allowlisted system images",
109 * gkePolicy: {
110 * imageAllowlist: {
111 * allowPattern: ["gcr.io/google-containers/*"],
112 * },
113 * },
114 * },
115 * );
116 * ```
117 *
118 * ### Updating a Platform Policy
119 * **Example:** Add a catch-all always-deny check
120 * ```typescript
121 * const policy = yield* GCP.BinaryAuthorization.PlatformsPolicy(
122 * "Default",
123 * {
124 * gkePolicy: {
125 * checkSets: [
126 * {
127 * displayName: "default",
128 * checks: [{ displayName: "deny", alwaysDeny: true }],
129 * },
130 * ],
131 * },
132 * },
133 * );
134 * ```
135 *
136 * @resource
137 * @category BinaryAuthorization
138 */
139 export const PlatformsPolicy = Resource<PlatformsPolicy>("GCP.BinaryAuthorization.PlatformsPolicy");
140
141 const getByName = missingGet(binaryauthorization.getProjectsPlatformsPolicies);
142
143 const toAttrs = (
144 policy: binaryauthorization.PlatformPolicy,
145 project: string,
146 ): PlatformsPolicy["Attributes"] => {
147 const name = policy.name ?? "";
148 const parsed = parsePolicyName(name);
149 const { description } = parseDescription(policy.description);
150 return {
151 name,
152 policyId: parsed.policyId,
153 platform: parsed.platform,
154 project: parsed.project || project,
155 description,
156 gkePolicy: policy.gkePolicy,
157 etag: policy.etag,
158 updateTime: policy.updateTime,
159 };
160 };
161
162 const toBody = (
163 news: PlatformsPolicyProps,
164 description: string,
165 etag: string | undefined,
166 ): binaryauthorization.PlatformPolicy => ({
167 description,
168 etag,
169 gkePolicy: gkePolicyOf(news.gkePolicy),
170 });
171
172 export const PlatformsPolicyProvider = () =>
173 Provider.succeed(PlatformsPolicy, {
174 stables: ["name", "policyId", "platform", "project"],
175
176 diff: Effect.fn(function* ({ news, olds, output }) {
177 if (!isResolved(news)) return undefined;
178 return replaceOnIdentity({
179 previousId: olds?.policyId ?? output?.policyId,
180 nextId: news.policyId,
181 previousParent: olds?.platform ?? output?.platform,
182 nextParent: news.platform ?? output?.platform ?? DEFAULT_PLATFORM,
183 });
184 }),
185
186 read: Effect.fn(function* ({ id, olds, output }) {
187 const env = yield* GcpEnvironment.current;
188 const policyId = yield* toPhysicalId(id, olds?.policyId, output?.policyId, "policy");
189 const platform = olds?.platform ?? output?.platform ?? DEFAULT_PLATFORM;
190 const name = output?.name ?? policyName(env.project, platform, policyId);
191 const existing = yield* getByName(name);
192 if (existing === undefined) return undefined;
193 const attrs = toAttrs(existing, env.project);
194 const { labels } = parseDescription(existing.description);
195 return (yield* ownedBy(id, labels)) ? attrs : Unowned(attrs);
196 }),
197
198 list: () =>
199 Effect.gen(function* () {
200 const env = yield* GcpEnvironment.current;
201 const items = yield* listPlatformPolicies(env.project);
202 return items
203 .filter((item) => hasOwnershipMarker(item.description))
204 .map((item) => toAttrs(item, env.project));
205 }),
206
207 reconcile: Effect.fn(function* ({ id, news, output }) {
208 const env = yield* GcpEnvironment.current;
209 const policyId = yield* toPhysicalId(id, news.policyId, output?.policyId, "policy");
210 const platform = news.platform ?? output?.platform ?? DEFAULT_PLATFORM;
211 const name = policyName(env.project, platform, policyId);
212 const ownership = yield* createOwnership(id);
213 const desiredDescription = encodeDescription(ownership, news.description);
214 const desiredGke = gkePolicyOf(news.gkePolicy);
215
216 let current = yield* getByName(output?.name ?? name);
217
218 if (current === undefined) {
219 const created = yield* retryTransient(
220 binaryauthorization.createProjectsPlatformsPolicies({
221 parent: `projects/${env.project}/platforms/${platform}`,
222 policyId,
223 body: toBody(news, desiredDescription, undefined),
224 }),
225 ).pipe(Effect.catchTag("Conflict", () => getByName(name)));
226 current = created ?? undefined;
227 }
228
229 if (current === undefined) {
230 return yield* new ResourceNotResolved({ resourceName: name });
231 }
232
233 const descriptionChanged = !sameText(current.description, desiredDescription);
234 const gkeChanged = !sameJson(gkePolicyOf(current.gkePolicy), desiredGke);
235
236 if (descriptionChanged || gkeChanged) {
237 current = yield* retryTransient(
238 binaryauthorization.replacePlatformPolicyProjectsPlatformsPolicies({
239 name: current.name ?? name,
240 body: toBody(news, desiredDescription, current.etag),
241 }),
242 );
243 }
244
245 return toAttrs(current, env.project);
246 }),
247
248 delete: Effect.fn(function* ({ output }) {
249 yield* binaryauthorization
250 .deleteProjectsPlatformsPolicies({
251 name: output.name,
252 etag: output.etag,
253 })
254 .pipe(
255 Effect.catchTag("Conflict", () =>
256 binaryauthorization.deleteProjectsPlatformsPolicies({
257 name: output.name,
258 }),
259 ),
260 Effect.catchTag("NotFound", () => Effect.void),
261 );
262 }),
263 });