import type * as WAFV2 from "@distilled.cloud/aws/wafv2";
import * as wafv2 from "@distilled.cloud/aws/wafv2";
import { Unowned } from "alchemy/AdoptPolicy";
import { deepEqual, isResolved } from "alchemy/Diff";
import { createPhysicalName } from "alchemy/PhysicalName";
import * as Provider from "alchemy/Provider";
import { Resource } from "alchemy/Resource";
import { createInternalTags, createTagsList, hasAlchemyTags } from "alchemy/Tags";
import * as Data from "effect/Data";
import * as Effect from "effect/Effect";
import type { Providers } from "../Providers.ts";
import {
fetchWafTags,
retryAssociatedItem,
retryOptimisticLock,
syncWafTags,
type WafScope,
withWafScope,
} from "./internal.ts";
export class WAFv2IPSetUnexpectedResponse extends Data.TaggedError("WAFv2IPSetUnexpectedResponse")<{
readonly message: string;
readonly cause?: unknown;
}> {}
export interface IPSetProps {
/**
* Name of the IP set. Must match `^[\w\-]+
.repos/alchemy-effect/packages/aws/src/WAFv2/IPSet.ts at main · sailfork/t3code-github · Sailfork
and be 1-128 characters.
* Changing the name replaces the IP set.
* @default a physical name derived from the app, stage and logical ID
*/
ipSetName?: string;
/**
* Scope of the IP set — `REGIONAL` (ambient region) or `CLOUDFRONT`
* (pinned to `us-east-1`). Must match the scope of the web ACLs and rule
* groups that reference it. Changing the scope replaces the IP set.
* @default "REGIONAL"
*/
scope?: WafScope;
/**
* IP address version of the entries. Changing the version replaces the
* IP set.
* @default "IPV4"
*/
ipAddressVersion?: WAFV2.IPAddressVersion;
/**
* IP addresses and ranges in CIDR notation (e.g. `192.0.2.44/32`,
* `2620:0:2d0:200::/64`). Mutable — updated in place.
*/
addresses: string[];
/**
* Description of the IP set.
*/
description?: string;
/**
* User-defined tags to apply to the IP set.
*/
tags?: Record<string, string>;
}
export interface IPSet extends Resource<
"AWS.WAFv2.IPSet",
IPSetProps,
{
/**
* Name of the IP set.
*/
ipSetName: string;
/**
* WAF-assigned unique ID of the IP set.
*/
ipSetId: string;
/**
* ARN of the IP set — reference it from a rule's
* `IPSetReferenceStatement`.
*/
ipSetArn: string;
/**
* Scope the IP set was created in.
*/
scope: WafScope;
/**
* IP address version of the entries.
*/
ipAddressVersion: WAFV2.IPAddressVersion;
/**
* Current addresses in the set.
*/
addresses: string[];
},
never,
Providers
> {}
/**
* An AWS WAFv2 IP set — a named collection of IP addresses and CIDR ranges
* referenced from web ACL and rule group rules via
* `IPSetReferenceStatement`.
*
* ### Creating IP Sets
* **Example:** Block List of IPv4 Addresses
* ```typescript
* const blockList = yield* AWS.WAFv2.IPSet("BlockList", {
* addresses: ["192.0.2.44/32", "203.0.113.0/24"],
* });
* ```
*
* **Example:** Reference from a Web ACL Rule
* ```typescript
* const acl = yield* AWS.WAFv2.WebACL("Firewall", {
* rules: [
* {
* Name: "block-bad-ips",
* Priority: 0,
* Statement: {
* IPSetReferenceStatement: { ARN: blockList.ipSetArn },
* },
* Action: { Block: {} },
* VisibilityConfig: {
* SampledRequestsEnabled: true,
* CloudWatchMetricsEnabled: true,
* MetricName: "block-bad-ips",
* },
* },
* ],
* });
* ```
*
* @resource
*/
export const IPSet = Resource<IPSet>("AWS.WAFv2.IPSet");
const defaultScope: WafScope = "REGIONAL";
const defaultIpVersion: WAFV2.IPAddressVersion = "IPV4";
const sortedAddresses = (addresses: readonly string[]) =>
[...addresses].sort((a, b) => a.localeCompare(b));
const toAttrs = (ipSet: WAFV2.IPSet, scope: WafScope) => ({
ipSetName: ipSet.Name,
ipSetId: ipSet.Id,
ipSetArn: ipSet.ARN,
scope,
ipAddressVersion: ipSet.IPAddressVersion,
addresses: [...ipSet.Addresses],
});
export const IPSetProvider = () =>
Provider.effect(
IPSet,
Effect.gen(function* () {
const createName = Effect.fn(function* (id: string, props: IPSetProps) {
return props.ipSetName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
});
const findIPSet = Effect.fn(function* (
scope: WafScope,
name: string,
cachedId: string | undefined,
) {
if (cachedId !== undefined) {
const byId = yield* withWafScope(
scope,
wafv2
.getIPSet({ Name: name, Scope: scope, Id: cachedId })
.pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
);
if (byId?.IPSet) {
return byId;
}
}
let marker: string | undefined;
for (let page = 0; page < 20; page++) {
const listed = yield* withWafScope(
scope,
wafv2.listIPSets({ Scope: scope, NextMarker: marker, Limit: 100 }),
);
const summary = listed.IPSets?.find((s) => s.Name === name);
if (summary?.Id !== undefined) {
return yield* withWafScope(
scope,
wafv2
.getIPSet({ Name: name, Scope: scope, Id: summary.Id })
.pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
);
}
if (!listed.NextMarker || (listed.IPSets?.length ?? 0) === 0) {
break;
}
marker = listed.NextMarker;
}
return undefined;
});
const listScope = Effect.fn(function* (scope: WafScope) {
const rows: ReturnType<typeof toAttrs>[] = [];
let marker: string | undefined;
for (let page = 0; page < 50; page++) {
const listed = yield* withWafScope(
scope,
wafv2.listIPSets({ Scope: scope, NextMarker: marker, Limit: 100 }),
);
const summaries = listed.IPSets ?? [];
const details = yield* Effect.forEach(
summaries,
(summary) =>
summary.Name !== undefined && summary.Id !== undefined
? withWafScope(
scope,
wafv2
.getIPSet({
Name: summary.Name,
Scope: scope,
Id: summary.Id,
})
.pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
)
: Effect.undefined,
{ concurrency: 5 },
);
for (const detail of details) {
if (detail?.IPSet) {
rows.push(toAttrs(detail.IPSet, scope));
}
}
if (!listed.NextMarker || summaries.length === 0) {
break;
}
marker = listed.NextMarker;
}
return rows;
});
return {
stables: ["ipSetName", "ipSetId", "ipSetArn", "scope", "ipAddressVersion"],
list: () =>
Effect.gen(function* () {
const regional = yield* listScope("REGIONAL");
const cloudfront = yield* listScope("CLOUDFRONT");
return [...regional, ...cloudfront];
}),
diff: Effect.fn(function* ({ id, news, olds }) {
if (!isResolved(news)) return undefined;
const oldName = yield* createName(id, olds ?? { addresses: [] });
const newName = yield* createName(id, news);
if (
oldName !== newName ||
(olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope) ||
(olds?.ipAddressVersion ?? defaultIpVersion) !==
(news.ipAddressVersion ?? defaultIpVersion)
) {
return { action: "replace" } as const;
}
}),
read: Effect.fn(function* ({ id, olds, output }) {
const scope = output?.scope ?? olds?.scope ?? defaultScope;
const name = output?.ipSetName ?? (yield* createName(id, olds ?? { addresses: [] }));
const found = yield* findIPSet(scope, name, output?.ipSetId);
if (!found?.IPSet) {
return undefined;
}
const attrs = toAttrs(found.IPSet, scope);
const tags = yield* fetchWafTags(scope, found.IPSet.ARN);
return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
}),
reconcile: Effect.fn(function* ({ id, news, output, session }) {
const scope = news.scope ?? defaultScope;
const name = output?.ipSetName ?? (yield* createName(id, news));
const internalTags = yield* createInternalTags(id);
const desiredTags = { ...news.tags, ...internalTags };
// 1. Observe.
let observed = yield* findIPSet(scope, name, output?.ipSetId);
// 2. Ensure — tolerate a duplicate-create race and re-read.
if (!observed?.IPSet) {
yield* withWafScope(
scope,
wafv2
.createIPSet({
Name: name,
Scope: scope,
IPAddressVersion: news.ipAddressVersion ?? defaultIpVersion,
Addresses: news.addresses,
Description: news.description,
Tags: createTagsList(desiredTags),
})
.pipe(Effect.catchTag("WAFDuplicateItemException", () => Effect.undefined)),
);
observed = yield* findIPSet(scope, name, undefined);
}
if (!observed?.IPSet) {
return yield* new WAFv2IPSetUnexpectedResponse({
message: `Failed to observe IPSet '${name}' after create`,
});
}
const ipSet = observed.IPSet;
yield* session.note(ipSet.ARN);
// 3. Sync addresses + description against OBSERVED state. WAF
// returns addresses in arbitrary order — compare as sets.
const drifted = !deepEqual(
{
Addresses: sortedAddresses(ipSet.Addresses),
Description: ipSet.Description,
},
{
Addresses: sortedAddresses(news.addresses),
Description: news.description,
},
{ stripNullish: true },
);
if (drifted) {
yield* retryOptimisticLock(
Effect.gen(function* () {
const fresh = yield* findIPSet(scope, name, ipSet.Id);
if (!fresh?.IPSet || fresh.LockToken === undefined) {
return;
}
yield* withWafScope(
scope,
wafv2.updateIPSet({
Name: name,
Scope: scope,
Id: fresh.IPSet.Id,
Addresses: news.addresses,
Description: news.description,
LockToken: fresh.LockToken,
}),
);
}),
);
}
// 3b. Sync tags against OBSERVED cloud tags.
yield* syncWafTags(scope, ipSet.ARN, desiredTags);
// 4. Return fresh attributes.
return {
...toAttrs(ipSet, scope),
addresses: [...news.addresses],
};
}),
delete: Effect.fn(function* ({ output }) {
const scope = output.scope;
// An IP set still referenced by a web ACL rule (deletion
// propagation) surfaces WAFAssociatedItemException — retry it.
yield* Effect.gen(function* () {
const found = yield* withWafScope(
scope,
wafv2
.getIPSet({
Name: output.ipSetName,
Scope: scope,
Id: output.ipSetId,
})
.pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.undefined)),
);
if (!found?.IPSet || found.LockToken === undefined) {
return;
}
yield* withWafScope(
scope,
wafv2
.deleteIPSet({
Name: output.ipSetName,
Scope: scope,
Id: output.ipSetId,
LockToken: found.LockToken,
})
.pipe(Effect.catchTag("WAFNonexistentItemException", () => Effect.void)),
);
}).pipe(retryOptimisticLock, retryAssociatedItem);
}),
};
}),
);
.repos/alchemy-effect/packages/aws/src/WAFv2/IPSet.ts at main · sailfork/t3code-github · Sailfork
and be 1-128 characters.\n * Changing the name replaces the IP set.\n * @default a physical name derived from the app, stage and logical ID\n */\n ipSetName?: string;\n /**\n * Scope of the IP set — `REGIONAL` (ambient region) or `CLOUDFRONT`\n * (pinned to `us-east-1`). Must match the scope of the web ACLs and rule\n * groups that reference it. Changing the scope replaces the IP set.\n * @default \"REGIONAL\"\n */\n scope?: WafScope;\n /**\n * IP address version of the entries. Changing the version replaces the\n * IP set.\n * @default \"IPV4\"\n */\n ipAddressVersion?: WAFV2.IPAddressVersion;\n /**\n * IP addresses and ranges in CIDR notation (e.g. `192.0.2.44/32`,\n * `2620:0:2d0:200::/64`). Mutable — updated in place.\n */\n addresses: string[];\n /**\n * Description of the IP set.\n */\n description?: string;\n /**\n * User-defined tags to apply to the IP set.\n */\n tags?: Record\u003cstring, string>;\n}\n\nexport interface IPSet extends Resource\u003c\n \"AWS.WAFv2.IPSet\",\n IPSetProps,\n {\n /**\n * Name of the IP set.\n */\n ipSetName: string;\n /**\n * WAF-assigned unique ID of the IP set.\n */\n ipSetId: string;\n /**\n * ARN of the IP set — reference it from a rule's\n * `IPSetReferenceStatement`.\n */\n ipSetArn: string;\n /**\n * Scope the IP set was created in.\n */\n scope: WafScope;\n /**\n * IP address version of the entries.\n */\n ipAddressVersion: WAFV2.IPAddressVersion;\n /**\n * Current addresses in the set.\n */\n addresses: string[];\n },\n never,\n Providers\n> {}\n\n/**\n * An AWS WAFv2 IP set — a named collection of IP addresses and CIDR ranges\n * referenced from web ACL and rule group rules via\n * `IPSetReferenceStatement`.\n *\n * ### Creating IP Sets\n * **Example:** Block List of IPv4 Addresses\n * ```typescript\n * const blockList = yield* AWS.WAFv2.IPSet(\"BlockList\", {\n * addresses: [\"192.0.2.44/32\", \"203.0.113.0/24\"],\n * });\n * ```\n *\n * **Example:** Reference from a Web ACL Rule\n * ```typescript\n * const acl = yield* AWS.WAFv2.WebACL(\"Firewall\", {\n * rules: [\n * {\n * Name: \"block-bad-ips\",\n * Priority: 0,\n * Statement: {\n * IPSetReferenceStatement: { ARN: blockList.ipSetArn },\n * },\n * Action: { Block: {} },\n * VisibilityConfig: {\n * SampledRequestsEnabled: true,\n * CloudWatchMetricsEnabled: true,\n * MetricName: \"block-bad-ips\",\n * },\n * },\n * ],\n * });\n * ```\n *\n * @resource\n */\nexport const IPSet = Resource\u003cIPSet>(\"AWS.WAFv2.IPSet\");\n\nconst defaultScope: WafScope = \"REGIONAL\";\nconst defaultIpVersion: WAFV2.IPAddressVersion = \"IPV4\";\n\nconst sortedAddresses = (addresses: readonly string[]) =>\n [...addresses].sort((a, b) => a.localeCompare(b));\n\nconst toAttrs = (ipSet: WAFV2.IPSet, scope: WafScope) => ({\n ipSetName: ipSet.Name,\n ipSetId: ipSet.Id,\n ipSetArn: ipSet.ARN,\n scope,\n ipAddressVersion: ipSet.IPAddressVersion,\n addresses: [...ipSet.Addresses],\n});\n\nexport const IPSetProvider = () =>\n Provider.effect(\n IPSet,\n Effect.gen(function* () {\n const createName = Effect.fn(function* (id: string, props: IPSetProps) {\n return props.ipSetName ?? (yield* createPhysicalName({ id, maxLength: 128 }));\n });\n\n const findIPSet = Effect.fn(function* (\n scope: WafScope,\n name: string,\n cachedId: string | undefined,\n ) {\n if (cachedId !== undefined) {\n const byId = yield* withWafScope(\n scope,\n wafv2\n .getIPSet({ Name: name, Scope: scope, Id: cachedId })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n );\n if (byId?.IPSet) {\n return byId;\n }\n }\n let marker: string | undefined;\n for (let page = 0; page \u003c 20; page++) {\n const listed = yield* withWafScope(\n scope,\n wafv2.listIPSets({ Scope: scope, NextMarker: marker, Limit: 100 }),\n );\n const summary = listed.IPSets?.find((s) => s.Name === name);\n if (summary?.Id !== undefined) {\n return yield* withWafScope(\n scope,\n wafv2\n .getIPSet({ Name: name, Scope: scope, Id: summary.Id })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n );\n }\n if (!listed.NextMarker || (listed.IPSets?.length ?? 0) === 0) {\n break;\n }\n marker = listed.NextMarker;\n }\n return undefined;\n });\n\n const listScope = Effect.fn(function* (scope: WafScope) {\n const rows: ReturnType\u003ctypeof toAttrs>[] = [];\n let marker: string | undefined;\n for (let page = 0; page \u003c 50; page++) {\n const listed = yield* withWafScope(\n scope,\n wafv2.listIPSets({ Scope: scope, NextMarker: marker, Limit: 100 }),\n );\n const summaries = listed.IPSets ?? [];\n const details = yield* Effect.forEach(\n summaries,\n (summary) =>\n summary.Name !== undefined && summary.Id !== undefined\n ? withWafScope(\n scope,\n wafv2\n .getIPSet({\n Name: summary.Name,\n Scope: scope,\n Id: summary.Id,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n )\n : Effect.undefined,\n { concurrency: 5 },\n );\n for (const detail of details) {\n if (detail?.IPSet) {\n rows.push(toAttrs(detail.IPSet, scope));\n }\n }\n if (!listed.NextMarker || summaries.length === 0) {\n break;\n }\n marker = listed.NextMarker;\n }\n return rows;\n });\n\n return {\n stables: [\"ipSetName\", \"ipSetId\", \"ipSetArn\", \"scope\", \"ipAddressVersion\"],\n\n list: () =>\n Effect.gen(function* () {\n const regional = yield* listScope(\"REGIONAL\");\n const cloudfront = yield* listScope(\"CLOUDFRONT\");\n return [...regional, ...cloudfront];\n }),\n\n diff: Effect.fn(function* ({ id, news, olds }) {\n if (!isResolved(news)) return undefined;\n const oldName = yield* createName(id, olds ?? { addresses: [] });\n const newName = yield* createName(id, news);\n if (\n oldName !== newName ||\n (olds?.scope ?? defaultScope) !== (news.scope ?? defaultScope) ||\n (olds?.ipAddressVersion ?? defaultIpVersion) !==\n (news.ipAddressVersion ?? defaultIpVersion)\n ) {\n return { action: \"replace\" } as const;\n }\n }),\n\n read: Effect.fn(function* ({ id, olds, output }) {\n const scope = output?.scope ?? olds?.scope ?? defaultScope;\n const name = output?.ipSetName ?? (yield* createName(id, olds ?? { addresses: [] }));\n const found = yield* findIPSet(scope, name, output?.ipSetId);\n if (!found?.IPSet) {\n return undefined;\n }\n const attrs = toAttrs(found.IPSet, scope);\n const tags = yield* fetchWafTags(scope, found.IPSet.ARN);\n return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);\n }),\n\n reconcile: Effect.fn(function* ({ id, news, output, session }) {\n const scope = news.scope ?? defaultScope;\n const name = output?.ipSetName ?? (yield* createName(id, news));\n const internalTags = yield* createInternalTags(id);\n const desiredTags = { ...news.tags, ...internalTags };\n\n // 1. Observe.\n let observed = yield* findIPSet(scope, name, output?.ipSetId);\n\n // 2. Ensure — tolerate a duplicate-create race and re-read.\n if (!observed?.IPSet) {\n yield* withWafScope(\n scope,\n wafv2\n .createIPSet({\n Name: name,\n Scope: scope,\n IPAddressVersion: news.ipAddressVersion ?? defaultIpVersion,\n Addresses: news.addresses,\n Description: news.description,\n Tags: createTagsList(desiredTags),\n })\n .pipe(Effect.catchTag(\"WAFDuplicateItemException\", () => Effect.undefined)),\n );\n observed = yield* findIPSet(scope, name, undefined);\n }\n\n if (!observed?.IPSet) {\n return yield* new WAFv2IPSetUnexpectedResponse({\n message: `Failed to observe IPSet '${name}' after create`,\n });\n }\n\n const ipSet = observed.IPSet;\n yield* session.note(ipSet.ARN);\n\n // 3. Sync addresses + description against OBSERVED state. WAF\n // returns addresses in arbitrary order — compare as sets.\n const drifted = !deepEqual(\n {\n Addresses: sortedAddresses(ipSet.Addresses),\n Description: ipSet.Description,\n },\n {\n Addresses: sortedAddresses(news.addresses),\n Description: news.description,\n },\n { stripNullish: true },\n );\n if (drifted) {\n yield* retryOptimisticLock(\n Effect.gen(function* () {\n const fresh = yield* findIPSet(scope, name, ipSet.Id);\n if (!fresh?.IPSet || fresh.LockToken === undefined) {\n return;\n }\n yield* withWafScope(\n scope,\n wafv2.updateIPSet({\n Name: name,\n Scope: scope,\n Id: fresh.IPSet.Id,\n Addresses: news.addresses,\n Description: news.description,\n LockToken: fresh.LockToken,\n }),\n );\n }),\n );\n }\n\n // 3b. Sync tags against OBSERVED cloud tags.\n yield* syncWafTags(scope, ipSet.ARN, desiredTags);\n\n // 4. Return fresh attributes.\n return {\n ...toAttrs(ipSet, scope),\n addresses: [...news.addresses],\n };\n }),\n\n delete: Effect.fn(function* ({ output }) {\n const scope = output.scope;\n // An IP set still referenced by a web ACL rule (deletion\n // propagation) surfaces WAFAssociatedItemException — retry it.\n yield* Effect.gen(function* () {\n const found = yield* withWafScope(\n scope,\n wafv2\n .getIPSet({\n Name: output.ipSetName,\n Scope: scope,\n Id: output.ipSetId,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.undefined)),\n );\n if (!found?.IPSet || found.LockToken === undefined) {\n return;\n }\n yield* withWafScope(\n scope,\n wafv2\n .deleteIPSet({\n Name: output.ipSetName,\n Scope: scope,\n Id: output.ipSetId,\n LockToken: found.LockToken,\n })\n .pipe(Effect.catchTag(\"WAFNonexistentItemException\", () => Effect.void)),\n );\n }).pipe(retryOptimisticLock, retryAssociatedItem);\n }),\n };\n }),\n );\n","preview":null,"history":null,"version":"667e2f7291d1599c6217f743a0b7657ed894d11e"},"/_session?shell=1":null}