@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 150 lines 6.23 KB
Raw
1 import * as Namespace from "alchemy/Namespace";
2 import * as Effect from "effect/Effect";
3 import * as Layer from "effect/Layer";
4 import { AWSEnvironment } from "../Environment.ts";
5 import {
6 RotationEventSource as SecretsManagerRotationEventSource,
7 type RotationEventSourceProps,
8 type RotationEventSourceService,
9 type SecretRotationEvent,
10 } from "../SecretsManager/RotationEventSource.ts";
11 import { RotationSchedule } from "../SecretsManager/RotationSchedule.ts";
12 import type { Secret } from "../SecretsManager/Secret.ts";
13 import * as Lambda from "./Function.ts";
14 import { Permission as LambdaPermission } from "./Permission.ts";
15
16 /**
17 * Narrow an arbitrary Lambda invocation payload to a Secrets Manager
18 * rotation event (`createSecret`/`setSecret`/`testSecret`/`finishSecret`).
19 *
20 * `ClientRequestToken` is deliberately NOT required: the validation
21 * invocation Secrets Manager performs when a rotation schedule is
22 * configured with `RotateImmediately: false` can arrive without one, and an
23 * unmatched event fails the whole invocation ("No event handler found"),
24 * which Secrets Manager records as a failed rotation attempt.
25 */
26 export const isSecretRotationEvent = (event: any): event is SecretRotationEvent =>
27 typeof event?.Step === "string" && typeof event?.SecretId === "string";
28
29 /**
30 * Lambda runtime implementation for
31 * `AWS.SecretsManager.onSecretRotation(...)`.
32 *
33 * This layer does three things at deploy time:
34 *
35 * 1. Grants `secretsmanager.amazonaws.com` permission to invoke the current
36 * function (scoped to this account via `aws:SourceAccount`).
37 * 2. Attaches the rotation-protocol IAM actions for the bound secret
38 * (`DescribeSecret`, `GetSecretValue`, `PutSecretValue`,
39 * `UpdateSecretVersionStage` on the secret + `GetRandomPassword`).
40 * 3. Provisions the {@link RotationSchedule} configuring the secret's
41 * rotation to invoke this function — threaded through the Permission so
42 * Secrets Manager's invoke-permission validation passes.
43 *
44 * At runtime it narrows incoming invocations to rotation events for the
45 * bound secret and forwards them to the supplied handler.
46 * ### Rotating Secrets
47 * **Example:** Handle Rotation Steps
48 * ```typescript
49 * yield* SecretsManager.onSecretRotation(
50 * secret,
51 * { rotationRules: { automaticallyAfter: "30 days" } },
52 * (event) => rotate(event).pipe(Effect.orDie),
53 * );
54 * ```
55 *
56 * @binding
57 */
58 export const SecretRotationEventSource = Layer.effect(
59 SecretsManagerRotationEventSource,
60 // The impl resolves plan-time services (Permission, RotationSchedule)
61 // whereas RotationEventSourceService erases the requirement channel to
62 // `never`.
63 // @effect-diagnostics-next-line missingEffectContext:off
64 Effect.gen(function* () {
65 // this layer can only be used in a Lambda Function
66 const host = yield* Lambda.eventSourceHost("AWS.Lambda.SecretRotationEventSource");
67 const Permission = yield* LambdaPermission;
68 const Rotation = yield* RotationSchedule;
69
70 return Effect.fn(function* <Req = never>(
71 secret: Secret,
72 props: RotationEventSourceProps,
73 process: (event: SecretRotationEvent) => Effect.Effect<void, never, Req>,
74 ) {
75 // Resolving the ARN also registers it on the host environment;
76 // re-yield per invocation inside the listener below.
77 const SecretArn = yield* secret.secretArn;
78
79 // Deploy-time: grant the invoke permission, the rotation-protocol IAM
80 // actions, and provision the rotation schedule. Skipped once running
81 // inside the deployed Function (the global guard), where the only work
82 // is registering the runtime handler below. Namespaced under the host
83 // so the sub-resources' logical identity is stable per host function.
84 if (!globalThis.__ALCHEMY_RUNTIME__) {
85 yield* Namespace.push(
86 host.LogicalId,
87 Effect.gen(function* () {
88 yield* host.bind`Allow(${host}, AWS.SecretsManager.RotationEventSource(${secret}))`({
89 policyStatements: [
90 {
91 Effect: "Allow",
92 Action: [
93 "secretsmanager:DescribeSecret",
94 "secretsmanager:GetSecretValue",
95 "secretsmanager:PutSecretValue",
96 "secretsmanager:UpdateSecretVersionStage",
97 ],
98 Resource: [secret.secretArn],
99 },
100 {
101 Effect: "Allow",
102 Action: ["secretsmanager:GetRandomPassword"],
103 Resource: ["*"],
104 },
105 ],
106 });
107
108 // Secrets Manager VALIDATES it can invoke the rotation function
109 // when `RotateSecret` configures the schedule, so the Permission
110 // must exist BEFORE the RotationSchedule. Rotation invocations
111 // carry no SourceArn — scope by account per the Secrets Manager
112 // confused-deputy guidance.
113 const { accountId } = yield* AWSEnvironment.current as unknown as Effect.Effect<{
114 accountId: string;
115 }>;
116 const permission = yield* Permission(`${secret.LogicalId}-Rotation-Permission`, {
117 action: "lambda:InvokeFunction",
118 functionName: Lambda.qualifiedArnOf(host),
119 principal: "secretsmanager.amazonaws.com",
120 sourceAccount: accountId,
121 });
122
123 // The Permission echoes the `functionName` prop (the function
124 // ARN) as an attribute — threading it as the rotation Lambda ARN
125 // makes the schedule reconcile only AFTER the invoke permission
126 // exists.
127 yield* Rotation(`${secret.LogicalId}-RotationSchedule`, {
128 secretId: secret.secretArn,
129 rotationLambdaArn: permission.functionName,
130 rotationRules: props.rotationRules,
131 rotateImmediately: props.rotateImmediately,
132 });
133 }),
134 );
135 }
136
137 yield* host.listen(
138 Effect.gen(function* () {
139 const secretArn = yield* SecretArn;
140
141 return (event: any) => {
142 if (isSecretRotationEvent(event) && event.SecretId === secretArn) {
143 return process(event).pipe(Effect.orDie);
144 }
145 };
146 }),
147 );
148 }) as RotationEventSourceService;
149 }),
150 );