@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 565 lines 19.1 KB
Raw
1 import * as privateca from "@distilled.cloud/gcp/privateca_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 { waitForOperation as waitForGcpOperation } from "../Operation.ts";
21 import type { Providers } from "../Providers.ts";
22
23 const DEFAULT_TIER = "DEVOPS";
24 const MAX_NAME_LENGTH = 63;
25
26 export type CaPoolTier = privateca.CaPoolTierEnum | (string & {});
27
28 export type PublishingOptionsEncodingFormat =
29 | privateca.PublishingOptionsEncodingFormatEnum
30 | (string & {});
31
32 export type PublishingOptions = {
33 /**
34 * When true, publishes each CA certificate and includes its URL in the
35 * Authority Information Access extension of issued certificates.
36 */
37 publishCaCert?: boolean;
38 /**
39 * When true, publishes each CA CRL and includes its URL in the CRL
40 * Distribution Points extension of issued certificates.
41 */
42 publishCrl?: boolean;
43 /**
44 * Encoding of published CA certificates and CRLs. `PEM` or `DER`.
45 * Defaults to `PEM` when omitted.
46 */
47 encodingFormat?: PublishingOptionsEncodingFormat;
48 };
49
50 export type EncryptionSpec = {
51 /**
52 * Cloud KMS CryptoKey used to encrypt Subject, SubjectAltNames, and
53 * PEM certificate fields at rest
54 * (`projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}`).
55 * Immutable — changing it replaces the pool.
56 */
57 cloudKmsKey?: string;
58 };
59
60 /**
61 * Issuance controls applied to every certificate minted from this pool.
62 * See Certificate Authority Service `IssuancePolicy`.
63 */
64 export type IssuancePolicy = privateca.IssuancePolicy;
65
66 export type CaPoolProps = {
67 /**
68 * CaPool id (the `{caPool}` segment of
69 * `projects/{project}/locations/{location}/caPools/{caPool}`).
70 * If omitted, a unique name is generated from the stack, stage, and
71 * logical id. Must match `[a-zA-Z0-9_-]{1,63}`. Immutable — changing it
72 * replaces the pool.
73 */
74 caPoolId?: string;
75 /**
76 * Certificate Authority Service location (`us-central1`, `us-east1`,
77 * …). Immutable — changing it replaces the pool. `US-CENTRAL1` is
78 * accepted and normalized to `us-central1`.
79 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
80 */
81 location?: string;
82 /**
83 * Pool tier. `DEVOPS` is cheaper and intended for tests and
84 * non-production; `ENTERPRISE` enables CA-certificate and CRL
85 * publication. Immutable — changing it replaces the pool.
86 * @default "DEVOPS"
87 */
88 tier?: CaPoolTier;
89 /**
90 * User labels. Alchemy ownership labels are merged in automatically.
91 */
92 labels?: Record<string, string>;
93 /**
94 * How CA certificates and CRLs are published for authorities in this
95 * pool.
96 */
97 publishingOptions?: PublishingOptions;
98 /**
99 * Controls over certificate issuance from this pool (lifetime, allowed
100 * key types, identity constraints, baseline X.509 values).
101 */
102 issuancePolicy?: IssuancePolicy;
103 /**
104 * Customer-managed encryption for certificate fields at rest.
105 * Immutable — changing it replaces the pool.
106 */
107 encryptionSpec?: EncryptionSpec;
108 };
109
110 export type CaPool = Resource<
111 "GCP.PrivateCA.CaPool",
112 CaPoolProps,
113 {
114 /** Full resource name `projects/{project}/locations/{location}/caPools/{caPool}`. */
115 name: string;
116 /** CaPool id (last path segment). */
117 caPoolId: string;
118 /** Project id. */
119 project: string;
120 /** Location id (`us-central1`, …). */
121 location: string;
122 /** Pool tier (`DEVOPS` or `ENTERPRISE`). */
123 tier: string;
124 /** User labels (Alchemy ownership labels stripped). */
125 labels: Record<string, string>;
126 /** Publishing options currently configured on the pool. */
127 publishingOptions: PublishingOptions | undefined;
128 /** Issuance policy currently configured on the pool. */
129 issuancePolicy: IssuancePolicy | undefined;
130 /** CMEK spec, if any. */
131 encryptionSpec: EncryptionSpec | undefined;
132 },
133 never,
134 Providers
135 >;
136
137 /**
138 * A Certificate Authority Service CaPool — a group of Certificate
139 * Authorities that share issuance policy and form a trust anchor.
140 *
141 * Changing `caPoolId`, `location`, `tier`, or `encryptionSpec` replaces
142 * the resource. Labels, `publishingOptions`, and `issuancePolicy` update
143 * in place.
144 *
145 * ### Creating a CaPool
146 * **Example:** Generated name
147 * ```typescript
148 * const pool = yield* GCP.PrivateCA.CaPool("AppCa", {});
149 * ```
150 *
151 * **Example:** Explicit id, labels, and publishing
152 * ```typescript
153 * const pool = yield* GCP.PrivateCA.CaPool("AppCa", {
154 * caPoolId: "app-ca",
155 * location: "us-central1",
156 * tier: "DEVOPS",
157 * labels: { env: "prod" },
158 * publishingOptions: {
159 * publishCaCert: false,
160 * publishCrl: false,
161 * },
162 * });
163 * ```
164 *
165 * ### Issuance Policy
166 * **Example:** Cap lifetime and allow config-based issuance
167 * ```typescript
168 * const pool = yield* GCP.PrivateCA.CaPool("LeafCa", {
169 * tier: "DEVOPS",
170 * issuancePolicy: {
171 * maximumLifetime: "2592000s",
172 * allowedIssuanceModes: {
173 * allowConfigBasedIssuance: true,
174 * allowCsrBasedIssuance: true,
175 * },
176 * identityConstraints: {
177 * allowSubjectPassthrough: true,
178 * allowSubjectAltNamesPassthrough: true,
179 * },
180 * },
181 * });
182 * ```
183 *
184 * @resource
185 * @category PrivateCA
186 */
187 export const CaPool = Resource<CaPool>("GCP.PrivateCA.CaPool");
188
189 export class CaPoolNotResolved extends Data.TaggedError("GCP.PrivateCA.CaPoolNotResolved")<{
190 resourceName: string;
191 }> {}
192
193 export class CaPoolStillExists extends Data.TaggedError("GCP.PrivateCA.CaPoolStillExists")<{
194 resourceName: string;
195 }> {}
196
197 const lastSegment = (value: string) => {
198 const trimmed = value.replace(/\/+$/, "");
199 const parts = trimmed.split("/");
200 return parts[parts.length - 1] || trimmed;
201 };
202
203 const rfc1035 = (name: string): string => {
204 let next = name
205 .toLowerCase()
206 .replace(/[^a-z0-9-]/g, "-")
207 .replace(/-+/g, "-")
208 .replace(/^-+/, "")
209 .replace(/-+$/, "");
210 next = next.slice(0, MAX_NAME_LENGTH).replace(/-+$/, "");
211 return next.length > 0 ? next : "ca-pool";
212 };
213
214 const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
215
216 const normalizeTier = (tier: string | undefined) => {
217 const value = (tier ?? DEFAULT_TIER).toUpperCase();
218 return value === "TIER_UNSPECIFIED" ? DEFAULT_TIER : value;
219 };
220
221 const resourceName = (project: string, location: string, caPoolId: string) =>
222 `projects/${project}/locations/${location}/caPools/${caPoolId}`;
223
224 const parseName = (name: string) => {
225 const parts = name.split("/").filter((part) => part.length > 0);
226 const poolsAt = parts.lastIndexOf("caPools");
227 const locationsAt = parts.lastIndexOf("locations");
228 const projectsAt = parts.lastIndexOf("projects");
229 return {
230 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
231 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
232 caPoolId: poolsAt >= 0 && parts[poolsAt + 1] ? parts[poolsAt + 1]! : lastSegment(name),
233 };
234 };
235
236 const userLabels = (
237 labels: Record<string, string | undefined> | null | undefined,
238 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
239
240 const toId = (id: string, caPoolId: string | undefined, existing?: string) =>
241 Effect.gen(function* () {
242 if (caPoolId !== undefined) return caPoolId;
243 if (existing !== undefined) return existing;
244 return rfc1035(
245 yield* createPhysicalName({
246 id,
247 maxLength: MAX_NAME_LENGTH,
248 lowercase: true,
249 }),
250 );
251 });
252
253 const canonical = (value: unknown): unknown => {
254 if (value === undefined || value === null) return undefined;
255 if (typeof value === "boolean" || typeof value === "number") return value;
256 if (typeof value === "string") {
257 return value.length === 0 ? undefined : value;
258 }
259 if (Array.isArray(value)) {
260 const items = value.map(canonical).filter((item) => item !== undefined);
261 return items.length === 0 ? undefined : items;
262 }
263 if (typeof value === "object") {
264 const entries = Object.entries(value as Record<string, unknown>)
265 .map(([key, item]) => [key, canonical(item)] as const)
266 .filter(([, item]) => item !== undefined)
267 .sort(([left], [right]) => left.localeCompare(right));
268 if (entries.length === 0) return undefined;
269 return Object.fromEntries(entries);
270 }
271 return undefined;
272 };
273
274 const fingerprint = (value: unknown): string => JSON.stringify(canonical(value) ?? null);
275
276 const encodingOf = (value: string | undefined) => {
277 if (value === undefined || value === "" || value === "ENCODING_FORMAT_UNSPECIFIED") {
278 return undefined;
279 }
280 return value;
281 };
282
283 const toPublishingOptions = (
284 options: PublishingOptions | privateca.PublishingOptions | undefined,
285 ): PublishingOptions => ({
286 publishCaCert: options?.publishCaCert === true,
287 publishCrl: options?.publishCrl === true,
288 encodingFormat: encodingOf(options?.encodingFormat),
289 });
290
291 const publishingFingerprint = (
292 options: PublishingOptions | privateca.PublishingOptions | undefined,
293 ) =>
294 fingerprint({
295 publishCaCert: options?.publishCaCert === true,
296 publishCrl: options?.publishCrl === true,
297 encodingFormat: encodingOf(options?.encodingFormat) ?? "PEM",
298 });
299
300 const toEncryptionSpec = (
301 spec: EncryptionSpec | privateca.EncryptionSpec | undefined,
302 ): EncryptionSpec | undefined => {
303 const cloudKmsKey = spec?.cloudKmsKey;
304 if (cloudKmsKey === undefined || cloudKmsKey.length === 0) return undefined;
305 return { cloudKmsKey };
306 };
307
308 const toIssuancePolicy = (policy: IssuancePolicy | undefined): IssuancePolicy | undefined => {
309 if (policy === undefined) return undefined;
310 const next = canonical(policy);
311 return next === undefined ? undefined : (next as IssuancePolicy);
312 };
313
314 const toAttrs = (pool: privateca.CaPool, project: string) => {
315 const name = pool.name ?? "";
316 const parsed = parseName(name);
317 return {
318 name,
319 caPoolId: parsed.caPoolId,
320 project: parsed.project || project,
321 location: parsed.location,
322 tier: normalizeTier(pool.tier),
323 labels: userLabels(pool.labels),
324 publishingOptions: toPublishingOptions(pool.publishingOptions),
325 issuancePolicy: toIssuancePolicy(pool.issuancePolicy),
326 encryptionSpec: toEncryptionSpec(pool.encryptionSpec),
327 };
328 };
329
330 const getByName = (name: string) =>
331 privateca
332 .getProjectsLocationsCaPools({ name })
333 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
334
335 /**
336 * Wait for a Certificate Authority Service operation; CA creation and
337 * activation take a few minutes. ALREADY_EXISTS (code 6) counts as success
338 * (create race); with `notFoundOk`, so does NOT_FOUND (code 5, delete race)
339 * and an operation that is already gone.
340 */
341 const waitForOperation = (operation: privateca.Operation, options?: { notFoundOk?: boolean }) =>
342 waitForGcpOperation(operation, (name) => privateca.getProjectsLocationsOperations({ name }), {
343 budget: "15 minutes",
344 }).pipe(
345 Effect.catchIf(
346 (error) =>
347 (error._tag === "GCP.OperationFailed" &&
348 (error.code === 6 || (options?.notFoundOk === true && error.code === 5))) ||
349 (options?.notFoundOk === true && error._tag === "NotFound"),
350 () => Effect.succeed(operation),
351 ),
352 );
353
354 const waitUntilExists = (name: string) =>
355 getByName(name).pipe(
356 Effect.flatMap((pool) =>
357 pool ? Effect.succeed(pool) : Effect.fail(new CaPoolNotResolved({ resourceName: name })),
358 ),
359 Effect.retry({
360 while: (error) => error._tag === "GCP.PrivateCA.CaPoolNotResolved",
361 times: 8,
362 schedule: Schedule.spaced("1 second"),
363 }),
364 );
365
366 const waitUntilGone = (name: string) =>
367 getByName(name).pipe(
368 Effect.flatMap((pool) =>
369 pool === undefined ? Effect.void : Effect.fail(new CaPoolStillExists({ resourceName: name })),
370 ),
371 Effect.retry({
372 while: (error) => error._tag === "GCP.PrivateCA.CaPoolStillExists",
373 times: 10,
374 schedule: Schedule.spaced("1 second"),
375 }),
376 );
377
378 const listOwnedCaPools = (project: string) =>
379 privateca.listProjectsLocationsCaPools
380 .pages({
381 parent: `projects/${project}/locations/-`,
382 pageSize: 1000,
383 })
384 .pipe(
385 Stream.flatMap((page) => Stream.fromIterable(page.caPools ?? [])),
386 Stream.filter((pool) =>
387 Object.keys(pool.labels ?? {}).some((key) => key.startsWith("alchemy-")),
388 ),
389 Stream.map((pool) => toAttrs(pool, project)),
390 Stream.runCollect,
391 Effect.map((chunk) => Array.from(chunk)),
392 Effect.catchTag("NotFound", () => Effect.succeed([])),
393 );
394
395 const toCreateBody = (
396 news: CaPoolProps,
397 desiredLabels: Record<string, string>,
398 ): privateca.CaPool => {
399 const body: privateca.CaPool = {
400 tier: normalizeTier(news.tier),
401 labels: desiredLabels,
402 };
403 if (news.publishingOptions !== undefined) {
404 body.publishingOptions = toPublishingOptions(news.publishingOptions);
405 }
406 const issuance = toIssuancePolicy(news.issuancePolicy);
407 if (issuance !== undefined) {
408 body.issuancePolicy = issuance;
409 }
410 const encryption = toEncryptionSpec(news.encryptionSpec);
411 if (encryption !== undefined) {
412 body.encryptionSpec = encryption;
413 }
414 return body;
415 };
416
417 export const CaPoolProvider = () =>
418 Provider.succeed(CaPool, {
419 stables: ["name", "caPoolId", "project", "location", "tier"],
420
421 diff: Effect.fn(function* ({ news, olds, output }) {
422 if (!isResolved(news)) return undefined;
423 const env = yield* GcpEnvironment.current;
424
425 const previousId = olds?.caPoolId ?? output?.caPoolId;
426 const nextId = news.caPoolId ?? previousId;
427 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
428
429 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
430 const nextLocation = normalizeLocation(
431 news.location ?? olds?.location ?? output?.location ?? env.region,
432 );
433 const locationChanged = previousLocation !== nextLocation;
434
435 const previousTier = normalizeTier(olds?.tier ?? output?.tier);
436 const nextTier = normalizeTier(news.tier ?? olds?.tier ?? output?.tier);
437 const tierChanged = previousTier !== nextTier;
438
439 const previousKey = olds?.encryptionSpec?.cloudKmsKey ?? output?.encryptionSpec?.cloudKmsKey;
440 const nextKey = news.encryptionSpec?.cloudKmsKey ?? previousKey;
441 const encryptionChanged = news.encryptionSpec !== undefined && previousKey !== nextKey;
442
443 if (!idChanged && !locationChanged && !tierChanged && !encryptionChanged) {
444 return undefined;
445 }
446
447 return {
448 action: "replace" as const,
449 deleteFirst:
450 !idChanged && !locationChanged && previousId !== undefined && nextId === previousId,
451 };
452 }),
453
454 read: Effect.fn(function* ({ id, olds, output }) {
455 const env = yield* GcpEnvironment.current;
456 const caPoolId = yield* toId(id, olds?.caPoolId, output?.caPoolId);
457 const location = normalizeLocation(olds?.location ?? output?.location ?? env.region);
458 const name = output?.name ?? resourceName(env.project, location, caPoolId);
459 const existing = yield* getByName(name);
460 if (existing === undefined) return undefined;
461 const attrs = toAttrs(existing, env.project);
462 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
463 }),
464
465 list: () =>
466 Effect.gen(function* () {
467 const env = yield* GcpEnvironment.current;
468 return yield* listOwnedCaPools(env.project);
469 }),
470
471 reconcile: Effect.fn(function* ({ id, news, output }) {
472 const env = yield* GcpEnvironment.current;
473 const caPoolId = yield* toId(id, news.caPoolId, output?.caPoolId);
474 const location = normalizeLocation(news.location ?? output?.location ?? env.region);
475 const name = resourceName(env.project, location, caPoolId);
476 const desiredLabels = {
477 ...toLabels(news.labels),
478 ...(yield* createInternalLabels(id)),
479 };
480
481 let current = yield* getByName(name);
482
483 if (current === undefined) {
484 const created = yield* privateca
485 .createProjectsLocationsCaPools({
486 parent: `projects/${env.project}/locations/${location}`,
487 caPoolId,
488 body: toCreateBody(news, desiredLabels),
489 })
490 .pipe(
491 Effect.retry({
492 while: (error) => error._tag === "Conflict",
493 times: 5,
494 schedule: Schedule.spaced("2 seconds"),
495 }),
496 Effect.catchTag("Conflict", () => Effect.undefined),
497 );
498 if (created !== undefined) {
499 yield* waitForOperation(created);
500 }
501 current = yield* waitUntilExists(name);
502 }
503
504 if (current === undefined) {
505 return yield* new CaPoolNotResolved({ resourceName: name });
506 }
507
508 const observedLabels = tagRecord(current.labels);
509 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
510 const labelsChanged = upsert.length > 0 || removed.length > 0;
511
512 const desiredPublishing = toPublishingOptions(news.publishingOptions);
513 const publishingChanged =
514 news.publishingOptions !== undefined &&
515 publishingFingerprint(news.publishingOptions) !==
516 publishingFingerprint(current.publishingOptions);
517
518 const desiredIssuance = toIssuancePolicy(news.issuancePolicy);
519 const issuanceChanged =
520 news.issuancePolicy !== undefined &&
521 fingerprint(desiredIssuance) !== fingerprint(toIssuancePolicy(current.issuancePolicy));
522
523 if (labelsChanged || publishingChanged || issuanceChanged) {
524 const updateMask = [
525 labelsChanged ? "labels" : undefined,
526 publishingChanged ? "publishingOptions" : undefined,
527 issuanceChanged ? "issuancePolicy" : undefined,
528 ].filter((field): field is string => field !== undefined);
529
530 const operation = yield* privateca.patchProjectsLocationsCaPools({
531 name,
532 updateMask: updateMask.join(","),
533 body: {
534 name,
535 labels: desiredLabels,
536 publishingOptions: desiredPublishing,
537 issuancePolicy: desiredIssuance,
538 },
539 });
540 yield* waitForOperation(operation);
541 current = yield* waitUntilExists(name);
542 }
543
544 if (current === undefined) {
545 return yield* new CaPoolNotResolved({ resourceName: name });
546 }
547
548 return toAttrs(current, env.project);
549 }),
550
551 delete: Effect.fn(function* ({ output }) {
552 const operation = yield* privateca.deleteProjectsLocationsCaPools({ name: output.name }).pipe(
553 Effect.retry({
554 while: (error) => error._tag === "Conflict",
555 times: 8,
556 schedule: Schedule.spaced("2 seconds"),
557 }),
558 Effect.catchTag("NotFound", () => Effect.undefined),
559 );
560 if (operation !== undefined) {
561 yield* waitForOperation(operation, { notFoundOk: true });
562 }
563 yield* waitUntilGone(output.name);
564 }),
565 });