The best way to control Claude Code, Codex and more from any computer or phone
| 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 type { Providers } from "../Providers.ts"; |
| 12 | import { |
| 13 | fetchWafTags, |
| 14 | normalizeWafRules, |
| 15 | retryAssociatedItem, |
| 16 | retryOptimisticLock, |
| 17 | retryUnavailableEntity, |
| 18 | syncWafTags, |
| 19 | type WafScope, |
| 20 | withWafScope, |
| 21 | } from "./internal.ts"; |
| 22 | |
| 23 | export class WAFv2RuleGroupUnexpectedResponse extends Data.TaggedError( |
| 24 | "WAFv2RuleGroupUnexpectedResponse", |
| 25 | )<{ |
| 26 | readonly message: string; |
| 27 | readonly cause?: unknown; |
| 28 | }> {} |
| 29 | |
| 30 | export interface RuleGroupProps { |
| 31 | /** |
| 32 | * Name of the rule group. Must match `^[\w\-]+$` and be 1-128 characters. |
| 33 | * Changing the name replaces the rule group. |
| 34 | * @default a physical name derived from the app, stage and logical ID |
| 35 | */ |
| 36 | ruleGroupName?: string; |
| 37 | /** |
| 38 | * Scope of the rule group — `REGIONAL` (ambient region) or `CLOUDFRONT` |
| 39 | * (pinned to `us-east-1`). Must match the scope of the web ACLs that |
| 40 | * reference it. Changing the scope replaces the rule group. |
| 41 | * @default "REGIONAL" |
| 42 | */ |
| 43 | scope?: WafScope; |
| 44 | /** |
| 45 | * Web ACL capacity units (WCU) reserved for this rule group. Immutable — |
| 46 | * changing the capacity replaces the rule group. |
| 47 | */ |
| 48 | capacity: number; |
| 49 | /** |
| 50 | * Rules to evaluate, in `Priority` order. Raw WAFv2 API shapes. |
| 51 | */ |
| 52 | rules?: WAFV2.Rule[]; |
| 53 | /** |
| 54 | * CloudWatch metrics and sampled-request settings for the rule group. |
| 55 | * @default sampled requests + metrics enabled, MetricName = the rule group name |
| 56 | */ |
| 57 | visibilityConfig?: WAFV2.VisibilityConfig; |
| 58 | /** |
| 59 | * Description of the rule group. |
| 60 | */ |
| 61 | description?: string; |
| 62 | /** |
| 63 | * Custom response bodies referenced by rule actions in this rule group. |
| 64 | */ |
| 65 | customResponseBodies?: { |
| 66 | [key: string]: WAFV2.CustomResponseBody | undefined; |
| 67 | }; |
| 68 | /** |
| 69 | * User-defined tags to apply to the rule group. |
| 70 | */ |
| 71 | tags?: Record<string, string>; |
| 72 | } |
| 73 | |
| 74 | export interface RuleGroup extends Resource< |
| 75 | "AWS.WAFv2.RuleGroup", |
| 76 | RuleGroupProps, |
| 77 | { |
| 78 | /** |
| 79 | * Name of the rule group. |
| 80 | */ |
| 81 | ruleGroupName: string; |
| 82 | /** |
| 83 | * WAF-assigned unique ID of the rule group. |
| 84 | */ |
| 85 | ruleGroupId: string; |
| 86 | /** |
| 87 | * ARN of the rule group — reference it from a web ACL rule's |
| 88 | * `RuleGroupReferenceStatement`. |
| 89 | */ |
| 90 | ruleGroupArn: string; |
| 91 | /** |
| 92 | * Scope the rule group was created in. |
| 93 | */ |
| 94 | scope: WafScope; |
| 95 | /** |
| 96 | * Immutable WCU capacity of the rule group. |
| 97 | */ |
| 98 | capacity: number; |
| 99 | }, |
| 100 | never, |
| 101 | Providers |
| 102 | > {} |
| 103 | |
| 104 | /** |
| 105 | * An AWS WAFv2 rule group — a reusable, capacity-bounded collection of rules |
| 106 | * referenced from web ACLs via `RuleGroupReferenceStatement`. |
| 107 | * |
| 108 | * The `capacity` (web ACL capacity units, WCU) is fixed at creation; |
| 109 | * changing it replaces the rule group. |
| 110 | * |
| 111 | * ### Creating Rule Groups |
| 112 | * **Example:** Rule Group with a Byte-Match Rule |
| 113 | * ```typescript |
| 114 | * const group = yield* AWS.WAFv2.RuleGroup("BlockAdminPaths", { |
| 115 | * capacity: 50, |
| 116 | * rules: [ |
| 117 | * { |
| 118 | * Name: "block-admin", |
| 119 | * Priority: 0, |
| 120 | * Statement: { |
| 121 | * ByteMatchStatement: { |
| 122 | * SearchString: new TextEncoder().encode("/admin"), |
| 123 | * FieldToMatch: { UriPath: {} }, |
| 124 | * TextTransformations: [{ Priority: 0, Type: "LOWERCASE" }], |
| 125 | * PositionalConstraint: "STARTS_WITH", |
| 126 | * }, |
| 127 | * }, |
| 128 | * Action: { Block: {} }, |
| 129 | * VisibilityConfig: { |
| 130 | * SampledRequestsEnabled: true, |
| 131 | * CloudWatchMetricsEnabled: true, |
| 132 | * MetricName: "block-admin", |
| 133 | * }, |
| 134 | * }, |
| 135 | * ], |
| 136 | * }); |
| 137 | * ``` |
| 138 | * |
| 139 | * **Example:** Reference from a Web ACL |
| 140 | * ```typescript |
| 141 | * const acl = yield* AWS.WAFv2.WebACL("Firewall", { |
| 142 | * rules: [ |
| 143 | * { |
| 144 | * Name: "custom-rules", |
| 145 | * Priority: 0, |
| 146 | * Statement: { |
| 147 | * RuleGroupReferenceStatement: { ARN: group.ruleGroupArn }, |
| 148 | * }, |
| 149 | * OverrideAction: { None: {} }, |
| 150 | * VisibilityConfig: { |
| 151 | * SampledRequestsEnabled: true, |
| 152 | * CloudWatchMetricsEnabled: true, |
| 153 | * MetricName: "custom-rules", |
| 154 | * }, |
| 155 | * }, |
| 156 | * ], |
| 157 | * }); |
| 158 | * ``` |
| 159 | * |
| 160 | * @resource |
| 161 | */ |
| 162 | export const RuleGroup = Resource<RuleGroup>("AWS.WAFv2.RuleGroup"); |
| 163 | |
| 164 | const defaultScope: WafScope = "REGIONAL"; |
| 165 | |
| 166 | const defaultVisibilityConfig = (name: string): WAFV2.VisibilityConfig => ({ |
| 167 | SampledRequestsEnabled: true, |
| 168 | CloudWatchMetricsEnabled: true, |
| 169 | MetricName: name, |
| 170 | }); |
| 171 | |
| 172 | const toAttrs = (group: WAFV2.RuleGroup, scope: WafScope) => ({ |
| 173 | ruleGroupName: group.Name, |
| 174 | ruleGroupId: group.Id, |
| 175 | ruleGroupArn: group.ARN, |
| 176 | scope, |
| 177 | capacity: group.Capacity, |
| 178 | }); |
| 179 | |
| 180 | export const RuleGroupProvider = () => |
| 181 | Provider.effect( |
| 182 | RuleGroup, |
| 183 | Effect.gen(function* () { |
| 184 | const createName = Effect.fn(function* (id: string, props: Partial<RuleGroupProps>) { |
| 185 | return props.ruleGroupName ?? (yield* createPhysicalName({ id, maxLength: 128 })); |
| 186 | }); |
| 187 | |
| 188 | const findRuleGroup = Effect.fn(function* ( |
| 189 | scope: WafScope, |
| 190 | name: string, |
| 191 | cachedId: string | undefined, |
| 192 | ) { |
| 193 | if (cachedId !== undefined) { |
| 194 | const byId = yield* withWafScope( |
| 195 | scope, |
| 196 | wafv2 |
| 197 | .getRuleGroup({ Name: name, Scope: scope, Id: cachedId }) |
| 198 | .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), |
| 199 | ); |
| 200 | if (byId?.RuleGroup) { |
| 201 | return byId; |
| 202 | } |
| 203 | } |
| 204 | let marker: string | undefined; |
| 205 | for (let page = 0; page < 20; page++) { |
| 206 | const listed = yield* withWafScope( |
| 207 | scope, |
| 208 | wafv2.listRuleGroups({ |
| 209 | Scope: scope, |
| 210 | NextMarker: marker, |
| 211 | Limit: 100, |
| 212 | }), |
| 213 | ); |
| 214 | const summary = listed.RuleGroups?.find((s) => s.Name === name); |
| 215 | if (summary?.Id !== undefined) { |
| 216 | return yield* withWafScope( |
| 217 | scope, |
| 218 | wafv2 |
| 219 | .getRuleGroup({ Name: name, Scope: scope, Id: summary.Id }) |
| 220 | .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), |
| 221 | ); |
| 222 | } |
| 223 | if (!listed.NextMarker || (listed.RuleGroups?.length ?? 0) === 0) { |
| 224 | break; |
| 225 | } |
| 226 | marker = listed.NextMarker; |
| 227 | } |
| 228 | return undefined; |
| 229 | }); |
| 230 | |
| 231 | const listScope = Effect.fn(function* (scope: WafScope) { |
| 232 | const rows: ReturnType<typeof toAttrs>[] = []; |
| 233 | let marker: string | undefined; |
| 234 | for (let page = 0; page < 50; page++) { |
| 235 | const listed = yield* withWafScope( |
| 236 | scope, |
| 237 | wafv2.listRuleGroups({ |
| 238 | Scope: scope, |
| 239 | NextMarker: marker, |
| 240 | Limit: 100, |
| 241 | }), |
| 242 | ); |
| 243 | const summaries = listed.RuleGroups ?? []; |
| 244 | const details = yield* Effect.forEach( |
| 245 | summaries, |
| 246 | (summary) => |
| 247 | summary.Name !== undefined && summary.Id !== undefined |
| 248 | ? withWafScope( |
| 249 | scope, |
| 250 | wafv2 |
| 251 | .getRuleGroup({ |
| 252 | Name: summary.Name, |
| 253 | Scope: scope, |
| 254 | Id: summary.Id, |
| 255 | }) |
| 256 | .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), |
| 257 | ) |
| 258 | : Effect.undefined, |
| 259 | { concurrency: 5 }, |
| 260 | ); |
| 261 | for (const detail of details) { |
| 262 | if (detail?.RuleGroup) { |
| 263 | rows.push(toAttrs(detail.RuleGroup, scope)); |
| 264 | } |
| 265 | } |
| 266 | if (!listed.NextMarker || summaries.length === 0) { |
| 267 | break; |
| 268 | } |
| 269 | marker = listed.NextMarker; |
| 270 | } |
| 271 | return rows; |
| 272 | }); |
| 273 | |
| 274 | return { |
| 275 | stables: ["ruleGroupName", "ruleGroupId", "ruleGroupArn", "scope", "capacity"], |
| 276 | |
| 277 | list: () => |
| 278 | Effect.gen(function* () { |
| 279 | const regional = yield* listScope("REGIONAL"); |
| 280 | const cloudfront = yield* listScope("CLOUDFRONT"); |
| 281 | return [...regional, ...cloudfront]; |
| 282 | }), |
| 283 | |
| 284 | diff: Effect.fn(function* ({ id, news, olds }) { |
| 285 | if (!isResolved(news)) return undefined; |
| 286 | const oldName = yield* createName(id, olds ?? {}); |
| 287 | const newName = yield* createName(id, news); |
| 288 | if ( |
| 289 | oldName !== newName || |
| 290 | (olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope) || |
| 291 | olds?.capacity !== news.capacity |
| 292 | ) { |
| 293 | return { action: "replace" } as const; |
| 294 | } |
| 295 | }), |
| 296 | |
| 297 | read: Effect.fn(function* ({ id, olds, output }) { |
| 298 | const scope = output?.scope ?? olds?.scope ?? defaultScope; |
| 299 | const name = output?.ruleGroupName ?? (yield* createName(id, olds ?? {})); |
| 300 | const found = yield* findRuleGroup(scope, name, output?.ruleGroupId); |
| 301 | if (!found?.RuleGroup) { |
| 302 | return undefined; |
| 303 | } |
| 304 | const attrs = toAttrs(found.RuleGroup, scope); |
| 305 | const tags = yield* fetchWafTags(scope, found.RuleGroup.ARN); |
| 306 | return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs); |
| 307 | }), |
| 308 | |
| 309 | reconcile: Effect.fn(function* ({ id, news, output, session }) { |
| 310 | const scope = news.scope ?? defaultScope; |
| 311 | const name = output?.ruleGroupName ?? (yield* createName(id, news)); |
| 312 | const internalTags = yield* createInternalTags(id); |
| 313 | const desiredTags = { ...news.tags, ...internalTags }; |
| 314 | const desiredVisibility = news.visibilityConfig ?? defaultVisibilityConfig(name); |
| 315 | // props survive engine serialization as plain JSON — restore |
| 316 | // ByteMatchStatement SearchString blobs to Uint8Array |
| 317 | const desiredRules = normalizeWafRules(news.rules); |
| 318 | |
| 319 | // 1. Observe. |
| 320 | let observed = yield* findRuleGroup(scope, name, output?.ruleGroupId); |
| 321 | |
| 322 | // 2. Ensure — tolerate a duplicate-create race and re-read. |
| 323 | if (!observed?.RuleGroup) { |
| 324 | yield* retryUnavailableEntity( |
| 325 | withWafScope( |
| 326 | scope, |
| 327 | wafv2 |
| 328 | .createRuleGroup({ |
| 329 | Name: name, |
| 330 | Scope: scope, |
| 331 | Capacity: news.capacity, |
| 332 | Rules: desiredRules, |
| 333 | VisibilityConfig: desiredVisibility, |
| 334 | Description: news.description, |
| 335 | CustomResponseBodies: news.customResponseBodies, |
| 336 | Tags: createTagsList(desiredTags), |
| 337 | }) |
| 338 | .pipe(Effect.catchTag("WAFDuplicateItemException", () => Effect.undefined)), |
| 339 | ), |
| 340 | ); |
| 341 | observed = yield* findRuleGroup(scope, name, undefined); |
| 342 | } |
| 343 | |
| 344 | if (!observed?.RuleGroup) { |
| 345 | return yield* new WAFv2RuleGroupUnexpectedResponse({ |
| 346 | message: `Failed to observe RuleGroup '${name}' after create`, |
| 347 | }); |
| 348 | } |
| 349 | |
| 350 | const group = observed.RuleGroup; |
| 351 | yield* session.note(group.ARN); |
| 352 | |
| 353 | // 3. Sync rules, visibility and description against OBSERVED state. |
| 354 | const observedAspects: Record<string, unknown> = { |
| 355 | Rules: group.Rules ?? [], |
| 356 | VisibilityConfig: group.VisibilityConfig, |
| 357 | Description: group.Description, |
| 358 | }; |
| 359 | const desiredAspects: Record<string, unknown> = { |
| 360 | Rules: desiredRules, |
| 361 | VisibilityConfig: desiredVisibility, |
| 362 | Description: news.description, |
| 363 | }; |
| 364 | if (news.customResponseBodies !== undefined) { |
| 365 | observedAspects.CustomResponseBodies = group.CustomResponseBodies; |
| 366 | desiredAspects.CustomResponseBodies = news.customResponseBodies; |
| 367 | } |
| 368 | if (!deepEqual(observedAspects, desiredAspects, { stripNullish: true })) { |
| 369 | yield* retryOptimisticLock( |
| 370 | Effect.gen(function* () { |
| 371 | const fresh = yield* findRuleGroup(scope, name, group.Id); |
| 372 | if (!fresh?.RuleGroup || fresh.LockToken === undefined) { |
| 373 | return; |
| 374 | } |
| 375 | yield* retryUnavailableEntity( |
| 376 | withWafScope( |
| 377 | scope, |
| 378 | wafv2.updateRuleGroup({ |
| 379 | Name: name, |
| 380 | Scope: scope, |
| 381 | Id: fresh.RuleGroup.Id, |
| 382 | Rules: desiredRules, |
| 383 | VisibilityConfig: desiredVisibility, |
| 384 | Description: news.description, |
| 385 | CustomResponseBodies: news.customResponseBodies, |
| 386 | LockToken: fresh.LockToken, |
| 387 | }), |
| 388 | ), |
| 389 | ); |
| 390 | }), |
| 391 | ); |
| 392 | } |
| 393 | |
| 394 | // 3b. Sync tags against OBSERVED cloud tags. |
| 395 | yield* syncWafTags(scope, group.ARN, desiredTags); |
| 396 | |
| 397 | // 4. Return fresh attributes. |
| 398 | return toAttrs(group, scope); |
| 399 | }), |
| 400 | |
| 401 | delete: Effect.fn(function* ({ output }) { |
| 402 | const scope = output.scope; |
| 403 | // A rule group still referenced by a web ACL (deletion propagation) |
| 404 | // surfaces WAFAssociatedItemException — retry through it. |
| 405 | yield* Effect.gen(function* () { |
| 406 | const found = yield* withWafScope( |
| 407 | scope, |
| 408 | wafv2 |
| 409 | .getRuleGroup({ |
| 410 | Name: output.ruleGroupName, |
| 411 | Scope: scope, |
| 412 | Id: output.ruleGroupId, |
| 413 | }) |
| 414 | .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)), |
| 415 | ); |
| 416 | if (!found?.RuleGroup || found.LockToken === undefined) { |
| 417 | return; |
| 418 | } |
| 419 | yield* withWafScope( |
| 420 | scope, |
| 421 | wafv2 |
| 422 | .deleteRuleGroup({ |
| 423 | Name: output.ruleGroupName, |
| 424 | Scope: scope, |
| 425 | Id: output.ruleGroupId, |
| 426 | LockToken: found.LockToken, |
| 427 | }) |
| 428 | .pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.void)), |
| 429 | ); |
| 430 | }).pipe(retryOptimisticLock, retryAssociatedItem); |
| 431 | }), |
| 432 | }; |
| 433 | }), |
| 434 | ); |