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

main
ts 618 lines 23.3 KB
Raw
1 import * as secretsmanager from "@distilled.cloud/aws/secrets-manager";
2 import { OwnedBySomeoneElse } 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 { createInternalTags, diffTags, hasAlchemyTags } from "alchemy/Tags";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { PolicyDocument } from "../IAM/Policy.ts";
14 import { normalizePolicyDocument, stringifyPolicyDocument } from "../IAM/Policy.ts";
15 import type { Providers } from "../Providers.ts";
16
17 export class SecretUnexpectedResponse extends Data.TaggedError("SecretUnexpectedResponse")<{
18 readonly message: string;
19 readonly cause?: unknown;
20 }> {}
21
22 export interface GenerateSecretStringProps extends secretsmanager.GetRandomPasswordRequest {
23 /**
24 * JSON template merged with the generated password.
25 * @default "{}"
26 */
27 secretStringTemplate?: string;
28 /**
29 * Key written into the generated secret payload.
30 * @default "password"
31 */
32 generateStringKey?: string;
33 }
34
35 export interface SecretProps {
36 /**
37 * Secret name. If omitted, Alchemy generates a deterministic physical name.
38 */
39 name?: string;
40 /**
41 * Optional description for the secret.
42 */
43 description?: string;
44 /**
45 * Optional KMS key used to encrypt the secret.
46 */
47 kmsKeyId?: string;
48 /**
49 * Plain string secret value.
50 */
51 secretString?: Redacted.Redacted<string>;
52 /**
53 * Binary secret value.
54 */
55 secretBinary?: Redacted.Redacted<Uint8Array<ArrayBufferLike>>;
56 /**
57 * Generate a password and store it inside a JSON secret string.
58 */
59 generateSecretString?: GenerateSecretStringProps;
60 /**
61 * Resource-based permission policy attached to the secret
62 * (`PutResourcePolicy`). Accepts a typed {@link PolicyDocument} or a raw
63 * JSON string as an escape hatch (e.g. for adoption of an existing
64 * policy). Omitting the prop removes any policy previously attached by
65 * Alchemy.
66 */
67 resourcePolicy?: PolicyDocument | string;
68 /**
69 * Number of days (a whole number from 7 to 30) AWS keeps the secret recoverable after Alchemy
70 * deletes it (`DeleteSecret`'s `RecoveryWindowInDays`).
71 *
72 * When omitted, deletion is immediate: the secret is deleted with
73 * `ForceDeleteWithoutRecovery` and its value cannot be restored. When set,
74 * the secret stays scheduled for deletion for this many days and can be
75 * restored with `RestoreSecret`. While it is scheduled, AWS does not allow
76 * another secret with the same name, so re-adding a `Secret` with the same
77 * explicit {@link name} restores the pending secret and converges it to the
78 * desired props instead of creating a new one. (Without `name`, a re-added
79 * `Secret` gets a new generated name and creates a new secret.) Only a
80 * pending secret that carries this resource's Alchemy ownership tags is
81 * restored; any other one fails with `OwnedBySomeoneElse`.
82 *
83 * @default undefined (delete immediately, no recovery window)
84 */
85 recoveryWindowInDays?: number;
86 /**
87 * User-defined tags for the secret.
88 */
89 tags?: Record<string, string>;
90 }
91
92 export interface Secret extends Resource<
93 "AWS.SecretsManager.Secret",
94 SecretProps,
95 {
96 /**
97 * ARN of the secret.
98 */
99 secretArn: string;
100 /**
101 * Name of the secret.
102 */
103 secretName: string;
104 /**
105 * Version ID of the `AWSCURRENT` secret value, if a value has been set.
106 */
107 versionId: string | undefined;
108 /**
109 * Description of the secret.
110 */
111 description: string | undefined;
112 /**
113 * KMS key ID (or ARN) used to encrypt the secret value, if a
114 * customer-managed key was configured.
115 */
116 kmsKeyId: string | undefined;
117 /**
118 * Tags on the secret.
119 */
120 tags: Record<string, string>;
121 /**
122 * The resource-based policy (canonical JSON), as observed. Lets
123 * `alchemy drift` detect out-of-band changes.
124 */
125 resourcePolicy?: string;
126 },
127 never,
128 Providers
129 > {}
130
131 /**
132 * An AWS Secrets Manager secret.
133 *
134 * `Secret` owns the lifecycle of the secret metadata and current value. It can
135 * store a caller-provided value or generate a password-backed JSON payload for
136 * downstream resources such as Aurora clusters and RDS proxies.
137 * ### Creating Secrets
138 * **Example:** Static Secret String
139 * ```typescript
140 * const secret = yield* Secret("DbSecret", {
141 * secretString: Redacted.make(JSON.stringify({
142 * username: "app",
143 * password: "super-secret",
144 * })),
145 * });
146 * ```
147 *
148 * **Example:** Generated Password Secret
149 * ```typescript
150 * const secret = yield* Secret("DbSecret", {
151 * generateSecretString: {
152 * secretStringTemplate: JSON.stringify({ username: "app" }),
153 * generateStringKey: "password",
154 * PasswordLength: 32,
155 * },
156 * });
157 * ```
158 *
159 * ### Resource Policies
160 * **Example:** Typed Resource Policy
161 * ```typescript
162 * const secret = yield* Secret("SharedSecret", {
163 * secretString: Redacted.make("shared-value"),
164 * resourcePolicy: {
165 * Version: "2012-10-17",
166 * Statement: [
167 * {
168 * Effect: "Allow",
169 * Principal: { AWS: `arn:aws:iam::${accountId}:root` },
170 * Action: ["secretsmanager:GetSecretValue"],
171 * Resource: "*",
172 * },
173 * ],
174 * },
175 * });
176 * ```
177 *
178 * @resource
179 */
180 export const Secret = Resource<Secret>("AWS.SecretsManager.Secret");
181
182 const toTagRecord = (
183 tags: Array<{ Key?: string; Value?: string }> | undefined,
184 ): Record<string, string> =>
185 Object.fromEntries(
186 (tags ?? [])
187 .filter(
188 (tag): tag is { Key: string; Value: string } =>
189 typeof tag.Key === "string" && typeof tag.Value === "string",
190 )
191 .map((tag) => [tag.Key, tag.Value]),
192 );
193
194 /**
195 * Bounded retry through the async `ForceDeleteWithoutRecovery` window
196 * (`InvalidRequestException` "already scheduled for deletion"; force
197 * deletions complete within seconds).
198 *
199 * Expressed as an explicitly-typed helper: inlining `Effect.retry` here
200 * leaves `Retry.Return`'s conditional type unresolved in the provider's
201 * inferred layer type, which TypeScript's declaration emit widens to an
202 * `unknown` R — poisoning the whole `AWS.providers()` union for every
203 * downstream consumer.
204 */
205 const retryThroughDeletionWindow = <A, E extends { _tag: string }, R>(
206 self: Effect.Effect<A, E, R>,
207 ): Effect.Effect<A, E, R> =>
208 Effect.retry(self, {
209 while: (e) =>
210 e._tag === "InvalidRequestException" &&
211 isDeletionInProgress((e as { message?: string }).message),
212 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
213 });
214
215 const isDeletionInProgress = (message: string | undefined): boolean => {
216 const normalized = message?.toLowerCase();
217 return (
218 normalized?.includes("scheduled for deletion") === true ||
219 normalized?.includes("marked for deletion") === true
220 );
221 };
222
223 /**
224 * Raised when `recoveryWindowInDays` is not a whole number from 7 to 30, the
225 * range `DeleteSecret` accepts.
226 */
227 export class SecretRecoveryWindowOutOfRange extends Data.TaggedError(
228 "SecretRecoveryWindowOutOfRange",
229 )<{
230 message: string;
231 recoveryWindowInDays: number;
232 }> {}
233
234 const validateRecoveryWindow = (recoveryWindowInDays: number | undefined) =>
235 recoveryWindowInDays === undefined ||
236 (Number.isInteger(recoveryWindowInDays) &&
237 recoveryWindowInDays >= 7 &&
238 recoveryWindowInDays <= 30)
239 ? Effect.void
240 : Effect.fail(
241 new SecretRecoveryWindowOutOfRange({
242 message: `recoveryWindowInDays must be a whole number from 7 to 30, got ${recoveryWindowInDays}.`,
243 recoveryWindowInDays,
244 }),
245 );
246
247 class SecretNotVisible extends Data.TaggedError("SecretNotVisible")<{
248 readonly secretId: string;
249 }> {}
250
251 class SecretStillExists extends Data.TaggedError("SecretStillExists")<{
252 readonly secretId: string;
253 }> {}
254
255 export const SecretProvider = () =>
256 Provider.effect(
257 Secret,
258 Effect.gen(function* () {
259 const toSecretName = (id: string, props: SecretProps) =>
260 props.name ? Effect.succeed(props.name) : createPhysicalName({ id, maxLength: 512 });
261
262 const createValue = Effect.fn(function* (props: SecretProps) {
263 if (props.secretBinary !== undefined) {
264 return { SecretBinary: props.secretBinary } as const;
265 }
266
267 if (props.secretString !== undefined) {
268 return { SecretString: props.secretString } as const;
269 }
270
271 if (props.generateSecretString) {
272 const {
273 secretStringTemplate = "{}",
274 generateStringKey = "password",
275 ...request
276 } = props.generateSecretString;
277 const password = yield* secretsmanager.getRandomPassword(request);
278 const generated = password.RandomPassword
279 ? typeof password.RandomPassword === "string"
280 ? password.RandomPassword
281 : Redacted.value(password.RandomPassword)
282 : "";
283 const template = JSON.parse(secretStringTemplate) as Record<string, unknown>;
284 return {
285 SecretString: JSON.stringify({
286 ...template,
287 [generateStringKey]: generated,
288 }),
289 } as const;
290 }
291
292 return {} as const;
293 });
294
295 /**
296 * The attributes `read` and `reconcile` both report, observed on the
297 * secret, so a converged secret reads unchanged. The version is the
298 * live `AWSCURRENT` one, so a value written out of band shows up.
299 */
300 const observeSecretAttributes = Effect.fn(function* (
301 described: secretsmanager.DescribeSecretResponse & { ARN: string; Name: string },
302 ) {
303 const policy = yield* secretsmanager.getResourcePolicy({ SecretId: described.ARN }).pipe(
304 Effect.map((response) => response.ResourcePolicy),
305 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
306 );
307 return {
308 secretArn: described.ARN,
309 secretName: described.Name,
310 versionId: Object.entries(described.VersionIdsToStages ?? {}).find(([, stages]) =>
311 stages?.includes("AWSCURRENT"),
312 )?.[0],
313 description: described.Description,
314 kmsKeyId: described.KmsKeyId,
315 tags: toTagRecord(described.Tags),
316 resourcePolicy: policy === undefined ? undefined : normalizePolicyDocument(policy),
317 };
318 });
319
320 const readSecret = Effect.fn(function* (secretId: string) {
321 const described = yield* secretsmanager
322 .describeSecret({
323 SecretId: secretId,
324 })
325 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
326 // A secret with `DeletedDate` set is scheduled for deletion (our
327 // delete uses `ForceDeleteWithoutRecovery`, which still completes
328 // asynchronously). It cannot be updated, so treat it as missing —
329 // reconcile recreates it once the pending deletion finishes.
330 return described?.DeletedDate ? undefined : described;
331 });
332
333 // `CreateSecret` may return before `DescribeSecret` can observe the new
334 // secret. Keep this wait provider-local so every caller (including nuke
335 // recovery and adoption) gets the same bounded consistency handling.
336 const readSecretAfterCreate = (secretId: string) =>
337 Effect.retry(
338 readSecret(secretId).pipe(
339 Effect.flatMap((secret) =>
340 secret?.ARN && secret.Name
341 ? Effect.succeed(secret)
342 : Effect.fail(new SecretNotVisible({ secretId })),
343 ),
344 ),
345 {
346 while: (error) => error._tag === "SecretNotVisible",
347 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
348 },
349 );
350
351 // A secret deleted with a recovery window keeps its name until the
352 // window ends, so re-adding the same `Secret` must bring it back rather
353 // than create a second one (`CreateSecret` would be refused). Only
354 // applies when the caller opted into a recovery window; the default
355 // force-deletion path keeps its create-through-the-window retry. A
356 // pending secret without this resource's ownership tags belongs to
357 // someone else and is never restored.
358 const restoreIfPendingDeletion = Effect.fn(function* (id: string, secretId: string) {
359 const described = yield* secretsmanager
360 .describeSecret({ SecretId: secretId })
361 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
362 if (!described?.DeletedDate) {
363 return;
364 }
365 if (!(yield* hasAlchemyTags(id, toTagRecord(described.Tags)))) {
366 return yield* new OwnedBySomeoneElse({
367 message: `Secret '${secretId}' is scheduled for deletion and was not created by this resource, so it was not restored. Restore or delete it in Secrets Manager, or choose another name.`,
368 resourceType: Secret.Type,
369 logicalId: id,
370 physicalName: secretId,
371 });
372 }
373 yield* secretsmanager.restoreSecret({ SecretId: secretId });
374 });
375
376 // Force deletion is asynchronous. `DeletedDate` means the operation was
377 // accepted, not that the resource is absent, so deletion completion must
378 // be checked with the raw API rather than `readSecret`.
379 const waitForSecretAbsence = (secretId: string) =>
380 Effect.retry(
381 secretsmanager
382 .describeSecret({ SecretId: secretId })
383 .pipe(Effect.flatMap(() => Effect.fail(new SecretStillExists({ secretId })))),
384 {
385 while: (error) => error._tag === "SecretStillExists",
386 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
387 },
388 ).pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
389
390 return {
391 stables: ["secretArn", "secretName"],
392 diff: Effect.fn(function* ({ id, olds, news }) {
393 if (!isResolved(news)) return undefined;
394 if ((yield* toSecretName(id, olds ?? {})) !== (yield* toSecretName(id, news ?? {}))) {
395 return { action: "replace" } as const;
396 }
397 }),
398 read: Effect.fn(function* ({ id, olds, output }) {
399 const secretName = output?.secretName ?? (yield* toSecretName(id, olds ?? {}));
400 const described = yield* readSecret(output?.secretArn ?? secretName);
401 if (!described?.ARN || !described.Name) {
402 return undefined;
403 }
404
405 return yield* observeSecretAttributes({
406 ...described,
407 ARN: described.ARN,
408 Name: described.Name,
409 });
410 }),
411 reconcile: Effect.fn(function* ({ id, news, output, session }) {
412 yield* validateRecoveryWindow(news.recoveryWindowInDays);
413 const secretName = output?.secretName ?? (yield* toSecretName(id, news));
414 const internalTags = yield* createInternalTags(id);
415 const desiredTags = { ...internalTags, ...news.tags };
416 const hasNewValue =
417 news.secretString !== undefined ||
418 news.secretBinary !== undefined ||
419 news.generateSecretString !== undefined;
420
421 // Observe — describe the secret using whichever identifier we
422 // have (ARN preferred, name as fallback).
423 let observed = yield* readSecret(output?.secretArn ?? secretName);
424
425 // Ensure — create if missing. Tolerate `ResourceExistsException`
426 // by re-describing; the sync step below converges metadata and
427 // value. Recreating a physical name right after our own
428 // `ForceDeleteWithoutRecovery` can race the asynchronous deletion
429 // and fail with `InvalidRequestException` ("already scheduled for
430 // deletion") — force deletions complete within seconds, so retry
431 // through that window (bounded).
432 if (!observed?.ARN && news.recoveryWindowInDays !== undefined) {
433 yield* restoreIfPendingDeletion(id, secretName);
434 observed = yield* readSecret(secretName);
435 }
436
437 if (!observed?.ARN) {
438 // Data-FIRST `Effect.retry(self, options)`: the data-last form
439 // infers `Retry.Options<E>`'s `E` from BOTH `while` and the
440 // schedule's input slot (`unknown` for `Schedule.fixed`), and the
441 // unioned candidates collapse this provider's layer to an
442 // `unknown` R that then poisons all of `AWS.providers()`.
443 yield* retryThroughDeletionWindow(
444 secretsmanager
445 .createSecret({
446 Name: secretName,
447 Description: news.description,
448 KmsKeyId: news.kmsKeyId,
449 Tags: Object.entries(desiredTags).map(([Key, Value]) => ({
450 Key,
451 Value,
452 })),
453 ...(yield* createValue(news)),
454 })
455 .pipe(Effect.catchTag("ResourceExistsException", () => Effect.void)),
456 );
457 observed = yield* readSecretAfterCreate(secretName);
458 }
459
460 if (!observed?.ARN || !observed.Name) {
461 return yield* new SecretUnexpectedResponse({
462 message: `Failed to describe Secret '${secretName}'`,
463 });
464 }
465
466 const secretArn = observed.ARN;
467
468 // Sync metadata + value. `updateSecret` accepts description,
469 // KMS key, and the secret value in one call. We always send
470 // metadata (idempotent) and only send a new value if the user
471 // provided one — `updateSecret` requires SecretString or
472 // SecretBinary to actually rotate, but is fine to call without
473 // them to update description/kmsKeyId only.
474 const valuePayload = yield* createValue(news);
475 const updated = yield* secretsmanager.updateSecret({
476 SecretId: secretArn,
477 Description: news.description,
478 KmsKeyId: news.kmsKeyId,
479 ...valuePayload,
480 });
481
482 // Sync tags — diff observed cloud tags against desired.
483 const observedTags = toTagRecord(observed.Tags);
484 const { removed, upsert } = diffTags(observedTags, desiredTags);
485
486 if (upsert.length > 0) {
487 yield* secretsmanager.tagResource({
488 SecretId: secretArn,
489 Tags: upsert,
490 });
491 }
492
493 if (removed.length > 0) {
494 yield* secretsmanager.untagResource({
495 SecretId: secretArn,
496 TagKeys: removed,
497 });
498 }
499
500 // Sync the resource-based policy — diff the observed policy
501 // against the desired one (both canonicalized via
502 // `normalizePolicyDocument`) so a re-deploy of an equivalent
503 // document is a no-op API-wise.
504 const desiredPolicy =
505 news.resourcePolicy === undefined
506 ? undefined
507 : typeof news.resourcePolicy === "string"
508 ? news.resourcePolicy
509 : stringifyPolicyDocument(news.resourcePolicy);
510 const observedPolicy = yield* secretsmanager
511 .getResourcePolicy({ SecretId: secretArn })
512 .pipe(
513 Effect.map((response) => response.ResourcePolicy),
514 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
515 );
516
517 if (desiredPolicy !== undefined) {
518 if (
519 observedPolicy === undefined ||
520 normalizePolicyDocument(observedPolicy) !== normalizePolicyDocument(desiredPolicy)
521 ) {
522 yield* secretsmanager.putResourcePolicy({
523 SecretId: secretArn,
524 ResourcePolicy: desiredPolicy,
525 });
526 }
527 } else if (observedPolicy !== undefined) {
528 yield* secretsmanager
529 .deleteResourcePolicy({ SecretId: secretArn })
530 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
531 }
532
533 yield* session.note(secretArn);
534 // DescribeSecret lags writes (and a just-restored secret), so poll
535 // until it reflects the description written above.
536 const final = yield* secretsmanager.describeSecret({ SecretId: secretArn }).pipe(
537 Effect.retry({
538 while: (e) => e._tag === "ResourceNotFoundException",
539 schedule: Schedule.spaced("1 second"),
540 times: 10,
541 }),
542 Effect.repeat({
543 until: (described) =>
544 news.description === undefined || described.Description === news.description,
545 schedule: Schedule.spaced("1 second"),
546 times: 10,
547 }),
548 );
549 const attributes = yield* observeSecretAttributes({
550 ...final,
551 ARN: secretArn,
552 Name: observed.Name,
553 });
554 return {
555 ...attributes,
556 // DescribeSecret can lag a just-written value.
557 versionId: hasNewValue
558 ? (updated.VersionId ?? attributes.versionId)
559 : attributes.versionId,
560 tags: desiredTags,
561 };
562 }),
563 delete: Effect.fn(function* ({ olds, output }) {
564 const recoveryWindowInDays = olds?.recoveryWindowInDays;
565 yield* secretsmanager
566 .deleteSecret({
567 SecretId: output.secretArn,
568 ...(recoveryWindowInDays === undefined
569 ? { ForceDeleteWithoutRecovery: true }
570 : { RecoveryWindowInDays: recoveryWindowInDays }),
571 })
572 .pipe(
573 Effect.catchTags({
574 ResourceNotFoundException: () => Effect.void,
575 InvalidRequestException: (error) =>
576 isDeletionInProgress(error.message) ? Effect.void : Effect.fail(error),
577 }),
578 );
579 // With a recovery window the secret intentionally stays visible to
580 // `DescribeSecret` (scheduled for deletion) until the window ends.
581 if (recoveryWindowInDays === undefined) {
582 yield* waitForSecretAbsence(output.secretArn);
583 }
584 }),
585 // `listSecrets` returns full secret metadata (ARN, name, description,
586 // KMS key, and tags) inline, so we hydrate the exact `read` Attributes
587 // shape directly — without fetching plaintext values via
588 // `getSecretValue`. `versionId` is per-value state not surfaced by the
589 // list API, so it is `undefined` (matching `read` when there is no
590 // prior output).
591 list: () =>
592 secretsmanager.listSecrets.pages({}).pipe(
593 Stream.runCollect,
594 Effect.map((chunk) =>
595 Array.from(chunk).flatMap((page) =>
596 (page.SecretList ?? [])
597 .filter(
598 (
599 entry,
600 ): entry is secretsmanager.SecretListEntry & {
601 ARN: string;
602 Name: string;
603 } => entry.ARN != null && entry.Name != null,
604 )
605 .map((entry) => ({
606 secretArn: entry.ARN,
607 secretName: entry.Name,
608 versionId: undefined,
609 description: entry.Description,
610 kmsKeyId: entry.KmsKeyId,
611 tags: toTagRecord(entry.Tags),
612 })),
613 ),
614 ),
615 ),
616 };
617 }),
618 );