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

main
ts 630 lines 19.9 KB
Raw
1 import * as kms from "@distilled.cloud/aws/kms";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, diffTags } from "alchemy/Tags";
6 import { toWireDays } from "alchemy/Util/Duration";
7 import * as Data from "effect/Data";
8 import type * as Duration from "effect/Duration";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import * as Stream from "effect/Stream";
12 import type { AccountID } from "../Environment.ts";
13 import type { PolicyDocument } from "../IAM/Policy.ts";
14 import { normalizePolicyDocument, stringifyPolicyDocument } from "../IAM/Policy.ts";
15 import type { Providers } from "../Providers.ts";
16 import type { RegionID } from "../Region.ts";
17
18 export type KeyId = string;
19 export type KeyArn = `arn:aws:kms:${RegionID}:${AccountID}:key/${KeyId}`;
20
21 export type { KeySpec, KeyState, KeyUsageType } from "@distilled.cloud/aws/kms";
22
23 export interface KeyProps {
24 /**
25 * Description for the KMS key.
26 */
27 description?: string;
28 /**
29 * Cryptographic operations that the key supports.
30 * @default "ENCRYPT_DECRYPT"
31 */
32 keyUsage?: kms.KeyUsageType;
33 /**
34 * Type of key material for the KMS key.
35 * @default "SYMMETRIC_DEFAULT"
36 */
37 keySpec?: kms.KeySpec;
38 /**
39 * Key policy, either as a structured {@link PolicyDocument} or a raw JSON
40 * string (escape hatch). If omitted, AWS creates and manages the default
41 * key policy.
42 */
43 policy?: PolicyDocument | string;
44 /**
45 * Whether to bypass KMS policy lockout safety checks when creating or updating
46 * the key policy.
47 * @default false
48 */
49 bypassPolicyLockoutSafetyCheck?: boolean;
50 /**
51 * Whether the KMS key is enabled.
52 * @default true
53 */
54 enabled?: boolean;
55 /**
56 * Whether automatic key rotation is enabled.
57 * @default false
58 */
59 enableKeyRotation?: boolean;
60 /**
61 * Rotation period when automatic key rotation is enabled. Accepts any
62 * `Duration.Input` (e.g. `"90 days"`, `Duration.days(90)`; a bare number
63 * is milliseconds); the wire unit is whole days.
64 */
65 rotationPeriod?: Duration.Input;
66 /**
67 * Whether to create a multi-region primary key.
68 * @default false
69 */
70 multiRegion?: boolean;
71 /**
72 * Waiting period before AWS permanently deletes the key after destroy
73 * schedules deletion. Accepts any `Duration.Input` (e.g. `"7 days"`,
74 * `Duration.days(7)`; a bare number is milliseconds); the wire unit is
75 * whole days.
76 * @default 30 days
77 */
78 deletionWindow?: Duration.Input;
79 /**
80 * User-defined tags to apply to the key.
81 */
82 tags?: Record<string, string>;
83 }
84
85 export interface Key extends Resource<
86 "AWS.KMS.Key",
87 KeyProps,
88 {
89 keyId: KeyId;
90 keyArn: KeyArn;
91 description: string | undefined;
92 keyUsage: kms.KeyUsageType;
93 keySpec: kms.KeySpec;
94 keyState: kms.KeyState | undefined;
95 enabled: boolean;
96 keyRotationEnabled: boolean | undefined;
97 rotationPeriodInDays: number | undefined;
98 multiRegion: boolean;
99 policy: string | undefined;
100 deletionWindowInDays: number;
101 tags: Record<string, string>;
102 },
103 never,
104 Providers
105 > {}
106
107 /**
108 * A customer managed AWS KMS key.
109 *
110 * ### Creating Keys
111 * **Example:** Symmetric Encryption Key
112 * ```typescript
113 * import * as KMS from "@alchemy.run/aws/KMS";
114 *
115 * const key = yield* KMS.Key("AppKey", {
116 * description: "Application encryption key",
117 * enableKeyRotation: true,
118 * deletionWindow: "7 days",
119 * });
120 * ```
121 *
122 * ### Key Policies
123 * **Example:** Key with Inline Policy
124 * ```typescript
125 * const key = yield* KMS.Key("PolicyKey", {
126 * policy: {
127 * Version: "2012-10-17",
128 * Statement: [{
129 * Effect: "Allow",
130 * Principal: { AWS: "arn:aws:iam::123456789012:root" },
131 * Action: ["kms:*"],
132 * Resource: "*",
133 * }],
134 * },
135 * });
136 * ```
137 *
138 * ### Runtime Operations
139 * Bind the KMS crypto operations to the key inside a Lambda function.
140 * Each binding grants least-privilege IAM (the exact key ARN) and injects
141 * the `KeyId` automatically.
142 *
143 * **Example:** Encrypt and Decrypt from a Lambda Function
144 * ```typescript
145 * // init
146 * const key = yield* AWS.KMS.Key("AppKey");
147 * const encrypt = yield* AWS.KMS.Encrypt(key);
148 * const decrypt = yield* AWS.KMS.Decrypt(key);
149 *
150 * // runtime
151 * const { CiphertextBlob } = yield* encrypt({
152 * Plaintext: new TextEncoder().encode("secret"),
153 * });
154 * const { Plaintext } = yield* decrypt({ CiphertextBlob });
155 * ```
156 *
157 * **Example:** Envelope Encryption with a Data Key
158 * ```typescript
159 * // init
160 * const generateDataKey = yield* AWS.KMS.GenerateDataKey(key);
161 *
162 * // runtime — encrypt locally with the plaintext key, store the blob
163 * const { Plaintext, CiphertextBlob } = yield* generateDataKey({
164 * KeySpec: "AES_256",
165 * });
166 * ```
167 */
168 export const Key = Resource<Key>("AWS.KMS.Key");
169
170 const defaultKeyUsage = "ENCRYPT_DECRYPT" as const;
171 const defaultKeySpec = "SYMMETRIC_DEFAULT" as const;
172 const defaultDeletionWindowInDays = 30;
173
174 export const KeyProvider = () =>
175 Provider.succeed(Key, {
176 stables: ["keyId", "keyArn"],
177 list: () =>
178 Effect.gen(function* () {
179 const keys = yield* kms.listKeys.pages({}).pipe(
180 Stream.runCollect,
181 Effect.map((chunk) =>
182 Array.from(chunk).flatMap((page) =>
183 (page.Keys ?? [])
184 .map((key) => key.KeyId)
185 .filter((keyId): keyId is string => keyId !== undefined),
186 ),
187 ),
188 );
189
190 const hydrated = yield* Effect.forEach(
191 keys,
192 (keyId) =>
193 readKey({
194 keyId,
195 deletionWindowInDays: defaultDeletionWindowInDays,
196 }),
197 { concurrency: 5 },
198 );
199
200 return hydrated.filter(
201 (key): key is Key["Attributes"] =>
202 key !== undefined && key.keyState !== "PendingDeletion",
203 );
204 }),
205 read: Effect.fn(function* ({ olds = {}, output }) {
206 // KMS keys have no stable user-assignable identity — only a
207 // cloud-generated keyId — so there is nothing to adopt. We only refresh
208 // a key we already own (via output.keyId); with no prior output the
209 // engine treats this as a greenfield create and mints a fresh key.
210 if (!output?.keyId) return undefined;
211 return yield* readKey({
212 keyId: output.keyId,
213 deletionWindowInDays:
214 output.deletionWindowInDays ??
215 toWireDays(olds.deletionWindow) ??
216 defaultDeletionWindowInDays,
217 });
218 }),
219 diff: Effect.fn(function* ({ news = {}, olds = {} }) {
220 if (!isResolved(news)) return;
221 if (
222 (news.keyUsage ?? defaultKeyUsage) !== (olds.keyUsage ?? defaultKeyUsage) ||
223 (news.keySpec ?? defaultKeySpec) !== (olds.keySpec ?? defaultKeySpec) ||
224 (news.multiRegion ?? false) !== (olds.multiRegion ?? false)
225 ) {
226 return { action: "replace" } as const;
227 }
228 }),
229 reconcile: Effect.fn(function* ({ id, news = {}, output, session }) {
230 const internalTags = yield* createInternalTags(id);
231 const desiredTags = { ...internalTags, ...news.tags };
232 const keyUsage = news.keyUsage ?? defaultKeyUsage;
233 const keySpec = news.keySpec ?? defaultKeySpec;
234 const enabled = news.enabled ?? true;
235 const enableKeyRotation = news.enableKeyRotation ?? false;
236 const multiRegion = news.multiRegion ?? false;
237 const deletionWindowInDays = toWireDays(news.deletionWindow) ?? defaultDeletionWindowInDays;
238 const rotationPeriodInDays = toWireDays(news.rotationPeriod);
239 const desiredPolicy =
240 news.policy === undefined
241 ? undefined
242 : typeof news.policy === "string"
243 ? news.policy
244 : stringifyPolicyDocument(news.policy);
245
246 // Observe via the cached identifier only — no tag-based discovery. On a
247 // create or replacement the engine calls reconcile with
248 // `output === undefined`, so we fall through to `createKey` and mint a
249 // fresh key rather than adopting an unrelated one (which would collapse a
250 // replacement into a no-op).
251 let state = output?.keyId
252 ? yield* readKey({ keyId: output.keyId, deletionWindowInDays })
253 : undefined;
254
255 if (state?.keyState === "PendingDeletion") {
256 yield* kms
257 .cancelKeyDeletion({ KeyId: state.keyId })
258 .pipe(Effect.catchTag("NotFoundException", () => Effect.void));
259 state = yield* readKey({ keyId: state.keyId, deletionWindowInDays });
260 }
261
262 if (state === undefined) {
263 const created = yield* kms.createKey({
264 Description: news.description,
265 KeyUsage: keyUsage,
266 KeySpec: keySpec,
267 Policy: desiredPolicy,
268 BypassPolicyLockoutSafetyCheck: news.bypassPolicyLockoutSafetyCheck,
269 Tags: toKmsTags(desiredTags),
270 MultiRegion: multiRegion,
271 });
272 const keyId = created.KeyMetadata?.KeyId;
273 if (!keyId) {
274 return yield* Effect.die(new Error("createKey returned no key ID"));
275 }
276 state = yield* readKey({ keyId, deletionWindowInDays });
277 if (!state) {
278 return yield* Effect.die(new Error(`failed to read created KMS key ${keyId}`));
279 }
280 }
281
282 const desiredDescription = news.description ?? "";
283 if ((state.description ?? "") !== desiredDescription) {
284 yield* kms
285 .updateKeyDescription({
286 KeyId: state.keyId,
287 Description: desiredDescription,
288 })
289 .pipe(
290 Effect.retry({
291 while: isKmsEventuallyConsistent,
292 schedule: kmsRetrySchedule,
293 }),
294 );
295 }
296
297 if (enabled && !state.enabled) {
298 yield* kms.enableKey({ KeyId: state.keyId }).pipe(
299 Effect.retry({
300 while: isKmsEventuallyConsistent,
301 schedule: kmsRetrySchedule,
302 }),
303 );
304 }
305
306 if (desiredPolicy !== undefined && !samePolicy(state.policy, desiredPolicy)) {
307 yield* kms
308 .putKeyPolicy({
309 KeyId: state.keyId,
310 PolicyName: "default",
311 Policy: desiredPolicy,
312 BypassPolicyLockoutSafetyCheck: news.bypassPolicyLockoutSafetyCheck,
313 })
314 .pipe(
315 Effect.retry({
316 while: isKmsEventuallyConsistent,
317 schedule: kmsRetrySchedule,
318 }),
319 );
320 }
321
322 if (
323 enableKeyRotation &&
324 (state.keyRotationEnabled !== true ||
325 (rotationPeriodInDays !== undefined &&
326 state.rotationPeriodInDays !== rotationPeriodInDays))
327 ) {
328 yield* kms
329 .enableKeyRotation({
330 KeyId: state.keyId,
331 RotationPeriodInDays: rotationPeriodInDays,
332 })
333 .pipe(
334 Effect.retry({
335 while: isKmsEventuallyConsistent,
336 schedule: kmsRetrySchedule,
337 }),
338 );
339 } else if (!enableKeyRotation && state.keyRotationEnabled) {
340 yield* kms.disableKeyRotation({ KeyId: state.keyId }).pipe(
341 Effect.retry({
342 while: isKmsEventuallyConsistent,
343 schedule: kmsRetrySchedule,
344 }),
345 );
346 }
347
348 if (!enabled && state.enabled) {
349 yield* kms.disableKey({ KeyId: state.keyId }).pipe(
350 Effect.retry({
351 while: isKmsEventuallyConsistent,
352 schedule: kmsRetrySchedule,
353 }),
354 );
355 }
356
357 const observedTags = yield* listKeyTags(state.keyId);
358 const { removed, upsert } = diffTags(observedTags, desiredTags);
359 if (upsert.length > 0) {
360 yield* kms
361 .tagResource({
362 KeyId: state.keyId,
363 Tags: toKmsTags(Object.fromEntries(upsert.map((tag) => [tag.Key, tag.Value]))),
364 })
365 .pipe(
366 Effect.retry({
367 while: isKmsEventuallyConsistent,
368 schedule: kmsRetrySchedule,
369 }),
370 );
371 }
372 if (removed.length > 0) {
373 yield* kms
374 .untagResource({
375 KeyId: state.keyId,
376 TagKeys: removed,
377 })
378 .pipe(
379 Effect.retry({
380 while: isKmsEventuallyConsistent,
381 schedule: kmsRetrySchedule,
382 }),
383 );
384 }
385
386 const updated = yield* readConvergedKey({
387 keyId: state.keyId,
388 deletionWindowInDays,
389 desiredDescription,
390 desiredEnabled: enabled,
391 desiredKeyRotationEnabled: enableKeyRotation,
392 desiredPolicy,
393 desiredRotationPeriodInDays: rotationPeriodInDays,
394 desiredTags,
395 });
396
397 yield* session.note(updated.keyArn);
398 return updated;
399 }),
400 delete: Effect.fn(function* ({ output, session }) {
401 yield* kms
402 .scheduleKeyDeletion({
403 KeyId: output.keyId,
404 PendingWindowInDays: output.deletionWindowInDays,
405 })
406 .pipe(
407 Effect.catchTags({
408 NotFoundException: () => Effect.void,
409 KMSInvalidStateException: () => Effect.void,
410 }),
411 );
412
413 const remaining = yield* Effect.repeat(
414 kms.describeKey({ KeyId: output.keyId }).pipe(
415 Effect.map((response) => response.KeyMetadata?.KeyState),
416 Effect.catchTag("NotFoundException", () => Effect.undefined),
417 ),
418 {
419 schedule: Schedule.fixed("250 millis"),
420 until: (state) => state === undefined || state === "PendingDeletion",
421 times: 20,
422 },
423 );
424 if (remaining !== undefined && remaining !== "PendingDeletion") {
425 return yield* Effect.die(
426 new Error(`KMS key ${output.keyId} remained ${remaining} after scheduling deletion`),
427 );
428 }
429 yield* session.note(`Scheduled KMS key deletion: ${output.keyId}`);
430 }),
431 });
432
433 const readKey = Effect.fn(function* ({
434 keyId,
435 deletionWindowInDays,
436 }: {
437 keyId: string;
438 deletionWindowInDays: number;
439 }) {
440 const described = yield* kms
441 .describeKey({ KeyId: keyId })
442 .pipe(Effect.catchTag("NotFoundException", () => Effect.undefined));
443
444 const metadata = described?.KeyMetadata;
445 if (!metadata?.Arn) return undefined;
446 if (metadata.KeyManager !== undefined && metadata.KeyManager !== "CUSTOMER") {
447 return undefined;
448 }
449
450 const [tags, rotation, policy] = yield* Effect.all(
451 [listKeyTags(metadata.KeyId), readKeyRotation(metadata.KeyId), readKeyPolicy(metadata.KeyId)],
452 { concurrency: "unbounded" },
453 );
454
455 return toAttrs({
456 metadata,
457 tags,
458 rotation,
459 policy,
460 deletionWindowInDays,
461 });
462 });
463
464 const readConvergedKey = Effect.fn(function* ({
465 keyId,
466 deletionWindowInDays,
467 desiredDescription,
468 desiredEnabled,
469 desiredKeyRotationEnabled,
470 desiredPolicy,
471 desiredRotationPeriodInDays,
472 desiredTags,
473 }: {
474 keyId: string;
475 deletionWindowInDays: number;
476 desiredDescription: string;
477 desiredEnabled: boolean;
478 desiredKeyRotationEnabled: boolean;
479 desiredPolicy: string | undefined;
480 desiredRotationPeriodInDays: number | undefined;
481 desiredTags: Record<string, string>;
482 }) {
483 const observeConverged = Effect.gen(function* () {
484 const key = yield* readKey({ keyId, deletionWindowInDays });
485 if (!key) {
486 return yield* new KmsKeyNotConverged();
487 }
488 if ((key.description ?? "") !== desiredDescription) {
489 return yield* new KmsKeyNotConverged();
490 }
491 if (key.enabled !== desiredEnabled) {
492 return yield* new KmsKeyNotConverged();
493 }
494 if (
495 !Object.entries(desiredTags).every(([name, value]) => key.tags[name] === value) ||
496 !Object.keys(key.tags).every((name) => desiredTags[name] === key.tags[name])
497 ) {
498 return yield* new KmsKeyNotConverged();
499 }
500 if (desiredPolicy !== undefined && !samePolicy(key.policy, desiredPolicy)) {
501 return yield* new KmsKeyNotConverged();
502 }
503 if (desiredEnabled) {
504 if (desiredKeyRotationEnabled && key.keyRotationEnabled !== true) {
505 return yield* new KmsKeyNotConverged();
506 }
507 if (!desiredKeyRotationEnabled && key.keyRotationEnabled === true) {
508 return yield* new KmsKeyNotConverged();
509 }
510 if (
511 desiredKeyRotationEnabled &&
512 desiredRotationPeriodInDays !== undefined &&
513 key.rotationPeriodInDays !== desiredRotationPeriodInDays
514 ) {
515 return yield* new KmsKeyNotConverged();
516 }
517 }
518 return key;
519 });
520
521 return yield* Effect.gen(function* () {
522 // KMS reads can briefly move backwards after a successful mutation (for
523 // example, GetKeyPolicy may serve the new policy once and then an older
524 // replica's default policy). A single matching read is therefore not a
525 // sufficient convergence signal under high concurrency. Require two
526 // consecutive observations before returning the resource to the engine.
527 yield* observeConverged;
528 yield* Effect.sleep("500 millis");
529 return yield* observeConverged;
530 }).pipe(
531 Effect.retry({
532 while: (error: { _tag: string }) =>
533 error._tag === "KmsKeyNotConverged" || isKmsEventuallyConsistent(error),
534 schedule: kmsRetrySchedule,
535 }),
536 );
537 });
538
539 const listKeyTags = Effect.fn(function* (keyId: string) {
540 const pages = yield* kms.listResourceTags.pages({ KeyId: keyId }).pipe(
541 Stream.runCollect,
542 Effect.catchTag("NotFoundException", () => Effect.succeed([])),
543 );
544
545 return toTagRecord(Array.from(pages).flatMap((page) => page.Tags ?? []));
546 });
547
548 const readKeyRotation = Effect.fn(function* (keyId: string) {
549 return yield* kms.getKeyRotationStatus({ KeyId: keyId }).pipe(
550 Effect.map((response) => ({
551 enabled: response.KeyRotationEnabled,
552 periodInDays: response.RotationPeriodInDays,
553 })),
554 Effect.catchTags({
555 UnsupportedOperationException: () => Effect.undefined,
556 KMSInvalidStateException: () => Effect.undefined,
557 NotFoundException: () => Effect.undefined,
558 }),
559 );
560 });
561
562 const readKeyPolicy = Effect.fn(function* (keyId: string) {
563 return yield* kms.getKeyPolicy({ KeyId: keyId, PolicyName: "default" }).pipe(
564 Effect.map((response) => response.Policy),
565 Effect.catchTags({
566 KMSInvalidStateException: () => Effect.undefined,
567 NotFoundException: () => Effect.undefined,
568 }),
569 );
570 });
571
572 const toAttrs = ({
573 metadata,
574 tags,
575 rotation,
576 policy,
577 deletionWindowInDays,
578 }: {
579 metadata: kms.KeyMetadata;
580 tags: Record<string, string>;
581 rotation: { enabled?: boolean; periodInDays?: number } | undefined;
582 policy: string | undefined;
583 deletionWindowInDays: number;
584 }): Key["Attributes"] => ({
585 keyId: metadata.KeyId,
586 keyArn: metadata.Arn as KeyArn,
587 description: metadata.Description,
588 keyUsage: metadata.KeyUsage ?? defaultKeyUsage,
589 keySpec: metadata.KeySpec ?? defaultKeySpec,
590 keyState: metadata.KeyState,
591 enabled: metadata.Enabled ?? false,
592 keyRotationEnabled: rotation?.enabled,
593 rotationPeriodInDays: rotation?.periodInDays,
594 multiRegion: metadata.MultiRegion ?? false,
595 policy,
596 deletionWindowInDays,
597 tags,
598 });
599
600 const toTagRecord = (tags: kms.Tag[] | undefined): Record<string, string> =>
601 Object.fromEntries(
602 (tags ?? [])
603 .filter(
604 (tag): tag is kms.Tag => typeof tag.TagKey === "string" && typeof tag.TagValue === "string",
605 )
606 .map((tag) => [tag.TagKey, tag.TagValue]),
607 );
608
609 const toKmsTags = (tags: Record<string, string>): kms.Tag[] =>
610 Object.entries(tags).map(([TagKey, TagValue]) => ({ TagKey, TagValue }));
611
612 /**
613 * Compare the observed key policy against the desired one using the shared
614 * IAM canonicalizer so a re-deploy of an equivalent document (different key
615 * order, whitespace, or PolicyDocument-vs-string form) is a no-op.
616 */
617 const samePolicy = (observed: string | undefined, desired: string | undefined) => {
618 if (observed === desired) return true;
619 if (observed === undefined || desired === undefined) return false;
620 return normalizePolicyDocument(observed) === normalizePolicyDocument(desired);
621 };
622
623 const isKmsEventuallyConsistent = (error: { _tag: string }) =>
624 error._tag === "DependencyTimeoutException" ||
625 error._tag === "KMSInternalException" ||
626 error._tag === "KMSInvalidStateException";
627
628 class KmsKeyNotConverged extends Data.TaggedError("KmsKeyNotConverged") {}
629
630 const kmsRetrySchedule = Schedule.max([Schedule.exponential(250), Schedule.recurs(7)]);