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