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

main
ts 529 lines 18.3 KB
Raw
1 import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
2 import * as wafv2 from "@distilled.cloud/aws/wafv2";
3 import { Unowned } from "alchemy/AdoptPolicy";
4 import { deepEqual, isResolved } from "alchemy/Diff";
5 import { createPhysicalName } from "alchemy/PhysicalName";
6 import * as Provider from "alchemy/Provider";
7 import { Resource } from "alchemy/Resource";
8 import { createInternalTags, createTagsList, hasAlchemyTags } from "alchemy/Tags";
9 import * as Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import { plainJson } from "../internal/Observe.ts";
12 import type { Providers } from "../Providers.ts";
13 import {
14 fetchWafTags,
15 normalizeWafRules,
16 retryAssociatedItem,
17 retryOptimisticLock,
18 retryUnavailableEntity,
19 syncWafTags,
20 type WafScope,
21 withWafScope,
22 } from "./internal.ts";
23
24 export class WebACLUnexpectedResponse extends Data.TaggedError("WebACLUnexpectedResponse")<{
25 readonly message: string;
26 readonly cause?: unknown;
27 }> {}
28
29 export interface WebACLProps {
30 /**
31 * Name of the web ACL. Must match `^[\w\-]+$` and be 1-128 characters.
32 * Changing the name replaces the web ACL.
33 * @default a physical name derived from the app, stage and logical ID
34 */
35 webAclName?: string;
36 /**
37 * Scope of the web ACL. `REGIONAL` protects regional resources (ALB,
38 * API Gateway, AppSync, Cognito user pool, App Runner, Verified Access)
39 * in the ambient region; `CLOUDFRONT` protects CloudFront distributions
40 * and is always provisioned in `us-east-1` (the provider pins the region
41 * automatically). Changing the scope replaces the web ACL.
42 * @default "REGIONAL"
43 */
44 scope?: WafScope;
45 /**
46 * Action to take on a request that matches none of the rules.
47 * @default { Allow: {} }
48 */
49 defaultAction?: WAFV2.DefaultAction;
50 /**
51 * Description of the web ACL.
52 */
53 description?: string;
54 /**
55 * Rules to evaluate, in `Priority` order. Supports custom statements
56 * (byte match, rate-based, geo, IP set references, ...) and managed rule
57 * groups (e.g. `AWSManagedRulesCommonRuleSet`). Raw WAFv2 API shapes.
58 */
59 rules?: WAFV2.Rule[];
60 /**
61 * CloudWatch metrics and sampled-request settings for the web ACL itself.
62 * @default sampled requests + metrics enabled, MetricName = the web ACL name
63 */
64 visibilityConfig?: WAFV2.VisibilityConfig;
65 /**
66 * Custom response bodies referenced by rule actions in this web ACL.
67 */
68 customResponseBodies?: {
69 [key: string]: WAFV2.CustomResponseBody | undefined;
70 };
71 /**
72 * Default CAPTCHA immunity-time configuration.
73 */
74 captchaConfig?: WAFV2.CaptchaConfig;
75 /**
76 * Default challenge immunity-time configuration.
77 */
78 challengeConfig?: WAFV2.ChallengeConfig;
79 /**
80 * Domains that WAF accepts for CAPTCHA/challenge tokens.
81 */
82 tokenDomains?: string[];
83 /**
84 * Association-level configuration (e.g. request body size limits).
85 */
86 associationConfig?: WAFV2.AssociationConfig;
87 /**
88 * User-defined tags to apply to the web ACL.
89 */
90 tags?: Record<string, string>;
91 }
92
93 export interface WebACL extends Resource<
94 "AWS.WAFv2.WebACL",
95 WebACLProps,
96 {
97 /**
98 * Name of the web ACL.
99 */
100 webAclName: string;
101 /**
102 * WAF-assigned unique ID of the web ACL.
103 */
104 webAclId: string;
105 /**
106 * ARN of the web ACL. Use this to associate regional resources
107 * (via {@link WebACLAssociation}) or as CloudFront's `webAclId`.
108 */
109 webAclArn: string;
110 /**
111 * Scope the web ACL was created in.
112 */
113 scope: WafScope;
114 /**
115 * The rules, default action, visibility settings, the optional aspects
116 * the props declare (custom responses, CAPTCHA/challenge, association
117 * config) and the tags, as observed. Lets `alchemy drift` detect
118 * out-of-band changes.
119 */
120 configuration?: {
121 defaultAction?: unknown;
122 description?: string;
123 rules: unknown[];
124 visibilityConfig?: unknown;
125 tokenDomains?: string[];
126 customResponseBodies?: unknown;
127 captchaConfig?: unknown;
128 challengeConfig?: unknown;
129 associationConfig?: unknown;
130 tags: Record<string, string>;
131 };
132 },
133 never,
134 Providers
135 > {}
136
137 /**
138 * An AWS WAFv2 Web ACL — a collection of rules that inspect and control web
139 * requests for the AWS resources it is associated with.
140 *
141 * `REGIONAL` web ACLs protect regional resources (Application Load Balancer,
142 * API Gateway, AppSync, Cognito user pools, App Runner, Verified Access) via
143 * {@link WebACLAssociation}. `CLOUDFRONT` web ACLs protect CloudFront
144 * distributions (set `Distribution.webAclId` to the web ACL's ARN) and are
145 * always provisioned in `us-east-1` — the provider pins the region for you.
146 *
147 * ### Creating Web ACLs
148 * **Example:** Allow-by-Default Web ACL with a Managed Rule Group
149 * ```typescript
150 * const acl = yield* AWS.WAFv2.WebACL("ApiFirewall", {
151 * rules: [
152 * {
153 * Name: "common-rule-set",
154 * Priority: 0,
155 * Statement: {
156 * ManagedRuleGroupStatement: {
157 * VendorName: "AWS",
158 * Name: "AWSManagedRulesCommonRuleSet",
159 * },
160 * },
161 * OverrideAction: { None: {} },
162 * VisibilityConfig: {
163 * SampledRequestsEnabled: true,
164 * CloudWatchMetricsEnabled: true,
165 * MetricName: "common-rule-set",
166 * },
167 * },
168 * ],
169 * });
170 * ```
171 *
172 * **Example:** Rate Limiting Requests per IP
173 * ```typescript
174 * const acl = yield* AWS.WAFv2.WebACL("RateLimited", {
175 * defaultAction: { Allow: {} },
176 * rules: [
177 * {
178 * Name: "rate-limit",
179 * Priority: 0,
180 * Statement: {
181 * RateBasedStatement: { Limit: 100, AggregateKeyType: "IP" },
182 * },
183 * Action: { Block: {} },
184 * VisibilityConfig: {
185 * SampledRequestsEnabled: true,
186 * CloudWatchMetricsEnabled: true,
187 * MetricName: "rate-limit",
188 * },
189 * },
190 * ],
191 * });
192 * ```
193 *
194 * ### CloudFront Scope
195 * **Example:** Web ACL for a CloudFront Distribution
196 * ```typescript
197 * const acl = yield* AWS.WAFv2.WebACL("EdgeFirewall", {
198 * scope: "CLOUDFRONT", // provisioned in us-east-1 automatically
199 * defaultAction: { Allow: {} },
200 * });
201 *
202 * const distribution = yield* AWS.CloudFront.Distribution("Site", {
203 * // ...
204 * webAclId: acl.webAclArn,
205 * });
206 * ```
207 *
208 * ### Protecting Regional Resources
209 * **Example:** Associate with a Cognito User Pool
210 * ```typescript
211 * const association = yield* AWS.WAFv2.WebACLAssociation("PoolFirewall", {
212 * webAclArn: acl.webAclArn,
213 * resourceArn: userPool.userPoolArn,
214 * });
215 * ```
216 *
217 * @resource
218 */
219 export const WebACL = Resource<WebACL>("AWS.WAFv2.WebACL");
220
221 const defaultScope: WafScope = "REGIONAL";
222
223 const defaultVisibilityConfig = (name: string): WAFV2.VisibilityConfig => ({
224 SampledRequestsEnabled: true,
225 CloudWatchMetricsEnabled: true,
226 MetricName: name,
227 });
228
229 const toAttrs = (acl: WAFV2.WebACL, scope: WafScope) => ({
230 webAclName: acl.Name,
231 webAclId: acl.Id,
232 webAclArn: acl.ARN,
233 scope,
234 });
235
236 /**
237 * The configuration `read` and `reconcile` both report, so a converged web
238 * ACL reads unchanged. Aspects WAF fills with defaults are observed only
239 * when the props declare them, matching what reconcile converges.
240 */
241 const observeWebACLConfiguration = (
242 acl: WAFV2.WebACL,
243 props: WebACLProps | undefined,
244 tags: Record<string, string>,
245 ) =>
246 plainJson({
247 defaultAction: acl.DefaultAction,
248 description: acl.Description || undefined,
249 rules: acl.Rules ?? [],
250 visibilityConfig: acl.VisibilityConfig,
251 tokenDomains: acl.TokenDomains?.length ? acl.TokenDomains : undefined,
252 customResponseBodies:
253 props?.customResponseBodies === undefined ? undefined : acl.CustomResponseBodies,
254 captchaConfig: props?.captchaConfig === undefined ? undefined : acl.CaptchaConfig,
255 challengeConfig: props?.challengeConfig === undefined ? undefined : acl.ChallengeConfig,
256 associationConfig: props?.associationConfig === undefined ? undefined : acl.AssociationConfig,
257 tags,
258 });
259
260 export const WebACLProvider = () =>
261 Provider.effect(
262 WebACL,
263 Effect.gen(function* () {
264 const createName = Effect.fn(function* (id: string, props: WebACLProps) {
265 return props.webAclName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
266 });
267
268 // Resolve a web ACL to its full detail + LockToken. Prefers the
269 // cached Id (fast path); falls back to searching list pages by name.
270 const findWebACL = Effect.fn(function* (
271 scope: WafScope,
272 name: string,
273 cachedId: string | undefined,
274 ) {
275 if (cachedId !== undefined) {
276 const byId = yield* withWafScope(
277 scope,
278 wafv2
279 .getWebACL({ Name: name, Scope: scope, Id: cachedId })
280 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
281 );
282 if (byId?.WebACL) {
283 return byId;
284 }
285 }
286 let marker: string | undefined;
287 for (let page = 0; page < 20; page++) {
288 const listed = yield* withWafScope(
289 scope,
290 wafv2.listWebACLs({ Scope: scope, NextMarker: marker, Limit: 100 }),
291 );
292 const summary = listed.WebACLs?.find((s) => s.Name === name);
293 if (summary?.Id !== undefined) {
294 return yield* withWafScope(
295 scope,
296 wafv2
297 .getWebACL({ Name: name, Scope: scope, Id: summary.Id })
298 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
299 );
300 }
301 if (!listed.NextMarker || (listed.WebACLs?.length ?? 0) === 0) {
302 break;
303 }
304 marker = listed.NextMarker;
305 }
306 return undefined;
307 });
308
309 const buildDesired = (name: string, props: WebACLProps) => ({
310 DefaultAction: props.defaultAction ?? { Allow: {} },
311 Description: props.description,
312 // props survive engine serialization as plain JSON — restore
313 // ByteMatchStatement SearchString blobs to Uint8Array
314 Rules: normalizeWafRules(props.rules),
315 VisibilityConfig: props.visibilityConfig ?? defaultVisibilityConfig(name),
316 CustomResponseBodies: props.customResponseBodies,
317 CaptchaConfig: props.captchaConfig,
318 ChallengeConfig: props.challengeConfig,
319 TokenDomains: props.tokenDomains,
320 AssociationConfig: props.associationConfig,
321 });
322
323 const listScope = Effect.fn(function* (scope: WafScope) {
324 const rows: ReturnType<typeof toAttrs>[] = [];
325 let marker: string | undefined;
326 for (let page = 0; page < 50; page++) {
327 const listed = yield* withWafScope(
328 scope,
329 wafv2.listWebACLs({ Scope: scope, NextMarker: marker, Limit: 100 }),
330 );
331 for (const summary of listed.WebACLs ?? []) {
332 if (summary.Name && summary.Id && summary.ARN) {
333 rows.push({
334 webAclName: summary.Name,
335 webAclId: summary.Id,
336 webAclArn: summary.ARN,
337 scope,
338 });
339 }
340 }
341 if (!listed.NextMarker || (listed.WebACLs?.length ?? 0) === 0) {
342 break;
343 }
344 marker = listed.NextMarker;
345 }
346 return rows;
347 });
348
349 return {
350 stables: ["webAclName", "webAclId", "webAclArn", "scope"],
351
352 list: () =>
353 Effect.gen(function* () {
354 const regional = yield* listScope("REGIONAL");
355 const cloudfront = yield* listScope("CLOUDFRONT");
356 return [...regional, ...cloudfront];
357 }),
358
359 diff: Effect.fn(function* ({ id, news, olds }) {
360 if (!isResolved(news)) return undefined;
361 const oldName = yield* createName(id, olds ?? {});
362 const newName = yield* createName(id, news);
363 if (oldName !== newName) {
364 return { action: "replace" } as const;
365 }
366 if ((olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope)) {
367 return { action: "replace" } as const;
368 }
369 }),
370
371 read: Effect.fn(function* ({ id, olds, output }) {
372 const scope = output?.scope ?? olds?.scope ?? defaultScope;
373 const name = output?.webAclName ?? (yield* createName(id, olds ?? {}));
374 const found = yield* findWebACL(scope, name, output?.webAclId);
375 if (!found?.WebACL) {
376 return undefined;
377 }
378 const tags = yield* fetchWafTags(scope, found.WebACL.ARN);
379 const attrs = {
380 ...toAttrs(found.WebACL, scope),
381 configuration: observeWebACLConfiguration(found.WebACL, olds, tags),
382 };
383 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
384 }),
385
386 reconcile: Effect.fn(function* ({ id, news, output, session }) {
387 const scope = news.scope ?? defaultScope;
388 const name = output?.webAclName ?? (yield* createName(id, news));
389 const internalTags = yield* createInternalTags(id);
390 const desiredTags = { ...news.tags, ...internalTags };
391 const desired = buildDesired(name, news);
392
393 // 1. Observe — cloud state is authoritative; output only caches Id.
394 let observed = yield* findWebACL(scope, name, output?.webAclId);
395
396 // 2. Ensure — create if missing; a WAFDuplicateItemException is a
397 // race with a concurrent creator, so fall through to re-read.
398 if (!observed?.WebACL) {
399 yield* retryUnavailableEntity(
400 withWafScope(
401 scope,
402 wafv2
403 .createWebACL({
404 Name: name,
405 Scope: scope,
406 ...desired,
407 Tags: createTagsList(desiredTags),
408 })
409 .pipe(Effect.catchTag("WAFDuplicateItemException", () => Effect.undefined)),
410 ),
411 );
412 observed = yield* findWebACL(scope, name, undefined);
413 }
414
415 if (!observed?.WebACL) {
416 return yield* new WebACLUnexpectedResponse({
417 message: `Failed to observe WebACL '${name}' after create`,
418 });
419 }
420
421 const acl = observed.WebACL;
422 yield* session.note(acl.ARN);
423
424 // 3. Sync — diff the OBSERVED mutable aspects against desired and
425 // apply a single updateWebACL when drifted. The update re-reads
426 // the LockToken inside the retry so optimistic-lock conflicts
427 // converge.
428 const observedAspects: Record<string, unknown> = {
429 DefaultAction: acl.DefaultAction,
430 Description: acl.Description,
431 Rules: acl.Rules ?? [],
432 VisibilityConfig: acl.VisibilityConfig,
433 TokenDomains: acl.TokenDomains,
434 };
435 const desiredAspects: Record<string, unknown> = {
436 DefaultAction: desired.DefaultAction,
437 Description: desired.Description,
438 Rules: desired.Rules,
439 VisibilityConfig: desired.VisibilityConfig,
440 TokenDomains: desired.TokenDomains,
441 };
442 // WAF materializes defaults for aspects the user never set (e.g.
443 // CaptchaConfig immunity time), so only compare the optional
444 // aspects the user actually declared.
445 if (news.customResponseBodies !== undefined) {
446 observedAspects.CustomResponseBodies = acl.CustomResponseBodies;
447 desiredAspects.CustomResponseBodies = desired.CustomResponseBodies;
448 }
449 if (news.captchaConfig !== undefined) {
450 observedAspects.CaptchaConfig = acl.CaptchaConfig;
451 desiredAspects.CaptchaConfig = desired.CaptchaConfig;
452 }
453 if (news.challengeConfig !== undefined) {
454 observedAspects.ChallengeConfig = acl.ChallengeConfig;
455 desiredAspects.ChallengeConfig = desired.ChallengeConfig;
456 }
457 if (news.associationConfig !== undefined) {
458 observedAspects.AssociationConfig = acl.AssociationConfig;
459 desiredAspects.AssociationConfig = desired.AssociationConfig;
460 }
461 if (!deepEqual(observedAspects, desiredAspects, { stripNullish: true })) {
462 yield* retryOptimisticLock(
463 Effect.gen(function* () {
464 const fresh = yield* findWebACL(scope, name, acl.Id);
465 if (!fresh?.WebACL || fresh.LockToken === undefined) {
466 return;
467 }
468 yield* retryUnavailableEntity(
469 withWafScope(
470 scope,
471 wafv2.updateWebACL({
472 Name: name,
473 Scope: scope,
474 Id: fresh.WebACL.Id,
475 LockToken: fresh.LockToken,
476 ...desired,
477 }),
478 ),
479 );
480 }),
481 );
482 }
483
484 // 3b. Sync tags against OBSERVED cloud tags.
485 yield* syncWafTags(scope, acl.ARN, desiredTags);
486
487 // 4. Return fresh attributes.
488 const final = yield* findWebACL(scope, name, acl.Id);
489 return {
490 ...toAttrs(acl, scope),
491 configuration: observeWebACLConfiguration(final?.WebACL ?? acl, news, desiredTags),
492 };
493 }),
494
495 delete: Effect.fn(function* ({ output }) {
496 const scope = output.scope;
497 // Re-read for a fresh LockToken on every attempt; tolerate the
498 // ACL already being gone, a stale lock, or a still-propagating
499 // disassociation.
500 yield* Effect.gen(function* () {
501 const found = yield* withWafScope(
502 scope,
503 wafv2
504 .getWebACL({
505 Name: output.webAclName,
506 Scope: scope,
507 Id: output.webAclId,
508 })
509 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
510 );
511 if (!found?.WebACL || found.LockToken === undefined) {
512 return;
513 }
514 yield* withWafScope(
515 scope,
516 wafv2
517 .deleteWebACL({
518 Name: output.webAclName,
519 Scope: scope,
520 Id: output.webAclId,
521 LockToken: found.LockToken,
522 })
523 .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.void)),
524 );
525 }).pipe(retryOptimisticLock, retryAssociatedItem);
526 }),
527 };
528 }),
529 );