@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 256 lines 9.16 KB
Raw
1 import * as secretsmanager from "@distilled.cloud/aws/secrets-manager";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { toWireDays, toWireHours } from "alchemy/Util/Duration";
6 import type * as Duration from "effect/Duration";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11
12 export interface RotationRules {
13 /**
14 * Rotate automatically after this interval (e.g. `"30 days"`). Rounded to
15 * whole days on the wire (`AutomaticallyAfterDays`).
16 */
17 automaticallyAfter?: Duration.Input;
18 /**
19 * Length of the rotation window (e.g. `"3 hours"`). Rounded to whole
20 * hours on the wire (`Duration`, `"3h"`).
21 */
22 window?: Duration.Input;
23 /**
24 * A `rate()` or `cron()` schedule expression, e.g. `"rate(4 hours)"` or
25 * `"cron(0 8 1 * ? *)"`. Mutually exclusive with `automaticallyAfter`.
26 */
27 scheduleExpression?: string;
28 }
29
30 /** Convert the typed {@link RotationRules} to the wire shape. */
31 export const toWireRotationRules = (
32 rules: RotationRules | undefined,
33 ): secretsmanager.RotationRulesType | undefined => {
34 if (rules === undefined) {
35 return undefined;
36 }
37 const hours = toWireHours(rules.window);
38 return {
39 AutomaticallyAfterDays: toWireDays(rules.automaticallyAfter),
40 Duration: hours === undefined ? undefined : `${hours}h`,
41 ScheduleExpression: rules.scheduleExpression,
42 };
43 };
44
45 export interface RotationScheduleProps {
46 /**
47 * ARN (preferred) or name of the secret whose rotation is being
48 * configured.
49 */
50 secretId: string;
51 /**
52 * ARN of the Lambda function that implements the rotation protocol
53 * (`createSecret`/`setSecret`/`testSecret`/`finishSecret`).
54 */
55 rotationLambdaArn?: string;
56 /**
57 * When the rotation runs. Provide `scheduleExpression` or
58 * `automaticallyAfter`.
59 */
60 rotationRules?: RotationRules;
61 /**
62 * Rotate the secret immediately when the schedule is created/updated. If
63 * `false`, Secrets Manager only tests the rotation configuration by
64 * running the `testSecret` step of the rotation function.
65 * @default false
66 */
67 rotateImmediately?: boolean;
68 }
69
70 export interface RotationSchedule extends Resource<
71 "AWS.SecretsManager.RotationSchedule",
72 RotationScheduleProps,
73 {
74 /**
75 * ARN of the secret the rotation is configured on.
76 */
77 secretArn: string;
78 /**
79 * Name of the secret.
80 */
81 secretName: string;
82 /**
83 * ARN of the rotation Lambda function.
84 */
85 rotationLambdaArn: string | undefined;
86 /**
87 * Whether automatic rotation is enabled on the secret.
88 */
89 rotationEnabled: boolean;
90 },
91 never,
92 Providers
93 > {}
94
95 /**
96 * Configures automatic rotation on a Secrets Manager secret
97 * (`RotateSecret` with a rotation Lambda + rules; `CancelRotateSecret` on
98 * delete).
99 *
100 * Usually created for you by {@link onSecretRotation}, which also wires the
101 * invoke permission and the runtime handler — reach for the resource
102 * directly only when the rotation function is managed outside the current
103 * stack.
104 * ### Scheduling Rotation
105 * **Example:** Rotate Every 30 Days
106 * ```typescript
107 * const schedule = yield* RotationSchedule("DbSecretRotation", {
108 * secretId: secret.secretArn,
109 * rotationLambdaArn: rotationFunctionArn,
110 * rotationRules: { automaticallyAfter: "30 days" },
111 * });
112 * ```
113 *
114 * **Example:** Cron Schedule with a Rotation Window
115 * ```typescript
116 * const schedule = yield* RotationSchedule("DbSecretRotation", {
117 * secretId: secret.secretArn,
118 * rotationLambdaArn: rotationFunctionArn,
119 * rotationRules: {
120 * scheduleExpression: "cron(0 8 1 * ? *)",
121 * window: "3 hours",
122 * },
123 * });
124 * ```
125 *
126 * @resource
127 */
128 export const RotationSchedule = Resource<RotationSchedule>("AWS.SecretsManager.RotationSchedule");
129
130 /**
131 * Bounded retry while Secrets Manager can't yet invoke the rotation Lambda
132 * (`InvalidRequestException` — the `lambda:InvokeFunction` permission for
133 * principal `secretsmanager.amazonaws.com` propagates asynchronously right
134 * after it is created).
135 *
136 * Explicitly-typed helper: inlining `Effect.retry` here leaves
137 * `Retry.Return`'s conditional type unresolved in the provider's inferred
138 * layer type, which declaration emit widens to an `unknown` R — poisoning
139 * `AWS.providers()` for every consumer (same shape as in `Secret.ts`).
140 */
141 const retryWhileInvokePermissionPropagates = <A, E extends { _tag: string }, R>(
142 self: Effect.Effect<A, E, R>,
143 ): Effect.Effect<A, E, R> =>
144 Effect.retry(self, {
145 while: (e) =>
146 e._tag === "InvalidRequestException" &&
147 ((e as { message?: string }).message?.includes("Lambda") ?? false),
148 schedule: Schedule.max([Schedule.fixed("3 seconds"), Schedule.recurs(10)]),
149 });
150
151 export const RotationScheduleProvider = () =>
152 Provider.effect(
153 RotationSchedule,
154 Effect.gen(function* () {
155 const readRotation = Effect.fn(function* (secretId: string) {
156 return yield* secretsmanager
157 .describeSecret({ SecretId: secretId })
158 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
159 });
160
161 return {
162 stables: ["secretArn", "secretName"],
163 diff: Effect.fn(function* ({ olds, news }) {
164 if (!isResolved(news)) return undefined;
165 if (olds && olds.secretId !== news.secretId) {
166 return { action: "replace" } as const;
167 }
168 }),
169 read: Effect.fn(function* ({ olds, output }) {
170 const secretId = output?.secretArn ?? olds?.secretId;
171 if (secretId === undefined) {
172 return undefined;
173 }
174 const described = yield* readRotation(secretId);
175 if (!described?.ARN || !described.Name || !described.RotationEnabled) {
176 return undefined;
177 }
178 return {
179 secretArn: described.ARN,
180 secretName: described.Name,
181 rotationLambdaArn: described.RotationLambdaARN,
182 rotationEnabled: described.RotationEnabled === true,
183 };
184 }),
185 reconcile: Effect.fn(function* ({ news, output, session }) {
186 const secretId = output?.secretArn ?? news.secretId;
187
188 // Configure (or reconverge) rotation. `rotateSecret` is a true
189 // upsert of the rotation configuration; with
190 // `RotateImmediately: false` Secrets Manager only validates the
191 // config by invoking the rotation function's `testSecret` step.
192 // Right after the invoke permission is created Secrets Manager may
193 // not see it yet — retry through that propagation window.
194 const rotated = yield* retryWhileInvokePermissionPropagates(
195 secretsmanager.rotateSecret({
196 SecretId: secretId,
197 RotationLambdaARN: news.rotationLambdaArn,
198 RotationRules: toWireRotationRules(news.rotationRules),
199 RotateImmediately: news.rotateImmediately ?? false,
200 }),
201 );
202
203 const secretArn = rotated.ARN ?? secretId;
204 const described = yield* readRotation(secretArn);
205 yield* session.note(secretArn);
206 return {
207 secretArn: described?.ARN ?? secretArn,
208 secretName: described?.Name ?? rotated.Name ?? secretId,
209 rotationLambdaArn: described?.RotationLambdaARN ?? news.rotationLambdaArn,
210 rotationEnabled: described?.RotationEnabled === true,
211 };
212 }),
213 delete: Effect.fn(function* ({ output }) {
214 // `CancelRotateSecret` turns off automatic rotation (and cancels
215 // any rotation in progress). Idempotent: missing secret or
216 // rotation-not-configured are treated as already-deleted.
217 yield* secretsmanager
218 .cancelRotateSecret({ SecretId: output.secretArn })
219 .pipe(
220 Effect.catchTag(
221 ["ResourceNotFoundException", "InvalidRequestException"],
222 () => Effect.void,
223 ),
224 );
225 }),
226 // A rotation schedule is configuration on a secret, not a separately
227 // enumerable object — `listSecrets` surfaces the rotation state
228 // (`RotationEnabled`, `RotationLambdaARN`) inline, so hydrate the
229 // exact `read` Attributes shape for every secret that has rotation
230 // enabled.
231 list: () =>
232 secretsmanager.listSecrets.pages({}).pipe(
233 Stream.runCollect,
234 Effect.map((chunk) =>
235 Array.from(chunk).flatMap((page) =>
236 (page.SecretList ?? [])
237 .filter(
238 (
239 entry,
240 ): entry is secretsmanager.SecretListEntry & {
241 ARN: string;
242 Name: string;
243 } => entry.ARN != null && entry.Name != null && entry.RotationEnabled === true,
244 )
245 .map((entry) => ({
246 secretArn: entry.ARN,
247 secretName: entry.Name,
248 rotationLambdaArn: entry.RotationLambdaARN,
249 rotationEnabled: true,
250 })),
251 ),
252 ),
253 ),
254 };
255 }),
256 );