@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, 04:45 UTC

main
ts 219 lines 8.69 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { ConfigRule } from "@alchemy.run/aws/Config";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as config from "@distilled.cloud/aws/config-service";
6 import * as iam from "@distilled.cloud/aws/iam";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as Schedule from "effect/Schedule";
10 import { makeConfigTestLease } from "./TestLease.ts";
11
12 const { test, beforeAll, afterAll } = Test.make({ providers: AWS.providers() });
13 const testLease = makeConfigTestLease();
14
15 // Acquire outside the individual lifecycle timer. Bindings holds the same
16 // account/Region recorder lease for its file-long fixture, and queueing behind
17 // it is scheduling rather than part of this rule's cloud-operation budget.
18 beforeAll(testLease.acquire, { timeout: 240_000 });
19 afterAll(testLease.release);
20
21 // Ungated typed-error probe: prove the distilled error union carries the
22 // not-found tag this provider's read/delete paths depend on. Runs in every
23 // CI pass at near-zero cost.
24 test.provider(
25 "describeConfigRules on a nonexistent rule fails with NoSuchConfigRuleException",
26 () =>
27 Effect.gen(function* () {
28 const error = yield* Effect.flip(
29 config.describeConfigRules({
30 ConfigRuleNames: ["alchemy-nonexistent-config-rule-probe"],
31 }),
32 );
33 expect(error._tag).toBe("NoSuchConfigRuleException");
34 }),
35 { tags: ["provider:aws", "provider:aws:config", "live"] },
36 );
37
38 const findRule = (ruleName: string) =>
39 config.describeConfigRules({ ConfigRuleNames: [ruleName] }).pipe(
40 Effect.map((r) => (r.ConfigRules ?? []).at(0)),
41 Effect.catchTag("NoSuchConfigRuleException", () => Effect.succeed(undefined)),
42 );
43
44 class RuleStillExists extends Data.TaggedError("RuleStillExists")<{
45 readonly ruleName: string;
46 readonly state: string;
47 }> {}
48
49 // Rule deletion is asynchronous — DELETING is an irreversible terminal
50 // trajectory, so gone-or-DELETING both count as deleted.
51 const assertRuleDeleting = (ruleName: string) =>
52 findRule(ruleName).pipe(
53 Effect.flatMap((rule) =>
54 rule === undefined || rule.ConfigRuleState === "DELETING"
55 ? Effect.void
56 : Effect.fail(
57 new RuleStillExists({
58 ruleName,
59 state: rule.ConfigRuleState ?? "unknown",
60 }),
61 ),
62 ),
63 Effect.retry({
64 while: (e) => e._tag === "RuleStillExists",
65 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
66 }),
67 );
68
69 // PutConfigRule requires a configuration recorder in the account/region
70 // (NoAvailableConfigurationRecorderException otherwise). Capture-and-restore:
71 // if the account has none, stand up a minimal recorder on the Config
72 // service-linked role for the duration of the test and delete it afterwards;
73 // an existing foreign recorder is left untouched. The recorder name is a
74 // deterministic constant unique to this test so a leftover from a
75 // previously-killed run is RECLAIMED (and thus cleaned up at the end)
76 // instead of orphaning forever.
77 const TEST_RECORDER_NAME = "alchemy-test-configrule-recorder";
78
79 const ensureRecorder = Effect.gen(function* () {
80 const existing = yield* config.describeConfigurationRecorders({});
81 const recorders = existing.ConfigurationRecorders ?? [];
82 if (recorders.some((r) => r.name === TEST_RECORDER_NAME)) {
83 // Leftover from a previously-killed run — reclaim it so the release
84 // finalizer deletes it when this run finishes.
85 return true;
86 }
87 if (recorders.length > 0) {
88 // A foreign recorder already exists (only one per account/region is
89 // allowed) — use it, never touch it.
90 return false;
91 }
92 yield* iam
93 .createServiceLinkedRole({ AWSServiceName: "config.amazonaws.com" })
94 .pipe(Effect.catchTag("InvalidInputException", () => Effect.succeed(undefined)));
95 const role = yield* iam.getRole({ RoleName: "AWSServiceRoleForConfig" });
96 // A freshly-created service-linked role can be transiently rejected until
97 // IAM propagates.
98 yield* config
99 .putConfigurationRecorder({
100 ConfigurationRecorder: {
101 name: TEST_RECORDER_NAME,
102 roleARN: role.Role.Arn,
103 recordingGroup: { resourceTypes: ["AWS::S3::Bucket"] },
104 },
105 })
106 .pipe(
107 Effect.retry({
108 while: (e) => e._tag === "InvalidRoleException",
109 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(15)]),
110 }),
111 );
112 return true;
113 });
114
115 // Idempotent: tolerates the recorder already being gone.
116 const removeRecorderIfCreated = (created: boolean) =>
117 created
118 ? config
119 .deleteConfigurationRecorder({
120 ConfigurationRecorderName: TEST_RECORDER_NAME,
121 })
122 .pipe(
123 Effect.catchTag("NoSuchConfigurationRecorderException", () => Effect.void),
124 Effect.orDie,
125 )
126 : Effect.void;
127
128 test.provider(
129 "create, update, replace on rename, delete managed config rule",
130 (stack) =>
131 Effect.gen(function* () {
132 yield* stack.destroy();
133 // acquireRelease guarantees the out-of-band recorder is deleted on
134 // success, failure, AND interruption; the deterministic name +
135 // reclaim in ensureRecorder means a re-run converges on any orphan
136 // from a previously-killed run.
137 yield* Effect.acquireRelease(ensureRecorder, (created) => removeRecorderIfCreated(created));
138
139 yield* Effect.gen(function* () {
140 const rule = yield* stack.deploy(
141 Effect.gen(function* () {
142 return yield* ConfigRule("VersioningRule", {
143 description: "buckets must have versioning enabled",
144 source: {
145 owner: "AWS",
146 sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED",
147 },
148 scope: { complianceResourceTypes: ["AWS::S3::Bucket"] },
149 tags: { Environment: "test" },
150 });
151 }),
152 );
153
154 expect(rule.configRuleName).toBeDefined();
155 expect(rule.configRuleArn).toContain(":config-rule/");
156 expect(rule.configRuleId).toContain("config-rule-");
157
158 // Out-of-band verification via distilled.
159 const created = yield* findRule(rule.configRuleName);
160 expect(created?.Source.Owner).toBe("AWS");
161 expect(created?.Source.SourceIdentifier).toBe("S3_BUCKET_VERSIONING_ENABLED");
162 expect(created?.Description).toBe("buckets must have versioning enabled");
163 expect(created?.Scope?.ComplianceResourceTypes).toEqual(["AWS::S3::Bucket"]);
164 const tags = yield* config
165 .listTagsForResource({ ResourceArn: rule.configRuleArn })
166 .pipe(Effect.map((r) => Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value]))));
167 expect(tags.Environment).toBe("test");
168 expect(tags["alchemy::id"]).toBe("VersioningRule");
169
170 // Update the description and tags in place.
171 const updated = yield* stack.deploy(
172 Effect.gen(function* () {
173 return yield* ConfigRule("VersioningRule", {
174 description: "buckets must have versioning enabled (v2)",
175 source: {
176 owner: "AWS",
177 sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED",
178 },
179 scope: { complianceResourceTypes: ["AWS::S3::Bucket"] },
180 tags: { Environment: "prod" },
181 });
182 }),
183 );
184 expect(updated.configRuleName).toBe(rule.configRuleName);
185 expect(updated.configRuleArn).toBe(rule.configRuleArn);
186
187 const afterUpdate = yield* findRule(rule.configRuleName);
188 expect(afterUpdate?.Description).toBe("buckets must have versioning enabled (v2)");
189 const updatedTags = yield* config
190 .listTagsForResource({ ResourceArn: rule.configRuleArn })
191 .pipe(Effect.map((r) => Object.fromEntries((r.Tags ?? []).map((t) => [t.Key, t.Value]))));
192 expect(updatedTags.Environment).toBe("prod");
193
194 // Renaming replaces the rule.
195 const renamed = yield* stack.deploy(
196 Effect.gen(function* () {
197 return yield* ConfigRule("VersioningRule", {
198 configRuleName: "alchemy-test-config-rule-renamed",
199 source: {
200 owner: "AWS",
201 sourceIdentifier: "S3_BUCKET_VERSIONING_ENABLED",
202 },
203 scope: { complianceResourceTypes: ["AWS::S3::Bucket"] },
204 });
205 }),
206 );
207 expect(renamed.configRuleName).toBe("alchemy-test-config-rule-renamed");
208 expect(renamed.configRuleArn).not.toBe(rule.configRuleArn);
209 yield* assertRuleDeleting(rule.configRuleName);
210
211 yield* stack.destroy();
212 yield* assertRuleDeleting(renamed.configRuleName);
213 });
214 }),
215 {
216 tags: ["provider:aws", "provider:aws:config", "provider:aws:iam", "live"],
217 timeout: 120_000,
218 },
219 );