@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 281 lines 9.73 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { WebACL } from "@alchemy.run/aws/WAFv2";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
6 import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
7 import * as wafv2 from "@distilled.cloud/aws/wafv2";
8 import * as Data from "effect/Data";
9 import * as Effect from "effect/Effect";
10 import * as Schedule from "effect/Schedule";
11 import { driftOf, repairDrift, waitForDrift } from "../drift.ts";
12
13 const { test } = Test.make({ providers: AWS.providers() });
14
15 class WebACLStillExists extends Data.TaggedError("WebACLStillExists")<{
16 readonly name: string;
17 }> {}
18
19 const assertWebAclDeleted = (name: string, id: string, scope: "REGIONAL" | "CLOUDFRONT") =>
20 wafv2.getWebACL({ Name: name, Scope: scope, Id: id }).pipe(
21 Effect.flatMap(() => Effect.fail(new WebACLStillExists({ name }))),
22 Effect.catchTag("WAFNonexistentItemException", () => Effect.void),
23 Effect.retry({
24 while: (e) => e._tag === "WebACLStillExists",
25 schedule: Schedule.max([Schedule.exponential(500), Schedule.recurs(8)]),
26 }),
27 );
28
29 const visibility = (metricName: string): WAFV2.VisibilityConfig => ({
30 SampledRequestsEnabled: true,
31 CloudWatchMetricsEnabled: true,
32 MetricName: metricName,
33 });
34
35 const BLOCKED_PATH = new TextEncoder().encode("/blocked");
36
37 // Flagship rule set: a managed rule group, a rate-based rule and a custom
38 // byte-match rule.
39 const flagshipRules: WAFV2.Rule[] = [
40 {
41 Name: "managed-common",
42 Priority: 0,
43 Statement: {
44 ManagedRuleGroupStatement: {
45 VendorName: "AWS",
46 Name: "AWSManagedRulesCommonRuleSet",
47 },
48 },
49 OverrideAction: { None: {} },
50 VisibilityConfig: visibility("managed-common"),
51 },
52 {
53 Name: "rate-limit",
54 Priority: 1,
55 Statement: {
56 RateBasedStatement: { Limit: 100, AggregateKeyType: "IP" },
57 },
58 Action: { Block: {} },
59 VisibilityConfig: visibility("rate-limit"),
60 },
61 {
62 Name: "block-path",
63 Priority: 2,
64 Statement: {
65 ByteMatchStatement: {
66 SearchString: BLOCKED_PATH,
67 FieldToMatch: { UriPath: {} },
68 TextTransformations: [{ Priority: 0, Type: "LOWERCASE" }],
69 PositionalConstraint: "STARTS_WITH",
70 },
71 },
72 Action: { Block: {} },
73 VisibilityConfig: visibility("block-path"),
74 },
75 ];
76
77 test.provider(
78 "create with managed + rate-based + byte-match rules, update, delete",
79 (stack) =>
80 Effect.gen(function* () {
81 // reconcile away any prior partial/crashed deployment
82 yield* stack.destroy();
83
84 const acl = yield* stack.deploy(
85 Effect.gen(function* () {
86 return yield* WebACL("LifecycleAcl", {
87 rules: flagshipRules,
88 tags: { Environment: "test" },
89 });
90 }),
91 );
92
93 expect(acl.scope).toBe("REGIONAL");
94 expect(acl.webAclArn).toContain(":wafv2:");
95 expect(acl.webAclArn).toContain("/webacl/");
96
97 // out-of-band verification via distilled
98 const created = yield* wafv2.getWebACL({
99 Name: acl.webAclName,
100 Scope: "REGIONAL",
101 Id: acl.webAclId,
102 });
103 expect(created.WebACL?.DefaultAction?.Allow).toBeDefined();
104 const ruleNames = (created.WebACL?.Rules ?? []).map((r) => r.Name);
105 expect(ruleNames).toEqual(["managed-common", "rate-limit", "block-path"]);
106 const managed = created.WebACL?.Rules?.find((r) => r.Name === "managed-common");
107 expect(managed?.Statement?.ManagedRuleGroupStatement?.Name).toBe(
108 "AWSManagedRulesCommonRuleSet",
109 );
110 const rate = created.WebACL?.Rules?.find((r) => r.Name === "rate-limit");
111 expect(rate?.Statement?.RateBasedStatement?.Limit).toBe(100);
112
113 const tags = yield* wafv2.listTagsForResource({
114 ResourceARN: acl.webAclArn,
115 });
116 const tagRecord = Object.fromEntries(
117 (tags.TagInfoForResource?.TagList ?? []).map((t) => [t.Key, t.Value]),
118 );
119 expect(tagRecord.Environment).toBe("test");
120 expect(tagRecord["alchemy::id"]).toBe("LifecycleAcl");
121
122 // update in place: block by default, drop to a single rule, retag
123 const updated = yield* stack.deploy(
124 Effect.gen(function* () {
125 return yield* WebACL("LifecycleAcl", {
126 defaultAction: { Block: {} },
127 description: "block by default",
128 rules: [flagshipRules[1]],
129 tags: { Environment: "test", Extra: "1" },
130 });
131 }),
132 );
133 expect(updated.webAclId).toBe(acl.webAclId);
134
135 const afterUpdate = yield* wafv2.getWebACL({
136 Name: acl.webAclName,
137 Scope: "REGIONAL",
138 Id: acl.webAclId,
139 });
140 expect(afterUpdate.WebACL?.DefaultAction?.Block).toBeDefined();
141 expect(afterUpdate.WebACL?.Description).toBe("block by default");
142 expect(afterUpdate.WebACL?.Rules?.length).toBe(1);
143 expect(afterUpdate.WebACL?.Rules?.[0]?.Name).toBe("rate-limit");
144
145 const updatedTags = yield* wafv2.listTagsForResource({
146 ResourceARN: acl.webAclArn,
147 });
148 const updatedRecord = Object.fromEntries(
149 (updatedTags.TagInfoForResource?.TagList ?? []).map((t) => [t.Key, t.Value]),
150 );
151 expect(updatedRecord.Extra).toBe("1");
152
153 yield* stack.destroy();
154 yield* assertWebAclDeleted(acl.webAclName, acl.webAclId, "REGIONAL");
155 }),
156 { tags: ["provider:aws", "provider:aws:wafv2", "live"], timeout: 120_000 },
157 );
158
159 test.provider(
160 "explicit name change replaces the web ACL",
161 (stack) =>
162 Effect.gen(function* () {
163 // reconcile away any prior partial/crashed deployment
164 yield* stack.destroy();
165
166 const first = yield* stack.deploy(
167 Effect.gen(function* () {
168 return yield* WebACL("RenamedAcl", {
169 webAclName: "alchemy-test-wafv2-rename-a",
170 });
171 }),
172 );
173 expect(first.webAclName).toBe("alchemy-test-wafv2-rename-a");
174
175 const second = yield* stack.deploy(
176 Effect.gen(function* () {
177 return yield* WebACL("RenamedAcl", {
178 webAclName: "alchemy-test-wafv2-rename-b",
179 });
180 }),
181 );
182 expect(second.webAclName).toBe("alchemy-test-wafv2-rename-b");
183 expect(second.webAclId).not.toBe(first.webAclId);
184
185 // the old web ACL is gone after replacement
186 yield* assertWebAclDeleted(first.webAclName, first.webAclId, "REGIONAL");
187
188 yield* stack.destroy();
189 yield* assertWebAclDeleted(second.webAclName, second.webAclId, "REGIONAL");
190 }),
191 { tags: ["provider:aws", "provider:aws:wafv2", "live"], timeout: 120_000 },
192 );
193
194 // CLOUDFRONT-scoped web ACLs are pinned to us-east-1 by the provider. The
195 // lifecycle is identical to REGIONAL (~2s; a web ACL bills $5/month prorated
196 // hourly). Opt out with AWS_TEST_WAF_CLOUDFRONT=0.
197 test.provider.skipIf(process.env.AWS_TEST_WAF_CLOUDFRONT === "0")(
198 "CLOUDFRONT scope provisions in us-east-1",
199 (stack) =>
200 Effect.gen(function* () {
201 // reconcile away any prior partial/crashed deployment
202 yield* stack.destroy();
203
204 const acl = yield* stack.deploy(
205 Effect.gen(function* () {
206 return yield* WebACL("EdgeAcl", { scope: "CLOUDFRONT" });
207 }),
208 );
209 expect(acl.scope).toBe("CLOUDFRONT");
210 expect(acl.webAclArn).toContain(":us-east-1:");
211 expect(acl.webAclArn).toContain("global/webacl/");
212
213 // out-of-band verification pinned to us-east-1
214 const created = yield* wafv2
215 .getWebACL({
216 Name: acl.webAclName,
217 Scope: "CLOUDFRONT",
218 Id: acl.webAclId,
219 })
220 .pipe(Effect.provideService(AwsRegion, Effect.succeed("us-east-1")));
221 expect(created.WebACL?.ARN).toBe(acl.webAclArn);
222
223 yield* stack.destroy();
224 yield* assertWebAclDeleted(acl.webAclName, acl.webAclId, "CLOUDFRONT").pipe(
225 Effect.provideService(AwsRegion, Effect.succeed("us-east-1")),
226 );
227 }),
228 { tags: ["provider:aws", "provider:aws:wafv2", "live"], timeout: 120_000 },
229 );
230
231 // #2688: `read` must observe the rules, default action and tags, or an
232 // out-of-band change reads as `unchanged`.
233 test.provider(
234 "drift detects and repairs out-of-band rule and default action changes",
235 (stack) =>
236 Effect.gen(function* () {
237 yield* stack.destroy();
238
239 const acl = yield* stack.deploy(
240 WebACL("DriftAcl", {
241 rules: [flagshipRules[1], flagshipRules[2]],
242 tags: { team: "declared" },
243 }),
244 );
245 expect((yield* driftOf(stack, "DriftAcl"))?.action).toBe("unchanged");
246
247 const current = yield* wafv2.getWebACL({
248 Name: acl.webAclName,
249 Scope: "REGIONAL",
250 Id: acl.webAclId,
251 });
252 yield* wafv2.updateWebACL({
253 Name: acl.webAclName,
254 Scope: "REGIONAL",
255 Id: acl.webAclId,
256 LockToken: current.LockToken!,
257 DefaultAction: { Block: {} },
258 Rules: [flagshipRules[1]],
259 VisibilityConfig: current.WebACL!.VisibilityConfig,
260 });
261
262 const drifted = yield* waitForDrift(stack, "DriftAcl", "drifted");
263 expect(drifted?.attr?.configuration?.defaultAction).toEqual({ Block: {} });
264 expect(drifted?.attr?.configuration?.rules).toHaveLength(1);
265
266 const repaired = yield* repairDrift(stack);
267 expect(repaired.resources.DriftAcl?.action).toBe("repaired");
268 expect((yield* waitForDrift(stack, "DriftAcl", "unchanged"))?.action).toBe("unchanged");
269 const restored = yield* wafv2.getWebACL({
270 Name: acl.webAclName,
271 Scope: "REGIONAL",
272 Id: acl.webAclId,
273 });
274 expect(restored.WebACL?.DefaultAction?.Allow).toBeDefined();
275 expect(restored.WebACL?.Rules?.map((r) => r.Name)).toEqual(["rate-limit", "block-path"]);
276
277 yield* stack.destroy();
278 yield* assertWebAclDeleted(acl.webAclName, acl.webAclId, "REGIONAL");
279 }),
280 { tags: ["provider:aws", "provider:aws:wafv2", "live"], timeout: 180_000 },
281 );