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

main
ts 450 lines 15.4 KB
Raw
1 import type * as EC2 from "@distilled.cloud/aws/ec2";
2 import * as ec2 from "@distilled.cloud/aws/ec2";
3 import { isResolved } from "alchemy/Diff";
4 import * as Provider from "alchemy/Provider";
5 import { Resource } from "alchemy/Resource";
6 import * as Data from "effect/Data";
7 import * as Effect from "effect/Effect";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import type { Providers } from "../Providers.ts";
11 import type { NetworkAclId } from "./NetworkAcl.ts";
12
13 export class NetworkAclEntryUnexpectedResponse extends Data.TaggedError(
14 "NetworkAclEntryUnexpectedResponse",
15 )<{
16 readonly message: string;
17 readonly cause?: unknown;
18 }> {}
19
20 export interface NetworkAclEntryProps {
21 /**
22 * The ID of the network ACL.
23 */
24 networkAclId: NetworkAclId;
25 /**
26 * The rule number for the entry (1-32766).
27 * Rules are evaluated in order from lowest to highest.
28 */
29 ruleNumber: number;
30 /**
31 * The protocol number.
32 * A value of "-1" means all protocols.
33 * Common values: 6 (TCP), 17 (UDP), 1 (ICMP)
34 */
35 protocol: string;
36 /**
37 * Whether to allow or deny the traffic that matches the rule.
38 */
39 ruleAction: EC2.RuleAction;
40 /**
41 * Whether this is an egress (outbound) rule.
42 * @default false
43 */
44 egress?: boolean;
45 /**
46 * The IPv4 CIDR block.
47 * Either cidrBlock or ipv6CidrBlock must be specified.
48 */
49 cidrBlock?: string;
50 /**
51 * The IPv6 CIDR block.
52 * Either cidrBlock or ipv6CidrBlock must be specified.
53 */
54 ipv6CidrBlock?: string;
55 /**
56 * ICMP type and code. Required if protocol is 1 (ICMP) or 58 (ICMPv6).
57 */
58 icmpTypeCode?: {
59 /** The ICMP code. Use -1 to specify all codes. */
60 code?: number;
61 /** The ICMP type. Use -1 to specify all types. */
62 type?: number;
63 };
64 /**
65 * The port range for TCP/UDP protocols.
66 */
67 portRange?: {
68 /** The first port in the range. */
69 from?: number;
70 /** The last port in the range. */
71 to?: number;
72 };
73 }
74
75 export interface NetworkAclEntry extends Resource<
76 "AWS.EC2.NetworkAclEntry",
77 NetworkAclEntryProps,
78 {
79 /** The ID of the network ACL. */
80 networkAclId: NetworkAclId;
81 /** The rule number. */
82 ruleNumber: number;
83 /** Whether this is an egress rule. */
84 egress: boolean;
85 /** The protocol. */
86 protocol: string;
87 /** The rule action (allow or deny). */
88 ruleAction: EC2.RuleAction;
89 /** The IPv4 CIDR block. */
90 cidrBlock?: string;
91 /** The IPv6 CIDR block. */
92 ipv6CidrBlock?: string;
93 /** The ICMP type and code. */
94 icmpTypeCode?: {
95 code?: number;
96 type?: number;
97 };
98 /** The port range. */
99 portRange?: {
100 from?: number;
101 to?: number;
102 };
103 },
104 never,
105 Providers
106 > {}
107 /**
108 * A single rule in a `NetworkAcl` — a numbered, stateless allow/deny entry that
109 * matches traffic by protocol, CIDR (IPv4 or IPv6), and, for TCP/UDP, a port
110 * range.
111 *
112 * Each entry is identified by its `(networkAclId, ruleNumber, egress)` triple,
113 * and changing any of those three replaces the entry. Rules are evaluated from
114 * the lowest `ruleNumber` upward and the first match wins, so leave gaps between
115 * numbers to make room for future rules. Because NACLs are stateless, always add
116 * a matching ephemeral-port rule for return traffic.
117 *
118 * ### Inbound Rules
119 * Inbound rules (`egress: false`) match traffic entering the subnet. A common
120 * pattern is to allow trusted source ranges plus the ephemeral ports needed for
121 * return traffic.
122 * **Example:** Allow Inbound Traffic from the VPC CIDR
123 * ```typescript
124 * const allowVpc = yield* AWS.EC2.NetworkAclEntry("AllowVpc", {
125 * networkAclId: acl.networkAclId,
126 * ruleNumber: 100,
127 * protocol: "-1",
128 * ruleAction: "allow",
129 * egress: false,
130 * cidrBlock: "10.0.0.0/16",
131 * });
132 * ```
133 * `protocol: "-1"` matches all protocols and `cidrBlock` scopes the rule to the
134 * VPC's IPv4 range; the low `ruleNumber` (100) makes it take precedence over
135 * higher-numbered rules.
136 *
137 * **Example:** Allow Inbound Ephemeral Ports (NAT Return Traffic)
138 * ```typescript
139 * const allowEphemeral = yield* AWS.EC2.NetworkAclEntry("AllowEphemeral", {
140 * networkAclId: acl.networkAclId,
141 * ruleNumber: 200,
142 * protocol: "6",
143 * ruleAction: "allow",
144 * egress: false,
145 * cidrBlock: "0.0.0.0/0",
146 * portRange: { from: 1024, to: 65535 },
147 * });
148 * ```
149 * Because the ACL is stateless, responses to outbound requests arrive on
150 * ephemeral ports and need their own inbound rule; `protocol: "6"` is TCP and
151 * `portRange` restricts the match to the ephemeral port range.
152 *
153 * **Example:** Deny a Specific IPv6 Range
154 * ```typescript
155 * const denyRange = yield* AWS.EC2.NetworkAclEntry("DenyBadActor", {
156 * networkAclId: acl.networkAclId,
157 * ruleNumber: 50,
158 * protocol: "-1",
159 * ruleAction: "deny",
160 * egress: false,
161 * ipv6CidrBlock: "2001:db8:1234::/48",
162 * });
163 * ```
164 * `ruleAction: "deny"` with a very low `ruleNumber` blocks an IPv6 range before
165 * any allow rule can match it; use `ipv6CidrBlock` instead of `cidrBlock` to
166 * target IPv6 traffic.
167 *
168 * ### Outbound Rules
169 * Outbound rules (`egress: true`) match traffic leaving the subnet and are
170 * numbered in their own sequence, independent of the inbound rules.
171 * **Example:** Allow All Outbound Traffic
172 * ```typescript
173 * const allowEgress = yield* AWS.EC2.NetworkAclEntry("AllowEgress", {
174 * networkAclId: acl.networkAclId,
175 * ruleNumber: 100,
176 * protocol: "-1",
177 * ruleAction: "allow",
178 * egress: true,
179 * cidrBlock: "0.0.0.0/0",
180 * });
181 * ```
182 * Setting `egress: true` makes this an outbound rule; allowing all protocols to
183 * `0.0.0.0/0` is typical when you want the subnet to initiate connections freely.
184 *
185 * ### ICMP Rules
186 * **Example:** Allow Inbound ICMP Echo (Ping)
187 * ```typescript
188 * const allowPing = yield* AWS.EC2.NetworkAclEntry("AllowPing", {
189 * networkAclId: acl.networkAclId,
190 * ruleNumber: 300,
191 * protocol: "1",
192 * ruleAction: "allow",
193 * egress: false,
194 * cidrBlock: "10.0.0.0/16",
195 * icmpTypeCode: { type: 8, code: -1 },
196 * });
197 * ```
198 * ICMP (`protocol: "1"`) has no ports, so `icmpTypeCode` selects the message
199 * type instead — type 8 is echo request and `code: -1` matches all codes.
200 *
201 * @resource
202 */
203 export const NetworkAclEntry = Resource<NetworkAclEntry>("AWS.EC2.NetworkAclEntry");
204
205 export const NetworkAclEntryProvider = () =>
206 Provider.effect(
207 NetworkAclEntry,
208 Effect.gen(function* () {
209 const findEntry = (networkAclId: string, ruleNumber: number, egress: boolean) =>
210 ec2.describeNetworkAcls({ NetworkAclIds: [networkAclId] }).pipe(
211 Effect.catchTag("InvalidNetworkAclID.NotFound", () =>
212 Effect.succeed({ NetworkAcls: [] }),
213 ),
214 Effect.map((r) =>
215 r.NetworkAcls?.[0]?.Entries?.find(
216 (e) => e.RuleNumber === ruleNumber && e.Egress === egress,
217 ),
218 ),
219 );
220
221 const toAttrs = (
222 props: NetworkAclEntryProps,
223 entry: NonNullable<
224 Awaited<
225 ReturnType<
226 typeof findEntry extends (...args: any) => Effect.Effect<infer R, any, any>
227 ? () => Promise<R>
228 : never
229 >
230 >
231 >,
232 ) => ({
233 networkAclId: props.networkAclId as NetworkAclId,
234 ruleNumber: entry.RuleNumber!,
235 egress: entry.Egress!,
236 protocol: entry.Protocol!,
237 ruleAction: entry.RuleAction!,
238 cidrBlock: entry.CidrBlock,
239 ipv6CidrBlock: entry.Ipv6CidrBlock,
240 icmpTypeCode: entry.IcmpTypeCode
241 ? {
242 code: entry.IcmpTypeCode.Code,
243 type: entry.IcmpTypeCode.Type,
244 }
245 : undefined,
246 portRange: entry.PortRange
247 ? {
248 from: entry.PortRange.From,
249 to: entry.PortRange.To,
250 }
251 : undefined,
252 });
253
254 return {
255 stables: [],
256
257 // Entries are embedded in describeNetworkAcls (each NetworkAcl owns an
258 // Entries[]). Flatten every ACL's entries into the full Attributes
259 // shape. Skip the AWS-managed default-deny rule (32767) since it is not
260 // a user-manageable entry.
261 list: () =>
262 ec2.describeNetworkAcls.pages({}).pipe(
263 Stream.runCollect,
264 Effect.map((chunk) =>
265 Array.from(chunk).flatMap((page) =>
266 (page.NetworkAcls ?? [])
267 // Entries on AWS's default ACL are service-managed account
268 // baseline, not independently owned resources. Enumerating
269 // their rule-100 allow entries made every clean nuke mutate
270 // the rematerialized default VPC and report two false
271 // stragglers.
272 .filter((acl) => acl.IsDefault !== true)
273 .flatMap((acl) =>
274 (acl.Entries ?? [])
275 .filter((e) => e.RuleNumber !== 32767)
276 .map((entry) => ({
277 networkAclId: acl.NetworkAclId as NetworkAclId,
278 ruleNumber: entry.RuleNumber!,
279 egress: entry.Egress!,
280 protocol: entry.Protocol!,
281 ruleAction: entry.RuleAction!,
282 cidrBlock: entry.CidrBlock,
283 ipv6CidrBlock: entry.Ipv6CidrBlock,
284 icmpTypeCode: entry.IcmpTypeCode
285 ? {
286 code: entry.IcmpTypeCode.Code,
287 type: entry.IcmpTypeCode.Type,
288 }
289 : undefined,
290 portRange: entry.PortRange
291 ? {
292 from: entry.PortRange.From,
293 to: entry.PortRange.To,
294 }
295 : undefined,
296 })),
297 ),
298 ),
299 ),
300 ),
301
302 read: Effect.fn(function* ({ olds, output }) {
303 if (!output) return undefined;
304 const entry = yield* findEntry(
305 olds.networkAclId as string,
306 output.ruleNumber,
307 output.egress,
308 );
309 if (!entry) {
310 return yield* new NetworkAclEntryUnexpectedResponse({
311 message: `Network ACL Entry not found: ${output.networkAclId} rule ${output.ruleNumber} egress=${output.egress}`,
312 });
313 }
314 return toAttrs(olds, entry);
315 }),
316
317 diff: Effect.fn(function* ({ news, olds }) {
318 if (!isResolved(news)) return;
319 // If network ACL, rule number, or egress changes, need to replace
320 if (
321 news.networkAclId !== olds.networkAclId ||
322 news.ruleNumber !== olds.ruleNumber ||
323 news.egress !== olds.egress
324 ) {
325 return { action: "replace" };
326 }
327 // Other properties can be updated by replacing the entry
328 }),
329
330 reconcile: Effect.fn(function* ({ news, session }) {
331 const entryParams = {
332 NetworkAclId: news.networkAclId as string,
333 RuleNumber: news.ruleNumber,
334 Protocol: news.protocol,
335 RuleAction: news.ruleAction,
336 Egress: news.egress ?? false,
337 CidrBlock: news.cidrBlock,
338 Ipv6CidrBlock: news.ipv6CidrBlock,
339 IcmpTypeCode: news.icmpTypeCode
340 ? {
341 Code: news.icmpTypeCode.code,
342 Type: news.icmpTypeCode.type,
343 }
344 : undefined,
345 PortRange: news.portRange
346 ? {
347 From: news.portRange.from,
348 To: news.portRange.to,
349 }
350 : undefined,
351 DryRun: false,
352 };
353
354 // Observe — entries are identified by (networkAclId, ruleNumber,
355 // egress); look up the live entry to decide between create and
356 // replace.
357 const observed = yield* findEntry(
358 news.networkAclId as string,
359 news.ruleNumber,
360 news.egress ?? false,
361 );
362
363 // Ensure / Sync — if the entry doesn't exist, create it; otherwise
364 // ReplaceNetworkAclEntry overwrites its mutable properties in place.
365 if (observed === undefined) {
366 yield* session.note(`Creating Network ACL Entry (rule ${news.ruleNumber})...`);
367 yield* ec2.createNetworkAclEntry(entryParams);
368 yield* session.note(`Network ACL Entry created: rule ${news.ruleNumber}`);
369 } else {
370 yield* session.note(`Updating Network ACL Entry (rule ${news.ruleNumber})...`);
371 yield* ec2.replaceNetworkAclEntry(entryParams);
372 yield* session.note(`Network ACL Entry updated: rule ${news.ruleNumber}`);
373 }
374
375 // Re-read final state. A freshly created/replaced entry can lag
376 // `describeNetworkAcls` by a moment (EC2 eventual consistency), so
377 // poll until it appears, bounded.
378 const entry = yield* findEntry(
379 news.networkAclId as string,
380 news.ruleNumber,
381 news.egress ?? false,
382 ).pipe(
383 Effect.flatMap((e) =>
384 e ? Effect.succeed(e) : Effect.fail({ _tag: "EntryNotYetVisible" } as const),
385 ),
386 Effect.retry({
387 while: (e) => e._tag === "EntryNotYetVisible",
388 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(8)]),
389 }),
390 Effect.catchTag("EntryNotYetVisible", () =>
391 Effect.fail(
392 new NetworkAclEntryUnexpectedResponse({
393 message: "Network ACL Entry not found after reconcile",
394 }),
395 ),
396 ),
397 );
398 return toAttrs(news, entry);
399 }),
400
401 delete: Effect.fn(function* ({ output, session }) {
402 const networkAclId = output.networkAclId;
403 yield* session.note(`Deleting Network ACL Entry (rule ${output.ruleNumber})...`);
404
405 yield* ec2
406 .deleteNetworkAclEntry({
407 NetworkAclId: networkAclId,
408 RuleNumber: output.ruleNumber,
409 Egress: output.egress,
410 DryRun: false,
411 })
412 .pipe(
413 Effect.catchTags({
414 "InvalidNetworkAclEntry.NotFound": () => Effect.void,
415 "InvalidNetworkAclID.NotFound": () => Effect.void,
416 }),
417 );
418
419 // Delete success is only an acknowledgement. Observe the exact
420 // (ACL, rule number, direction) tuple until it is absent so nuke
421 // cannot report success while the entry is still enumerable.
422 yield* findEntry(networkAclId, output.ruleNumber, output.egress).pipe(
423 Effect.flatMap((entry) =>
424 entry === undefined
425 ? Effect.void
426 : Effect.fail(
427 new NetworkAclEntryStillVisible({
428 networkAclId,
429 ruleNumber: output.ruleNumber,
430 egress: output.egress,
431 }),
432 ),
433 ),
434 Effect.retry({
435 while: (error) => error instanceof NetworkAclEntryStillVisible,
436 schedule: Schedule.max([Schedule.fixed(1000), Schedule.recurs(10)]),
437 }),
438 );
439
440 yield* session.note(`Network ACL Entry deleted: rule ${output.ruleNumber}`);
441 }),
442 };
443 }),
444 );
445
446 class NetworkAclEntryStillVisible extends Data.TaggedError("NetworkAclEntryStillVisible")<{
447 networkAclId: string;
448 ruleNumber: number;
449 egress: boolean;
450 }> {}