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

main
ts 188 lines 7.83 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { DelegatedAdministrator } from "@alchemy.run/aws/Organizations";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as organizations from "@distilled.cloud/aws/organizations";
5 import * as Provider from "alchemy/Provider";
6 import { isResourceState, State, type ResourceState } from "alchemy/State";
7 import * as Effect from "effect/Effect";
8 import * as OrganizationLease from "./OrganizationLease.ts";
9
10 const { test } = OrganizationLease.make({ providers: AWS.providers() }, "shared");
11
12 // Read-only `list()` test (AWS account/region-scoped collection with a
13 // per-account service fan-out). Resolve the provider from context via the
14 // typed `Provider.findProvider`, call `list()`, and assert the result is a
15 // well-typed `Attributes[]`.
16 //
17 // `list()` is designed to degrade gracefully off the org management account:
18 // `listDelegatedAdministrators` rejects with `AWSOrganizationsNotInUseException`
19 // / `AccessDeniedException` / `UnsupportedAPIEndpointException` when the caller
20 // isn't an org management/delegated account, which `list()` catches and maps to
21 // `[]`. So this case passes on any account — it just returns `[]` when the
22 // account can't enumerate delegated administrators.
23 test.provider(
24 "list enumerates delegated administrators",
25 () =>
26 Effect.gen(function* () {
27 const provider = yield* Provider.findProvider(DelegatedAdministrator);
28 const all = yield* provider.list();
29
30 expect(Array.isArray(all)).toBe(true);
31
32 for (const item of all) {
33 expect(typeof item.accountId).toBe("string");
34 expect(typeof item.servicePrincipal).toBe("string");
35 }
36 }),
37 { tags: ["provider:aws", "provider:aws:organizations", "live"] },
38 );
39
40 // Full lifecycle list test — requires an org MANAGEMENT account plus a member
41 // account to register as a delegated administrator. Gate behind env vars so an
42 // entitled account runs it unchanged. Off a management account
43 // `registerDelegatedAdministrator` rejects with
44 // `AWSOrganizationsNotInUseException` / `AccessDeniedException`, so this is
45 // skipped by default. On the emulator the organization lease provisions the
46 // member account when AWS_ORG_DELEGATED_ADMIN_ACCOUNT_ID is unset.
47 const servicePrincipal =
48 process.env.AWS_ORG_DELEGATED_ADMIN_SERVICE_PRINCIPAL ?? "config.amazonaws.com";
49
50 // Destroying the test's resource deregisters the account, so refuse to take
51 // over a registration that existed before the test.
52 const resolveUnregisteredMember = Effect.gen(function* () {
53 const accountId = yield* OrganizationLease.delegatedAdminAccountId;
54 const services = yield* organizations
55 .listDelegatedServicesForAccount({ AccountId: accountId })
56 .pipe(
57 Effect.map((response) => response.DelegatedServices ?? []),
58 Effect.catchTag("AccountNotRegisteredException", () =>
59 Effect.succeed<organizations.DelegatedService[]>([]),
60 ),
61 );
62 if (services.some((item) => item.ServicePrincipal === servicePrincipal)) {
63 return yield* Effect.fail(
64 new Error(
65 `account ${accountId} is already a delegated administrator for ${servicePrincipal}`,
66 ),
67 );
68 }
69 return accountId;
70 });
71
72 // Both lifecycles own the same (account, principal) registration, so they
73 // must not overlap.
74 describe.sequential("delegated administrator lifecycle", () => {
75 test.provider.skipIf(!OrganizationLease.canProvideDelegatedAdminAccount)(
76 "list contains the deployed delegated administrator",
77 (stack) =>
78 Effect.gen(function* () {
79 yield* stack.destroy();
80 const memberAccountId = yield* resolveUnregisteredMember;
81
82 const admin = yield* stack.deploy(
83 Effect.gen(function* () {
84 return yield* DelegatedAdministrator("ListDelegatedAdmin", {
85 accountId: memberAccountId,
86 servicePrincipal,
87 });
88 }),
89 );
90
91 const provider = yield* Provider.findProvider(DelegatedAdministrator);
92 const all = yield* provider.list();
93
94 expect(
95 all.some(
96 (item) =>
97 item.accountId === admin.accountId &&
98 item.servicePrincipal === admin.servicePrincipal,
99 ),
100 ).toBe(true);
101
102 yield* stack.destroy();
103 }),
104 { tags: ["provider:aws", "provider:aws:organizations", "live"] },
105 );
106
107 // Regression test for https://github.com/alchemy-run/alchemy/issues/736.
108 //
109 // An interrupted first deploy persists the registration as
110 // `status: "creating"` with no attributes — and the Output-valued props
111 // (`accountId` typically comes from an `Account` resource) do not survive
112 // the state round-trip: they deserialize as `undefined`. Plan's
113 // creating-recovery branch then calls `provider.read` with those junk olds,
114 // which pre-fix crashed in
115 // `listDelegatedServicesForAccount({ AccountId: undefined })`
116 // (`ParseError: Expected string, got undefined`) and wedged the stack.
117 //
118 // Simulate exactly that state row after a real deploy and assert the next
119 // deploy recovers: `read` reports "not found", the engine re-drives the
120 // create, and reconcile observes the existing registration before
121 // registering — SAME (accountId, servicePrincipal) identity, no duplicate.
122 //
123 // Same gating as the lifecycle test above: requires an org MANAGEMENT
124 // account plus a member account to register (a management account cannot
125 // delegate itself — `ConstraintViolationException`), so this is skipped
126 // unless AWS_ORG_DELEGATED_ADMIN_ACCOUNT_ID is set or the emulator provides one.
127 test.provider.skipIf(!OrganizationLease.canProvideDelegatedAdminAccount)(
128 "recovers a half-created delegated administrator whose creating-state lost Output-valued props (#736)",
129 (stack) =>
130 Effect.gen(function* () {
131 yield* stack.destroy();
132 const memberAccountId = yield* resolveUnregisteredMember;
133
134 const deployAdmin = () =>
135 stack.deploy(
136 Effect.gen(function* () {
137 return yield* DelegatedAdministrator("WedgedDelegatedAdmin", {
138 accountId: memberAccountId,
139 servicePrincipal,
140 });
141 }),
142 );
143
144 const created = yield* deployAdmin();
145
146 // Rewrite the registration's persisted row into the wedged shape an
147 // interrupted deploy leaves behind: `creating`, no attributes, and
148 // every Output-valued prop lost in the round-trip.
149 const state = yield* yield* State;
150 const stage = stack.stage;
151 const fqns = yield* state.list({ stack: stack.name, stage });
152 const rows = yield* Effect.forEach(fqns, (fqn) =>
153 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
154 );
155 const wedged = rows.find(
156 (r): r is { fqn: string; row: ResourceState } =>
157 isResourceState(r.row) &&
158 r.row.resourceType === "AWS.Organizations.DelegatedAdministrator",
159 );
160 if (!wedged) {
161 return yield* Effect.die(
162 new Error("no AWS.Organizations.DelegatedAdministrator state row found after deploy"),
163 );
164 }
165 yield* state.set({
166 stack: stack.name,
167 stage,
168 fqn: wedged.fqn,
169 value: {
170 ...wedged.row,
171 status: "creating",
172 attr: undefined,
173 props: { ...wedged.row.props, accountId: undefined, servicePrincipal: undefined },
174 },
175 });
176
177 // Before the fix this failed in plan: `read` called
178 // `listDelegatedServicesForAccount({ AccountId: undefined })` with the
179 // junk olds.
180 const recovered = yield* deployAdmin();
181 expect(recovered.accountId).toEqual(created.accountId);
182 expect(recovered.servicePrincipal).toEqual(created.servicePrincipal);
183
184 yield* stack.destroy();
185 }),
186 { tags: ["provider:aws", "provider:aws:organizations", "live"], timeout: 240_000 },
187 );
188 });