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

main
ts 247 lines 9.02 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpClient from "effect/http/HttpClient";
8 import * as HttpClientRequest from "effect/http/HttpClientRequest";
9 import * as Schedule from "effect/Schedule";
10 import IamTestFunctionLive, { IamTestFunction } from "./handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "IamBindings");
15
16 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
17 // over 60s on a fresh deploy.
18 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
19
20 let baseUrl: string;
21
22 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
23 readonly status: number;
24 readonly body: string;
25 }> {}
26
27 // The shared Lambda fixture occasionally answers a transient 5xx (cold
28 // re-init, IAM propagation on the freshly attached policy that the handler's
29 // `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine 4xx/assertion
30 // failure surfaces immediately.
31 const send = (request: HttpClientRequest.HttpClientRequest) =>
32 HttpClient.execute(request).pipe(
33 Effect.flatMap((response) =>
34 response.status >= 500
35 ? response.text.pipe(
36 Effect.flatMap((body) =>
37 Effect.fail(new TransientUpstream({ status: response.status, body })),
38 ),
39 )
40 : Effect.succeed(response),
41 ),
42 Effect.retry({
43 while: (e) => e._tag === "TransientUpstream",
44 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
45 }),
46 );
47
48 const getJson = (path: string) =>
49 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(Effect.flatMap((r) => r.json));
50
51 describe.sequential(
52 "IAM Bindings",
53 { tags: ["provider:aws", "provider:aws:iam", "provider:aws:lambda", "live"] },
54 () => {
55 beforeAll(
56 Effect.gen(function* () {
57 yield* Effect.logInfo("IAM test setup: destroying previous resources");
58 yield* sharedStack.destroy();
59
60 yield* Effect.logInfo("IAM test setup: deploying fixture");
61 const { functionUrl } = yield* sharedStack.deploy(
62 Effect.gen(function* () {
63 return yield* IamTestFunction;
64 }).pipe(Effect.provide(IamTestFunctionLive)),
65 );
66
67 expect(functionUrl).toBeTruthy();
68 baseUrl = functionUrl!.replace(/\/+$/, "");
69
70 const readinessUrl = `${baseUrl}/bindings`;
71 yield* Effect.logInfo(`IAM test setup: probing readiness at ${readinessUrl}`);
72 yield* HttpClient.get(readinessUrl).pipe(
73 Effect.flatMap((response) =>
74 response.status === 200
75 ? Effect.succeed(response)
76 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
77 ),
78 Effect.tapError((error) =>
79 Effect.logWarning(`IAM test setup: fixture not ready yet (${String(error)})`),
80 ),
81 Effect.retry({ schedule: readinessPolicy }),
82 );
83 }),
84 { timeout: 240_000 },
85 );
86
87 afterAll(sharedStack.destroy(), { timeout: 120_000 });
88
89 describe("binding registration", () => {
90 test.provider("all 13 capabilities initialize in the runtime", (_stack) =>
91 Effect.gen(function* () {
92 const response = yield* getJson("/bindings");
93 expect((response as any).bound).toHaveLength(13);
94 }),
95 );
96 });
97
98 describe("GetAccountSummary", () => {
99 test.provider(
100 "reads the account entity/quota counters",
101 (_stack) =>
102 Effect.gen(function* () {
103 const response = (yield* getJson("/account-summary")) as any;
104 expect(response.keys).toBeGreaterThan(0);
105 // The fixture user exists, so the account has at least one user.
106 expect(response.users).toBeGreaterThanOrEqual(1);
107 }),
108 { timeout: 60_000 },
109 );
110 });
111
112 describe("GetAccountAuthorizationDetails", () => {
113 test.provider(
114 "snapshots the account's users (fixture user included)",
115 (_stack) =>
116 Effect.gen(function* () {
117 const response = (yield* getJson("/authorization-details")) as any;
118 expect(response.users).toBeGreaterThanOrEqual(1);
119 }),
120 { timeout: 60_000 },
121 );
122 });
123
124 describe("GenerateCredentialReport + GetCredentialReport", () => {
125 test.provider(
126 "generates and downloads the credential report (or reports not-ready, typed)",
127 (_stack) =>
128 Effect.gen(function* () {
129 const response = (yield* getJson("/credential-report")) as any;
130 // First-ever generation in an account can exceed the fixture's
131 // bounded poll — the typed not-ready tags are the accepted
132 // alternative (an IAM gap would 500 as AccessDeniedException).
133 expect([
134 "Ok",
135 "CredentialReportNotReadyException",
136 "CredentialReportNotPresentException",
137 ]).toContain(response.tag);
138 if (response.tag === "Ok") {
139 expect(response.bytes).toBeGreaterThan(0);
140 }
141 }),
142 { timeout: 60_000 },
143 );
144 });
145
146 describe("Access advisor (Generate/Get ServiceLastAccessedDetails + WithEntities)", () => {
147 test.provider(
148 "runs the access-advisor job for the fixture user and drills into s3",
149 (_stack) =>
150 Effect.gen(function* () {
151 const response = (yield* getJson("/service-last-accessed")) as any;
152 expect(["COMPLETED", "IN_PROGRESS"]).toContain(response.status);
153 if (response.status === "COMPLETED") {
154 // The inline policy allows s3, so the job lists >= 1 service.
155 expect(response.services).toBeGreaterThanOrEqual(1);
156 expect(response.entities).toBeGreaterThanOrEqual(0);
157 }
158 }),
159 { timeout: 60_000 },
160 );
161 });
162
163 describe("ListPoliciesGrantingServiceAccess", () => {
164 test.provider(
165 "finds the inline policy granting the fixture user s3 access",
166 (_stack) =>
167 Effect.gen(function* () {
168 const response = (yield* getJson("/policies-granting-access")) as any;
169 expect(response.policies).toBeGreaterThanOrEqual(1);
170 }),
171 { timeout: 60_000 },
172 );
173 });
174
175 describe("SimulateCustomPolicy", () => {
176 test.provider(
177 "evaluates the custom policy to allowed",
178 (_stack) =>
179 Effect.gen(function* () {
180 const response = (yield* getJson("/simulate-custom")) as any;
181 expect(response.decision).toBe("allowed");
182 }),
183 { timeout: 60_000 },
184 );
185 });
186
187 describe("SimulatePrincipalPolicy", () => {
188 test.provider(
189 "evaluates the fixture user's inline policy to allowed",
190 (_stack) =>
191 Effect.gen(function* () {
192 const response = (yield* getJson("/simulate-principal")) as any;
193 expect(response.decision).toBe("allowed");
194 }),
195 { timeout: 60_000 },
196 );
197 });
198
199 describe("GetContextKeysForCustomPolicy", () => {
200 test.provider(
201 "extracts aws:username from the custom policy's condition",
202 (_stack) =>
203 Effect.gen(function* () {
204 const response = (yield* getJson("/context-keys-custom")) as any;
205 expect(response.contextKeys).toContain("aws:username");
206 }),
207 { timeout: 60_000 },
208 );
209 });
210
211 describe("GetContextKeysForPrincipalPolicy", () => {
212 test.provider(
213 "resolves context keys for the fixture user (none expected, typed success)",
214 (_stack) =>
215 Effect.gen(function* () {
216 const response = (yield* getJson("/context-keys-principal")) as any;
217 expect(Array.isArray(response.contextKeys)).toBe(true);
218 }),
219 { timeout: 60_000 },
220 );
221 });
222
223 describe("GetAccessKeyLastUsed", () => {
224 test.provider(
225 "echoes the owning user for the bound access key (proving AccessKeyId injection)",
226 (_stack) =>
227 Effect.gen(function* () {
228 // GetAccessKeyLastUsed on a just-created key is eventually
229 // consistent: IAM answers 200 with UserName absent until the key
230 // propagates (its error union is CommonErrors only — there is no
231 // typed NotFound to observe). Poll, bounded, until the owning user
232 // is echoed.
233 const response = (yield* getJson("/access-key-last-used").pipe(
234 Effect.repeat({
235 schedule: Schedule.spaced("3 seconds"),
236 until: (r): boolean => Boolean((r as any).userName),
237 times: 10,
238 }),
239 )) as any;
240 expect(response.userName).toBeTruthy();
241 expect(response.userName).toBe(response.expectedUserName);
242 }),
243 { timeout: 60_000 },
244 );
245 });
246 },
247 );