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

main
ts 236 lines 9.38 KB
Raw
1 import { Subnet, Vpc } from "@alchemy.run/aws/EC2";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
3 import * as NetworkFirewall from "@alchemy.run/aws/NetworkFirewall";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import { HttpServerRequest } from "effect/http/HttpServerRequest";
7 import * as HttpServerResponse from "effect/http/HttpServerResponse";
8 import * as Layer from "effect/Layer";
9 import * as Result from "effect/Result";
10 import * as Schedule from "effect/Schedule";
11 import path from "pathe";
12
13 const main = path.resolve(import.meta.dirname, "firewall-handler.ts");
14
15 export class NetworkFirewallFirewallBindingsFunction extends Lambda.Function<Lambda.Function>()(
16 "NetworkFirewallFirewallBindingsFunction",
17 ) {}
18
19 /**
20 * Firewall-scoped bindings fixture. A firewall takes ~5-10 minutes to
21 * provision its endpoints, so this fixture is only deployed by the
22 * `AWS_TEST_NETWORKFIREWALL=1`-gated tests in `FirewallBindings.test.ts`.
23 */
24 export default NetworkFirewallFirewallBindingsFunction.make(
25 {
26 main,
27 functionUrl: true,
28 timeout: Duration.seconds(120),
29 },
30 Effect.gen(function* () {
31 const vpc = yield* Vpc("BindingsVpc", {
32 cidrBlock: "10.78.0.0/16",
33 tags: { fixture: "nfw-bindings" },
34 });
35 const subnet = yield* Subnet("BindingsFirewallSubnet", {
36 vpcId: vpc.vpcId,
37 cidrBlock: "10.78.1.0/24",
38 tags: { fixture: "nfw-bindings" },
39 });
40 const policy = yield* NetworkFirewall.FirewallPolicy("BindingsFwPolicy", {
41 firewallPolicy: {
42 StatelessDefaultActions: ["aws:pass"],
43 StatelessFragmentDefaultActions: ["aws:pass"],
44 },
45 });
46 const firewall = yield* NetworkFirewall.Firewall("BindingsFirewall", {
47 firewallPolicyArn: policy.firewallPolicyArn,
48 vpcId: vpc.vpcId,
49 subnetMappings: [{ SubnetId: subnet.subnetId }],
50 tags: { fixture: "nfw-bindings" },
51 });
52
53 const bound = {
54 describeFirewall: yield* NetworkFirewall.DescribeFirewall(firewall),
55 startFlowCapture: yield* NetworkFirewall.StartFlowCapture(firewall),
56 startFlowFlush: yield* NetworkFirewall.StartFlowFlush(firewall),
57 describeFlowOperation: yield* NetworkFirewall.DescribeFlowOperation(firewall),
58 listFlowOperations: yield* NetworkFirewall.ListFlowOperations(firewall),
59 listFlowOperationResults: yield* NetworkFirewall.ListFlowOperationResults(firewall),
60 startAnalysisReport: yield* NetworkFirewall.StartAnalysisReport(firewall),
61 listAnalysisReports: yield* NetworkFirewall.ListAnalysisReports(firewall),
62 getAnalysisReportResults: yield* NetworkFirewall.GetAnalysisReportResults(firewall),
63 };
64
65 // Flow operations target exactly one firewall endpoint ("Exactly one of
66 // AvailabilityZone, AvailabilityZoneId, VpcEndpointId, or
67 // VpcEndpointAssociationArn must be set"). The firewall's sync states are
68 // keyed by the Availability Zone of each endpoint.
69 const firewallAz = bound
70 .describeFirewall()
71 .pipe(Effect.map((r) => Object.keys(r.FirewallStatus?.SyncStates ?? {})[0]));
72
73 // A narrow filter so the capture/flush stays tiny.
74 const flowFilters = [{ SourceAddress: { AddressDefinition: "10.78.1.10/32" } }];
75
76 return {
77 fetch: Effect.gen(function* () {
78 const request = yield* HttpServerRequest;
79 const url = new URL(request.originalUrl);
80 const pathname = url.pathname;
81
82 if (request.method === "GET" && pathname === "/bindings") {
83 return yield* HttpServerResponse.json({
84 bound: Object.keys(bound),
85 });
86 }
87
88 // Firewall-scoped describe — the firewall ARN is injected.
89 if (request.method === "GET" && pathname === "/firewall") {
90 const response = yield* bound.describeFirewall();
91 return yield* HttpServerResponse.json({
92 status: response.FirewallStatus?.Status,
93 endpointCount: Object.keys(response.FirewallStatus?.SyncStates ?? {}).length,
94 });
95 }
96
97 // Full flow-operation loop: start a capture, poll (bounded) until
98 // terminal, then read it back through the list interfaces. Each
99 // step reports its typed failure so a single grant gap is
100 // diagnosable from the JSON instead of a generic 500.
101 if (request.method === "GET" && pathname === "/flow") {
102 const az = yield* Effect.result(firewallAz);
103 if (Result.isFailure(az)) {
104 return yield* HttpServerResponse.json({
105 step: "describeFirewall",
106 tag: az.failure._tag,
107 error: String(az.failure),
108 });
109 }
110 const started = yield* Effect.result(
111 bound.startFlowCapture({ AvailabilityZone: az.success, FlowFilters: flowFilters }),
112 );
113 if (Result.isFailure(started)) {
114 return yield* HttpServerResponse.json({
115 step: "startFlowCapture",
116 tag: started.failure._tag,
117 error: String(started.failure),
118 });
119 }
120 const FlowOperationId = started.success.FlowOperationId!;
121 const polled = yield* Effect.result(
122 bound.describeFlowOperation({ AvailabilityZone: az.success, FlowOperationId }).pipe(
123 Effect.repeat({
124 schedule: Schedule.spaced("2 seconds"),
125 until: (r): boolean => r.FlowOperationStatus !== "IN_PROGRESS",
126 times: 20,
127 }),
128 ),
129 );
130 if (Result.isFailure(polled)) {
131 return yield* HttpServerResponse.json({
132 step: "describeFlowOperation",
133 tag: polled.failure._tag,
134 error: String(polled.failure),
135 });
136 }
137 const listed = yield* Effect.result(
138 bound.listFlowOperations({
139 AvailabilityZone: az.success,
140 FlowOperationType: "FLOW_CAPTURE",
141 }),
142 );
143 if (Result.isFailure(listed)) {
144 return yield* HttpServerResponse.json({
145 step: "listFlowOperations",
146 tag: listed.failure._tag,
147 error: String(listed.failure),
148 });
149 }
150 const results = yield* Effect.result(
151 bound.listFlowOperationResults({ AvailabilityZone: az.success, FlowOperationId }),
152 );
153 if (Result.isFailure(results)) {
154 return yield* HttpServerResponse.json({
155 step: "listFlowOperationResults",
156 tag: results.failure._tag,
157 error: String(results.failure),
158 });
159 }
160 return yield* HttpServerResponse.json({
161 step: "ok",
162 flowOperationId: FlowOperationId,
163 status: polled.success.FlowOperationStatus,
164 operations: (listed.success.FlowOperations ?? []).length,
165 flows: (results.success.Flows ?? []).length,
166 });
167 }
168
169 // Flush — success or any typed rejection proves the grant.
170 if (request.method === "GET" && pathname === "/flush") {
171 const tag = yield* firewallAz.pipe(
172 Effect.flatMap((AvailabilityZone) =>
173 bound.startFlowFlush({ AvailabilityZone, FlowFilters: flowFilters }),
174 ),
175 Effect.map(() => "ok"),
176 Effect.catch((e) => Effect.succeed(e._tag)),
177 );
178 return yield* HttpServerResponse.json({ tag });
179 }
180
181 // Analysis-report interface. The fixture firewall has no analysis
182 // types enabled, so StartAnalysisReport and a bogus
183 // GetAnalysisReportResults round-trip to typed rejections (an IAM
184 // gap would surface AccessDeniedException instead); the list is a
185 // real (empty) read.
186 if (request.method === "GET" && pathname === "/analysis") {
187 const startTag = yield* bound.startAnalysisReport({ AnalysisType: "TLS_SNI" }).pipe(
188 Effect.map(() => "ok"),
189 Effect.catch((e) => Effect.succeed(e._tag)),
190 );
191 const listed = yield* Effect.result(bound.listAnalysisReports());
192 if (Result.isFailure(listed)) {
193 return yield* HttpServerResponse.json({
194 step: "listAnalysisReports",
195 tag: listed.failure._tag,
196 error: String(listed.failure),
197 });
198 }
199 const getTag = yield* bound
200 .getAnalysisReportResults({
201 AnalysisReportId: "alchemy-nonexistent-analysis-report-id",
202 })
203 .pipe(
204 Effect.map(() => "ok"),
205 Effect.catch((e) => Effect.succeed(e._tag)),
206 );
207 return yield* HttpServerResponse.json({
208 step: "ok",
209 startTag,
210 reports: (listed.success.AnalysisReports ?? []).length,
211 getTag,
212 });
213 }
214
215 return yield* HttpServerResponse.json(
216 { error: "Not found", method: request.method, pathname },
217 { status: 404 },
218 );
219 }).pipe(Effect.orDie),
220 };
221 }).pipe(
222 Effect.provide(
223 Layer.mergeAll(
224 NetworkFirewall.DescribeFirewallHttp,
225 NetworkFirewall.StartFlowCaptureHttp,
226 NetworkFirewall.StartFlowFlushHttp,
227 NetworkFirewall.DescribeFlowOperationHttp,
228 NetworkFirewall.ListFlowOperationsHttp,
229 NetworkFirewall.ListFlowOperationResultsHttp,
230 NetworkFirewall.StartAnalysisReportHttp,
231 NetworkFirewall.ListAnalysisReportsHttp,
232 NetworkFirewall.GetAnalysisReportResultsHttp,
233 ),
234 ),
235 ),
236 );