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

main
ts 273 lines 10.2 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 CognitoTestFunctionLive, { CognitoTestFunction } from "./handler";
11
12 const testOptions = { providers: AWS.providers() };
13 const { test, beforeAll, afterAll } = Test.make(testOptions);
14 const sharedStack = Core.scratchStack(testOptions, "CognitoBindings");
15
16 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
17 // over 60s on a fresh deploy under parallel-suite load.
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 // Retry transient 5xx only (cold re-init, IAM propagation); 4xx and
28 // assertion failures surface immediately.
29 const send = (request: HttpClientRequest.HttpClientRequest) =>
30 HttpClient.execute(request).pipe(
31 Effect.flatMap((response) =>
32 response.status >= 500
33 ? response.text.pipe(
34 Effect.flatMap((body) =>
35 Effect.fail(new TransientUpstream({ status: response.status, body })),
36 ),
37 )
38 : Effect.succeed(response),
39 ),
40 Effect.retry({
41 while: (e) => e._tag === "TransientUpstream",
42 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
43 }),
44 );
45
46 const decodeJwtPayload = (token: string): Record<string, unknown> =>
47 JSON.parse(Buffer.from(token.split(".")[1]!, "base64url").toString("utf8"));
48
49 describe(
50 "Cognito Bindings",
51 {
52 tags: [
53 "provider:aws",
54 "provider:aws:cognito",
55 "provider:aws:iam",
56 "provider:aws:lambda",
57 "live",
58 ],
59 },
60 () => {
61 beforeAll(
62 Effect.gen(function* () {
63 yield* Effect.logInfo("Cognito test setup: destroying previous stack");
64 yield* sharedStack.destroy();
65
66 yield* Effect.logInfo("Cognito test setup: deploying fixture");
67 const { functionUrl } = yield* sharedStack.deploy(
68 Effect.gen(function* () {
69 return yield* CognitoTestFunction;
70 }).pipe(Effect.provide(CognitoTestFunctionLive)),
71 );
72
73 expect(functionUrl).toBeTruthy();
74 baseUrl = functionUrl!.replace(/\/+$/, "");
75 const readinessUrl = `${baseUrl}/config`;
76
77 yield* Effect.logInfo(`Cognito test setup: probing readiness at ${readinessUrl}`);
78 yield* HttpClient.get(readinessUrl).pipe(
79 Effect.flatMap((response) =>
80 response.status === 200
81 ? Effect.succeed(response)
82 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
83 ),
84 Effect.tapError((error) =>
85 Effect.logWarning(`Cognito test setup: fixture not ready yet (${String(error)})`),
86 ),
87 Effect.retry({ schedule: readinessPolicy }),
88 );
89 }),
90 { timeout: 240_000 },
91 );
92
93 afterAll(sharedStack.destroy(), { timeout: 120_000 });
94
95 describe("UserPoolAuth", () => {
96 test.provider(
97 "USER_PASSWORD_AUTH returns valid Cognito JWTs",
98 (_stack) =>
99 Effect.gen(function* () {
100 const config = (yield* send(HttpClientRequest.get(`${baseUrl}/config`)).pipe(
101 Effect.flatMap((r) => r.json),
102 )) as { userPoolId: string; clientId: string };
103 expect(config.userPoolId).toMatch(/^[a-z0-9-]+_[A-Za-z0-9]+$/);
104
105 const response = (yield* send(
106 HttpClientRequest.post(`${baseUrl}/auth-flow?username=authflow-user`),
107 ).pipe(Effect.flatMap((r) => r.json))) as {
108 challengeName: string | undefined;
109 idToken: string | undefined;
110 accessToken: string | undefined;
111 refreshToken: string | undefined;
112 tokenType: string | undefined;
113 getUserUsername: string | undefined;
114 };
115
116 expect(response.challengeName).toBeUndefined();
117 expect(response.tokenType).toBe("Bearer");
118 expect(response.idToken).toBeTruthy();
119 expect(response.accessToken).toBeTruthy();
120 expect(response.refreshToken).toBeTruthy();
121 expect(response.getUserUsername).toBe("authflow-user");
122
123 // The ID token must be a real Cognito JWT issued by our pool.
124 const payload = decodeJwtPayload(response.idToken!);
125 expect(payload.iss).toContain("cognito-idp.");
126 expect(payload.iss).toContain(`/${config.userPoolId}`);
127 expect(payload.token_use).toBe("id");
128 expect(payload["cognito:username"]).toBe("authflow-user");
129 expect(payload.aud).toBe(config.clientId);
130
131 const accessPayload = decodeJwtPayload(response.accessToken!);
132 expect(accessPayload.token_use).toBe("access");
133 expect(accessPayload.client_id).toBe(config.clientId);
134 }),
135 { timeout: 120_000 },
136 );
137
138 test.provider(
139 "signUp + adminConfirmSignUp enables password auth",
140 (_stack) =>
141 Effect.gen(function* () {
142 const response = (yield* send(
143 HttpClientRequest.post(`${baseUrl}/sign-up-flow?username=signup-user`),
144 ).pipe(Effect.flatMap((r) => r.json))) as {
145 userConfirmed: boolean;
146 userSub: string;
147 confirmedStatus: string;
148 hasIdToken: boolean;
149 };
150
151 expect(response.userConfirmed).toBe(false);
152 expect(response.userSub).toBeTruthy();
153 expect(response.confirmedStatus).toBe("CONFIRMED");
154 expect(response.hasIdToken).toBe(true);
155 }),
156 { timeout: 120_000 },
157 );
158 });
159
160 describe("UserPoolAdmin", () => {
161 test.provider(
162 "admin user lifecycle: create, disable, enable, groups, list, delete",
163 (_stack) =>
164 Effect.gen(function* () {
165 const response = (yield* send(
166 HttpClientRequest.post(`${baseUrl}/user-lifecycle?username=lifecycle-user`),
167 ).pipe(Effect.flatMap((r) => r.json))) as {
168 createdStatus: string;
169 disabledEnabled: boolean;
170 groupMembers: string[];
171 listedCount: number;
172 deleted: boolean;
173 };
174
175 expect(response.createdStatus).toBe("FORCE_CHANGE_PASSWORD");
176 expect(response.disabledEnabled).toBe(false);
177 expect(response.groupMembers).toContain("lifecycle-user");
178 expect(response.listedCount).toBe(1);
179 expect(response.deleted).toBe(true);
180 }),
181 { timeout: 120_000 },
182 );
183
184 test.provider(
185 "extended admin surface: attribute deletion, group listings, devices",
186 (_stack) =>
187 Effect.gen(function* () {
188 const response = (yield* send(
189 HttpClientRequest.post(`${baseUrl}/admin-extended?username=admin-extended-user`),
190 ).pipe(Effect.flatMap((r) => r.json))) as {
191 nickname: string | undefined;
192 nicknameAfter: string | null;
193 userGroups: string[];
194 allGroups: string[];
195 deviceCount: number;
196 };
197
198 expect(response.nickname).toBe("admin-extended");
199 expect(response.nicknameAfter).toBeNull();
200 expect(response.userGroups.length).toBe(1);
201 expect(response.allGroups).toEqual(expect.arrayContaining(response.userGroups));
202 // no remembered devices on a fresh user (or device tracking off)
203 expect(response.deviceCount).toBeLessThanOrEqual(0);
204 }),
205 { timeout: 120_000 },
206 );
207 });
208
209 describe("UserPoolAuth self-service", () => {
210 test.provider(
211 "changePassword, attribute self-service, token refresh, deleteUser",
212 (_stack) =>
213 Effect.gen(function* () {
214 const response = (yield* send(
215 HttpClientRequest.post(`${baseUrl}/self-service?username=self-service-user`),
216 ).pipe(Effect.flatMap((r) => r.json))) as {
217 changedPasswordAuth: boolean;
218 nickname: string | undefined;
219 nicknameAfter: string | null;
220 refreshedHasAccessToken: boolean;
221 deleted: boolean;
222 };
223
224 expect(response.changedPasswordAuth).toBe(true);
225 expect(response.nickname).toBe("self-service");
226 expect(response.nicknameAfter).toBeNull();
227 expect(response.refreshedHasAccessToken).toBe(true);
228 expect(response.deleted).toBe(true);
229 }),
230 { timeout: 120_000 },
231 );
232 });
233
234 describe("IdentityPoolAuth", () => {
235 test.provider(
236 "guest getId vends AWS credentials and an OIDC token",
237 (_stack) =>
238 Effect.gen(function* () {
239 const response = (yield* send(HttpClientRequest.post(`${baseUrl}/identity-flow`)).pipe(
240 Effect.flatMap((r) => r.json),
241 )) as {
242 identityId: string;
243 hasAccessKeyId: boolean;
244 hasSessionToken: boolean;
245 hasOpenIdToken: boolean;
246 };
247
248 expect(response.identityId).toMatch(/^[a-z0-9-]+:/);
249 expect(response.hasAccessKeyId).toBe(true);
250 expect(response.hasSessionToken).toBe(true);
251 expect(response.hasOpenIdToken).toBe(true);
252 }),
253 { timeout: 120_000 },
254 );
255 });
256
257 describe("IdentityPoolAdmin", () => {
258 test.provider(
259 "describeIdentity, listIdentities, deleteIdentities",
260 (_stack) =>
261 Effect.gen(function* () {
262 const response = (yield* send(HttpClientRequest.post(`${baseUrl}/identity-flow`)).pipe(
263 Effect.flatMap((r) => r.json),
264 )) as { identityId: string; describedIdentityId: string; listedContains: boolean };
265
266 expect(response.describedIdentityId).toBe(response.identityId);
267 expect(response.listedContains).toBe(true);
268 }),
269 { timeout: 120_000 },
270 );
271 });
272 },
273 );