@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 552 lines 20.5 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Core from "@alchemy.run/test/Core";
4 import * as eventbridge from "@distilled.cloud/aws/eventbridge";
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 OrganizationsTestFunctionLive, { OrganizationsTestFunction } from "./handler";
11 import * as OrganizationLease from "./OrganizationLease.ts";
12
13 const testOptions = { providers: AWS.providers() };
14 const { test, beforeAll, afterAll } = OrganizationLease.make(testOptions, "shared");
15 const sharedStack = Core.scratchStack(testOptions, "OrganizationsBindings");
16
17 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
18 // over 60s on a fresh deploy.
19 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
20
21 let baseUrl: string;
22 let functionArn: string;
23
24 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
25 readonly status: number;
26 readonly body: string;
27 }> {}
28
29 // The shared Lambda fixture occasionally answers a transient 5xx under load
30 // (cold re-init, IAM propagation on the freshly attached policy that the
31 // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
32 // 4xx/assertion failure surfaces immediately.
33 const send = (request: HttpClientRequest.HttpClientRequest) =>
34 HttpClient.execute(request).pipe(
35 Effect.flatMap((response) =>
36 response.status >= 500
37 ? response.text.pipe(
38 Effect.flatMap((body) =>
39 Effect.fail(new TransientUpstream({ status: response.status, body })),
40 ),
41 )
42 : Effect.succeed(response),
43 ),
44 Effect.retry({
45 while: (e) => e._tag === "TransientUpstream",
46 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
47 }),
48 );
49
50 // The freshly attached IAM policy can take ~10-30s to propagate to the
51 // Lambda's role; until it does, granted calls surface a transient
52 // AccessDeniedException. Poll (bounded) until the response is no longer
53 // access-denied so grant-proof assertions see steady-state behavior.
54 const getJson = (path: string) =>
55 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(
56 Effect.flatMap((r) => r.json),
57 Effect.repeat({
58 schedule: Schedule.spaced("3 seconds"),
59 until: (response): boolean => (response as { tag?: string }).tag !== "AccessDeniedException",
60 times: 10,
61 }),
62 );
63
64 // The testing account is the management account of a standing organization
65 // (SCPs available), so the tree/policy/delegation reads return live data.
66 // Every route still tolerates the typed not-in-organization tag so the suite
67 // stays correct on a detached account.
68 describe.sequential(
69 "Organizations Bindings",
70 { tags: ["provider:aws", "provider:aws:lambda", "provider:aws:organizations", "live"] },
71 () => {
72 beforeAll(
73 Effect.gen(function* () {
74 yield* Effect.logInfo("Organizations test setup: destroying previous resources");
75 yield* sharedStack.destroy();
76
77 yield* Effect.logInfo("Organizations test setup: deploying fixture");
78 const attrs = yield* sharedStack.deploy(
79 Effect.gen(function* () {
80 return yield* OrganizationsTestFunction;
81 }).pipe(Effect.provide(OrganizationsTestFunctionLive)),
82 );
83
84 expect(attrs.functionUrl).toBeTruthy();
85 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
86 functionArn = attrs.functionArn;
87
88 const readinessUrl = `${baseUrl}/bindings`;
89 yield* Effect.logInfo(`Organizations test setup: probing readiness at ${readinessUrl}`);
90 yield* HttpClient.get(readinessUrl).pipe(
91 Effect.flatMap((response) =>
92 response.status === 200
93 ? Effect.succeed(response)
94 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
95 ),
96 Effect.tapError((error) =>
97 Effect.logWarning(`Organizations test setup: fixture not ready yet (${String(error)})`),
98 ),
99 Effect.retry({ schedule: readinessPolicy }),
100 );
101 }),
102 { timeout: 240_000 },
103 );
104
105 afterAll(sharedStack.destroy(), { timeout: 120_000 });
106
107 describe("binding registration", () => {
108 test.provider("all 26 capabilities initialize in the runtime", (_stack) =>
109 Effect.gen(function* () {
110 const response = (yield* getJson("/bindings")) as { bound: string[] };
111 expect(response.bound).toHaveLength(26);
112 }),
113 );
114 });
115
116 describe("DescribeOrganization", () => {
117 test.provider("reads the organization", (_stack) =>
118 Effect.gen(function* () {
119 const response = (yield* getJson("/organization")) as
120 | { ok: true; id: string | null; managementAccountId: string | null }
121 | { ok: false; tag: string };
122 if (response.ok) {
123 expect(response.id).toMatch(/^o-/);
124 expect(response.managementAccountId).toMatch(/^\d{12}$/);
125 } else {
126 expect(["AWSOrganizationsNotInUseException"]).toContain(response.tag);
127 }
128 }),
129 );
130 });
131
132 describe("ListRoots", () => {
133 test.provider("lists the organization roots", (_stack) =>
134 Effect.gen(function* () {
135 const response = (yield* getJson("/roots")) as
136 | { ok: true; count: number; rootId: string | null }
137 | { ok: false; tag: string };
138 if (response.ok) {
139 expect(response.count).toBeGreaterThanOrEqual(1);
140 expect(response.rootId).toMatch(/^r-/);
141 } else {
142 expect(["AWSOrganizationsNotInUseException"]).toContain(response.tag);
143 }
144 }),
145 );
146 });
147
148 describe("ListAccounts", () => {
149 test.provider("lists the organization accounts", (_stack) =>
150 Effect.gen(function* () {
151 const response = (yield* getJson("/accounts")) as
152 | { ok: true; count: number }
153 | { ok: false; tag: string };
154 if (response.ok) {
155 expect(response.count).toBeGreaterThanOrEqual(1);
156 } else {
157 expect(["AWSOrganizationsNotInUseException"]).toContain(response.tag);
158 }
159 }),
160 );
161 });
162
163 describe("ListAccountsForParent", () => {
164 test.provider("lists the accounts directly under the root", (_stack) =>
165 Effect.gen(function* () {
166 const response = (yield* getJson("/accounts-for-parent")) as
167 | { ok: true; count: number }
168 | { ok: false; tag: string };
169 if (response.ok) {
170 expect(response.count).toBeGreaterThanOrEqual(0);
171 } else {
172 expect(["AWSOrganizationsNotInUseException", "NoRoot"]).toContain(response.tag);
173 }
174 }),
175 );
176 });
177
178 describe("ListOrganizationalUnitsForParent", () => {
179 test.provider("lists the OUs directly under the root", (_stack) =>
180 Effect.gen(function* () {
181 const response = (yield* getJson("/ous-for-parent")) as
182 | { ok: true; count: number }
183 | { ok: false; tag: string };
184 if (response.ok) {
185 expect(response.count).toBeGreaterThanOrEqual(0);
186 } else {
187 expect(["AWSOrganizationsNotInUseException", "NoRoot"]).toContain(response.tag);
188 }
189 }),
190 );
191 });
192
193 describe("ListChildren", () => {
194 test.provider("lists the account children of the root", (_stack) =>
195 Effect.gen(function* () {
196 const response = (yield* getJson("/children")) as
197 | { ok: true; count: number }
198 | { ok: false; tag: string };
199 if (response.ok) {
200 expect(response.count).toBeGreaterThanOrEqual(0);
201 } else {
202 expect(["AWSOrganizationsNotInUseException", "NoRoot"]).toContain(response.tag);
203 }
204 }),
205 );
206 });
207
208 describe("ListParents", () => {
209 test.provider("finds the management account's parent", (_stack) =>
210 Effect.gen(function* () {
211 const response = (yield* getJson("/parents")) as
212 | { ok: true; count: number }
213 | { ok: false; tag: string };
214 if (response.ok) {
215 expect(response.count).toBeGreaterThanOrEqual(1);
216 } else {
217 expect(["AWSOrganizationsNotInUseException", "NoOrganization"]).toContain(response.tag);
218 }
219 }),
220 );
221 });
222
223 describe("ListPolicies", () => {
224 test.provider("lists the service control policies", (_stack) =>
225 Effect.gen(function* () {
226 const response = (yield* getJson("/policies")) as
227 | { ok: true; count: number }
228 | { ok: false; tag: string };
229 if (response.ok) {
230 // Every organization with SCPs available has p-FullAWSAccess.
231 expect(response.count).toBeGreaterThanOrEqual(1);
232 } else {
233 expect(["AWSOrganizationsNotInUseException"]).toContain(response.tag);
234 }
235 }),
236 );
237 });
238
239 describe("ListPoliciesForTarget", () => {
240 test.provider("lists the SCPs attached to the root", (_stack) =>
241 Effect.gen(function* () {
242 const response = (yield* getJson("/policies-for-target")) as
243 | { ok: true; count: number }
244 | { ok: false; tag: string };
245 if (response.ok) {
246 expect(response.count).toBeGreaterThanOrEqual(0);
247 } else {
248 expect(["AWSOrganizationsNotInUseException", "NoRoot"]).toContain(response.tag);
249 }
250 }),
251 );
252 });
253
254 describe("ListTargetsForPolicy", () => {
255 test.provider("lists the targets of a discovered SCP", (_stack) =>
256 Effect.gen(function* () {
257 const response = (yield* getJson("/targets-for-policy")) as
258 | { ok: true; count: number }
259 | { ok: false; tag: string };
260 if (response.ok) {
261 expect(response.count).toBeGreaterThanOrEqual(0);
262 } else {
263 expect(["AWSOrganizationsNotInUseException", "NoPolicy"]).toContain(response.tag);
264 }
265 }),
266 );
267 });
268
269 describe("DescribeEffectivePolicy", () => {
270 test.provider("yields the effective tag policy or the typed not-found tag", (_stack) =>
271 Effect.gen(function* () {
272 const response = (yield* getJson("/effective-policy")) as
273 | { ok: true; policyType: string | null }
274 | { ok: false; tag: string };
275 if (response.ok) {
276 expect(response.policyType).toBe("TAG_POLICY");
277 } else {
278 // No tag policies exist in the standing organization — the typed
279 // tag proves the grant.
280 expect([
281 "AWSOrganizationsNotInUseException",
282 "ConstraintViolationException",
283 "EffectivePolicyNotFoundException",
284 "TargetNotFoundException",
285 ]).toContain(response.tag);
286 }
287 }),
288 );
289 });
290
291 describe("ListAccountsWithInvalidEffectivePolicy", () => {
292 test.provider("yields a count or the policy-type-gated typed tag", (_stack) =>
293 Effect.gen(function* () {
294 const response = (yield* getJson("/invalid-effective-policy-accounts")) as
295 | { ok: true; count: number }
296 | { ok: false; tag: string };
297 if (response.ok) {
298 expect(response.count).toBeGreaterThanOrEqual(0);
299 } else {
300 expect([
301 "AWSOrganizationsNotInUseException",
302 "ConstraintViolationException",
303 "EffectivePolicyNotFoundException",
304 "InvalidInputException",
305 "UnsupportedAPIEndpointException",
306 ]).toContain(response.tag);
307 }
308 }),
309 );
310 });
311
312 describe("ListEffectivePolicyValidationErrors", () => {
313 test.provider("yields a count or the policy-type-gated typed tag", (_stack) =>
314 Effect.gen(function* () {
315 const response = (yield* getJson("/effective-policy-validation-errors")) as
316 | { ok: true; count: number }
317 | { ok: false; tag: string };
318 if (response.ok) {
319 expect(response.count).toBeGreaterThanOrEqual(0);
320 } else {
321 expect([
322 "AWSOrganizationsNotInUseException",
323 "AccountNotFoundException",
324 "ConstraintViolationException",
325 "EffectivePolicyNotFoundException",
326 "InvalidInputException",
327 "UnsupportedAPIEndpointException",
328 "NoOrganization",
329 ]).toContain(response.tag);
330 }
331 }),
332 );
333 });
334
335 describe("ListDelegatedAdministrators", () => {
336 test.provider("lists the delegated administrators", (_stack) =>
337 Effect.gen(function* () {
338 const response = (yield* getJson("/delegated-administrators")) as
339 | { ok: true; count: number }
340 | { ok: false; tag: string };
341 if (response.ok) {
342 expect(response.count).toBeGreaterThanOrEqual(0);
343 } else {
344 expect(["AWSOrganizationsNotInUseException"]).toContain(response.tag);
345 }
346 }),
347 );
348 });
349
350 describe("ListDelegatedServicesForAccount", () => {
351 test.provider("surfaces the typed not-registered tag for the management account", (_stack) =>
352 Effect.gen(function* () {
353 const response = (yield* getJson("/delegated-services")) as
354 | { ok: true; count: number }
355 | { ok: false; tag: string };
356 if (response.ok) {
357 expect(response.count).toBeGreaterThanOrEqual(0);
358 } else {
359 // The management account is never a delegated administrator —
360 // the typed tag proves the grant.
361 expect([
362 "AWSOrganizationsNotInUseException",
363 "AccountNotRegisteredException",
364 "NoOrganization",
365 ]).toContain(response.tag);
366 }
367 }),
368 );
369 });
370
371 describe("ListAWSServiceAccessForOrganization", () => {
372 test.provider("lists the trusted-access service principals", (_stack) =>
373 Effect.gen(function* () {
374 const response = (yield* getJson("/service-access")) as
375 | { ok: true; count: number }
376 | { ok: false; tag: string };
377 if (response.ok) {
378 expect(response.count).toBeGreaterThanOrEqual(0);
379 } else {
380 expect(["AWSOrganizationsNotInUseException"]).toContain(response.tag);
381 }
382 }),
383 );
384 });
385
386 describe("ListTagsForResource", () => {
387 test.provider("reads the management account's tags", (_stack) =>
388 Effect.gen(function* () {
389 const response = (yield* getJson("/tags")) as
390 | { ok: true; count: number }
391 | { ok: false; tag: string };
392 if (response.ok) {
393 expect(response.count).toBeGreaterThanOrEqual(0);
394 } else {
395 expect([
396 "AWSOrganizationsNotInUseException",
397 "TargetNotFoundException",
398 "NoOrganization",
399 ]).toContain(response.tag);
400 }
401 }),
402 );
403 });
404
405 describe("ListCreateAccountStatus", () => {
406 test.provider("lists the account-creation requests", (_stack) =>
407 Effect.gen(function* () {
408 const response = (yield* getJson("/create-account-statuses")) as
409 | { ok: true; count: number }
410 | { ok: false; tag: string };
411 if (response.ok) {
412 expect(response.count).toBeGreaterThanOrEqual(0);
413 } else {
414 expect([
415 "AWSOrganizationsNotInUseException",
416 "UnsupportedAPIEndpointException",
417 ]).toContain(response.tag);
418 }
419 }),
420 );
421 });
422
423 describe("DescribeCreateAccountStatus", () => {
424 test.provider(
425 "surfaces a typed error for a nonexistent request (proving the grant)",
426 (_stack) =>
427 Effect.gen(function* () {
428 const response = (yield* getJson("/create-account-status-not-found")) as {
429 tag: string;
430 };
431 expect([
432 "AWSOrganizationsNotInUseException",
433 "CreateAccountStatusNotFoundException",
434 "InvalidInputException",
435 "UnsupportedAPIEndpointException",
436 ]).toContain(response.tag);
437 }),
438 );
439 });
440
441 describe("ListHandshakesForAccount", () => {
442 test.provider("lists the account's handshakes", (_stack) =>
443 Effect.gen(function* () {
444 const response = (yield* getJson("/handshakes-account")) as
445 | { ok: true; count: number }
446 | { ok: false; tag: string };
447 if (response.ok) {
448 expect(response.count).toBeGreaterThanOrEqual(0);
449 } else {
450 expect(["ConcurrentModificationException"]).toContain(response.tag);
451 }
452 }),
453 );
454 });
455
456 describe("ListHandshakesForOrganization", () => {
457 test.provider("lists the organization's handshakes", (_stack) =>
458 Effect.gen(function* () {
459 const response = (yield* getJson("/handshakes-org")) as
460 | { ok: true; count: number }
461 | { ok: false; tag: string };
462 if (response.ok) {
463 expect(response.count).toBeGreaterThanOrEqual(0);
464 } else {
465 expect([
466 "AWSOrganizationsNotInUseException",
467 "ConcurrentModificationException",
468 ]).toContain(response.tag);
469 }
470 }),
471 );
472 });
473
474 describe("DescribeHandshake", () => {
475 test.provider(
476 "surfaces a typed error for a nonexistent handshake (proving the grant)",
477 (_stack) =>
478 Effect.gen(function* () {
479 const response = (yield* getJson("/handshake-not-found")) as { tag: string };
480 expect(["HandshakeNotFoundException", "InvalidInputException"]).toContain(response.tag);
481 }),
482 );
483 });
484
485 describe("AcceptHandshake", () => {
486 test.provider(
487 "surfaces a typed error for a nonexistent handshake (proving the grant)",
488 (_stack) =>
489 Effect.gen(function* () {
490 const response = (yield* getJson("/accept-handshake-not-found")) as { tag: string };
491 expect([
492 "AWSOrganizationsNotInUseException",
493 "HandshakeNotFoundException",
494 "InvalidInputException",
495 ]).toContain(response.tag);
496 }),
497 );
498 });
499
500 describe("DeclineHandshake", () => {
501 test.provider(
502 "surfaces a typed error for a nonexistent handshake (proving the grant)",
503 (_stack) =>
504 Effect.gen(function* () {
505 const response = (yield* getJson("/decline-handshake-not-found")) as { tag: string };
506 expect(["HandshakeNotFoundException", "InvalidInputException"]).toContain(response.tag);
507 }),
508 );
509 });
510
511 describe("CancelHandshake", () => {
512 test.provider(
513 "surfaces a typed error for a nonexistent handshake (proving the grant)",
514 (_stack) =>
515 Effect.gen(function* () {
516 const response = (yield* getJson("/cancel-handshake-not-found")) as { tag: string };
517 expect(["HandshakeNotFoundException", "InvalidInputException"]).toContain(response.tag);
518 }),
519 );
520 });
521
522 describe("InviteAccountToOrganization", () => {
523 test.provider("surfaces a typed error for an invalid target (proving the grant)", (_stack) =>
524 Effect.gen(function* () {
525 const response = (yield* getJson("/invite-invalid")) as { tag: string };
526 expect([
527 "AWSOrganizationsNotInUseException",
528 "ConstraintViolationException",
529 "HandshakeConstraintViolationException",
530 "InvalidInputException",
531 ]).toContain(response.tag);
532 }),
533 );
534 });
535
536 describe("consumeOrganizationsEvents", { tags: ["provider:aws:eventbridge"] }, () => {
537 test.provider("the deploy created an EventBridge rule targeting the function", (_stack) =>
538 Effect.gen(function* () {
539 // Out-of-band via distilled: the fixture's
540 // consumeOrganizationsEvents must have materialized as a rule on
541 // the default bus with the Lambda as target. (Runtime firing needs
542 // a real organization change surfaced through CloudTrail in
543 // us-east-1, far slower than the speed doctrine allows.)
544 const { RuleNames } = yield* eventbridge.listRuleNamesByTarget({
545 TargetArn: functionArn,
546 });
547 expect((RuleNames ?? []).length).toBeGreaterThanOrEqual(1);
548 }),
549 );
550 });
551 },
552 );