@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, 06:00 UTC

main
ts 279 lines 10.6 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 * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as Option from "effect/Option";
8 import * as Stream from "effect/Stream";
9 import type { Providers } from "../Providers.ts";
10 import { getDefaultVpcScope } from "./defaultVpcScope.ts";
11 import type { NetworkAclId } from "./NetworkAcl.ts";
12 import type { SubnetId } from "./Subnet.ts";
13
14 export class NetworkAclAssociationUnexpectedResponse extends Data.TaggedError(
15 "NetworkAclAssociationUnexpectedResponse",
16 )<{
17 readonly message: string;
18 readonly cause?: unknown;
19 }> {}
20
21 export class NetworkAclAssociationOperationFailed extends Data.TaggedError(
22 "NetworkAclAssociationOperationFailed",
23 )<{
24 readonly message: string;
25 readonly cause?: unknown;
26 }> {}
27
28 export type NetworkAclAssociationId<ID extends string = string> = `aclassoc-${ID}`;
29 export const NetworkAclAssociationId = <ID extends string>(
30 id: ID,
31 ): ID & NetworkAclAssociationId<ID> => `aclassoc-${id}` as ID & NetworkAclAssociationId<ID>;
32
33 export interface NetworkAclAssociationProps {
34 /**
35 * The ID of the new network ACL to associate with the subnet.
36 */
37 networkAclId: NetworkAclId;
38
39 /**
40 * The ID of the subnet to associate with the network ACL.
41 */
42 subnetId: SubnetId;
43 }
44
45 export interface NetworkAclAssociation extends Resource<
46 "AWS.EC2.NetworkAclAssociation",
47 NetworkAclAssociationProps,
48 {
49 /**
50 * The ID of the association between the network ACL and the subnet.
51 */
52 associationId: NetworkAclAssociationId;
53 /**
54 * The ID of the network ACL the subnet is associated with.
55 */
56 networkAclId: NetworkAclId;
57 /**
58 * The ID of the associated subnet.
59 */
60 subnetId: SubnetId;
61 },
62 never,
63 Providers
64 > {}
65 /**
66 * Associates a subnet with a `NetworkAcl`, replacing whichever ACL the subnet
67 * currently uses (every subnet is always associated with exactly one network
68 * ACL — the VPC's default until you point it at a custom one).
69 *
70 * Changing `subnetId` replaces the association, while changing only
71 * `networkAclId` re-points the same subnet at a different ACL in place. On
72 * delete, the subnet is reverted to the VPC's default network ACL so it is never
73 * left without one.
74 *
75 * ### Associating Subnets
76 * A subnet starts out attached to the VPC's default ACL; this resource moves it
77 * onto a custom ACL so the rules you defined with `NetworkAclEntry` take effect
78 * for that subnet.
79 * **Example:** Move a Subnet onto a Custom Network ACL
80 * ```typescript
81 * const association = yield* AWS.EC2.NetworkAclAssociation("PrivateSubnetNaclAssoc", {
82 * networkAclId: privateNetworkAcl.networkAclId,
83 * subnetId: privateSubnet.subnetId,
84 * });
85 * ```
86 * This detaches the subnet from the default ACL and attaches it to your custom
87 * ACL; destroying the association automatically reverts the subnet to the
88 * default ACL, which is the safe way to "remove" a custom ACL from a subnet.
89 *
90 * @resource
91 */
92 export const NetworkAclAssociation = Resource<NetworkAclAssociation>(
93 "AWS.EC2.NetworkAclAssociation",
94 );
95
96 export const NetworkAclAssociationProvider = () =>
97 Provider.effect(
98 NetworkAclAssociation,
99 Effect.gen(function* () {
100 const findAssociation = (subnetId: string) =>
101 ec2
102 .describeNetworkAcls({
103 Filters: [{ Name: "association.subnet-id", Values: [subnetId] }],
104 })
105 .pipe(
106 Effect.map((r) => {
107 const acl = r.NetworkAcls?.[0];
108 const assoc = acl?.Associations?.find((a) => a.SubnetId === subnetId);
109 return assoc
110 ? {
111 associationId: assoc.NetworkAclAssociationId!,
112 networkAclId: assoc.NetworkAclId!,
113 subnetId: assoc.SubnetId!,
114 }
115 : undefined;
116 }),
117 );
118
119 return NetworkAclAssociation.Provider.of({
120 stables: ["subnetId"],
121
122 // NACL associations are embedded in describeNetworkAcls. Each NetworkAcl
123 // carries an Associations[] of {subnet, acl, associationId}; flatten
124 // every page's associations to enumerate them all in the region.
125 list: () =>
126 Effect.gen(function* () {
127 // Associations on the default VPC's default network ACL are
128 // furniture AWS auto-provisions for its subnets; never
129 // census/nuke them. Associations to user-created (non-default)
130 // ACLs inside the default VPC are still listed.
131 const defaultVpc = yield* getDefaultVpcScope;
132 return yield* ec2.describeNetworkAcls.pages({}).pipe(
133 Stream.runCollect,
134 Effect.map((chunk) =>
135 Array.from(chunk).flatMap((page) =>
136 (page.NetworkAcls ?? [])
137 .filter(
138 (acl) =>
139 defaultVpc.vpcId === undefined ||
140 !(acl.VpcId === defaultVpc.vpcId && acl.IsDefault),
141 )
142 .flatMap((acl) =>
143 (acl.Associations ?? [])
144 .filter(
145 (
146 a,
147 ): a is ec2.NetworkAclAssociation & {
148 NetworkAclAssociationId: string;
149 NetworkAclId: string;
150 SubnetId: string;
151 } =>
152 a.NetworkAclAssociationId != null &&
153 a.NetworkAclId != null &&
154 a.SubnetId != null,
155 )
156 .map((a) => ({
157 associationId: a.NetworkAclAssociationId as NetworkAclAssociationId,
158 networkAclId: a.NetworkAclId as NetworkAclId,
159 subnetId: a.SubnetId as SubnetId,
160 })),
161 ),
162 ),
163 ),
164 );
165 }),
166
167 read: Effect.fn(function* ({ olds }) {
168 if (!olds) return undefined;
169 const assoc = yield* findAssociation(olds.subnetId as string);
170 if (!assoc) {
171 return yield* new NetworkAclAssociationUnexpectedResponse({
172 message: `Network ACL Association not found for subnet ${olds.subnetId}`,
173 });
174 }
175 return {
176 associationId: assoc.associationId as NetworkAclAssociationId,
177 networkAclId: assoc.networkAclId as NetworkAclId,
178 subnetId: assoc.subnetId as SubnetId,
179 };
180 }),
181
182 diff: Effect.fn(function* ({ news, olds }) {
183 if (!isResolved(news)) return;
184 // Subnet change requires replacement
185 if (news.subnetId !== olds.subnetId) {
186 return { action: "replace" };
187 }
188 // Network ACL change can be done via replaceNetworkAclAssociation
189 }),
190
191 reconcile: Effect.fn(function* ({ news, session }) {
192 // Observe — find the subnet's current association. EC2 guarantees
193 // every subnet always has exactly one NACL association, so the
194 // lookup always returns something for a live subnet.
195 const currentAssoc = yield* findAssociation(news.subnetId as string);
196 if (!currentAssoc) {
197 return yield* new NetworkAclAssociationOperationFailed({
198 message: `No existing Network ACL Association found for subnet ${news.subnetId}`,
199 });
200 }
201
202 // Sync — if the subnet already points at the desired NACL, the
203 // association is already correct and we just report it. Otherwise
204 // ReplaceNetworkAclAssociation atomically swaps it.
205 if (currentAssoc.networkAclId === (news.networkAclId as string)) {
206 return {
207 associationId: currentAssoc.associationId as NetworkAclAssociationId,
208 networkAclId: news.networkAclId as NetworkAclId,
209 subnetId: news.subnetId as SubnetId,
210 };
211 }
212
213 yield* session.note(
214 `Associating subnet ${news.subnetId} with NACL ${news.networkAclId}...`,
215 );
216 const result = yield* ec2.replaceNetworkAclAssociation({
217 AssociationId: currentAssoc.associationId,
218 NetworkAclId: news.networkAclId as string,
219 DryRun: false,
220 });
221 const newAssociationId = result.NewAssociationId!;
222 yield* session.note(`Network ACL Association: ${newAssociationId}`);
223 return {
224 associationId: newAssociationId as NetworkAclAssociationId,
225 networkAclId: news.networkAclId as NetworkAclId,
226 subnetId: news.subnetId as SubnetId,
227 };
228 }),
229
230 delete: Effect.fn(function* ({ olds, output, session }) {
231 yield* session.note(`Deleting Network ACL Association...`);
232
233 // When deleting, we need to associate the subnet back to the default NACL
234 // Find the default NACL for the VPC
235 const subnetResult = yield* ec2
236 .describeSubnets({
237 SubnetIds: [olds.subnetId as string],
238 })
239 .pipe(
240 // If subnet is already deleted, association is gone too
241 Effect.catchTag("InvalidSubnetID.NotFound", () => Effect.succeed({ Subnets: [] })),
242 );
243 const vpcId = subnetResult.Subnets?.[0]?.VpcId;
244
245 if (!vpcId) {
246 // Subnet is already deleted, so the association is gone
247 yield* session.note(`Subnet already deleted, association is gone`);
248 return;
249 }
250
251 const defaultAcl = yield* ec2.describeNetworkAcls
252 .items({
253 Filters: [
254 { Name: "vpc-id", Values: [vpcId] },
255 { Name: "default", Values: ["true"] },
256 ],
257 })
258 .pipe(Stream.runHead, Effect.map(Option.getOrUndefined));
259
260 const defaultAclId = defaultAcl?.NetworkAclId;
261
262 if (defaultAclId && defaultAclId !== (olds.networkAclId as string)) {
263 // Replace with default NACL
264 yield* ec2
265 .replaceNetworkAclAssociation({
266 AssociationId: output.associationId,
267 NetworkAclId: defaultAclId,
268 DryRun: false,
269 })
270 .pipe(Effect.catchTag("InvalidAssociationID.NotFound", () => Effect.void));
271
272 yield* session.note(`Network ACL Association reverted to default`);
273 } else {
274 yield* session.note(`Already using default Network ACL, nothing to do`);
275 }
276 }),
277 });
278 }),
279 );