@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, 06:00 UTC

main
ts 387 lines 14 KB
Raw
1 import { fileURLToPath } from "node:url";
2 import * as AWS from "@alchemy.run/aws";
3 import { UserPool } from "@alchemy.run/aws/Cognito";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as cip from "@distilled.cloud/aws/cognito-identity-provider";
7 import * as Cause from "effect/Cause";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Exit from "effect/Exit";
11 import * as Schedule from "effect/Schedule";
12
13 const customEmailSenderPath = fileURLToPath(
14 new URL("./custom-email-sender-handler.ts", import.meta.url),
15 );
16
17 const { test } = Test.make({ providers: AWS.providers() });
18
19 class UserPoolStillExists extends Data.TaggedError("UserPoolStillExists")<{
20 readonly userPoolId: string;
21 }> {}
22
23 const assertPoolDeleted = (userPoolId: string) =>
24 cip.describeUserPool({ UserPoolId: userPoolId }).pipe(
25 Effect.flatMap(() => Effect.fail(new UserPoolStillExists({ userPoolId }))),
26 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
27 Effect.retry({
28 while: (e) => e._tag === "UserPoolStillExists",
29 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
30 }),
31 );
32
33 test.provider(
34 "create, update policy and tags, no-op, delete user pool",
35 (stack) =>
36 Effect.gen(function* () {
37 yield* stack.destroy();
38
39 const pool = yield* stack.deploy(
40 Effect.gen(function* () {
41 return yield* UserPool("LifecyclePool", {
42 passwordPolicy: { minimumLength: 10 },
43 adminCreateUserOnly: true,
44 tags: { Environment: "test" },
45 });
46 }),
47 );
48
49 expect(pool.userPoolId).toMatch(/^[a-z0-9-]+_[A-Za-z0-9]+$/);
50 expect(pool.userPoolArn).toContain(":userpool/");
51 expect(pool.userPoolName).toBeDefined();
52
53 // out-of-band verification via distilled
54 const created = yield* cip.describeUserPool({
55 UserPoolId: pool.userPoolId,
56 });
57 expect(created.UserPool?.Name).toBe(pool.userPoolName);
58 expect(created.UserPool?.Policies?.PasswordPolicy?.MinimumLength).toBe(10);
59 expect(created.UserPool?.AdminCreateUserConfig?.AllowAdminCreateUserOnly).toBe(true);
60 expect(created.UserPool?.MfaConfiguration).toBe("OFF");
61 expect(created.UserPool?.DeletionProtection).toBe("INACTIVE");
62
63 const tags = yield* cip.listTagsForResource({
64 ResourceArn: pool.userPoolArn,
65 });
66 expect(tags.Tags?.Environment).toBe("test");
67 expect(tags.Tags?.["alchemy::id"]).toBe("LifecyclePool");
68
69 // update the password policy and tag set in place
70 const updated = yield* stack.deploy(
71 Effect.gen(function* () {
72 return yield* UserPool("LifecyclePool", {
73 passwordPolicy: { minimumLength: 14, requireSymbols: false },
74 adminCreateUserOnly: true,
75 tags: { Environment: "test", Extra: "1" },
76 });
77 }),
78 );
79 expect(updated.userPoolId).toBe(pool.userPoolId);
80
81 const afterUpdate = yield* cip.describeUserPool({
82 UserPoolId: pool.userPoolId,
83 });
84 expect(afterUpdate.UserPool?.Policies?.PasswordPolicy?.MinimumLength).toBe(14);
85 expect(afterUpdate.UserPool?.Policies?.PasswordPolicy?.RequireSymbols).toBe(false);
86 const updatedTags = yield* cip.listTagsForResource({
87 ResourceArn: pool.userPoolArn,
88 });
89 expect(updatedTags.Tags?.Extra).toBe("1");
90
91 // removing a tag converges
92 yield* stack.deploy(
93 Effect.gen(function* () {
94 return yield* UserPool("LifecyclePool", {
95 passwordPolicy: { minimumLength: 14, requireSymbols: false },
96 adminCreateUserOnly: true,
97 tags: { Environment: "test" },
98 });
99 }),
100 );
101 const afterRemoval = yield* cip.listTagsForResource({
102 ResourceArn: pool.userPoolArn,
103 });
104 expect(afterRemoval.Tags?.Extra).toBeUndefined();
105 expect(afterRemoval.Tags?.Environment).toBe("test");
106
107 yield* stack.destroy();
108 yield* assertPoolDeleted(pool.userPoolId);
109 }),
110 { tags: ["provider:aws", "provider:aws:cognito", "live"], timeout: 120_000 },
111 );
112
113 test.provider(
114 "custom schema attributes are added in place; sign-in change replaces",
115 (stack) =>
116 Effect.gen(function* () {
117 yield* stack.destroy();
118
119 const pool = yield* stack.deploy(
120 Effect.gen(function* () {
121 return yield* UserPool("SchemaPool", {
122 schema: [{ name: "tenantId", mutable: true }],
123 });
124 }),
125 );
126
127 const created = yield* cip.describeUserPool({
128 UserPoolId: pool.userPoolId,
129 });
130 const names = (created.UserPool?.SchemaAttributes ?? []).map((a) => a.Name);
131 expect(names).toContain("custom:tenantId");
132
133 // adding an attribute updates in place
134 const withMore = yield* stack.deploy(
135 Effect.gen(function* () {
136 return yield* UserPool("SchemaPool", {
137 schema: [
138 { name: "tenantId", mutable: true },
139 { name: "plan", mutable: true },
140 ],
141 });
142 }),
143 );
144 expect(withMore.userPoolId).toBe(pool.userPoolId);
145 const afterAdd = yield* cip.describeUserPool({
146 UserPoolId: pool.userPoolId,
147 });
148 const afterAddNames = (afterAdd.UserPool?.SchemaAttributes ?? []).map((a) => a.Name);
149 expect(afterAddNames).toContain("custom:plan");
150
151 // switching to email sign-in is immutable ⇒ replacement
152 const replaced = yield* stack.deploy(
153 Effect.gen(function* () {
154 return yield* UserPool("SchemaPool", {
155 schema: [
156 { name: "tenantId", mutable: true },
157 { name: "plan", mutable: true },
158 ],
159 usernameAttributes: ["email"],
160 });
161 }),
162 );
163 expect(replaced.userPoolId).not.toBe(pool.userPoolId);
164 const replacedPool = yield* cip.describeUserPool({
165 UserPoolId: replaced.userPoolId,
166 });
167 expect(replacedPool.UserPool?.UsernameAttributes).toEqual(["email"]);
168 yield* assertPoolDeleted(pool.userPoolId);
169
170 yield* stack.destroy();
171 yield* assertPoolDeleted(replaced.userPoolId);
172 }),
173 { tags: ["provider:aws", "provider:aws:cognito", "live"], timeout: 120_000 },
174 );
175
176 // Regression: https://github.com/alchemy-run/alchemy/issues/1311 — email OTP
177 // through a CustomEmailSender needs `Policies.SignInPolicy`,
178 // `LambdaConfig.CustomEmailSender` and `LambdaConfig.KMSKeyID`, which the
179 // provider used to strip (it only ever sent the string trigger slots), and
180 // an unrelated update must never clear an already-configured sender.
181 test.provider(
182 "email OTP sign-in policy with a custom email sender and KMS key",
183 (stack) =>
184 Effect.gen(function* () {
185 yield* stack.destroy();
186
187 const sender = (passwordMinimumLength: number, withSender: boolean) =>
188 Effect.gen(function* () {
189 const key = yield* AWS.KMS.Key("CodeKey", {
190 description: "alchemy cognito custom sender codes",
191 deletionWindow: "7 days",
192 });
193 const fn = yield* AWS.Lambda.Function("EmailSender", {
194 main: customEmailSenderPath,
195 handler: "handler",
196 isExternal: true,
197 functionUrl: false,
198 });
199 const pool = yield* UserPool("OtpPool", {
200 tier: "ESSENTIALS",
201 usernameAttributes: ["email"],
202 passwordPolicy: { minimumLength: passwordMinimumLength },
203 signInPolicy: {
204 allowedFirstAuthFactors: ["PASSWORD", "EMAIL_OTP"],
205 },
206 ...(withSender
207 ? {
208 customEmailSender: { lambdaArn: fn.functionArn },
209 kmsKeyId: key.keyArn,
210 }
211 : {}),
212 });
213 return { pool, fn, key };
214 });
215
216 const created = yield* stack.deploy(sender(8, true));
217
218 const describe = () =>
219 cip
220 .describeUserPool({ UserPoolId: created.pool.userPoolId })
221 .pipe(Effect.map((r) => r.UserPool!));
222
223 const initial = yield* describe();
224 expect(initial.UserPoolTier).toBe("ESSENTIALS");
225 expect([...(initial.Policies?.SignInPolicy?.AllowedFirstAuthFactors ?? [])].sort()).toEqual([
226 "EMAIL_OTP",
227 "PASSWORD",
228 ]);
229 expect(initial.LambdaConfig?.CustomEmailSender).toEqual({
230 LambdaArn: created.fn.functionArn,
231 LambdaVersion: "V1_0",
232 });
233 expect(initial.LambdaConfig?.KMSKeyID).toBe(created.key.keyArn);
234
235 // An unrelated update (password policy) must keep the custom sender,
236 // KMS key and sign-in policy intact — updateUserPool resets anything
237 // omitted from its body.
238 const updated = yield* stack.deploy(sender(12, true));
239 expect(updated.pool.userPoolId).toBe(created.pool.userPoolId);
240 const afterUnrelated = yield* describe();
241 expect(afterUnrelated.Policies?.PasswordPolicy?.MinimumLength).toBe(12);
242 expect(
243 [...(afterUnrelated.Policies?.SignInPolicy?.AllowedFirstAuthFactors ?? [])].sort(),
244 ).toEqual(["EMAIL_OTP", "PASSWORD"]);
245 expect(afterUnrelated.LambdaConfig?.CustomEmailSender).toEqual({
246 LambdaArn: created.fn.functionArn,
247 LambdaVersion: "V1_0",
248 });
249 expect(afterUnrelated.LambdaConfig?.KMSKeyID).toBe(created.key.keyArn);
250
251 // Explicitly dropping the sender clears it (and the key) on the pool.
252 const removed = yield* stack.deploy(sender(12, false));
253 expect(removed.pool.userPoolId).toBe(created.pool.userPoolId);
254 const afterRemoval = yield* describe();
255 expect(afterRemoval.LambdaConfig?.CustomEmailSender).toBeUndefined();
256 expect(afterRemoval.LambdaConfig?.KMSKeyID).toBeUndefined();
257 expect(afterRemoval.Policies?.PasswordPolicy?.MinimumLength).toBe(12);
258
259 yield* stack.destroy();
260 yield* assertPoolDeleted(created.pool.userPoolId);
261 }),
262 {
263 tags: [
264 "provider:aws",
265 "provider:aws:cognito",
266 "provider:aws:kms",
267 "provider:aws:lambda",
268 "live",
269 ],
270 timeout: 180_000,
271 },
272 );
273
274 // UpdateUserPool resets any field omitted from its body to the service
275 // default — an unrelated update must echo the observed EmailConfiguration
276 // back rather than clear it.
277 test.provider(
278 "email configuration is set, survives unrelated updates, and converges",
279 (stack) =>
280 Effect.gen(function* () {
281 yield* stack.destroy();
282
283 const pool = yield* stack.deploy(
284 Effect.gen(function* () {
285 return yield* UserPool("EmailPool", {
286 autoVerifiedAttributes: ["email"],
287 emailConfiguration: {
288 replyToEmailAddress: "support@example.com",
289 },
290 });
291 }),
292 );
293
294 const describe = () =>
295 cip.describeUserPool({ UserPoolId: pool.userPoolId }).pipe(Effect.map((r) => r.UserPool!));
296
297 const created = yield* describe();
298 expect(created.EmailConfiguration?.EmailSendingAccount).toBe("COGNITO_DEFAULT");
299 expect(created.EmailConfiguration?.ReplyToEmailAddress).toBe("support@example.com");
300
301 // an unrelated update that OMITS emailConfiguration must preserve the
302 // observed configuration (updateUserPool would otherwise reset it)
303 const updated = yield* stack.deploy(
304 Effect.gen(function* () {
305 return yield* UserPool("EmailPool", {
306 autoVerifiedAttributes: ["email"],
307 passwordPolicy: { minimumLength: 12 },
308 });
309 }),
310 );
311 expect(updated.userPoolId).toBe(pool.userPoolId);
312 const afterUnrelated = yield* describe();
313 expect(afterUnrelated.Policies?.PasswordPolicy?.MinimumLength).toBe(12);
314 expect(afterUnrelated.EmailConfiguration?.ReplyToEmailAddress).toBe("support@example.com");
315
316 // changing the declared configuration converges
317 yield* stack.deploy(
318 Effect.gen(function* () {
319 return yield* UserPool("EmailPool", {
320 autoVerifiedAttributes: ["email"],
321 passwordPolicy: { minimumLength: 12 },
322 emailConfiguration: {
323 replyToEmailAddress: "help@example.com",
324 },
325 });
326 }),
327 );
328 const afterChange = yield* describe();
329 expect(afterChange.EmailConfiguration?.ReplyToEmailAddress).toBe("help@example.com");
330 expect(afterChange.EmailConfiguration?.EmailSendingAccount).toBe("COGNITO_DEFAULT");
331
332 yield* stack.destroy();
333 yield* assertPoolDeleted(pool.userPoolId);
334 }),
335 { tags: ["provider:aws", "provider:aws:cognito", "live"], timeout: 120_000 },
336 );
337
338 test.provider(
339 "customEmailSender without kmsKeyId and passwordless factors on LITE fail early",
340 (stack) =>
341 Effect.gen(function* () {
342 yield* stack.destroy();
343
344 const failureTag = (exit: Exit.Exit<unknown, unknown>) => {
345 expect(Exit.isFailure(exit)).toBe(true);
346 if (!Exit.isFailure(exit)) return undefined;
347 const reason = exit.cause.reasons.find(Cause.isFailReason);
348 return (reason?.error as { _tag?: string } | undefined)?._tag;
349 };
350
351 const missingKey = yield* stack
352 .deploy(
353 UserPool("InvalidPool", {
354 customEmailSender: {
355 lambdaArn: "arn:aws:lambda:us-east-1:123456789012:function:sender",
356 },
357 }),
358 )
359 .pipe(Effect.exit);
360 expect(failureTag(missingKey)).toBe("InvalidUserPoolConfiguration");
361
362 const liteOtp = yield* stack
363 .deploy(
364 UserPool("InvalidPool", {
365 tier: "LITE",
366 signInPolicy: {
367 allowedFirstAuthFactors: ["PASSWORD", "EMAIL_OTP"],
368 },
369 }),
370 )
371 .pipe(Effect.exit);
372 expect(failureTag(liteOtp)).toBe("InvalidUserPoolConfiguration");
373
374 const developerWithoutSource = yield* stack
375 .deploy(
376 UserPool("InvalidPool", {
377 emailConfiguration: { emailSendingAccount: "DEVELOPER" },
378 }),
379 )
380 .pipe(Effect.exit);
381 expect(failureTag(developerWithoutSource)).toBe("InvalidUserPoolConfiguration");
382
383 // nothing was created — the validation runs before any API call
384 yield* stack.destroy();
385 }),
386 { tags: ["provider:aws", "provider:aws:cognito", "live"], timeout: 60_000 },
387 );