@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 550 lines 18.3 KB
Raw
1 import * as certificatemanager from "@distilled.cloud/gcp/certificatemanager_v1";
2 import { Unowned } from "alchemy/AdoptPolicy";
3 import { isResolved } from "alchemy/Diff";
4 import { createPhysicalName } from "alchemy/PhysicalName";
5 import * as Provider from "alchemy/Provider";
6 import { Resource } from "alchemy/Resource";
7 import { tagRecord } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import { GcpEnvironment } from "../Environment.ts";
13 import {
14 createInternalLabels,
15 diffLabels,
16 hasAlchemyLabels,
17 stripInternalLabels,
18 toLabels,
19 } from "../Labels.ts";
20 import type { Providers } from "../Providers.ts";
21 import { waitForOperation } from "./operations.ts";
22
23 const DEFAULT_LOCATION = "global";
24 const MAX_NAME_LENGTH = 63;
25
26 export type TrustConfigTrustAnchor = {
27 /** PEM-encoded root certificate used as a trust anchor. Up to 5kB. */
28 pemCertificate?: string;
29 };
30
31 export type TrustConfigIntermediateCA = {
32 /**
33 * PEM-encoded intermediate CA used while building a validation path.
34 * Up to 5kB. Not supported for the workload-certificate / SPIFFE
35 * feature.
36 */
37 pemCertificate?: string;
38 };
39
40 export type TrustConfigTrustStore = {
41 /** Trust anchors used when validating client certificates. */
42 trustAnchors?: TrustConfigTrustAnchor[];
43 /**
44 * Intermediate CAs used during path building. Currently unsupported
45 * when the TrustConfig is used for SPIFFE / workload certificates.
46 */
47 intermediateCas?: TrustConfigIntermediateCA[];
48 };
49
50 export type TrustConfigAllowlistedCertificate = {
51 /**
52 * PEM-encoded certificate that is always considered valid when it
53 * parses, proof of private-key possession is established, and SAN
54 * constraints are met. Up to 5kB.
55 */
56 pemCertificate?: string;
57 };
58
59 export type TrustConfigProps = {
60 /**
61 * TrustConfig id (the `{trustConfig}` segment of
62 * `projects/{project}/locations/{location}/trustConfigs/{trustConfig}`).
63 * If omitted, a unique name is generated from the stack, stage, and
64 * logical id. Must be 1-63 characters and match `[a-z0-9-]{1,63}`.
65 * Immutable — changing it replaces the TrustConfig.
66 */
67 trustConfigId?: string;
68 /**
69 * Certificate Manager location (`global`, `us-central1`, …). Immutable —
70 * changing it replaces the TrustConfig. `US-CENTRAL1` is accepted and
71 * normalized to `us-central1`.
72 * @default "global"
73 */
74 location?: string;
75 /**
76 * Human-readable description.
77 */
78 description?: string;
79 /**
80 * User labels. Alchemy ownership labels are merged in automatically.
81 */
82 labels?: Record<string, string>;
83 /**
84 * Trust stores used with load-balancer mTLS. Only one store is
85 * currently allowed. Not supported for SPIFFE validation — use
86 * `spiffeTrustStores` instead.
87 */
88 trustStores?: TrustConfigTrustStore[];
89 /**
90 * Certificates that are always considered valid (allowlist).
91 */
92 allowlistedCertificates?: TrustConfigAllowlistedCertificate[];
93 /**
94 * Mapping from SPIFFE trust domain to a TrustStore. Used for SPIFFE
95 * certificate validation.
96 */
97 spiffeTrustStores?: Record<string, TrustConfigTrustStore>;
98 };
99
100 export type TrustConfig = Resource<
101 "GCP.CertificateManager.TrustConfig",
102 TrustConfigProps,
103 {
104 /** Full resource name `projects/{project}/locations/{location}/trustConfigs/{trustConfig}`. */
105 name: string;
106 /** TrustConfig id (last path segment). */
107 trustConfigId: string;
108 /** Project id. */
109 project: string;
110 /** Location id (`global`, `us-central1`, …). */
111 location: string;
112 /** User-provided description. */
113 description: string | undefined;
114 /** User labels (Alchemy ownership labels stripped). */
115 labels: Record<string, string>;
116 /** Trust stores configured for load-balancer mTLS. */
117 trustStores: TrustConfigTrustStore[];
118 /** Allowlisted certificates. */
119 allowlistedCertificates: TrustConfigAllowlistedCertificate[];
120 /** SPIFFE trust-domain to TrustStore mapping. */
121 spiffeTrustStores: Record<string, TrustConfigTrustStore>;
122 /** Server-computed checksum, used as an optimistic-concurrency token. */
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 Certificate Manager TrustConfig — the PKI used to validate client
135 * certificates in mutual TLS (load balancer or SPIFFE).
136 *
137 * Changing `trustConfigId` or `location` replaces the resource.
138 * Description, labels, trust stores, allowlisted certificates, and SPIFFE
139 * trust stores update in place.
140 *
141 * ### Creating a Trust Config
142 * **Example:** Generated name
143 * ```typescript
144 * const trust = yield* GCP.CertificateManager.TrustConfig("ClientMtls", {
145 * trustStores: [
146 * {
147 * trustAnchors: [{ pemCertificate }],
148 * },
149 * ],
150 * });
151 * ```
152 *
153 * **Example:** Named config with labels
154 * ```typescript
155 * const trust = yield* GCP.CertificateManager.TrustConfig("ClientMtls", {
156 * trustConfigId: "app-client-mtls",
157 * description: "prod mTLS roots",
158 * labels: { env: "prod" },
159 * trustStores: [
160 * {
161 * trustAnchors: [{ pemCertificate: rootPem }],
162 * intermediateCas: [{ pemCertificate: intermediatePem }],
163 * },
164 * ],
165 * });
166 * ```
167 *
168 * ### Allowlisted Certificates
169 * **Example:** Allowlist client certificates
170 * ```typescript
171 * const trust = yield* GCP.CertificateManager.TrustConfig("Allowlist", {
172 * allowlistedCertificates: [
173 * { pemCertificate: clientPemA },
174 * { pemCertificate: clientPemB },
175 * ],
176 * });
177 * ```
178 *
179 * ### Regional Trust Config
180 * **Example:** Trust config in us-central1
181 * ```typescript
182 * const trust = yield* GCP.CertificateManager.TrustConfig("RegionalMtls", {
183 * location: "us-central1",
184 * trustStores: [
185 * {
186 * trustAnchors: [{ pemCertificate }],
187 * },
188 * ],
189 * });
190 * ```
191 *
192 * @resource
193 * @category CertificateManager
194 */
195 export const TrustConfig = Resource<TrustConfig>("GCP.CertificateManager.TrustConfig");
196
197 export class TrustConfigNotResolved extends Data.TaggedError(
198 "GCP.CertificateManager.TrustConfigNotResolved",
199 )<{
200 resourceName: string;
201 }> {}
202
203 export class TrustConfigStillExists extends Data.TaggedError(
204 "GCP.CertificateManager.TrustConfigStillExists",
205 )<{
206 resourceName: string;
207 }> {}
208
209 const lastSegment = (value: string) => {
210 const trimmed = value.replace(/\/+$/, "");
211 const parts = trimmed.split("/");
212 return parts[parts.length - 1] || trimmed;
213 };
214
215 const rfc1035 = (name: string): string => {
216 let next = name
217 .toLowerCase()
218 .replace(/[^a-z0-9-]/g, "-")
219 .replace(/-+/g, "-")
220 .replace(/^-+/, "")
221 .replace(/-+$/, "");
222 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
223 return next.length > 0 ? next : "trust-config";
224 };
225
226 const normalizeLocation = (location: string | undefined) =>
227 lastSegment(location ?? DEFAULT_LOCATION).toLowerCase();
228
229 const resourceName = (project: string, location: string, trustConfigId: string) =>
230 `projects/${project}/locations/${location}/trustConfigs/${trustConfigId}`;
231
232 const parseName = (name: string) => {
233 const parts = name.split("/").filter((part) => part.length > 0);
234 const trustConfigsAt = parts.lastIndexOf("trustConfigs");
235 const locationsAt = parts.lastIndexOf("locations");
236 const projectsAt = parts.lastIndexOf("projects");
237 return {
238 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
239 location:
240 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : DEFAULT_LOCATION,
241 trustConfigId:
242 trustConfigsAt >= 0 && parts[trustConfigsAt + 1]
243 ? parts[trustConfigsAt + 1]!
244 : lastSegment(name),
245 };
246 };
247
248 const userLabels = (
249 labels: Record<string, string | undefined> | null | undefined,
250 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
251
252 const toId = (id: string, trustConfigId: string | undefined, existing?: string) =>
253 Effect.gen(function* () {
254 if (trustConfigId !== undefined) return trustConfigId;
255 if (existing !== undefined) return existing;
256 return rfc1035(
257 yield* createPhysicalName({
258 id,
259 maxLength: MAX_NAME_LENGTH,
260 lowercase: true,
261 }),
262 );
263 });
264
265 const normalizePem = (pem: string | undefined): string => (pem ?? "").replace(/\s+/g, "");
266
267 const pemEntries = (
268 entries: { pemCertificate?: string }[] | undefined,
269 ): { pemCertificate?: string }[] =>
270 (entries ?? [])
271 .map((entry) => ({ pemCertificate: entry.pemCertificate }))
272 .filter((entry) => (entry.pemCertificate ?? "").length > 0);
273
274 const toStore = (
275 store: certificatemanager.TrustStore | TrustConfigTrustStore | undefined,
276 ): TrustConfigTrustStore => ({
277 trustAnchors: pemEntries(store?.trustAnchors),
278 intermediateCas: pemEntries(store?.intermediateCas),
279 });
280
281 const toStores = (
282 stores: ReadonlyArray<certificatemanager.TrustStore | TrustConfigTrustStore> | null | undefined,
283 ): TrustConfigTrustStore[] => (stores ?? []).map((store) => toStore(store));
284
285 const toSpiffeStores = (
286 stores:
287 | Record<string, certificatemanager.TrustStore | TrustConfigTrustStore | undefined>
288 | null
289 | undefined,
290 ): Record<string, TrustConfigTrustStore> =>
291 Object.fromEntries(
292 Object.entries(stores ?? {})
293 .filter(
294 (entry): entry is [string, certificatemanager.TrustStore | TrustConfigTrustStore] =>
295 entry[1] !== undefined,
296 )
297 .map(([domain, store]) => [domain, toStore(store)]),
298 );
299
300 const pemFingerprint = (entries?: { pemCertificate?: string }[]) =>
301 pemEntries(entries)
302 .map((entry) => normalizePem(entry.pemCertificate))
303 .sort()
304 .join("\0");
305
306 const storeFingerprint = (store: TrustConfigTrustStore) =>
307 `${pemFingerprint(store.trustAnchors)}\n${pemFingerprint(store.intermediateCas)}`;
308
309 const storesFingerprint = (stores?: TrustConfigTrustStore[]) =>
310 toStores(stores).map(storeFingerprint).sort().join("||");
311
312 const spiffeFingerprint = (stores?: Record<string, TrustConfigTrustStore | undefined>) => {
313 const normalized = toSpiffeStores(stores);
314 return Object.keys(normalized)
315 .sort()
316 .map((domain) => `${domain}=${storeFingerprint(normalized[domain]!)}`)
317 .join("||");
318 };
319
320 const toAttrs = (config: certificatemanager.TrustConfig, project: string) => {
321 const name = config.name ?? "";
322 const parsed = parseName(name);
323 return {
324 name,
325 trustConfigId: parsed.trustConfigId,
326 project: parsed.project || project,
327 location: parsed.location,
328 description: config.description,
329 labels: userLabels(config.labels),
330 trustStores: toStores(config.trustStores),
331 allowlistedCertificates: pemEntries(config.allowlistedCertificates),
332 spiffeTrustStores: toSpiffeStores(config.spiffeTrustStores),
333 etag: config.etag,
334 createTime: config.createTime,
335 updateTime: config.updateTime,
336 };
337 };
338
339 const getByName = (name: string) =>
340 certificatemanager
341 .getProjectsLocationsTrustConfigs({ name })
342 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
343
344 const waitUntilExists = (name: string) =>
345 getByName(name).pipe(
346 Effect.flatMap((config) =>
347 config
348 ? Effect.succeed(config)
349 : Effect.fail(new TrustConfigNotResolved({ resourceName: name })),
350 ),
351 Effect.retry({
352 while: (error) => error._tag === "GCP.CertificateManager.TrustConfigNotResolved",
353 times: 8,
354 schedule: Schedule.spaced("1 second"),
355 }),
356 );
357
358 const waitUntilGone = (name: string) =>
359 getByName(name).pipe(
360 Effect.flatMap((config) =>
361 config === undefined
362 ? Effect.void
363 : Effect.fail(new TrustConfigStillExists({ resourceName: name })),
364 ),
365 Effect.retry({
366 while: (error) => error._tag === "GCP.CertificateManager.TrustConfigStillExists",
367 times: 10,
368 schedule: Schedule.spaced("1 second"),
369 }),
370 );
371
372 const listOwnedTrustConfigs = (project: string) =>
373 certificatemanager.listProjectsLocationsTrustConfigs
374 .pages({
375 parent: `projects/${project}/locations/-`,
376 pageSize: 1000,
377 })
378 .pipe(
379 Stream.flatMap((page) => Stream.fromIterable(page.trustConfigs ?? [])),
380 Stream.filter((config) =>
381 Object.keys(config.labels ?? {}).some((key) => key.startsWith("alchemy-")),
382 ),
383 Stream.map((config) => toAttrs(config, project)),
384 Stream.runCollect,
385 Effect.map((chunk) => Array.from(chunk)),
386 Effect.catchTag("NotFound", () => Effect.succeed([])),
387 );
388
389 const toCreateBody = (
390 news: TrustConfigProps,
391 desiredLabels: Record<string, string>,
392 ): certificatemanager.TrustConfig => {
393 const body: certificatemanager.TrustConfig = {
394 description: news.description,
395 labels: desiredLabels,
396 };
397 const trustStores = toStores(news.trustStores);
398 if (trustStores.length > 0) {
399 body.trustStores = trustStores;
400 }
401 const allowlisted = pemEntries(news.allowlistedCertificates);
402 if (allowlisted.length > 0) {
403 body.allowlistedCertificates = allowlisted;
404 }
405 const spiffe = toSpiffeStores(news.spiffeTrustStores);
406 if (Object.keys(spiffe).length > 0) {
407 body.spiffeTrustStores = spiffe;
408 }
409 return body;
410 };
411
412 export const TrustConfigProvider = () =>
413 Provider.succeed(TrustConfig, {
414 stables: ["name", "trustConfigId", "project", "location", "createTime"],
415
416 diff: Effect.fn(function* ({ news, olds, output }) {
417 if (!isResolved(news)) return undefined;
418
419 const previousId = olds?.trustConfigId ?? output?.trustConfigId;
420 const nextId = news.trustConfigId ?? previousId;
421 const previousLocation = normalizeLocation(olds?.location ?? output?.location);
422 const nextLocation = normalizeLocation(news.location ?? olds?.location ?? output?.location);
423
424 const replace =
425 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
426 previousLocation !== nextLocation;
427
428 if (!replace) return undefined;
429 return { action: "replace" as const };
430 }),
431
432 read: Effect.fn(function* ({ id, olds, output }) {
433 const env = yield* GcpEnvironment.current;
434 const trustConfigId = yield* toId(id, olds?.trustConfigId, output?.trustConfigId);
435 const location = normalizeLocation(olds?.location ?? output?.location);
436 const name = output?.name ?? resourceName(env.project, location, trustConfigId);
437 const existing = yield* getByName(name);
438 if (existing === undefined) return undefined;
439 const attrs = toAttrs(existing, env.project);
440 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
441 }),
442
443 list: () =>
444 Effect.gen(function* () {
445 const env = yield* GcpEnvironment.current;
446 return yield* listOwnedTrustConfigs(env.project);
447 }),
448
449 reconcile: Effect.fn(function* ({ id, news, output }) {
450 const env = yield* GcpEnvironment.current;
451 const trustConfigId = yield* toId(id, news.trustConfigId, output?.trustConfigId);
452 const location = normalizeLocation(news.location ?? output?.location);
453 const name = resourceName(env.project, location, trustConfigId);
454 const desiredLabels = {
455 ...toLabels(news.labels),
456 ...(yield* createInternalLabels(id)),
457 };
458
459 let current = yield* getByName(name);
460
461 if (current === undefined) {
462 const created = yield* certificatemanager
463 .createProjectsLocationsTrustConfigs({
464 parent: `projects/${env.project}/locations/${location}`,
465 trustConfigId,
466 body: toCreateBody(news, desiredLabels),
467 })
468 .pipe(
469 Effect.retry({
470 while: (error) => error._tag === "Conflict",
471 times: 5,
472 schedule: Schedule.spaced("2 seconds"),
473 }),
474 Effect.catchTag("Conflict", () => Effect.undefined),
475 );
476 if (created !== undefined) {
477 yield* waitForOperation(created);
478 }
479 current = yield* waitUntilExists(name);
480 }
481
482 if (current === undefined) {
483 return yield* new TrustConfigNotResolved({ resourceName: name });
484 }
485
486 const observedLabels = tagRecord(current.labels);
487 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
488 const labelsChanged = upsert.length > 0 || removed.length > 0;
489 const descriptionChanged = (current.description ?? "") !== (news.description ?? "");
490 const desiredStores = toStores(news.trustStores);
491 const storesChanged =
492 storesFingerprint(desiredStores) !== storesFingerprint(current.trustStores);
493 const desiredAllowlisted = pemEntries(news.allowlistedCertificates);
494 const allowlistedChanged =
495 pemFingerprint(desiredAllowlisted) !== pemFingerprint(current.allowlistedCertificates);
496 const desiredSpiffe = toSpiffeStores(news.spiffeTrustStores);
497 const spiffeChanged =
498 spiffeFingerprint(desiredSpiffe) !== spiffeFingerprint(current.spiffeTrustStores);
499
500 if (
501 labelsChanged ||
502 descriptionChanged ||
503 storesChanged ||
504 allowlistedChanged ||
505 spiffeChanged
506 ) {
507 const updateMask = [
508 labelsChanged ? "labels" : undefined,
509 descriptionChanged ? "description" : undefined,
510 storesChanged ? "trustStores" : undefined,
511 allowlistedChanged ? "allowlistedCertificates" : undefined,
512 spiffeChanged ? "spiffeTrustStores" : undefined,
513 ].filter((field): field is string => field !== undefined);
514
515 const operation = yield* certificatemanager.patchProjectsLocationsTrustConfigs({
516 name,
517 updateMask: updateMask.join(","),
518 body: {
519 name,
520 labels: desiredLabels,
521 description: news.description,
522 trustStores: desiredStores,
523 allowlistedCertificates: desiredAllowlisted,
524 spiffeTrustStores: desiredSpiffe,
525 },
526 });
527 yield* waitForOperation(operation);
528 current = yield* waitUntilExists(name);
529 }
530
531 return toAttrs(current, env.project);
532 }),
533
534 delete: Effect.fn(function* ({ output }) {
535 const operation = yield* certificatemanager
536 .deleteProjectsLocationsTrustConfigs({ name: output.name })
537 .pipe(
538 Effect.retry({
539 while: (error) => error._tag === "Conflict",
540 times: 8,
541 schedule: Schedule.spaced("2 seconds"),
542 }),
543 Effect.catchTag("NotFound", () => Effect.undefined),
544 );
545 if (operation !== undefined) {
546 yield* waitForOperation(operation, { notFoundOk: true });
547 }
548 yield* waitUntilGone(output.name);
549 }),
550 });