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

main
ts 228 lines 8.17 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as AWS from "@alchemy.run/aws";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as LambdaWeb from "@distilled.cloud/aws/lambda-web";
6 import * as sts from "@distilled.cloud/aws/sts";
7 import * as Cause from "effect/Cause";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { driftActions, repairDrift, waitForDrift } from "../drift.ts";
11
12 const asyncServerMain = fileURLToPath(new URL("./fixtures/web/async-server.ts", import.meta.url));
13
14 const { test } = Test.make({ providers: AWS.providers() });
15
16 const tags = ["provider:aws", "provider:aws:lambda", "live"];
17
18 interface Statement {
19 Sid: string;
20 Effect: string;
21 Principal: { AWS?: string; Service?: string };
22 Resource: string;
23 }
24
25 const statementsOf = (functionArn: string) =>
26 LambdaWeb.getResourcePolicy({ resourceArn: functionArn }).pipe(
27 Effect.map((r) => (JSON.parse(r.policy) as { Statement: Statement[] }).Statement),
28 Effect.catchTag("ResourceNotFoundException", () => Effect.succeed([] as Statement[])),
29 );
30
31 test.provider(
32 "grants coexist in one policy; removing one keeps the other",
33 (stack) =>
34 Effect.gen(function* () {
35 yield* stack.destroy();
36 const { Account: accountId } = yield* sts.getCallerIdentity({});
37
38 const deploy = (grants: ("Partner" | "Auditor")[]) =>
39 stack.deploy(
40 Effect.gen(function* () {
41 const api = yield* AWS.Lambda.WebFunction("Granted", {
42 main: asyncServerMain,
43 authType: "IamAuth",
44 });
45 const permissions: Partial<
46 Record<"Partner" | "Auditor", AWS.Lambda.WebFunctionPermission>
47 > = {};
48 for (const grant of grants) {
49 permissions[grant] = yield* AWS.Lambda.WebFunctionPermission(grant, {
50 endpoint: api,
51 principal: accountId!,
52 });
53 }
54 return { api, permissions };
55 }),
56 );
57
58 const { api, permissions } = yield* deploy(["Partner", "Auditor"]);
59 const statementIds = {
60 Partner: permissions.Partner!.statementId,
61 Auditor: permissions.Auditor!.statementId,
62 };
63 const both = yield* statementsOf(api.functionArn);
64 expect(both.map((s) => s.Sid).sort()).toEqual(
65 [statementIds.Partner!, statementIds.Auditor!].sort(),
66 );
67 for (const statement of both) {
68 expect(statement.Resource).toBe(api.endpointArn);
69 expect(statement.Principal.AWS).toContain(accountId!);
70 }
71
72 yield* deploy(["Auditor"]);
73 const remaining = yield* statementsOf(api.functionArn);
74 expect(remaining.map((s) => s.Sid)).toEqual([statementIds.Auditor!]);
75
76 yield* deploy([]);
77 expect(yield* statementsOf(api.functionArn)).toEqual([]);
78
79 yield* stack.destroy();
80 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
81 { tags, timeout: 240_000 },
82 );
83
84 test.provider(
85 "refuses to grant invoke on a public endpoint",
86 (stack) =>
87 Effect.gen(function* () {
88 yield* stack.destroy();
89 const { Account: accountId } = yield* sts.getCallerIdentity({});
90 const failure = yield* stack
91 .deploy(
92 Effect.gen(function* () {
93 const api = yield* AWS.Lambda.WebFunction("Public", {
94 main: asyncServerMain,
95 authType: "ApplicationManaged",
96 });
97 return yield* AWS.Lambda.WebFunctionPermission("Grant", {
98 endpoint: api,
99 principal: accountId!,
100 });
101 }),
102 )
103 .pipe(Effect.exit);
104 expect(failure._tag).toBe("Failure");
105 if (failure._tag === "Failure") {
106 expect(String(Cause.squash(failure.cause))).toContain("public");
107 }
108 yield* stack.destroy();
109 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
110 { tags, timeout: 180_000 },
111 );
112
113 // #2688: the web function, its endpoints and its grants must observe the
114 // endpoint limits, tags and the full grant statement, or out-of-band changes
115 // read as `unchanged`.
116 test.provider(
117 "drift detects and repairs out-of-band endpoint limits and grant changes",
118 (stack) =>
119 Effect.gen(function* () {
120 yield* stack.destroy();
121 const { Account: accountId } = yield* sts.getCallerIdentity({});
122
123 const { api } = yield* stack.deploy(
124 Effect.gen(function* () {
125 const api = yield* AWS.Lambda.WebFunction("DriftWeb", {
126 main: asyncServerMain,
127 authType: "IamAuth",
128 rateLimit: 100,
129 tags: { team: "declared" },
130 });
131 yield* AWS.Lambda.WebFunctionEndpoint("DriftDoor", {
132 function: api,
133 authType: "IamAuth",
134 rateLimit: 200,
135 });
136 yield* AWS.Lambda.WebFunctionPermission("DriftGrant", {
137 endpoint: api,
138 principal: accountId!,
139 });
140 return { api };
141 }),
142 );
143 const allUnchanged = (actions: Record<string, string | undefined>) =>
144 Object.values(actions).every((action) => action === "unchanged");
145 expect(allUnchanged(yield* driftActions(stack))).toBe(true);
146
147 const settle = <A, E extends { _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
148 effect.pipe(
149 Effect.retry({
150 while: (e) => e._tag === "ConflictException",
151 schedule: Schedule.spaced("2 seconds"),
152 times: 15,
153 }),
154 );
155 yield* settle(
156 LambdaWeb.updateWebFunctionEndpoint({
157 functionName: api.functionName,
158 endpointName: api.endpointName,
159 throttleConfig: { rateLimit: 300 },
160 }),
161 );
162 yield* settle(
163 LambdaWeb.updateWebFunctionEndpoint({
164 functionName: api.functionName,
165 endpointName: "DriftDoor",
166 throttleConfig: { rateLimit: 400 },
167 }),
168 );
169 const policy = yield* LambdaWeb.getResourcePolicy({ resourceArn: api.functionArn });
170 const document = JSON.parse(policy.policy) as { Statement: Record<string, unknown>[] };
171 yield* LambdaWeb.putResourcePolicy({
172 resourceArn: api.functionArn,
173 revisionId: policy.revisionId,
174 policy: JSON.stringify({
175 ...document,
176 Statement: document.Statement.map((statement) => ({ ...statement, Effect: "Deny" })),
177 }),
178 });
179
180 expect((yield* waitForDrift(stack, "DriftWeb", "drifted"))?.attr?.rateLimit).toBe(300);
181 expect((yield* waitForDrift(stack, "DriftDoor", "drifted"))?.attr?.rateLimit).toBe(400);
182 expect((yield* waitForDrift(stack, "DriftGrant", "drifted"))?.attr?.statement?.Effect).toBe(
183 "Deny",
184 );
185
186 yield* repairDrift(stack);
187 const after = yield* driftActions(stack).pipe(
188 Effect.repeat({
189 until: allUnchanged,
190 schedule: Schedule.spaced("2 seconds"),
191 times: 15,
192 }),
193 );
194 expect(after).toEqual({
195 DriftWeb: "unchanged",
196 DriftDoor: "unchanged",
197 DriftGrant: "unchanged",
198 });
199 const restored = yield* LambdaWeb.getWebFunctionEndpoint({
200 functionName: api.functionName,
201 endpointName: api.endpointName,
202 });
203 expect(restored.throttleConfig?.rateLimit).toBe(100);
204 const statements = yield* statementsOf(api.functionArn);
205 expect(statements.map((s) => s.Effect)).toEqual(["Allow"]);
206
207 // A deleted built-in endpoint must read as drift, not as the last
208 // persisted address.
209 yield* settle(
210 LambdaWeb.deleteWebFunctionEndpoint({
211 functionName: api.functionName,
212 endpointName: api.endpointName,
213 }),
214 );
215 const gone = yield* waitForDrift(stack, "DriftWeb", "drifted");
216 expect(gone?.attr?.url).toBe("");
217 yield* repairDrift(stack);
218 expect((yield* waitForDrift(stack, "DriftWeb", "unchanged"))?.action).toBe("unchanged");
219 const recreated = yield* LambdaWeb.getWebFunctionEndpoint({
220 functionName: api.functionName,
221 endpointName: api.endpointName,
222 });
223 expect(recreated.throttleConfig?.rateLimit).toBe(100);
224
225 yield* stack.destroy();
226 }).pipe(Effect.onError(() => stack.destroy().pipe(Effect.ignore))),
227 { tags, timeout: 360_000 },
228 );