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

main
ts 229 lines 9.36 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { Policy, PolicyAttachment, Root, RootPolicyType } from "@alchemy.run/aws/Organizations";
3 import { 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 Schedule from "effect/Schedule";
9 import * as OrganizationLease from "./OrganizationLease.ts";
10
11 const { test } = OrganizationLease.make({ providers: AWS.providers() }, "shared");
12
13 // `list()` enumerates every (policyId, targetId) attachment by fanning out over
14 // all policy types (listPolicies per type) and listing each policy's targets
15 // (listTargetsForPolicy per policy). This runs read-only: when the testing
16 // account isn't an org management account / delegated administrator, the typed
17 // AccessDeniedException / AWSOrganizationsNotInUseException catches degrade the
18 // result to [], so the assertion holds without deploying anything.
19 test.provider(
20 "list enumerates policy attachments",
21 () =>
22 Effect.gen(function* () {
23 const provider = yield* Provider.findProvider(PolicyAttachment);
24 const all = yield* provider.list();
25
26 expect(Array.isArray(all)).toBe(true);
27
28 for (const attachment of all) {
29 expect(typeof attachment.policyId).toBe("string");
30 expect(typeof attachment.targetId).toBe("string");
31 }
32 }),
33 { tags: ["provider:aws", "provider:aws:organizations", "live"] },
34 );
35
36 // Regression test for https://github.com/alchemy-run/alchemy/issues/736.
37 //
38 // An interrupted first deploy persists the attachment as `status: "creating"`
39 // with no attributes — and the Output-valued props (`policyId` from the Policy
40 // resource, `targetId` from the Root or RootPolicyType resource) do not survive the
41 // state round-trip: they deserialize as `undefined`. Plan's creating-recovery
42 // branch then calls `provider.read` with those junk props, which crashed in
43 // `listTargetsForPolicy({ PolicyId: undefined })` and wedged the stack.
44 //
45 // Simulate exactly that state row after a real deploy and assert the next
46 // deploy recovers: `read` reports "not found", the engine re-drives the
47 // create, and reconcile observes the existing attachment before attaching —
48 // SAME (policyId, targetId) identity, no duplicate attachment.
49 //
50 // Requires an org MANAGEMENT account (enablePolicyType / createPolicy /
51 // attachPolicy all reject off one), so gate behind the same env var the other
52 // Organizations lifecycle tests use.
53 test.provider.skipIf(!process.env.AWS_ORG_MANAGEMENT_ACCOUNT)(
54 "recovers a half-created attachment whose creating-state lost Output-valued props (#736)",
55 (stack) =>
56 Effect.gen(function* () {
57 const policyName = "alchemy-test-736-attachment";
58
59 // A prior interrupted run may have left an (untagged, hence unowned)
60 // SCP with our deterministic name behind — the adoption probe would
61 // then fail the create with `OwnedBySomeoneElse`. Clean it up
62 // out-of-band before deploying, and again on scope close.
63 const cleanLeftoverPolicies = Effect.gen(function* () {
64 const policies = yield* organizations.listPolicies({
65 Filter: "SERVICE_CONTROL_POLICY",
66 });
67 const leftovers = (policies.Policies ?? []).filter(
68 (policy): policy is organizations.PolicySummary & { Id: string } =>
69 policy.Name === policyName && policy.Id != null,
70 );
71 for (const leftover of leftovers) {
72 const targets = yield* organizations
73 .listTargetsForPolicy({ PolicyId: leftover.Id })
74 .pipe(
75 Effect.catchTag("PolicyNotFoundException", () => Effect.succeed({ Targets: [] })),
76 );
77 for (const target of targets.Targets ?? []) {
78 if (target.TargetId == null) continue;
79 yield* organizations
80 .detachPolicy({
81 PolicyId: leftover.Id,
82 TargetId: target.TargetId,
83 })
84 .pipe(
85 Effect.catchTag(
86 [
87 "PolicyNotAttachedException",
88 "PolicyNotFoundException",
89 "TargetNotFoundException",
90 ],
91 () => Effect.void,
92 ),
93 );
94 }
95 // The detach above can lag — retry the delete through the typed
96 // `PolicyInUseException` (bounded), and tolerate already-gone.
97 yield* organizations.deletePolicy({ PolicyId: leftover.Id }).pipe(
98 Effect.retry({
99 while: (error) => error._tag === "PolicyInUseException",
100 schedule: Schedule.spaced("3 seconds"),
101 times: 8,
102 }),
103 Effect.catchTag("PolicyNotFoundException", () => Effect.void),
104 );
105 }
106 });
107 yield* cleanLeftoverPolicies;
108 yield* Effect.addFinalizer(() => cleanLeftoverPolicies.pipe(Effect.ignore));
109
110 yield* stack.destroy();
111
112 const scpEnabled = organizations
113 .listRoots({})
114 .pipe(
115 Effect.map((page) =>
116 (page.Roots ?? []).some((root) =>
117 (root.PolicyTypes ?? []).some(
118 (summary) =>
119 summary.Type === "SERVICE_CONTROL_POLICY" && summary.Status === "ENABLED",
120 ),
121 ),
122 ),
123 );
124 // Own the SCP policy type only if it was disabled before the test:
125 // destroying an adopted enablement would detach every SCP in the
126 // organization.
127 const ownScpType = !(yield* scpEnabled);
128
129 const deployStack = (includeAttachment: boolean) =>
130 stack.deploy(
131 Effect.gen(function* () {
132 // Import-style resource — adopts the single organization root.
133 const root = yield* Root("WedgedRoot", {});
134 const targetId = ownScpType
135 ? (yield* RootPolicyType("WedgedScpType", {
136 rootId: root.rootId,
137 policyType: "SERVICE_CONTROL_POLICY",
138 })).rootId
139 : root.rootId;
140 // Allow-all SCP — attaching it alongside the AWS-managed
141 // FullAWSAccess policy changes nothing about effective access.
142 const policy = yield* Policy("WedgedScp", {
143 name: policyName,
144 type: "SERVICE_CONTROL_POLICY",
145 document: {
146 Version: "2012-10-17",
147 Statement: [{ Effect: "Allow", Action: ["*"], Resource: "*" }],
148 },
149 });
150 if (!includeAttachment) {
151 return undefined;
152 }
153 return yield* PolicyAttachment("WedgedAttachment", {
154 // Both identity props are Output-valued — the #736 shape.
155 policyId: policy.policyId,
156 // When the test owns the policy type, thread its output so the
157 // attachment plans after SERVICE_CONTROL_POLICY is enabled.
158 targetId,
159 });
160 }),
161 );
162
163 // Stage 1: enable the policy type (if owned) + create the SCP, WITHOUT the
164 // attachment. `enablePolicyType` completes asynchronously
165 // (PENDING_ENABLE), and `attachPolicy` rejects with the typed
166 // `PolicyTypeNotEnabledException` until it lands — so wait (bounded)
167 // for ENABLED before deploying the attachment.
168 yield* deployStack(false);
169 yield* scpEnabled.pipe(
170 Effect.repeat({
171 schedule: Schedule.spaced("3 seconds"),
172 until: (enabled) => enabled,
173 times: 10,
174 }),
175 );
176
177 // Stage 2: deploy the attachment itself.
178 const created = yield* deployStack(true);
179 if (created === undefined) {
180 return yield* Effect.die(new Error("stage-2 deploy returned no attachment"));
181 }
182
183 // Rewrite the attachment's persisted row into the wedged shape an
184 // interrupted deploy leaves behind: `creating`, no attributes, and
185 // every Output-valued prop lost in the round-trip.
186 const state = yield* yield* State;
187 const stage = stack.stage;
188 const fqns = yield* state.list({ stack: stack.name, stage });
189 const rows = yield* Effect.forEach(fqns, (fqn) =>
190 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
191 );
192 const wedged = rows.find(
193 (r): r is { fqn: string; row: ResourceState } =>
194 isResourceState(r.row) && r.row.resourceType === "AWS.Organizations.PolicyAttachment",
195 );
196 if (!wedged) {
197 return yield* Effect.die(
198 new Error("no AWS.Organizations.PolicyAttachment state row found after deploy"),
199 );
200 }
201 yield* state.set({
202 stack: stack.name,
203 stage,
204 fqn: wedged.fqn,
205 value: {
206 ...wedged.row,
207 status: "creating",
208 attr: undefined,
209 props: {
210 ...wedged.row.props,
211 policyId: undefined,
212 targetId: undefined,
213 },
214 },
215 });
216
217 // Before the fix this failed in plan: `read` called
218 // `listTargetsForPolicy({ PolicyId: undefined })` with the junk olds.
219 const recovered = yield* deployStack(true);
220 expect(recovered?.policyId).toEqual(created.policyId);
221 expect(recovered?.targetId).toEqual(created.targetId);
222
223 yield* stack.destroy();
224 }),
225 {
226 tags: ["provider:aws", "provider:aws:organizations", "live"],
227 timeout: 240_000,
228 },
229 );