@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 04:45 UTC

main
ts 417 lines 16 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 { 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 Data from "effect/Data";
10 import * as Effect from "effect/Effect";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import type { Providers } from "../Providers.ts";
14 import { nfwTagsToRecord, recordToNfwTags } from "./internal.ts";
15
16 export interface FirewallProps {
17 /**
18 * Name of the firewall. Must be 1-128 alphanumeric characters or hyphens.
19 * If omitted, a deterministic physical name is generated. Changing the
20 * name replaces the firewall.
21 */
22 firewallName?: string;
23 /**
24 * ARN of the {@link FirewallPolicy} that defines the firewall's traffic
25 * inspection behavior. Updated in place via `AssociateFirewallPolicy`.
26 */
27 firewallPolicyArn: string;
28 /**
29 * ID of the VPC the firewall protects. Changing the VPC replaces the
30 * firewall.
31 */
32 vpcId: string;
33 /**
34 * The public subnets (one per Availability Zone) that Network Firewall
35 * provisions firewall endpoints into. Uses raw Network Firewall API
36 * structures (`{ SubnetId, IPAddressType? }`). Updated in place via
37 * `AssociateSubnets` / `DisassociateSubnets`.
38 */
39 subnetMappings: NFW.SubnetMapping[];
40 /**
41 * Whether the firewall is protected against deletion. The provider
42 * automatically clears this flag before deleting the firewall.
43 * @default false
44 */
45 deleteProtection?: boolean;
46 /**
47 * Whether the firewall is protected against changes to its subnet
48 * associations.
49 * @default false
50 */
51 subnetChangeProtection?: boolean;
52 /**
53 * Whether the firewall is protected against a change of firewall policy.
54 * @default false
55 */
56 firewallPolicyChangeProtection?: boolean;
57 /**
58 * Human-readable description of the firewall.
59 */
60 description?: string;
61 /**
62 * Tags to apply to the firewall. Merged with internal Alchemy tags.
63 */
64 tags?: Record<string, string>;
65 }
66
67 export interface Firewall extends Resource<
68 "AWS.NetworkFirewall.Firewall",
69 FirewallProps,
70 {
71 /** Name of the firewall. */
72 firewallName: string;
73 /** ARN of the firewall. */
74 firewallArn: string;
75 /** Server-assigned unique id of the firewall. */
76 firewallId: string;
77 /** ID of the VPC the firewall is provisioned into. */
78 vpcId: string;
79 /**
80 * The VPC endpoint IDs of the provisioned firewall endpoints, one per
81 * subnet mapping, sorted for determinism. Use these as route targets.
82 */
83 endpointIds: string[];
84 },
85 never,
86 Providers
87 > {}
88
89 /**
90 * An AWS Network Firewall firewall — provisions managed firewall endpoints
91 * into your VPC subnets and inspects traffic according to an associated
92 * {@link FirewallPolicy}.
93 *
94 * Endpoint provisioning takes several minutes (typically 5-10), and deleting
95 * a firewall waits for the endpoints to deprovision.
96 * ### Creating Firewalls
97 * **Example:** Firewall in a VPC
98 * ```typescript
99 * import * as EC2 from "@alchemy.run/aws/EC2";
100 * import * as NetworkFirewall from "@alchemy.run/aws/NetworkFirewall";
101 *
102 * const vpc = yield* EC2.Vpc("Vpc", { cidrBlock: "10.0.0.0/16" });
103 * const subnet = yield* EC2.Subnet("FirewallSubnet", {
104 * vpcId: vpc.vpcId,
105 * cidrBlock: "10.0.1.0/24",
106 * });
107 *
108 * const policy = yield* NetworkFirewall.FirewallPolicy("Policy", {
109 * firewallPolicy: {
110 * StatelessDefaultActions: ["aws:pass"],
111 * StatelessFragmentDefaultActions: ["aws:pass"],
112 * },
113 * });
114 *
115 * const firewall = yield* NetworkFirewall.Firewall("Firewall", {
116 * firewallPolicyArn: policy.firewallPolicyArn,
117 * vpcId: vpc.vpcId,
118 * subnetMappings: [{ SubnetId: subnet.subnetId }],
119 * });
120 * ```
121 *
122 * @resource
123 */
124 export const Firewall = Resource<Firewall>("AWS.NetworkFirewall.Firewall");
125
126 /** Raised (internally, for bounded retry) while a firewall is provisioning. */
127 export class FirewallNotReady extends Data.TaggedError("FirewallNotReady")<{
128 message: string;
129 }> {}
130
131 /** Raised (internally, for bounded retry) while a firewall is deleting. */
132 export class FirewallNotDeleted extends Data.TaggedError("FirewallNotDeleted")<{
133 message: string;
134 }> {}
135
136 // Explicitly-typed pipeable retry helpers (see internal.ts for why these are
137 // not inlined).
138 const retryWhileNotReady = <A, E extends { readonly _tag: string }, R>(
139 self: Effect.Effect<A, E, R>,
140 ): Effect.Effect<A, E, R> =>
141 Effect.retry(self, {
142 while: (e) => e._tag === "FirewallNotReady",
143 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(60)]),
144 });
145
146 const retryWhileNotDeleted = <A, E extends { readonly _tag: string }, R>(
147 self: Effect.Effect<A, E, R>,
148 ): Effect.Effect<A, E, R> =>
149 Effect.retry(self, {
150 while: (e) => e._tag === "FirewallNotDeleted",
151 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(80)]),
152 });
153
154 const retryWhileFirewallBusy = <A, E extends { readonly _tag: string }, R>(
155 self: Effect.Effect<A, E, R>,
156 ): Effect.Effect<A, E, R> =>
157 Effect.retry(self, {
158 while: (e) => e._tag === "InvalidOperationException",
159 schedule: Schedule.max([Schedule.fixed("15 seconds"), Schedule.recurs(20)]),
160 });
161
162 export const FirewallProvider = () =>
163 Provider.effect(
164 Firewall,
165 Effect.gen(function* () {
166 const createName = Effect.fn(function* (id: string, props: { firewallName?: string }) {
167 return props.firewallName ?? (yield* createPhysicalName({ id, maxLength: 128 }));
168 });
169
170 const endpointIds = (status: NFW.FirewallStatus | undefined): string[] =>
171 Object.values(status?.SyncStates ?? {})
172 .map((state) => state?.Attachment?.EndpointId)
173 .filter((id): id is string => id !== undefined)
174 .sort();
175
176 const toAttrs = (
177 firewall: NFW.Firewall,
178 status: NFW.FirewallStatus | undefined,
179 ): Firewall["Attributes"] => ({
180 firewallName: firewall.FirewallName ?? "",
181 firewallArn: firewall.FirewallArn ?? "",
182 firewallId: firewall.FirewallId,
183 vpcId: firewall.VpcId,
184 endpointIds: endpointIds(status),
185 });
186
187 const describe = Effect.fn(function* (name: string) {
188 return yield* nfw
189 .describeFirewall({ FirewallName: name })
190 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
191 });
192
193 // Bounded readiness wait. Endpoint provisioning typically completes in
194 // 5-10 minutes; budget ~15 min (60 * 15s).
195 const waitForReady = Effect.fn(function* (name: string) {
196 return yield* Effect.gen(function* () {
197 const response = yield* describe(name);
198 if (response?.Firewall === undefined) {
199 return yield* new FirewallNotReady({ message: `firewall '${name}' not found` });
200 }
201 if (response.FirewallStatus?.Status !== "READY") {
202 return yield* new FirewallNotReady({
203 message: `firewall '${name}' not ready (status: ${response.FirewallStatus?.Status})`,
204 });
205 }
206 return response;
207 }).pipe(retryWhileNotReady);
208 });
209
210 return Firewall.Provider.of({
211 stables: ["firewallName", "firewallArn", "firewallId", "vpcId"],
212
213 list: () =>
214 Effect.gen(function* () {
215 const pages = yield* nfw.listFirewalls.pages({}).pipe(Stream.runCollect);
216 const metas = Array.from(pages).flatMap((page) => page.Firewalls ?? []);
217 const items = yield* Effect.forEach(
218 metas,
219 (meta) =>
220 nfw.describeFirewall({ FirewallArn: meta.FirewallArn }).pipe(
221 Effect.map((r) =>
222 r.Firewall !== undefined ? toAttrs(r.Firewall, r.FirewallStatus) : undefined,
223 ),
224 Effect.catchTag("ResourceNotFoundException", () => Effect.undefined),
225 ),
226 { concurrency: 5 },
227 );
228 return items.filter((item): item is Firewall["Attributes"] => item !== undefined);
229 }),
230
231 read: Effect.fn(function* ({ id, olds, output }) {
232 const name = output?.firewallName ?? (yield* createName(id, olds ?? {}));
233 const found = yield* describe(name);
234 if (found?.Firewall === undefined) return undefined;
235 const attrs = toAttrs(found.Firewall, found.FirewallStatus);
236 const tags = nfwTagsToRecord(found.Firewall.Tags);
237 return (yield* hasAlchemyTags(id, tags)) ? attrs : Unowned(attrs);
238 }),
239
240 diff: Effect.fn(function* ({ id, news, olds }) {
241 if (!isResolved(news)) return undefined;
242 const oldName = yield* createName(id, olds);
243 const newName = yield* createName(id, news);
244 if (oldName !== newName || olds.vpcId !== news.vpcId) {
245 return { action: "replace" } as const;
246 }
247 }),
248
249 reconcile: Effect.fn(function* ({ id, news, output, session }) {
250 const name = output?.firewallName ?? (yield* createName(id, news));
251 const internalTags = yield* createInternalTags(id);
252 const desiredTags: Record<string, string> = {
253 ...news.tags,
254 ...internalTags,
255 };
256
257 // 1. Observe — cloud state is authoritative.
258 let observed = yield* describe(name);
259
260 // 2. Ensure — create if missing, then wait for READY so mutation
261 // calls below don't race endpoint provisioning.
262 if (observed?.Firewall === undefined) {
263 yield* session.note(`creating firewall ${name} (5-10 minutes)`);
264 yield* nfw.createFirewall({
265 FirewallName: name,
266 FirewallPolicyArn: news.firewallPolicyArn,
267 VpcId: news.vpcId,
268 SubnetMappings: news.subnetMappings,
269 DeleteProtection: news.deleteProtection ?? false,
270 SubnetChangeProtection: news.subnetChangeProtection ?? false,
271 FirewallPolicyChangeProtection: news.firewallPolicyChangeProtection ?? false,
272 Description: news.description,
273 Tags: recordToNfwTags(desiredTags),
274 });
275 }
276 observed = yield* waitForReady(name);
277 let firewall = observed.Firewall!;
278
279 // 3. Sync — each mutable aspect re-reads for a fresh UpdateToken,
280 // diffs OBSERVED against desired, and applies only the delta.
281 const refresh = Effect.fn(function* () {
282 observed = yield* waitForReady(name);
283 firewall = observed.Firewall!;
284 });
285
286 // 3a. Firewall policy association.
287 if (firewall.FirewallPolicyArn !== news.firewallPolicyArn) {
288 yield* nfw.associateFirewallPolicy({
289 UpdateToken: observed.UpdateToken,
290 FirewallName: name,
291 FirewallPolicyArn: news.firewallPolicyArn,
292 });
293 yield* refresh();
294 }
295
296 // 3b. Subnet associations.
297 const observedSubnetIds = new Set(firewall.SubnetMappings.map((m) => m.SubnetId));
298 const desiredSubnetIds = new Set(news.subnetMappings.map((m) => m.SubnetId));
299 const toAssociate = news.subnetMappings.filter((m) => !observedSubnetIds.has(m.SubnetId));
300 const toDisassociate = [...observedSubnetIds].filter(
301 (subnetId) => !desiredSubnetIds.has(subnetId),
302 );
303 if (toAssociate.length > 0) {
304 yield* nfw.associateSubnets({
305 UpdateToken: observed.UpdateToken,
306 FirewallName: name,
307 SubnetMappings: toAssociate,
308 });
309 yield* refresh();
310 }
311 if (toDisassociate.length > 0) {
312 yield* nfw.disassociateSubnets({
313 UpdateToken: observed.UpdateToken,
314 FirewallName: name,
315 SubnetIds: toDisassociate,
316 });
317 yield* refresh();
318 }
319
320 // 3c. Description.
321 if ((news.description ?? undefined) !== firewall.Description) {
322 yield* nfw.updateFirewallDescription({
323 UpdateToken: observed.UpdateToken,
324 FirewallName: name,
325 Description: news.description,
326 });
327 yield* refresh();
328 }
329
330 // 3d. Protection flags.
331 const desiredDeleteProtection = news.deleteProtection ?? false;
332 if ((firewall.DeleteProtection ?? false) !== desiredDeleteProtection) {
333 yield* nfw.updateFirewallDeleteProtection({
334 UpdateToken: observed.UpdateToken,
335 FirewallName: name,
336 DeleteProtection: desiredDeleteProtection,
337 });
338 yield* refresh();
339 }
340 const desiredSubnetChangeProtection = news.subnetChangeProtection ?? false;
341 if ((firewall.SubnetChangeProtection ?? false) !== desiredSubnetChangeProtection) {
342 yield* nfw.updateSubnetChangeProtection({
343 UpdateToken: observed.UpdateToken,
344 FirewallName: name,
345 SubnetChangeProtection: desiredSubnetChangeProtection,
346 });
347 yield* refresh();
348 }
349 const desiredPolicyChangeProtection = news.firewallPolicyChangeProtection ?? false;
350 if (
351 (firewall.FirewallPolicyChangeProtection ?? false) !== desiredPolicyChangeProtection
352 ) {
353 yield* nfw.updateFirewallPolicyChangeProtection({
354 UpdateToken: observed.UpdateToken,
355 FirewallName: name,
356 FirewallPolicyChangeProtection: desiredPolicyChangeProtection,
357 });
358 yield* refresh();
359 }
360
361 // 3e. Tags — diff against OBSERVED cloud tags.
362 const observedTags = nfwTagsToRecord(firewall.Tags);
363 const { upsert, removed } = diffTags(observedTags, desiredTags);
364 const arn = firewall.FirewallArn!;
365 if (upsert.length > 0) {
366 yield* nfw.tagResource({ ResourceArn: arn, Tags: upsert });
367 }
368 if (removed.length > 0) {
369 yield* nfw.untagResource({ ResourceArn: arn, TagKeys: removed });
370 }
371
372 yield* session.note(name);
373 return toAttrs(firewall, observed.FirewallStatus);
374 }),
375
376 delete: Effect.fn(function* ({ output, session }) {
377 const name = output.firewallName;
378 const observed = yield* nfw
379 .describeFirewall({ FirewallName: name })
380 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
381 if (observed === undefined) return;
382
383 // Clear delete protection first — DeleteFirewall requires it off.
384 if (observed.Firewall?.DeleteProtection) {
385 yield* nfw
386 .updateFirewallDeleteProtection({
387 UpdateToken: observed.UpdateToken,
388 FirewallName: name,
389 DeleteProtection: false,
390 })
391 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.void));
392 }
393
394 yield* session.note(
395 `deleting firewall ${name} (endpoints deprovision over several minutes)`,
396 );
397 yield* nfw.deleteFirewall({ FirewallName: name }).pipe(
398 retryWhileFirewallBusy,
399 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
400 );
401
402 // Wait until the firewall (and its endpoints) are fully gone so
403 // dependent deletions (subnets, VPC) don't hit DependencyViolations.
404 yield* Effect.gen(function* () {
405 const remaining = yield* nfw
406 .describeFirewall({ FirewallName: name })
407 .pipe(Effect.catchTag("ResourceNotFoundException", () => Effect.undefined));
408 if (remaining !== undefined) {
409 return yield* new FirewallNotDeleted({
410 message: `firewall '${name}' still deleting (status: ${remaining.FirewallStatus?.Status})`,
411 });
412 }
413 }).pipe(retryWhileNotDeleted);
414 }),
415 });
416 }),
417 );