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

main
ts 356 lines 12.2 KB
Raw
1 import * as ec2 from "@distilled.cloud/aws/ec2";
2 import { isResolved } from "alchemy/Diff";
3 import * as Provider from "alchemy/Provider";
4 import { Resource } from "alchemy/Resource";
5 import { createInternalTags, createTagsList, diffTags } from "alchemy/Tags";
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 { AccountID } from "../Environment.ts";
11 import { AWSEnvironment } from "../Environment.ts";
12 import type { Providers } from "../Providers.ts";
13 import type { RegionID } from "../Region.ts";
14 import type { VpcId } from "./Vpc.ts";
15
16 export class NetworkAclUnexpectedResponse extends Data.TaggedError("NetworkAclUnexpectedResponse")<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export type NetworkAclId<ID extends string = string> = `acl-${ID}`;
22 export const NetworkAclId = <ID extends string>(id: ID): ID & NetworkAclId<ID> =>
23 `acl-${id}` as ID & NetworkAclId<ID>;
24
25 export type NetworkAclArn<ID extends NetworkAclId = NetworkAclId> =
26 `arn:aws:ec2:${RegionID}:${AccountID}:network-acl/${ID}`;
27
28 export interface NetworkAclProps {
29 /**
30 * The VPC to create the network ACL in.
31 */
32 vpcId: VpcId;
33
34 /**
35 * Tags to assign to the network ACL.
36 */
37 tags?: Record<string, string>;
38 }
39
40 export interface NetworkAcl extends Resource<
41 "AWS.EC2.NetworkAcl",
42 NetworkAclProps,
43 {
44 /**
45 * The ID of the network ACL.
46 */
47 networkAclId: NetworkAclId;
48 /**
49 * The Amazon Resource Name (ARN) of the network ACL.
50 */
51 networkAclArn: NetworkAclArn;
52 /**
53 * The ID of the VPC the network ACL belongs to.
54 */
55 vpcId: VpcId;
56 /**
57 * Whether this is the default network ACL for the VPC.
58 */
59 isDefault: boolean;
60 /**
61 * The ID of the AWS account that owns the network ACL.
62 */
63 ownerId: string;
64 /**
65 * The rule entries (inbound and outbound) currently defined on the ACL.
66 */
67 entries?: Array<{
68 /** The rule number; rules are evaluated lowest to highest. */
69 ruleNumber: number;
70 /** The protocol number ("-1" means all protocols). */
71 protocol: string;
72 /** Whether the rule allows or denies matching traffic. */
73 ruleAction: ec2.RuleAction;
74 /** Whether this is an egress (outbound) rule. */
75 egress: boolean;
76 /** The IPv4 CIDR block the rule applies to. */
77 cidrBlock?: string;
78 /** The IPv6 CIDR block the rule applies to. */
79 ipv6CidrBlock?: string;
80 /** The ICMP type and code, for ICMP rules. */
81 icmpTypeCode?: {
82 code?: number;
83 type?: number;
84 };
85 /** The port range, for TCP/UDP rules. */
86 portRange?: {
87 from?: number;
88 to?: number;
89 };
90 }>;
91 /**
92 * The subnet associations currently attached to the network ACL.
93 */
94 associations?: Array<{
95 /** The ID of the association between the ACL and the subnet. */
96 networkAclAssociationId: string;
97 /** The ID of the associated network ACL. */
98 networkAclId: string;
99 /** The ID of the associated subnet. */
100 subnetId: string;
101 }>;
102 },
103 never,
104 Providers
105 > {}
106 /**
107 * A network ACL — a stateless firewall that controls inbound and outbound
108 * traffic at the *subnet* level, evaluated as an ordered list of numbered
109 * allow/deny rules.
110 *
111 * Unlike security groups (which are stateful and attach to interfaces), a
112 * network ACL is associated with subnets and evaluates return traffic
113 * independently, so you typically pair each inbound rule with a matching
114 * ephemeral-port outbound rule. The ACL itself only takes `vpcId` and `tags`;
115 * the actual rules live in `NetworkAclEntry` resources and subnet attachments
116 * in `NetworkAclAssociation` resources. Changing `vpcId` replaces the ACL.
117 *
118 * ### Creating Network ACLs
119 * **Example:** Basic Network ACL
120 * ```typescript
121 * const acl = yield* AWS.EC2.NetworkAcl("PrivateNetworkAcl", {
122 * vpcId: vpc.vpcId,
123 * tags: { Name: "private-nacl" },
124 * });
125 * ```
126 * This creates an empty custom ACL in the VPC — it starts with only the implicit
127 * default-deny rules, so until you add entries it blocks all traffic on any
128 * subnet you associate with it.
129 *
130 * ### Composing Rules and Associations
131 * A network ACL is only useful once you attach rules and point subnets at it.
132 * The typical pattern is one `NetworkAcl`, several `NetworkAclEntry` rules, and
133 * one `NetworkAclAssociation` per subnet.
134 * **Example:** Network ACL with an Inbound Rule and Subnet Association
135 * ```typescript
136 * const acl = yield* AWS.EC2.NetworkAcl("PrivateNetworkAcl", {
137 * vpcId: vpc.vpcId,
138 * });
139 *
140 * const allowVpc = yield* AWS.EC2.NetworkAclEntry("AllowVpc", {
141 * networkAclId: acl.networkAclId,
142 * ruleNumber: 100,
143 * protocol: "-1",
144 * ruleAction: "allow",
145 * egress: false,
146 * cidrBlock: "10.0.0.0/16",
147 * });
148 *
149 * const association = yield* AWS.EC2.NetworkAclAssociation("SubnetAssoc", {
150 * networkAclId: acl.networkAclId,
151 * subnetId: privateSubnet.subnetId,
152 * });
153 * ```
154 * The entry allows all traffic from within the VPC CIDR and the association
155 * makes the subnet use this ACL instead of the VPC default. Build up the full
156 * rule set by adding more `NetworkAclEntry` resources with increasing
157 * `ruleNumber`s.
158 *
159 * @resource
160 */
161 export const NetworkAcl = Resource<NetworkAcl>("AWS.EC2.NetworkAcl");
162
163 export const NetworkAclProvider = () =>
164 Provider.effect(
165 NetworkAcl,
166 Effect.gen(function* () {
167 const createTags = Effect.fn(function* (id: string, tags?: Record<string, string>) {
168 return {
169 Name: id,
170 ...(yield* createInternalTags(id)),
171 ...tags,
172 };
173 });
174
175 const describeNetworkAcl = (networkAclId: string) =>
176 ec2.describeNetworkAcls({ NetworkAclIds: [networkAclId] }).pipe(
177 Effect.map((r) => r.NetworkAcls?.[0]),
178 Effect.flatMap((acl) =>
179 acl
180 ? Effect.succeed(acl)
181 : Effect.fail(
182 new NetworkAclUnexpectedResponse({
183 message: `Network ACL ${networkAclId} not found`,
184 }),
185 ),
186 ),
187 );
188
189 const toAttrs = Effect.fn(function* (acl: ec2.NetworkAcl) {
190 const { accountId, region } = yield* AWSEnvironment.current;
191 return {
192 networkAclId: acl.NetworkAclId as NetworkAclId,
193 networkAclArn:
194 `arn:aws:ec2:${region}:${accountId}:network-acl/${acl.NetworkAclId}` as NetworkAclArn,
195 vpcId: acl.VpcId as VpcId,
196 isDefault: acl.IsDefault ?? false,
197 ownerId: acl.OwnerId!,
198 entries: acl.Entries?.map((e) => ({
199 ruleNumber: e.RuleNumber!,
200 protocol: e.Protocol!,
201 ruleAction: e.RuleAction!,
202 egress: e.Egress!,
203 cidrBlock: e.CidrBlock,
204 ipv6CidrBlock: e.Ipv6CidrBlock,
205 icmpTypeCode: e.IcmpTypeCode
206 ? {
207 code: e.IcmpTypeCode.Code,
208 type: e.IcmpTypeCode.Type,
209 }
210 : undefined,
211 portRange: e.PortRange
212 ? {
213 from: e.PortRange.From,
214 to: e.PortRange.To,
215 }
216 : undefined,
217 })),
218 associations: acl.Associations?.map((a) => ({
219 networkAclAssociationId: a.NetworkAclAssociationId!,
220 networkAclId: a.NetworkAclId!,
221 subnetId: a.SubnetId!,
222 })),
223 } satisfies NetworkAcl["Attributes"];
224 });
225
226 return {
227 stables: ["networkAclId", "networkAclArn", "ownerId", "isDefault"],
228
229 read: Effect.fn(function* ({ output }) {
230 if (!output) return undefined;
231 const acl = yield* describeNetworkAcl(output.networkAclId);
232 return yield* toAttrs(acl);
233 }),
234
235 list: () =>
236 Effect.gen(function* () {
237 // Filter default NACLs at the API: every VPC has one, they
238 // cannot be deleted, and paging through them under a concurrent
239 // suite stalls the list test past the per-test timeout — which
240 // then skips destroy and leaks the custom ACL + VPC.
241 const acls = yield* ec2.describeNetworkAcls
242 .pages({
243 Filters: [{ Name: "default", Values: ["false"] }],
244 })
245 .pipe(
246 Stream.runCollect,
247 Effect.map((chunk) =>
248 Array.from(chunk).flatMap((page) =>
249 (page.NetworkAcls ?? []).filter(
250 (acl): acl is ec2.NetworkAcl & { NetworkAclId: string } =>
251 acl.NetworkAclId != null && acl.IsDefault !== true,
252 ),
253 ),
254 ),
255 );
256 return yield* Effect.forEach(acls, (acl) => toAttrs(acl));
257 }),
258
259 diff: Effect.fn(function* ({ news, olds }) {
260 if (!isResolved(news)) return;
261 // VPC change requires replacement
262 if (news.vpcId !== olds.vpcId) {
263 return { action: "replace" };
264 }
265 // Tags can be updated in-place
266 }),
267
268 reconcile: Effect.fn(function* ({ id, news, output, session }) {
269 const desiredTags = yield* createTags(id, news.tags);
270
271 // Observe — find the NACL via cached id, else fall through to create.
272 let acl: ec2.NetworkAcl | undefined;
273 if (output?.networkAclId) {
274 const lookup = yield* ec2
275 .describeNetworkAcls({ NetworkAclIds: [output.networkAclId] })
276 .pipe(
277 Effect.catchTag("InvalidNetworkAclID.NotFound", () =>
278 Effect.succeed({ NetworkAcls: [] }),
279 ),
280 );
281 acl = lookup.NetworkAcls?.[0];
282 }
283
284 // Ensure — create the NACL when missing.
285 if (acl === undefined) {
286 yield* session.note("Creating Network ACL...");
287 const result = yield* ec2.createNetworkAcl({
288 VpcId: news.vpcId as string,
289 TagSpecifications: [
290 {
291 ResourceType: "network-acl",
292 Tags: createTagsList(desiredTags),
293 },
294 ],
295 DryRun: false,
296 });
297 const newAclId = result.NetworkAcl!.NetworkAclId!;
298 yield* session.note(`Network ACL created: ${newAclId}`);
299 acl = yield* describeNetworkAcl(newAclId);
300 }
301
302 const networkAclId = acl.NetworkAclId!;
303
304 // Sync tags — observed cloud tags vs desired.
305 const currentTags = Object.fromEntries(
306 (acl.Tags ?? []).map((t) => [t.Key!, t.Value!]),
307 ) as Record<string, string>;
308 const { removed, upsert } = diffTags(currentTags, desiredTags);
309 if (removed.length > 0) {
310 yield* ec2.deleteTags({
311 Resources: [networkAclId],
312 Tags: removed.map((key) => ({ Key: key })),
313 DryRun: false,
314 });
315 }
316 if (upsert.length > 0) {
317 yield* ec2.createTags({
318 Resources: [networkAclId],
319 Tags: upsert,
320 DryRun: false,
321 });
322 }
323
324 // Re-read final state.
325 const final = yield* describeNetworkAcl(networkAclId);
326 return yield* toAttrs(final);
327 }),
328
329 delete: Effect.fn(function* ({ output, session }) {
330 const networkAclId = output.networkAclId;
331
332 yield* session.note(`Deleting Network ACL: ${networkAclId}`);
333
334 yield* ec2
335 .deleteNetworkAcl({
336 NetworkAclId: networkAclId,
337 DryRun: false,
338 })
339 .pipe(
340 Effect.catchTag("InvalidNetworkAclID.NotFound", () => Effect.void),
341 // Retry on dependency violations (e.g., associations still being removed)
342 Effect.retry({
343 while: (e) => e._tag === "DependencyViolation",
344 schedule: Schedule.max([Schedule.exponential(1000, 1.5), Schedule.recurs(15)]).pipe(
345 Schedule.tap(({ attempt }) =>
346 session.note(`Waiting for dependencies to clear... (attempt ${attempt})`),
347 ),
348 ),
349 }),
350 );
351
352 yield* session.note(`Network ACL ${networkAclId} deleted`);
353 }),
354 };
355 }),
356 );