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

main
ts 1,003 lines 32.6 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_TYPE: privateca.CertificateAuthorityTypeEnum = "SELF_SIGNED";
24 const DEFAULT_LIFETIME = "315360000s";
25 const DEFAULT_ALGORITHM: privateca.KeyVersionSpecAlgorithmEnum = "EC_P256_SHA256";
26 const DEFAULT_DESIRED_STATE: DesiredState = "ENABLED";
27 const MAX_NAME_LENGTH = 63;
28 const STEADY_STATES = new Set(["ENABLED", "DISABLED", "STAGED", "AWAITING_USER_ACTIVATION"]);
29
30 export type DesiredState = "ENABLED" | "DISABLED" | "STAGED";
31
32 export type KeyVersionSpec = {
33 /**
34 * Algorithm for a Google-managed Cloud KMS key. Managed keys use
35 * `HSM` protection. Immutable — changing it replaces the CA.
36 */
37 algorithm?: privateca.KeyVersionSpecAlgorithmEnum | (string & {});
38 /**
39 * Existing Cloud KMS CryptoKeyVersion
40 * `projects/{project}/locations/{location}/keyRings/{keyRing}/cryptoKeys/{cryptoKey}/cryptoKeyVersions/{version}`.
41 * Immutable — changing it replaces the CA.
42 */
43 cloudKmsKeyVersion?: string;
44 };
45
46 export type Subject = {
47 /** Common name of the subject. */
48 commonName?: string;
49 /** Organization of the subject. */
50 organization?: string;
51 /** Organizational unit of the subject. */
52 organizationalUnit?: string;
53 /** Locality or city of the subject. */
54 locality?: string;
55 /** Province, territory, or regional state of the subject. */
56 province?: string;
57 /** Country code of the subject. */
58 countryCode?: string;
59 /** Street address of the subject. */
60 streetAddress?: string;
61 /** Postal code of the subject. */
62 postalCode?: string;
63 };
64
65 export type SubjectAltNames = {
66 /** Fully-qualified DNS names. */
67 dnsNames?: string[];
68 /** RFC 3986 URIs. */
69 uris?: string[];
70 /** RFC 2822 email addresses. */
71 emailAddresses?: string[];
72 /** IPv4 or IPv6 addresses. */
73 ipAddresses?: string[];
74 };
75
76 export type SubjectConfig = {
77 /** Distinguished name fields. */
78 subject?: Subject;
79 /** Subject alternative names. */
80 subjectAltName?: SubjectAltNames;
81 };
82
83 export type KeyUsageOptions = {
84 digitalSignature?: boolean;
85 contentCommitment?: boolean;
86 keyEncipherment?: boolean;
87 dataEncipherment?: boolean;
88 keyAgreement?: boolean;
89 certSign?: boolean;
90 crlSign?: boolean;
91 encipherOnly?: boolean;
92 decipherOnly?: boolean;
93 };
94
95 export type ExtendedKeyUsageOptions = {
96 serverAuth?: boolean;
97 clientAuth?: boolean;
98 codeSigning?: boolean;
99 emailProtection?: boolean;
100 timeStamping?: boolean;
101 ocspSigning?: boolean;
102 };
103
104 export type KeyUsage = {
105 /** High-level key uses (digital signature, cert sign, …). */
106 baseKeyUsage?: KeyUsageOptions;
107 /** Extended key uses (server auth, client auth, …). */
108 extendedKeyUsage?: ExtendedKeyUsageOptions;
109 };
110
111 export type CaOptions = {
112 /**
113 * Whether this certificate is a CA. Must be `true` for a
114 * CertificateAuthority.
115 */
116 isCa?: boolean;
117 /**
118 * Maximum depth of subordinate CA certificates allowed. Omit to leave
119 * the path-length constraint off the certificate.
120 */
121 maxIssuerPathLength?: number;
122 };
123
124 export type X509Config = {
125 /** CA basic-constraints options. */
126 caOptions?: CaOptions;
127 /** Key usage extension. */
128 keyUsage?: KeyUsage;
129 /** OCSP endpoints in the Authority Information Access extension. */
130 aiaOcspServers?: string[];
131 };
132
133 export type CertificateConfig = {
134 /** Subject and SAN fields written into the CA certificate. Immutable. */
135 subjectConfig?: SubjectConfig;
136 /** X.509 extensions written into the CA certificate. Immutable. */
137 x509Config?: X509Config;
138 };
139
140 export type UserDefinedAccessUrls = {
141 /** URLs where CRL information is published. */
142 crlAccessUrls?: string[];
143 /** URLs where the issuer CA certificate may be downloaded. */
144 aiaIssuingCertificateUrls?: string[];
145 };
146
147 export type SubordinateConfig = {
148 /**
149 * Issuing CertificateAuthority resource name
150 * `projects/{project}/locations/{location}/caPools/{caPool}/certificateAuthorities/{certificateAuthority}`.
151 */
152 certificateAuthority?: string;
153 /** PEM certificate chain of the issuers (leaf-to-root), excluding this CA. */
154 pemIssuerChain?: {
155 pemCertificates?: string[];
156 };
157 };
158
159 export type CertificateAuthorityProps = {
160 /**
161 * Parent CaPool. Full name
162 * `projects/{project}/locations/{location}/caPools/{caPool}` or the
163 * pool id (combined with `location`). Immutable — changing it replaces
164 * the CA.
165 */
166 caPool: string;
167 /**
168 * Location (`us-central1`, …). Used when `caPool` is a bare id.
169 * Immutable — changing it replaces the CA. `US-CENTRAL1` is accepted
170 * and normalized to `us-central1`.
171 * @default the stack's GCP region (`GCP.Region`, else the profile region, else `us-central1`)
172 */
173 location?: string;
174 /**
175 * CertificateAuthority id (the last path segment). If omitted, a unique
176 * name is generated from the stack, stage, and logical id. Must match
177 * `[a-zA-Z0-9_-]{1,63}`. Immutable — changing it replaces the CA.
178 */
179 certificateAuthorityId?: string;
180 /**
181 * `SELF_SIGNED` root or `SUBORDINATE`. Immutable — changing it
182 * replaces the CA.
183 * @default "SELF_SIGNED"
184 */
185 type?: privateca.CertificateAuthorityTypeEnum | (string & {});
186 /**
187 * Desired lifetime of the CA certificate (e.g. `"315360000s"`).
188 * Immutable — changing it replaces the CA.
189 * @default "315360000s"
190 */
191 lifetime?: string;
192 /**
193 * Signing key. Either `algorithm` (Google-managed HSM key) or
194 * `cloudKmsKeyVersion`. Immutable — changing it replaces the CA.
195 * @default { algorithm: "EC_P256_SHA256" }
196 */
197 keySpec?: KeyVersionSpec;
198 /**
199 * X.509 certificate config (subject + CA extensions). Immutable —
200 * changing it replaces the CA. When omitted, Alchemy fills a self-signed
201 * CA subject (`organization: "Alchemy"`, `commonName` = id) with
202 * `isCa: true` and cert/CRL sign usage.
203 */
204 config?: CertificateConfig;
205 /**
206 * User labels. Alchemy ownership labels are merged in automatically.
207 */
208 labels?: Record<string, string>;
209 /**
210 * Cloud Storage bucket that publishes the CA certificate and CRLs
211 * (bucket name only, no `gs://` prefix). Immutable.
212 */
213 gcsBucket?: string;
214 /**
215 * User-defined AIA/CRL URLs. The service does not publish to these
216 * URLs; they are mirrored by the operator. Updatable.
217 */
218 userDefinedAccessUrls?: UserDefinedAccessUrls;
219 /**
220 * Issuer information for a subordinate CA. Updatable, but the CA must
221 * continue to validate against the chain.
222 */
223 subordinateConfig?: SubordinateConfig;
224 /**
225 * PEM CA certificate used to activate a `SUBORDINATE` CA that is in
226 * `AWAITING_USER_ACTIVATION`. Pair with `subordinateConfig`.
227 */
228 pemCaCertificate?: string;
229 /**
230 * Target operational state. After create the API leaves the CA in
231 * `STAGED`. `ENABLED` calls enable; `DISABLED` calls disable; `STAGED`
232 * leaves the create-time state (it is not possible to return to
233 * `STAGED` from `ENABLED`/`DISABLED`).
234 * @default "ENABLED"
235 */
236 desiredState?: DesiredState | (string & {});
237 };
238
239 export type CertificateAuthorityAttrs = {
240 /** Full resource name `projects/{project}/locations/{location}/caPools/{caPool}/certificateAuthorities/{certificateAuthority}`. */
241 name: string;
242 /** CertificateAuthority id (last path segment). */
243 certificateAuthorityId: string;
244 /** Parent CaPool resource name. */
245 caPool: string;
246 /** Project id. */
247 project: string;
248 /** Location id (`us-central1`, …). */
249 location: string;
250 /** `SELF_SIGNED` or `SUBORDINATE`. */
251 type: string;
252 /** Server-reported state (`ENABLED`, `STAGED`, `DISABLED`, …). */
253 state: string | undefined;
254 /** CaPool tier (`ENTERPRISE`, `DEVOPS`). */
255 tier: string | undefined;
256 /** User labels (Alchemy ownership labels stripped). */
257 labels: Record<string, string>;
258 /** CA certificate lifetime. */
259 lifetime: string | undefined;
260 /** Signing-key spec currently applied. */
261 keySpec: KeyVersionSpec | undefined;
262 /** Cloud Storage bucket used for publishing, if any. */
263 gcsBucket: string | undefined;
264 /** PEM CA certificate chain (self-to-root). */
265 pemCaCertificates: string[];
266 /** User-defined AIA/CRL URLs. */
267 userDefinedAccessUrls: UserDefinedAccessUrls | undefined;
268 /** Subordinate issuer config, if any. */
269 subordinateConfig: SubordinateConfig | undefined;
270 /** URLs for the CA certificate and CRLs. */
271 caCertificateUrl: string | undefined;
272 /** CRL access URL. */
273 crlAccessUrl: string | undefined;
274 /** RFC3339 creation timestamp. */
275 createTime: string | undefined;
276 /** RFC3339 last-update timestamp. */
277 updateTime: string | undefined;
278 /** RFC3339 soft-delete timestamp, if the CA is `DELETED`. */
279 deleteTime: string | undefined;
280 /** RFC3339 purge timestamp, if the CA is `DELETED`. */
281 expireTime: string | undefined;
282 };
283
284 export type CertificateAuthority = Resource<
285 "GCP.PrivateCA.CertificateAuthority",
286 CertificateAuthorityProps,
287 CertificateAuthorityAttrs,
288 never,
289 Providers
290 >;
291
292 /**
293 * A Certificate Authority Service CertificateAuthority — a named CA in a
294 * CaPool that issues certificates.
295 *
296 * Changing `certificateAuthorityId`, `caPool`, `location`, `type`,
297 * `lifetime`, `keySpec`, `config`, or `gcsBucket` replaces the CA. Labels
298 * and `userDefinedAccessUrls` update in place. `desiredState` enable/disable
299 * the CA after create (`STAGED` is the API's create-time state).
300 *
301 * Destroy disables an `ENABLED` CA, then deletes it with `skipGracePeriod`
302 * so the 30-day undelete window is skipped (required for `pnpm nuke:gcp`).
303 * `STAGED` CAs are deleted directly. Provisioning a Google-managed HSM key
304 * typically takes under a minute on a `DEVOPS` pool.
305 *
306 * ### Creating a Certificate Authority
307 * **Example:** Generated name in an existing pool
308 * ```typescript
309 * const pool = yield* GCP.PrivateCA.CaPool("Pool", { tier: "DEVOPS" });
310 * const ca = yield* GCP.PrivateCA.CertificateAuthority("Root", {
311 * caPool: pool.name,
312 * });
313 * ```
314 *
315 * **Example:** Explicit id, labels, and subject
316 * ```typescript
317 * const ca = yield* GCP.PrivateCA.CertificateAuthority("Root", {
318 * caPool: pool.name,
319 * certificateAuthorityId: "app-root",
320 * type: "SELF_SIGNED",
321 * lifetime: "315360000s",
322 * keySpec: { algorithm: "EC_P256_SHA256" },
323 * desiredState: "ENABLED",
324 * labels: { env: "prod" },
325 * config: {
326 * subjectConfig: {
327 * subject: {
328 * organization: "Example",
329 * commonName: "Example Root CA",
330 * },
331 * },
332 * x509Config: {
333 * caOptions: { isCa: true },
334 * keyUsage: {
335 * baseKeyUsage: {
336 * certSign: true,
337 * crlSign: true,
338 * },
339 * },
340 * },
341 * },
342 * });
343 * ```
344 *
345 * ### Staging a CA
346 * **Example:** Leave the CA in STAGED after create
347 * ```typescript
348 * const ca = yield* GCP.PrivateCA.CertificateAuthority("Root", {
349 * caPool: pool.name,
350 * desiredState: "STAGED",
351 * });
352 * ```
353 *
354 * @resource
355 * @category PrivateCA
356 */
357 export const CertificateAuthority = Resource<CertificateAuthority>(
358 "GCP.PrivateCA.CertificateAuthority",
359 );
360
361 export class CertificateAuthorityNotResolved extends Data.TaggedError(
362 "GCP.PrivateCA.CertificateAuthorityNotResolved",
363 )<{
364 resourceName: string;
365 }> {}
366
367 export class CertificateAuthorityNotReady extends Data.TaggedError(
368 "GCP.PrivateCA.CertificateAuthorityNotReady",
369 )<{
370 resourceName: string;
371 state: string;
372 }> {}
373
374 export class CertificateAuthorityStillExists extends Data.TaggedError(
375 "GCP.PrivateCA.CertificateAuthorityStillExists",
376 )<{
377 resourceName: string;
378 }> {}
379
380 const lastSegment = (value: string) => {
381 const trimmed = value.replace(/\/+$/, "");
382 const parts = trimmed.split("/");
383 return parts[parts.length - 1] || trimmed;
384 };
385
386 const normalizeLocation = (location: string) => lastSegment(location).toLowerCase();
387
388 const normalizeType = (type: string | undefined) => {
389 const value = (type ?? DEFAULT_TYPE).toUpperCase();
390 return value === "TYPE_UNSPECIFIED" ? DEFAULT_TYPE : value;
391 };
392
393 const normalizeDesired = (state: string | undefined): DesiredState => {
394 const value = (state ?? DEFAULT_DESIRED_STATE).toUpperCase();
395 if (value === "DISABLED") return "DISABLED";
396 if (value === "STAGED") return "STAGED";
397 return "ENABLED";
398 };
399
400 const resourceName = (caPool: string, certificateAuthorityId: string) =>
401 `${caPool}/certificateAuthorities/${certificateAuthorityId}`;
402
403 const parseName = (name: string) => {
404 const parts = name.split("/").filter((part) => part.length > 0);
405 const casAt = parts.lastIndexOf("certificateAuthorities");
406 const poolsAt = parts.lastIndexOf("caPools");
407 const locationsAt = parts.lastIndexOf("locations");
408 const projectsAt = parts.lastIndexOf("projects");
409 const caPool = poolsAt >= 0 ? parts.slice(0, poolsAt + 2).join("/") : "";
410 return {
411 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
412 location: locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : "",
413 caPool,
414 certificateAuthorityId: casAt >= 0 && parts[casAt + 1] ? parts[casAt + 1]! : lastSegment(name),
415 };
416 };
417
418 const resolveParent = (project: string, caPool: string, location: string) => {
419 if (caPool.includes("/")) {
420 const parsed = parseName(
421 caPool.includes("/certificateAuthorities/") ? caPool : `${caPool}/certificateAuthorities/_`,
422 );
423 return {
424 parent: parsed.caPool,
425 location: parsed.location,
426 project: parsed.project || project,
427 };
428 }
429 const loc = normalizeLocation(location);
430 return {
431 parent: `projects/${project}/locations/${loc}/caPools/${caPool}`,
432 location: loc,
433 project,
434 };
435 };
436
437 const userLabels = (
438 labels: Record<string, string | undefined> | null | undefined,
439 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
440
441 const toId = (id: string, certificateAuthorityId: string | undefined, existing?: string) =>
442 Effect.gen(function* () {
443 return (
444 certificateAuthorityId ??
445 existing ??
446 (yield* createPhysicalName({
447 id,
448 maxLength: MAX_NAME_LENGTH,
449 lowercase: true,
450 }))
451 );
452 });
453
454 const keySpecOf = (
455 spec: privateca.KeyVersionSpec | KeyVersionSpec | undefined,
456 ): KeyVersionSpec | undefined => {
457 if (spec === undefined) return undefined;
458 return {
459 algorithm: spec.algorithm,
460 cloudKmsKeyVersion: spec.cloudKmsKeyVersion,
461 };
462 };
463
464 const urlsOf = (
465 urls: privateca.UserDefinedAccessUrls | UserDefinedAccessUrls | undefined,
466 ): UserDefinedAccessUrls | undefined => {
467 if (urls === undefined) return undefined;
468 return {
469 crlAccessUrls: urls.crlAccessUrls,
470 aiaIssuingCertificateUrls: urls.aiaIssuingCertificateUrls,
471 };
472 };
473
474 const subordinateOf = (
475 config: privateca.SubordinateConfig | SubordinateConfig | undefined,
476 ): SubordinateConfig | undefined => {
477 if (config === undefined) return undefined;
478 return {
479 certificateAuthority: config.certificateAuthority,
480 pemIssuerChain:
481 config.pemIssuerChain === undefined
482 ? undefined
483 : { pemCertificates: config.pemIssuerChain.pemCertificates },
484 };
485 };
486
487 const toAttrs = (
488 ca: privateca.CertificateAuthority,
489 project: string,
490 ): CertificateAuthorityAttrs => {
491 const name = ca.name ?? "";
492 const parsed = parseName(name);
493 return {
494 name,
495 certificateAuthorityId: parsed.certificateAuthorityId,
496 caPool: parsed.caPool,
497 project: parsed.project || project,
498 location: parsed.location,
499 type: normalizeType(ca.type),
500 state: ca.state,
501 tier: ca.tier,
502 labels: userLabels(ca.labels),
503 lifetime: ca.lifetime,
504 keySpec: keySpecOf(ca.keySpec),
505 gcsBucket: ca.gcsBucket,
506 pemCaCertificates: ca.pemCaCertificates ?? [],
507 userDefinedAccessUrls: urlsOf(ca.userDefinedAccessUrls),
508 subordinateConfig: subordinateOf(ca.subordinateConfig),
509 caCertificateUrl: ca.accessUrls?.caCertificateAccessUrl,
510 crlAccessUrl: ca.accessUrls?.crlAccessUrls?.[0],
511 createTime: ca.createTime,
512 updateTime: ca.updateTime,
513 deleteTime: ca.deleteTime,
514 expireTime: ca.expireTime,
515 };
516 };
517
518 const defaultConfig = (certificateAuthorityId: string): CertificateConfig => ({
519 subjectConfig: {
520 subject: {
521 organization: "Alchemy",
522 commonName: certificateAuthorityId,
523 },
524 },
525 x509Config: {
526 caOptions: { isCa: true },
527 keyUsage: {
528 baseKeyUsage: {
529 certSign: true,
530 crlSign: true,
531 },
532 },
533 },
534 });
535
536 const toCreateBody = (
537 news: CertificateAuthorityProps,
538 certificateAuthorityId: string,
539 desiredLabels: Record<string, string>,
540 ): privateca.CertificateAuthority => {
541 const config = news.config ?? defaultConfig(certificateAuthorityId);
542 return {
543 type: normalizeType(news.type),
544 lifetime: news.lifetime ?? DEFAULT_LIFETIME,
545 keySpec: {
546 algorithm: news.keySpec?.algorithm ?? DEFAULT_ALGORITHM,
547 cloudKmsKeyVersion: news.keySpec?.cloudKmsKeyVersion,
548 },
549 config: {
550 subjectConfig: config.subjectConfig,
551 x509Config: config.x509Config,
552 },
553 labels: desiredLabels,
554 gcsBucket: news.gcsBucket,
555 userDefinedAccessUrls: news.userDefinedAccessUrls,
556 subordinateConfig: news.subordinateConfig,
557 };
558 };
559
560 const jsonKey = (value: unknown) => JSON.stringify(value ?? null);
561
562 const keySpecKey = (spec: KeyVersionSpec | undefined) =>
563 jsonKey({
564 algorithm: (spec?.algorithm ?? "").toUpperCase(),
565 cloudKmsKeyVersion: spec?.cloudKmsKeyVersion ?? "",
566 });
567
568 const urlsKey = (urls: UserDefinedAccessUrls | undefined) =>
569 jsonKey({
570 crl: [...(urls?.crlAccessUrls ?? [])].sort(),
571 aia: [...(urls?.aiaIssuingCertificateUrls ?? [])].sort(),
572 });
573
574 const subordinateKey = (config: SubordinateConfig | undefined) =>
575 jsonKey({
576 certificateAuthority: config?.certificateAuthority ?? "",
577 pemCertificates: [...(config?.pemIssuerChain?.pemCertificates ?? [])],
578 });
579
580 const configKey = (config: CertificateConfig | undefined) => jsonKey(config);
581
582 const getByName = (name: string) =>
583 privateca
584 .getProjectsLocationsCaPoolsCertificateAuthorities({ name })
585 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
586
587 /**
588 * Wait for a Certificate Authority Service operation; CA creation and
589 * activation take a few minutes. ALREADY_EXISTS (code 6) counts as success
590 * (create race); with `notFoundOk`, so does NOT_FOUND (code 5, delete race)
591 * and an operation that is already gone.
592 */
593 const waitForOperation = (operation: privateca.Operation, options?: { notFoundOk?: boolean }) =>
594 waitForGcpOperation(operation, (name) => privateca.getProjectsLocationsOperations({ name }), {
595 budget: "15 minutes",
596 }).pipe(
597 Effect.catchIf(
598 (error) =>
599 (error._tag === "GCP.OperationFailed" &&
600 (error.code === 6 || (options?.notFoundOk === true && error.code === 5))) ||
601 (options?.notFoundOk === true && error._tag === "NotFound"),
602 () => Effect.succeed(operation),
603 ),
604 );
605
606 const waitUntilExists = (name: string) =>
607 getByName(name).pipe(
608 Effect.flatMap((ca) =>
609 ca
610 ? Effect.succeed(ca)
611 : Effect.fail(new CertificateAuthorityNotResolved({ resourceName: name })),
612 ),
613 Effect.retry({
614 while: (error) => error._tag === "GCP.PrivateCA.CertificateAuthorityNotResolved",
615 times: 8,
616 schedule: Schedule.spaced("1 second"),
617 }),
618 );
619
620 const waitUntilSteady = (name: string) =>
621 getByName(name).pipe(
622 Effect.filterOrFail(
623 (ca): ca is privateca.CertificateAuthority => ca !== undefined,
624 () => new CertificateAuthorityNotResolved({ resourceName: name }),
625 ),
626 Effect.filterOrFail(
627 (ca) => STEADY_STATES.has((ca.state ?? "").toUpperCase()),
628 (ca) =>
629 new CertificateAuthorityNotReady({
630 resourceName: name,
631 state: ca.state ?? "STATE_UNSPECIFIED",
632 }),
633 ),
634 Effect.retry({
635 while: (error) =>
636 error._tag === "GCP.PrivateCA.CertificateAuthorityNotReady" ||
637 error._tag === "GCP.PrivateCA.CertificateAuthorityNotResolved",
638 times: 10,
639 schedule: Schedule.spaced("5 seconds"),
640 }),
641 );
642
643 const isGone = (ca: privateca.CertificateAuthority | undefined) =>
644 ca === undefined || (ca.state ?? "").toUpperCase() === "DELETED";
645
646 const waitUntilGone = (name: string) =>
647 getByName(name).pipe(
648 Effect.flatMap((ca) =>
649 isGone(ca)
650 ? Effect.void
651 : Effect.fail(new CertificateAuthorityStillExists({ resourceName: name })),
652 ),
653 Effect.retry({
654 while: (error) => error._tag === "GCP.PrivateCA.CertificateAuthorityStillExists",
655 times: 10,
656 schedule: Schedule.spaced("2 seconds"),
657 }),
658 );
659
660 const runOperation = (
661 operation: privateca.Operation | undefined,
662 options?: { notFoundOk?: boolean },
663 ) =>
664 operation === undefined ? Effect.void : waitForOperation(operation, options).pipe(Effect.asVoid);
665
666 const listOwned = (project: string) =>
667 privateca.listProjectsLocationsCaPoolsCertificateAuthorities
668 .pages({
669 parent: `projects/${project}/locations/-/caPools/-`,
670 pageSize: 1000,
671 })
672 .pipe(
673 Stream.flatMap((page) => Stream.fromIterable(page.certificateAuthorities ?? [])),
674 Stream.filter(
675 (ca) =>
676 (ca.state ?? "").toUpperCase() !== "DELETED" &&
677 Object.keys(ca.labels ?? {}).some((key) => key.startsWith("alchemy-")),
678 ),
679 Stream.map((ca) => toAttrs(ca, project)),
680 Stream.runCollect,
681 Effect.map((chunk) => Array.from(chunk)),
682 Effect.catchTag("NotFound", () => Effect.succeed([])),
683 );
684
685 const disableIfNeeded = (current: privateca.CertificateAuthority) => {
686 const name = current.name ?? "";
687 const state = (current.state ?? "").toUpperCase();
688 // STAGED / DISABLED / AWAITING_USER_ACTIVATION can be deleted directly.
689 // Disable is only valid from ENABLED.
690 if (state !== "ENABLED") {
691 return Effect.succeed(current);
692 }
693 return privateca
694 .disableProjectsLocationsCaPoolsCertificateAuthorities({
695 name,
696 body: { ignoreDependentResources: true },
697 })
698 .pipe(
699 Effect.catchTags({
700 NotFound: () => Effect.undefined,
701 BadRequest: () => Effect.undefined,
702 Conflict: () => Effect.undefined,
703 }),
704 Effect.flatMap((operation) => runOperation(operation)),
705 Effect.flatMap(() => waitUntilSteady(name)),
706 Effect.catchTag("GCP.PrivateCA.CertificateAuthorityNotResolved", () =>
707 Effect.succeed(current),
708 ),
709 );
710 };
711
712 const syncDesiredState = (
713 name: string,
714 current: privateca.CertificateAuthority,
715 desired: DesiredState,
716 ) => {
717 const state = (current.state ?? "").toUpperCase();
718 if (desired === "ENABLED" && (state === "STAGED" || state === "DISABLED")) {
719 return privateca
720 .enableProjectsLocationsCaPoolsCertificateAuthorities({
721 name,
722 body: {},
723 })
724 .pipe(
725 Effect.flatMap((operation) => waitForOperation(operation)),
726 Effect.catchTags({
727 BadRequest: () => Effect.void,
728 Conflict: () => Effect.void,
729 }),
730 Effect.flatMap(() => waitUntilSteady(name)),
731 );
732 }
733 if (desired === "DISABLED" && (state === "STAGED" || state === "ENABLED")) {
734 return privateca
735 .disableProjectsLocationsCaPoolsCertificateAuthorities({
736 name,
737 body: { ignoreDependentResources: true },
738 })
739 .pipe(
740 Effect.flatMap((operation) => waitForOperation(operation)),
741 Effect.catchTags({
742 BadRequest: () => Effect.void,
743 Conflict: () => Effect.void,
744 }),
745 Effect.flatMap(() => waitUntilSteady(name)),
746 );
747 }
748 return Effect.succeed(current);
749 };
750
751 const activateIfNeeded = (
752 name: string,
753 current: privateca.CertificateAuthority,
754 news: CertificateAuthorityProps,
755 ) => {
756 const state = (current.state ?? "").toUpperCase();
757 if (
758 state !== "AWAITING_USER_ACTIVATION" ||
759 news.pemCaCertificate === undefined ||
760 news.subordinateConfig === undefined
761 ) {
762 return Effect.succeed(current);
763 }
764 return privateca
765 .activateProjectsLocationsCaPoolsCertificateAuthorities({
766 name,
767 body: {
768 pemCaCertificate: news.pemCaCertificate,
769 subordinateConfig: news.subordinateConfig,
770 },
771 })
772 .pipe(
773 Effect.flatMap((operation) => waitForOperation(operation)),
774 Effect.flatMap(() => waitUntilSteady(name)),
775 );
776 };
777
778 const undeleteIfNeeded = (current: privateca.CertificateAuthority) => {
779 const name = current.name ?? "";
780 if ((current.state ?? "").toUpperCase() !== "DELETED") {
781 return Effect.succeed(current);
782 }
783 return privateca
784 .undeleteProjectsLocationsCaPoolsCertificateAuthorities({
785 name,
786 body: {},
787 })
788 .pipe(
789 Effect.flatMap((operation) => waitForOperation(operation)),
790 Effect.flatMap(() => waitUntilSteady(name)),
791 );
792 };
793
794 export const CertificateAuthorityProvider = () =>
795 Provider.succeed(CertificateAuthority, {
796 stables: [
797 "name",
798 "certificateAuthorityId",
799 "caPool",
800 "project",
801 "location",
802 "type",
803 "createTime",
804 ],
805
806 diff: Effect.fn(function* ({ news, olds, output }) {
807 if (!isResolved(news)) return undefined;
808 const env = yield* GcpEnvironment.current;
809
810 const previousId = olds?.certificateAuthorityId ?? output?.certificateAuthorityId;
811 const nextId = news.certificateAuthorityId ?? previousId;
812 const previousPool = olds?.caPool ?? output?.caPool ?? "";
813 const nextPool = news.caPool;
814 const previousLocation = normalizeLocation(olds?.location ?? output?.location ?? env.region);
815 const nextLocation = normalizeLocation(news.location ?? output?.location ?? env.region);
816 const previousType = normalizeType(olds?.type ?? output?.type);
817 const nextType = normalizeType(news.type ?? output?.type);
818 const previousLifetime = olds?.lifetime ?? output?.lifetime ?? "";
819 const nextLifetime = news.lifetime ?? previousLifetime;
820 const previousBucket = olds?.gcsBucket ?? output?.gcsBucket ?? "";
821 const nextBucket = news.gcsBucket ?? previousBucket;
822 const previousKey = keySpecKey(olds?.keySpec ?? output?.keySpec);
823 const nextKey = news.keySpec === undefined ? previousKey : keySpecKey(news.keySpec);
824 const configChanged =
825 news.config !== undefined &&
826 olds?.config !== undefined &&
827 configKey(news.config) !== configKey(olds.config);
828
829 const replace =
830 (previousId !== undefined && nextId !== undefined && nextId !== previousId) ||
831 (previousPool !== "" && nextPool !== previousPool) ||
832 previousLocation !== nextLocation ||
833 previousType !== nextType ||
834 previousLifetime !== nextLifetime ||
835 previousBucket !== nextBucket ||
836 previousKey !== nextKey ||
837 configChanged;
838
839 if (!replace) return undefined;
840 return {
841 action: "replace" as const,
842 deleteFirst:
843 previousLocation === nextLocation &&
844 previousPool === nextPool &&
845 previousId !== undefined &&
846 nextId === previousId,
847 };
848 }),
849
850 read: Effect.fn(function* ({ id, olds, output }) {
851 const env = yield* GcpEnvironment.current;
852 const caPool = olds?.caPool ?? output?.caPool;
853 // A recovery read of an interrupted create gets persisted props whose
854 // unresolved parent reference was stripped; without the parent there
855 // is no name to look up, so report nothing found rather than calling
856 // the API with an empty path segment.
857 if (output?.name === undefined && (typeof caPool !== "string" || caPool.length === 0)) {
858 return undefined;
859 }
860 const certificateAuthorityId = yield* toId(
861 id,
862 olds?.certificateAuthorityId,
863 output?.certificateAuthorityId,
864 );
865 const { parent } = resolveParent(
866 env.project,
867 typeof caPool === "string" ? caPool : "",
868 olds?.location ?? output?.location ?? env.region,
869 );
870 const name = output?.name ?? resourceName(parent, certificateAuthorityId);
871 if (name.endsWith("/certificateAuthorities/") || name.endsWith("/_")) {
872 return undefined;
873 }
874 const existing = yield* getByName(name);
875 if (existing === undefined) return undefined;
876 if ((existing.state ?? "").toUpperCase() === "DELETED") {
877 return undefined;
878 }
879 const attrs = toAttrs(existing, env.project);
880 return (yield* hasAlchemyLabels(id, tagRecord(existing.labels))) ? attrs : Unowned(attrs);
881 }),
882
883 list: () =>
884 Effect.gen(function* () {
885 const env = yield* GcpEnvironment.current;
886 return yield* listOwned(env.project);
887 }),
888
889 reconcile: Effect.fn(function* ({ id, news, output }) {
890 const env = yield* GcpEnvironment.current;
891 const certificateAuthorityId = yield* toId(
892 id,
893 news.certificateAuthorityId,
894 output?.certificateAuthorityId,
895 );
896 const { parent, project } = resolveParent(
897 env.project,
898 news.caPool,
899 news.location ?? output?.location ?? env.region,
900 );
901 const name = resourceName(parent, certificateAuthorityId);
902 const desiredLabels = {
903 ...toLabels(news.labels),
904 ...(yield* createInternalLabels(id)),
905 };
906 const desiredState = normalizeDesired(news.desiredState);
907
908 let current = yield* getByName(output?.name ?? name);
909
910 if (current === undefined) {
911 const created = yield* privateca
912 .createProjectsLocationsCaPoolsCertificateAuthorities({
913 parent,
914 certificateAuthorityId,
915 body: toCreateBody(news, certificateAuthorityId, desiredLabels),
916 })
917 .pipe(Effect.catchTag("Conflict", () => Effect.undefined));
918 yield* runOperation(created);
919 current = yield* waitUntilExists(name);
920 }
921
922 if (current === undefined) {
923 return yield* new CertificateAuthorityNotResolved({ resourceName: name });
924 }
925
926 current = yield* undeleteIfNeeded(current);
927
928 if (!STEADY_STATES.has((current.state ?? "").toUpperCase())) {
929 current = yield* waitUntilSteady(name);
930 }
931
932 current = yield* activateIfNeeded(name, current, news);
933
934 const observedLabels = tagRecord(current.labels);
935 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
936 const labelsChanged = upsert.length > 0 || removed.length > 0;
937 const urlsChanged =
938 news.userDefinedAccessUrls !== undefined &&
939 urlsKey(urlsOf(current.userDefinedAccessUrls)) !== urlsKey(news.userDefinedAccessUrls);
940 const subordinateChanged =
941 news.subordinateConfig !== undefined &&
942 subordinateKey(subordinateOf(current.subordinateConfig)) !==
943 subordinateKey(news.subordinateConfig);
944
945 if (labelsChanged || urlsChanged || subordinateChanged) {
946 const updateMask = [
947 labelsChanged ? "labels" : undefined,
948 urlsChanged ? "userDefinedAccessUrls" : undefined,
949 subordinateChanged ? "subordinateConfig" : undefined,
950 ].filter((field): field is string => field !== undefined);
951
952 const patched = yield* privateca
953 .patchProjectsLocationsCaPoolsCertificateAuthorities({
954 name,
955 updateMask: updateMask.join(","),
956 body: {
957 name,
958 labels: desiredLabels,
959 userDefinedAccessUrls: news.userDefinedAccessUrls,
960 subordinateConfig: news.subordinateConfig,
961 },
962 })
963 .pipe(Effect.catchTag("BadRequest", () => Effect.undefined));
964 yield* runOperation(patched);
965 current = yield* waitUntilSteady(name);
966 }
967
968 current = yield* syncDesiredState(name, current, desiredState);
969
970 return toAttrs(current, project);
971 }),
972
973 delete: Effect.fn(function* ({ output }) {
974 const name = output.name;
975 const existing = yield* getByName(name);
976 if (existing === undefined) return;
977
978 if ((existing.state ?? "").toUpperCase() !== "DELETED") {
979 yield* disableIfNeeded(existing);
980 const operation = yield* privateca
981 .deleteProjectsLocationsCaPoolsCertificateAuthorities({
982 name,
983 skipGracePeriod: true,
984 ignoreActiveCertificates: true,
985 ignoreDependentResources: true,
986 })
987 .pipe(
988 Effect.catchTags({
989 NotFound: () => Effect.undefined,
990 BadRequest: () => Effect.undefined,
991 }),
992 Effect.retry({
993 while: (error) => error._tag === "Conflict",
994 times: 8,
995 schedule: Schedule.spaced("5 seconds"),
996 }),
997 );
998 yield* runOperation(operation, { notFoundOk: true });
999 }
1000
1001 yield* waitUntilGone(name);
1002 }),
1003 });