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

main
ts 292 lines 10.6 KB
Raw
1 import type * as NFW from "@distilled.cloud/aws/network-firewall";
2 import * as nfw from "@distilled.cloud/aws/network-firewall";
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, diffTags, hasAlchemyTags } from "alchemy/Tags";
9 import * as Effect from "effect/Effect";
10 import * as Stream from "effect/Stream";
11 import type { Providers } from "../Providers.ts";
12 import {
13 nfwTagsToRecord,
14 recordToNfwTags,
15 retryWhileNfwInUse,
16 retryWhileNfwNotFound,
17 } from "./internal.ts";
18
19 export interface RuleGroupProps {
20 /**
21 * Name of the rule group. Must be 1-128 alphanumeric characters or
22 * hyphens. If omitted, a deterministic physical name is generated.
23 * Changing the name replaces the rule group.
24 */
25 ruleGroupName?: string;
26 /**
27 * Whether the rule group inspects packets on their own (`STATELESS`) or
28 * in the context of their traffic flow (`STATEFUL`). Changing the type
29 * replaces the rule group.
30 */
31 type: "STATELESS" | "STATEFUL";
32 /**
33 * Maximum operating capacity the rule group can consume when applied.
34 * Capacity cannot be changed after creation — changing it replaces the
35 * rule group.
36 */
37 capacity: number;
38 /**
39 * The rule group definition (rule variables, reference sets, and the
40 * rules source). Provide either `ruleGroup` or `rules`, not both.
41 * Uses raw Network Firewall API structures.
42 */
43 ruleGroup?: NFW.RuleGroup;
44 /**
45 * A string containing stateful rules in Suricata format. Provide either
46 * `rules` or `ruleGroup`, not both. Only valid for `STATEFUL` groups.
47 */
48 rules?: string;
49 /**
50 * Which rule attributes (`SID`, `MSG`, `METADATA`) DescribeRuleGroupSummary
51 * includes in per-rule summaries. Only valid for `STATEFUL` groups; when
52 * omitted, summaries are not generated.
53 */
54 summaryConfiguration?: NFW.SummaryConfiguration;
55 /**
56 * Human-readable description of the rule group.
57 */
58 description?: string;
59 /**
60 * Tags to apply to the rule group. Merged with internal Alchemy tags.
61 */
62 tags?: Record<string, string>;
63 }
64
65 export interface RuleGroup extends Resource<
66 "AWS.NetworkFirewall.RuleGroup",
67 RuleGroupProps,
68 {
69 /** Name of the rule group. */
70 ruleGroupName: string;
71 /** ARN of the rule group. */
72 ruleGroupArn: string;
73 /** Server-assigned unique id of the rule group. */
74 ruleGroupId: string;
75 /** Rule group type (`STATELESS` or `STATEFUL`). */
76 type: string;
77 /** Reserved rule capacity of the group. */
78 capacity: number;
79 },
80 never,
81 Providers
82 > {}
83
84 /**
85 * An AWS Network Firewall rule group — a reusable collection of stateless
86 * or stateful network traffic inspection rules referenced by
87 * {@link FirewallPolicy | firewall policies}.
88 * ### Creating Rule Groups
89 * **Example:** Stateless Rule Group
90 * ```typescript
91 * import * as NetworkFirewall from "@alchemy.run/aws/NetworkFirewall";
92 *
93 * const stateless = yield* NetworkFirewall.RuleGroup("AllowHttp", {
94 * type: "STATELESS",
95 * capacity: 10,
96 * ruleGroup: {
97 * RulesSource: {
98 * StatelessRulesAndCustomActions: {
99 * StatelessRules: [
100 * {
101 * Priority: 1,
102 * RuleDefinition: {
103 * Actions: ["aws:pass"],
104 * MatchAttributes: {
105 * Protocols: [6],
106 * DestinationPorts: [{ FromPort: 80, ToPort: 80 }],
107 * },
108 * },
109 * },
110 * ],
111 * },
112 * },
113 * },
114 * });
115 * ```
116 *
117 * **Example:** Stateful Rule Group (Suricata rules)
118 * ```typescript
119 * const stateful = yield* NetworkFirewall.RuleGroup("BlockDomains", {
120 * type: "STATEFUL",
121 * capacity: 100,
122 * rules: 'drop tcp any any -> any any (msg:"drop all tcp"; sid:1; rev:1;)',
123 * });
124 * ```
125 *
126 * **Example:** Stateful Domain List
127 * ```typescript
128 * const domains = yield* NetworkFirewall.RuleGroup("DenyList", {
129 * type: "STATEFUL",
130 * capacity: 100,
131 * ruleGroup: {
132 * RulesSource: {
133 * RulesSourceList: {
134 * Targets: [".example.com"],
135 * TargetTypes: ["TLS_SNI", "HTTP_HOST"],
136 * GeneratedRulesType: "DENYLIST",
137 * },
138 * },
139 * },
140 * });
141 * ```
142 *
143 * @resource
144 */
145 export const RuleGroup = Resource<RuleGroup>("AWS.NetworkFirewall.RuleGroup");
146
147 export const RuleGroupProvider = () =>
148 Provider.effect(
149 RuleGroup,
150 Effect.gen(function* () {
151 const createName = Effect.fn(function* (id: string, props: { ruleGroupName?: string }) {
152 return props.ruleGroupName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
153 });
154
155 const toAttrs = (response: NFW.RuleGroupResponse): RuleGroup["Attributes"] => ({
156 ruleGroupName: response.RuleGroupName,
157 ruleGroupArn: response.RuleGroupArn,
158 ruleGroupId: response.RuleGroupId,
159 type: response.Type ?? "STATEFUL",
160 capacity: response.Capacity ?? 0,
161 });
162
163 return RuleGroup.Provider.of({
164 stables: ["ruleGroupName", "ruleGroupArn", "ruleGroupId", "type"],
165
166 list: () =>
167 Effect.gen(function* () {
168 const pages = yield* nfw.listRuleGroups
169 .pages({ Scope: "ACCOUNT" })
170 .pipe(Stream.runCollect);
171 const metas = Array.from(pages).flatMap((page) => page.RuleGroups ?? []);
172 const items = yield* Effect.forEach(
173 metas,
174 (meta) =>
175 nfw.describeRuleGroup({ RuleGroupArn: meta.Arn }).pipe(
176 Effect.map((r) => toAttrs(r.RuleGroupResponse)),
177 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
178 ),
179 { concurrency: 5 },
180 );
181 return items.filter((item): item is RuleGroup["Attributes"] => item !== undefined);
182 }),
183
184 read: Effect.fn(function* ({ id, olds, output }) {
185 const found =
186 output?.ruleGroupArn !== undefined
187 ? yield* nfw
188 .describeRuleGroup({ RuleGroupArn: output.ruleGroupArn })
189 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined))
190 : yield* nfw
191 .describeRuleGroup({
192 RuleGroupName: yield* createName(id, olds ?? {}),
193 Type: olds?.type,
194 })
195 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
196 if (found === undefined) return undefined;
197 const attrs = toAttrs(found.RuleGroupResponse);
198 const tags = nfwTagsToRecord(found.RuleGroupResponse.Tags);
199 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
200 }),
201
202 diff: Effect.fn(function* ({ id, news, olds }) {
203 if (!isResolved(news)) return undefined;
204 const oldName = yield* createName(id, olds);
205 const newName = yield* createName(id, news);
206 if (oldName !== newName || olds.type !== news.type || olds.capacity !== news.capacity) {
207 return { action: "replace" } as const;
208 }
209 }),
210
211 reconcile: Effect.fn(function* ({ id, news, output, session }) {
212 const name = output?.ruleGroupName ?? (yield* createName(id, news));
213 const internalTags = yield* createInternalTags(id);
214 const desiredTags: Record<string, string> = {
215 ...news.tags,
216 ...internalTags,
217 };
218
219 // 1. Observe — cloud state is authoritative.
220 let observed = yield* nfw
221 .describeRuleGroup({ RuleGroupName: name, Type: news.type })
222 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
223
224 // 2. Ensure — create if missing.
225 if (observed === undefined) {
226 yield* nfw.createRuleGroup({
227 RuleGroupName: name,
228 Type: news.type,
229 Capacity: news.capacity,
230 RuleGroup: news.ruleGroup,
231 Rules: news.rules,
232 Description: news.description,
233 SummaryConfiguration: news.summaryConfiguration,
234 Tags: recordToNfwTags(desiredTags),
235 });
236 observed = yield* nfw
237 .describeRuleGroup({ RuleGroupName: name, Type: news.type })
238 .pipe(retryWhileNfwNotFound);
239 }
240
241 // 3. Sync definition — compare desired against OBSERVED state and
242 // apply only when it differs.
243 const observedDescription = observed.RuleGroupResponse.Description;
244 const definitionDiffers =
245 (news.rules !== undefined &&
246 news.rules !== observed.RuleGroup?.RulesSource?.RulesString) ||
247 (news.ruleGroup !== undefined && !deepEqual(news.ruleGroup, observed.RuleGroup)) ||
248 (news.summaryConfiguration !== undefined &&
249 !deepEqual(
250 news.summaryConfiguration,
251 observed.RuleGroupResponse.SummaryConfiguration,
252 )) ||
253 (news.description ?? undefined) !== observedDescription;
254 if (definitionDiffers) {
255 yield* nfw.updateRuleGroup({
256 UpdateToken: observed.UpdateToken,
257 RuleGroupArn: observed.RuleGroupResponse.RuleGroupArn,
258 RuleGroup: news.ruleGroup,
259 Rules: news.rules,
260 Type: news.type,
261 Description: news.description,
262 SummaryConfiguration: news.summaryConfiguration,
263 });
264 }
265
266 // 3b. Sync tags — diff against OBSERVED cloud tags.
267 const observedTags = nfwTagsToRecord(observed.RuleGroupResponse.Tags);
268 const { upsert, removed } = diffTags(observedTags, desiredTags);
269 const arn = observed.RuleGroupResponse.RuleGroupArn;
270 if (upsert.length > 0) {
271 yield* nfw.tagResource({ ResourceArn: arn, Tags: upsert });
272 }
273 if (removed.length > 0) {
274 yield* nfw.untagResource({ ResourceArn: arn, TagKeys: removed });
275 }
276
277 yield* session.note(name);
278 return toAttrs(observed.RuleGroupResponse);
279 }),
280
281 delete: Effect.fn(function* ({ output }) {
282 // A rule group still referenced by a firewall policy (deleted
283 // moments ago by the engine) rejects deletion with
284 // InvalidOperationException — retry through the release window.
285 yield* nfw.deleteRuleGroup({ RuleGroupArn: output.ruleGroupArn }).pipe(
286 retryWhileNfwInUse,
287 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
288 );
289 }),
290 });
291 }),
292 );