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

main
ts 936 lines 30.7 KB
Raw
1 import * as kms from "@distilled.cloud/gcp/cloudkms_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 { tagRecord } from "alchemy/Tags";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { GcpEnvironment } from "../Environment.ts";
11 import {
12 createInternalLabels,
13 diffLabels,
14 hasAlchemyLabels,
15 stripInternalLabels,
16 toLabels,
17 } from "../Labels.ts";
18 import {
19 type OperationFailed,
20 type OperationTimedOut,
21 waitForOperation as waitForGcpOperation,
22 } from "../Operation.ts";
23 import type { Providers } from "../Providers.ts";
24 import { deterministicKmsId } from "./internal.ts";
25
26 const DEFAULT_PURPOSE: kms.CryptoKeyPurposeEnum = "ENCRYPT_DECRYPT";
27 const DEFAULT_ALGORITHM: kms.CryptoKeyVersionTemplateAlgorithmEnum = "GOOGLE_SYMMETRIC_ENCRYPTION";
28 const DEFAULT_PROTECTION: kms.CryptoKeyVersionTemplateProtectionLevelEnum = "SOFTWARE";
29 const DELETABLE_VERSION_STATES = new Set(["DESTROYED", "IMPORT_FAILED", "GENERATION_FAILED"]);
30 const DESTROYABLE_VERSION_STATES = new Set(["ENABLED", "DISABLED"]);
31 const USABLE_VERSION_STATES = new Set(["ENABLED", "PENDING_GENERATION"]);
32
33 /**
34 * Cloud KMS never deletes a key while any version is merely
35 * `DESTROY_SCHEDULED` (at least 24h), never deletes a key ring, and
36 * retires a deleted key's name forever. On delete Alchemy therefore never
37 * deletes the key: it destroys every version and replaces the ownership
38 * labels with this marker. A released key holds no usable key material, so
39 * any stack may reclaim it on create: reconcile re-stamps ownership and
40 * mints a fresh primary. This keeps both fixed and default (deterministic)
41 * `cryptoKeyId`s reusable across destroy/redeploy cycles.
42 */
43 export const RELEASED_LABEL = "alchemy-released";
44
45 const isReleased = (key: kms.CryptoKey) => (key.labels ?? {})[RELEASED_LABEL] !== undefined;
46
47 export type CryptoKeyVersionTemplate = {
48 /**
49 * Algorithm for new versions. Defaults to `GOOGLE_SYMMETRIC_ENCRYPTION`
50 * when `purpose` is `ENCRYPT_DECRYPT`.
51 */
52 algorithm?: kms.CryptoKeyVersionTemplateAlgorithmEnum | (string & {});
53 /**
54 * Protection level for new versions. Immutable — changing it replaces
55 * the key.
56 * @default "SOFTWARE"
57 */
58 protectionLevel?: kms.CryptoKeyVersionTemplateProtectionLevelEnum | (string & {});
59 };
60
61 export type CryptoKeyProps = {
62 /**
63 * Parent KeyRing. Full name
64 * `projects/{project}/locations/{location}/keyRings/{keyRing}` or the
65 * key ring id (combined with `location`). Immutable — changing it
66 * replaces the key.
67 */
68 keyRing: string;
69 /**
70 * Cloud KMS location (`us-central1`, `global`, `us`, …). Used when
71 * `keyRing` is a bare id. Immutable — changing it replaces the key.
72 * `US-CENTRAL1` is accepted and normalized to `us-central1`.
73 * @default the stack's GCP region (`GCP.Region`, profile region, `us-central1`)
74 */
75 location?: string;
76 /**
77 * CryptoKey id (the last path segment). If omitted, a deterministic
78 * name `{stack}-{id}-{stage}` is derived (no random suffix), plus a short
79 * hash of `purpose`, `versionTemplate.protectionLevel`, `importOnly`,
80 * `destroyScheduledDuration`, and `cryptoKeyBackend` when any differ
81 * from their defaults — so a redeploy after destroy reclaims the same
82 * key, and a replacement caused by those settings gets a distinct name.
83 * Must match `[a-zA-Z0-9_-]{1,63}`. Immutable — changing it replaces the
84 * key.
85 */
86 cryptoKeyId?: string;
87 /**
88 * Immutable purpose of this key.
89 * @default "ENCRYPT_DECRYPT"
90 */
91 purpose?: kms.CryptoKeyPurposeEnum;
92 /**
93 * Template for new CryptoKeyVersions. `protectionLevel` is immutable
94 * (replacement); `algorithm` can be patched.
95 */
96 versionTemplate?: CryptoKeyVersionTemplate;
97 /**
98 * User labels. Alchemy ownership labels are merged in automatically.
99 */
100 labels?: Record<string, string>;
101 /**
102 * Automatic rotation period (e.g. `"2592000s"`). ENCRYPT_DECRYPT keys
103 * only. Must be paired with `nextRotationTime` (Alchemy fills
104 * `now + period` when omitted).
105 */
106 rotationPeriod?: string;
107 /**
108 * RFC3339 time of the next automatic rotation. ENCRYPT_DECRYPT keys
109 * only.
110 */
111 nextRotationTime?: string;
112 /**
113 * How long versions stay in `DESTROY_SCHEDULED` before `DESTROYED`.
114 * Immutable. Minimum 24h except import-only keys.
115 */
116 destroyScheduledDuration?: string;
117 /**
118 * Create the key with no versions (and keep it version-less when a
119 * released key is reclaimed), e.g. for import-only or externally
120 * managed material.
121 * @default false
122 */
123 skipInitialVersionCreation?: boolean;
124 /**
125 * Whether this key may contain imported versions only. Immutable.
126 * @default false
127 */
128 importOnly?: boolean;
129 /**
130 * Backend for EXTERNAL_VPC / HSM_SINGLE_TENANT keys. Immutable.
131 */
132 cryptoKeyBackend?: string;
133 };
134
135 export type CryptoKeyAttrs = {
136 /** Full resource name `projects/.../cryptoKeys/{cryptoKey}`. */
137 name: string;
138 /** CryptoKey id (last path segment). */
139 cryptoKeyId: string;
140 /** Parent KeyRing resource name. */
141 keyRing: string;
142 /** Location id (`us-central1`, `global`, …). */
143 location: string;
144 /** Project id. */
145 project: string;
146 /** Key purpose. */
147 purpose: string;
148 /** User labels (Alchemy ownership labels stripped). */
149 labels: Record<string, string>;
150 /** Version template currently applied. */
151 versionTemplate: CryptoKeyVersionTemplate | undefined;
152 /** Automatic rotation period, if set. */
153 rotationPeriod: string | undefined;
154 /** Next automatic rotation time, if set. */
155 nextRotationTime: string | undefined;
156 /** Scheduled-destruction duration. */
157 destroyScheduledDuration: string | undefined;
158 /** Whether the key is import-only. */
159 importOnly: boolean;
160 /** External / single-tenant HSM backend, if any. */
161 cryptoKeyBackend: string | undefined;
162 /** Primary version resource name, if any. */
163 primaryVersion: string | undefined;
164 /** RFC3339 creation timestamp. */
165 createTime: string | undefined;
166 };
167
168 export type CryptoKey = Resource<
169 "GCP.KMS.CryptoKey",
170 CryptoKeyProps,
171 CryptoKeyAttrs,
172 never,
173 Providers
174 >;
175
176 /**
177 * A Cloud KMS CryptoKey — a named key that holds zero or more versions.
178 *
179 * Purpose, location, parent KeyRing, import-only, backend,
180 * `destroyScheduledDuration`, and `versionTemplate.protectionLevel` are
181 * immutable (changing them replaces the key). Labels, rotation, and
182 * `versionTemplate.algorithm` update in place.
183 *
184 * Cloud KMS only permanently deletes a CryptoKey after every version is
185 * gone, and a deleted CryptoKey's name is retired forever — it can never
186 * be created again in the project.
187 *
188 * Destroying a key therefore *releases* it instead of deleting it: every
189 * version is scheduled for destruction and the ownership labels are
190 * replaced by `alchemy-released`. A later deploy with the same
191 * `cryptoKeyId` — from this stack or any other — reclaims the released key
192 * and mints a fresh primary version. The default `cryptoKeyId` is
193 * deterministic per stack, stage, and logical id, so destroy/redeploy
194 * cycles reuse one key rather than leaving a new released key behind each
195 * time. Ciphertext encrypted under the old versions is not recoverable.
196 *
197 * ### Creating a CryptoKey
198 * **Example:** Generated name on an existing KeyRing
199 * ```typescript
200 * const ring = yield* GCP.KMS.KeyRing("Keys", {});
201 * const key = yield* GCP.KMS.CryptoKey("Data", {
202 * keyRing: ring.name,
203 * });
204 * ```
205 *
206 * **Example:** Explicit id, labels, and no initial version
207 * ```typescript
208 * const key = yield* GCP.KMS.CryptoKey("Data", {
209 * keyRing: ring.name,
210 * cryptoKeyId: "app-data",
211 * labels: { env: "prod" },
212 * skipInitialVersionCreation: true,
213 * });
214 * ```
215 *
216 * ### Encrypting and Decrypting
217 * **Example:** Encrypt then decrypt
218 * ```typescript
219 * const encrypt = yield* GCP.KMS.Encrypt(key);
220 * const decrypt = yield* GCP.KMS.Decrypt(key);
221 * const { ciphertext } = yield* encrypt({
222 * body: { plaintext: btoa("hello") },
223 * });
224 * const { plaintext } = yield* decrypt({
225 * body: { ciphertext },
226 * });
227 * ```
228 *
229 * @resource
230 * @category KMS
231 */
232 export const CryptoKey = Resource<CryptoKey>("GCP.KMS.CryptoKey");
233
234 export class CryptoKeyNotResolved extends Data.TaggedError("GCP.KMS.CryptoKeyNotResolved")<{
235 resourceName: string;
236 }> {}
237
238 export class CryptoKeyOperationFailed extends Data.TaggedError("GCP.KMS.CryptoKeyOperationFailed")<{
239 operation: string;
240 message: string;
241 }> {}
242
243 export class CryptoKeyVersionPending extends Data.TaggedError("GCP.KMS.CryptoKeyVersionPending")<{
244 resourceName: string;
245 state: string;
246 }> {}
247
248 const lastSegment = (value: string) => {
249 const trimmed = value.replace(/\/+$/, "");
250 const parts = trimmed.split("/");
251 return parts[parts.length - 1] || trimmed;
252 };
253
254 const normalizeLocation = (location: string | undefined, fallback: string) =>
255 lastSegment(location ?? fallback).toLowerCase();
256
257 const normalizeProtection = (
258 value: string | undefined,
259 ): kms.CryptoKeyVersionTemplateProtectionLevelEnum =>
260 !value || value === "PROTECTION_LEVEL_UNSPECIFIED"
261 ? DEFAULT_PROTECTION
262 : (value as kms.CryptoKeyVersionTemplateProtectionLevelEnum);
263
264 const parseName = (name: string, fallbackLocation: string) => {
265 const parts = name.split("/").filter((part) => part.length > 0);
266 const cryptoKeysAt = parts.lastIndexOf("cryptoKeys");
267 const keyRingsAt = parts.lastIndexOf("keyRings");
268 const locationsAt = parts.lastIndexOf("locations");
269 const projectsAt = parts.lastIndexOf("projects");
270 const keyRing = keyRingsAt >= 0 ? parts.slice(0, keyRingsAt + 2).join("/") : "";
271 return {
272 project: projectsAt >= 0 && parts[projectsAt + 1] ? parts[projectsAt + 1]! : "",
273 location:
274 locationsAt >= 0 && parts[locationsAt + 1] ? parts[locationsAt + 1]! : fallbackLocation,
275 keyRing,
276 cryptoKeyId:
277 cryptoKeysAt >= 0 && parts[cryptoKeysAt + 1] ? parts[cryptoKeysAt + 1]! : lastSegment(name),
278 };
279 };
280
281 const resolveParent = (
282 project: string,
283 keyRing: string,
284 location: string | undefined,
285 region: string,
286 ) => {
287 if (keyRing.includes("/")) {
288 const parsed = parseName(
289 keyRing.includes("/cryptoKeys/") ? keyRing : `${keyRing}/cryptoKeys/_`,
290 region,
291 );
292 return {
293 parent: parsed.keyRing,
294 location: parsed.location,
295 project: parsed.project || project,
296 };
297 }
298 const loc = normalizeLocation(location, region);
299 return {
300 parent: `projects/${project}/locations/${loc}/keyRings/${keyRing}`,
301 location: loc,
302 project,
303 };
304 };
305
306 const resourceName = (parent: string, cryptoKeyId: string) => `${parent}/cryptoKeys/${cryptoKeyId}`;
307
308 const userLabels = (
309 labels: Record<string, string | undefined> | null | undefined,
310 ): Record<string, string> => stripInternalLabels(tagRecord(labels));
311
312 type ImmutableKeyProps = Pick<
313 CryptoKeyProps,
314 "purpose" | "versionTemplate" | "importOnly" | "destroyScheduledDuration" | "cryptoKeyBackend"
315 >;
316
317 /**
318 * The replacement-triggering settings (besides id and parent) folded into
319 * the generated id, or `undefined` when all are defaults so the common
320 * case keeps the plain `{stack}-{id}-{stage}` name.
321 */
322 const immutableVariant = (props: ImmutableKeyProps | undefined) => {
323 const purpose = props?.purpose ?? DEFAULT_PURPOSE;
324 const protectionLevel = normalizeProtection(props?.versionTemplate?.protectionLevel);
325 const importOnly = props?.importOnly === true;
326 const destroyScheduledDuration = props?.destroyScheduledDuration;
327 const cryptoKeyBackend = props?.cryptoKeyBackend || undefined;
328 if (
329 purpose === DEFAULT_PURPOSE &&
330 protectionLevel === DEFAULT_PROTECTION &&
331 !importOnly &&
332 destroyScheduledDuration === undefined &&
333 cryptoKeyBackend === undefined
334 ) {
335 return undefined;
336 }
337 return {
338 purpose,
339 protectionLevel,
340 importOnly,
341 destroyScheduledDuration,
342 cryptoKeyBackend,
343 };
344 };
345
346 const toId = (
347 id: string,
348 props: (ImmutableKeyProps & { cryptoKeyId?: string }) | undefined,
349 existing?: string,
350 ) =>
351 Effect.gen(function* () {
352 return (
353 props?.cryptoKeyId ?? existing ?? (yield* deterministicKmsId(id, immutableVariant(props)))
354 );
355 });
356
357 const toAttrs = (key: kms.CryptoKey, project: string, region: string): CryptoKeyAttrs => {
358 const name = key.name ?? "";
359 const parsed = parseName(name, region);
360 const template = key.versionTemplate;
361 return {
362 name,
363 cryptoKeyId: parsed.cryptoKeyId,
364 keyRing: parsed.keyRing,
365 location: parsed.location,
366 project: parsed.project || project,
367 purpose: key.purpose ?? DEFAULT_PURPOSE,
368 labels: userLabels(key.labels),
369 versionTemplate:
370 template === undefined
371 ? undefined
372 : {
373 algorithm: template.algorithm,
374 protectionLevel: template.protectionLevel,
375 },
376 rotationPeriod: key.rotationPeriod,
377 nextRotationTime: key.nextRotationTime,
378 destroyScheduledDuration: key.destroyScheduledDuration,
379 importOnly: key.importOnly === true,
380 cryptoKeyBackend: key.cryptoKeyBackend,
381 primaryVersion: key.primary?.name,
382 createTime: key.createTime,
383 };
384 };
385
386 const getByName = (name: string) =>
387 kms
388 .getProjectsLocationsKeyRingsCryptoKeys({ name })
389 .pipe(Effect.catchTag("NotFound", () => Effect.undefined));
390
391 const paginate = <A, E, R>(
392 fetch: (
393 pageToken: string | undefined,
394 ) => Effect.Effect<{ items: A[]; nextPageToken?: string }, E, R>,
395 ) =>
396 Effect.gen(function* () {
397 const found: A[] = [];
398 let pageToken: string | undefined;
399 for (let page = 0; page < 10; page++) {
400 const response = yield* fetch(pageToken);
401 found.push(...response.items);
402 pageToken = response.nextPageToken;
403 if (pageToken === undefined || pageToken === "") break;
404 }
405 return found;
406 });
407
408 const listKeyRingsAt = (parent: string) =>
409 paginate((pageToken) =>
410 kms
411 .listProjectsLocationsKeyRings({
412 parent,
413 pageSize: 1000,
414 pageToken,
415 })
416 .pipe(
417 Effect.map((response) => ({
418 items: response.keyRings ?? [],
419 nextPageToken: response.nextPageToken,
420 })),
421 Effect.catchTag("NotFound", () =>
422 Effect.succeed({
423 items: [] as kms.KeyRing[],
424 nextPageToken: undefined,
425 }),
426 ),
427 ),
428 );
429
430 const listKeysInRing = (parent: string) =>
431 paginate((pageToken) =>
432 kms
433 .listProjectsLocationsKeyRingsCryptoKeys({
434 parent,
435 pageSize: 1000,
436 pageToken,
437 })
438 .pipe(
439 Effect.map((response) => ({
440 // Released keys hold no key material and belong to no stack.
441 items: (response.cryptoKeys ?? []).filter(
442 (key) =>
443 !isReleased(key) &&
444 Object.keys(key.labels ?? {}).some((label) => label.startsWith("alchemy-")),
445 ),
446 nextPageToken: response.nextPageToken,
447 })),
448 Effect.catchTag("NotFound", () =>
449 Effect.succeed({
450 items: [] as kms.CryptoKey[],
451 nextPageToken: undefined,
452 }),
453 ),
454 ),
455 );
456
457 const listCryptoKeysAt = (locationParent: string) =>
458 Effect.gen(function* () {
459 const rings = yield* listKeyRingsAt(locationParent);
460 const pages = yield* Effect.forEach(
461 rings,
462 (ring) => (ring.name ? listKeysInRing(ring.name) : Effect.succeed([] as kms.CryptoKey[])),
463 { concurrency: 4 },
464 );
465 return pages.flat();
466 });
467
468 const listVersions = (parent: string) =>
469 paginate((pageToken) =>
470 kms
471 .listProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({
472 parent,
473 pageSize: 1000,
474 pageToken,
475 })
476 .pipe(
477 Effect.map((response) => ({
478 items: response.cryptoKeyVersions ?? [],
479 nextPageToken: response.nextPageToken,
480 })),
481 Effect.catchTag("NotFound", () =>
482 Effect.succeed({
483 items: [] as kms.CryptoKeyVersion[],
484 nextPageToken: undefined,
485 }),
486 ),
487 ),
488 );
489
490 const waitOperation = (operation: kms.Operation) =>
491 waitForGcpOperation(operation, (name) => kms.getProjectsLocationsOperations({ name }), {
492 budget: "10 minutes",
493 }).pipe(
494 // Re-read the finished operation for its typed response.
495 Effect.flatMap(() =>
496 operation.name === undefined
497 ? Effect.succeed(operation)
498 : kms.getProjectsLocationsOperations({ name: operation.name }),
499 ),
500 );
501
502 const waitPrimaryReady = (
503 name: string,
504 ): Effect.Effect<
505 kms.CryptoKey,
506 | CryptoKeyNotResolved
507 | CryptoKeyOperationFailed
508 | CryptoKeyVersionPending
509 | kms.GetProjectsLocationsKeyRingsCryptoKeysError,
510 kms.GcpOpContext
511 > => {
512 const probe: Effect.Effect<
513 kms.CryptoKey,
514 | CryptoKeyNotResolved
515 | CryptoKeyOperationFailed
516 | CryptoKeyVersionPending
517 | kms.GetProjectsLocationsKeyRingsCryptoKeysError,
518 kms.GcpOpContext
519 > = getByName(name).pipe(
520 Effect.flatMap(
521 (
522 key,
523 ): Effect.Effect<
524 kms.CryptoKey,
525 CryptoKeyNotResolved | CryptoKeyOperationFailed | CryptoKeyVersionPending
526 > => {
527 if (key === undefined) {
528 return Effect.fail(new CryptoKeyNotResolved({ resourceName: name }));
529 }
530 const state = key.primary?.state;
531 if (state === undefined || state === "ENABLED") {
532 return Effect.succeed(key);
533 }
534 if (state === "GENERATION_FAILED") {
535 return Effect.fail(
536 new CryptoKeyOperationFailed({
537 operation: key.primary?.name ?? name,
538 message: key.primary?.generationFailureReason ?? state,
539 }),
540 );
541 }
542 return Effect.fail(
543 new CryptoKeyVersionPending({
544 resourceName: name,
545 state,
546 }),
547 );
548 },
549 ),
550 );
551 return probe.pipe(
552 Effect.retry({
553 while: (error) => error._tag === "GCP.KMS.CryptoKeyVersionPending",
554 times: 8,
555 schedule: Schedule.spaced("500 millis"),
556 }),
557 );
558 };
559
560 const desiredAlgorithm = (
561 purpose: kms.CryptoKeyPurposeEnum,
562 template: CryptoKeyVersionTemplate | undefined,
563 ) =>
564 template?.algorithm ?? (purpose === "ENCRYPT_DECRYPT" ? DEFAULT_ALGORITHM : template?.algorithm);
565
566 const nextRotationFromPeriod = (period: string) =>
567 Effect.sync(() => {
568 const match = /^(\d+)s$/.exec(period);
569 const seconds = match ? Number(match[1]) : 86_400;
570 return new Date(Date.now() + seconds * 1000).toISOString();
571 });
572
573 const destroyVersion = (name: string) =>
574 kms
575 .destroyProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({
576 name,
577 body: {},
578 })
579 .pipe(
580 Effect.catchTags({
581 NotFound: () => Effect.void,
582 BadRequest: () => Effect.void,
583 Conflict: () => Effect.void,
584 }),
585 );
586
587 const deleteVersion = (name: string) =>
588 kms.deleteProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({ name }).pipe(
589 Effect.catchTags({
590 NotFound: () => Effect.undefined,
591 BadRequest: () => Effect.undefined,
592 Conflict: () => Effect.undefined,
593 }),
594 Effect.flatMap(
595 (
596 operation,
597 ): Effect.Effect<
598 void,
599 | CryptoKeyOperationFailed
600 | OperationFailed
601 | OperationTimedOut
602 | kms.GetProjectsLocationsOperationsError,
603 kms.GcpOpContext
604 > => (operation === undefined ? Effect.void : waitOperation(operation).pipe(Effect.asVoid)),
605 ),
606 );
607
608 const clearRotation = (name: string, current: kms.CryptoKey) => {
609 if (!current.rotationPeriod && !current.nextRotationTime) {
610 return Effect.void;
611 }
612 return kms
613 .patchProjectsLocationsKeyRingsCryptoKeys({
614 name,
615 updateMask: "rotationPeriod,nextRotationTime",
616 body: {},
617 })
618 .pipe(
619 Effect.catchTag("NotFound", () => Effect.void),
620 Effect.asVoid,
621 );
622 };
623
624 /**
625 * Mark a key reclaimable: keep user labels, drop the stack/stage/id
626 * ownership labels, and add {@link RELEASED_LABEL}.
627 */
628 const releaseKey = (name: string, current: kms.CryptoKey) =>
629 isReleased(current)
630 ? Effect.void
631 : kms
632 .patchProjectsLocationsKeyRingsCryptoKeys({
633 name,
634 updateMask: "labels",
635 body: {
636 labels: { ...userLabels(current.labels), [RELEASED_LABEL]: "true" },
637 },
638 })
639 .pipe(
640 Effect.catchTag("NotFound", () => Effect.void),
641 Effect.asVoid,
642 );
643
644 /**
645 * Give a key usable material when it has none — a reclaimed released key,
646 * or one whose versions were destroyed out of band. Symmetric keys also
647 * need that version as their primary.
648 */
649 const ensureUsableVersion = (
650 name: string,
651 current: kms.CryptoKey,
652 purpose: kms.CryptoKeyPurposeEnum | (string & {}),
653 ) =>
654 Effect.gen(function* () {
655 const symmetric = purpose === "ENCRYPT_DECRYPT";
656 if (symmetric && USABLE_VERSION_STATES.has(current.primary?.state ?? "")) {
657 return current;
658 }
659 const versions = yield* listVersions(name);
660 let usable = versions.find((version) => USABLE_VERSION_STATES.has(version.state ?? ""));
661 if (usable === undefined) {
662 usable = yield* kms.createProjectsLocationsKeyRingsCryptoKeysCryptoKeyVersions({
663 parent: name,
664 body: {},
665 });
666 }
667 if (!symmetric) return current;
668 const versionId = lastSegment(usable.name ?? "");
669 yield* kms.updatePrimaryVersionProjectsLocationsKeyRingsCryptoKeys({
670 name,
671 body: { cryptoKeyVersionId: versionId },
672 });
673 return yield* waitPrimaryReady(name);
674 });
675
676 export const CryptoKeyProvider = () =>
677 Provider.succeed(CryptoKey, {
678 stables: [
679 "name",
680 "cryptoKeyId",
681 "keyRing",
682 "location",
683 "project",
684 "purpose",
685 "destroyScheduledDuration",
686 "importOnly",
687 "cryptoKeyBackend",
688 "createTime",
689 ],
690
691 diff: Effect.fn(function* ({ news, olds, output }) {
692 if (!isResolved(news)) return undefined;
693 const env = yield* GcpEnvironment.current;
694
695 const previousId = olds?.cryptoKeyId ?? output?.cryptoKeyId;
696 const nextId = news.cryptoKeyId ?? previousId;
697 const idChanged = previousId !== undefined && nextId !== undefined && nextId !== previousId;
698
699 const previousParent =
700 output?.keyRing ??
701 (olds?.keyRing
702 ? resolveParent("", olds.keyRing, olds.location, env.region).parent
703 : undefined);
704 const nextParent = resolveParent(
705 output?.project ?? "",
706 news.keyRing,
707 news.location ?? output?.location,
708 env.region,
709 ).parent;
710 const parentChanged = previousParent !== undefined && previousParent !== nextParent;
711
712 const previousPurpose = olds?.purpose ?? output?.purpose ?? DEFAULT_PURPOSE;
713 const nextPurpose = news.purpose ?? DEFAULT_PURPOSE;
714 const previousProtection = normalizeProtection(
715 olds?.versionTemplate?.protectionLevel ?? output?.versionTemplate?.protectionLevel,
716 );
717 const nextProtection = normalizeProtection(news.versionTemplate?.protectionLevel);
718 const previousImportOnly = olds?.importOnly ?? output?.importOnly ?? false;
719 const nextImportOnly = news.importOnly === true;
720 const previousDuration = olds?.destroyScheduledDuration ?? output?.destroyScheduledDuration;
721 const nextDuration = news.destroyScheduledDuration;
722 const previousBackend = olds?.cryptoKeyBackend ?? output?.cryptoKeyBackend;
723 const nextBackend = news.cryptoKeyBackend;
724
725 const replace =
726 idChanged ||
727 parentChanged ||
728 previousPurpose !== nextPurpose ||
729 previousProtection !== nextProtection ||
730 previousImportOnly !== nextImportOnly ||
731 (previousDuration !== undefined &&
732 nextDuration !== undefined &&
733 previousDuration !== nextDuration) ||
734 (previousBackend ?? "") !== (nextBackend ?? "");
735
736 if (!replace) return undefined;
737 return {
738 action: "replace" as const,
739 // A generated id folds every replacement trigger except the parent
740 // into its hash, and a parent change moves rings, so the new
741 // generation never collides with the old one. Only a fixed id
742 // reused in the same ring must release the old key first.
743 deleteFirst:
744 news.cryptoKeyId !== undefined &&
745 previousId !== undefined &&
746 nextId === previousId &&
747 !parentChanged,
748 };
749 }),
750
751 read: Effect.fn(function* ({ id, olds, output }) {
752 const env = yield* GcpEnvironment.current;
753 const cryptoKeyId = yield* toId(id, olds, output?.cryptoKeyId);
754 const name =
755 output?.name ??
756 (olds?.keyRing || output?.keyRing
757 ? resourceName(
758 resolveParent(
759 env.project,
760 olds?.keyRing ?? output?.keyRing ?? "",
761 olds?.location ?? output?.location,
762 env.region,
763 ).parent,
764 cryptoKeyId,
765 )
766 : undefined);
767 if (name === undefined) return undefined;
768 const existing = yield* getByName(name);
769 if (existing === undefined) return undefined;
770 const attrs = toAttrs(existing, env.project, env.region);
771 return isReleased(existing) || (yield* hasAlchemyLabels(id, tagRecord(existing.labels)))
772 ? attrs
773 : Unowned(attrs);
774 }),
775
776 list: () =>
777 Effect.gen(function* () {
778 const env = yield* GcpEnvironment.current;
779 const found: ReturnType<typeof toAttrs>[] = [];
780 let pageToken: string | undefined;
781 for (let page = 0; page < 10; page++) {
782 const response = yield* kms.listProjectsLocations({
783 name: `projects/${env.project}`,
784 pageSize: 100,
785 pageToken,
786 });
787 const parents = (response.locations ?? [])
788 .map((location) => location.name)
789 .filter((name): name is string => !!name);
790 const batches = yield* Effect.forEach(parents, (parent) => listCryptoKeysAt(parent), {
791 concurrency: 4,
792 });
793 for (const keys of batches) {
794 for (const key of keys) {
795 found.push(toAttrs(key, env.project, env.region));
796 }
797 }
798 pageToken = response.nextPageToken;
799 if (pageToken === undefined || pageToken === "") break;
800 }
801 return found;
802 }),
803
804 reconcile: Effect.fn(function* ({ id, news, output }) {
805 const env = yield* GcpEnvironment.current;
806 const cryptoKeyId = yield* toId(id, news, output?.cryptoKeyId);
807 const parent = resolveParent(
808 env.project,
809 news.keyRing,
810 news.location ?? output?.location,
811 env.region,
812 );
813 const name = resourceName(parent.parent, cryptoKeyId);
814 const purpose = news.purpose ?? DEFAULT_PURPOSE;
815 const algorithm = desiredAlgorithm(purpose, news.versionTemplate);
816 const protectionLevel = news.versionTemplate?.protectionLevel;
817 const desiredLabels = {
818 ...toLabels(news.labels),
819 ...(yield* createInternalLabels(id)),
820 };
821 const rotationPeriod = news.rotationPeriod;
822 const nextRotationTime = rotationPeriod
823 ? (news.nextRotationTime ?? (yield* nextRotationFromPeriod(rotationPeriod)))
824 : news.nextRotationTime;
825
826 let current = yield* getByName(name);
827
828 if (current === undefined) {
829 const created = yield* kms
830 .createProjectsLocationsKeyRingsCryptoKeys({
831 parent: parent.parent,
832 cryptoKeyId,
833 skipInitialVersionCreation: news.skipInitialVersionCreation,
834 body: {
835 purpose,
836 labels: desiredLabels,
837 versionTemplate: {
838 algorithm,
839 protectionLevel,
840 },
841 rotationPeriod,
842 nextRotationTime,
843 destroyScheduledDuration: news.destroyScheduledDuration,
844 importOnly: news.importOnly,
845 cryptoKeyBackend: news.cryptoKeyBackend,
846 },
847 })
848 .pipe(Effect.catchTag("Conflict", () => getByName(name)));
849 current = created ?? undefined;
850 if (
851 current !== undefined &&
852 news.skipInitialVersionCreation !== true &&
853 current.primary?.state === "PENDING_GENERATION"
854 ) {
855 current = yield* waitPrimaryReady(name);
856 }
857 }
858
859 if (current === undefined) {
860 return yield* new CryptoKeyNotResolved({ resourceName: name });
861 }
862
863 const observedLabels = tagRecord(current.labels);
864 const { upsert, removed } = diffLabels(observedLabels, desiredLabels);
865 const labelsChanged = upsert.length > 0 || removed.length > 0;
866 const observedAlgorithm = current.versionTemplate?.algorithm;
867 const algorithmChanged = algorithm !== undefined && observedAlgorithm !== algorithm;
868 const rotationChanged =
869 (current.rotationPeriod ?? "") !== (rotationPeriod ?? "") ||
870 (news.nextRotationTime !== undefined &&
871 (current.nextRotationTime ?? "") !== news.nextRotationTime);
872
873 if (labelsChanged || algorithmChanged || rotationChanged) {
874 const updateMask = [
875 labelsChanged ? "labels" : undefined,
876 algorithmChanged ? "versionTemplate.algorithm" : undefined,
877 rotationChanged ? "rotationPeriod" : undefined,
878 rotationChanged ? "nextRotationTime" : undefined,
879 ]
880 .filter((field): field is string => field !== undefined)
881 .join(",");
882 current = yield* kms.patchProjectsLocationsKeyRingsCryptoKeys({
883 name,
884 updateMask,
885 body: {
886 labels: desiredLabels,
887 versionTemplate: algorithmChanged
888 ? {
889 algorithm,
890 protectionLevel: protectionLevel ?? current.versionTemplate?.protectionLevel,
891 }
892 : undefined,
893 rotationPeriod,
894 nextRotationTime,
895 },
896 });
897 }
898
899 if (news.skipInitialVersionCreation !== true && news.importOnly !== true) {
900 current = yield* ensureUsableVersion(name, current, purpose);
901 }
902
903 return toAttrs(current, env.project, env.region);
904 }),
905
906 delete: Effect.fn(function* ({ output }) {
907 const name = output.name;
908 const current = yield* getByName(name);
909 if (current === undefined) return;
910
911 yield* clearRotation(name, current);
912 yield* releaseKey(name, current);
913
914 const versions = yield* listVersions(name);
915 yield* Effect.forEach(
916 versions,
917 (version) => {
918 const versionName = version.name;
919 if (versionName === undefined) return Effect.void;
920 const state = version.state ?? "";
921 if (DESTROYABLE_VERSION_STATES.has(state)) {
922 return destroyVersion(versionName);
923 }
924 if (DELETABLE_VERSION_STATES.has(state)) {
925 return deleteVersion(versionName);
926 }
927 return Effect.void;
928 },
929 { concurrency: 4 },
930 );
931
932 // The key itself is never deleted: KMS retires a deleted key's name
933 // forever, which would make this id (fixed or the deterministic
934 // default) undeployable. The released key is reclaimed on redeploy.
935 }),
936 });