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

main
ts 399 lines 15.6 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as SecurityHub from "@alchemy.run/aws/SecurityHub";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import path from "pathe";
9
10 const main = path.resolve(import.meta.dirname, "handler.ts");
11
12 export class SecurityHubTestFunction extends Lambda.Function<Lambda.Function>()(
13 "SecurityHubTestFunction",
14 ) {}
15
16 /**
17 * Routes answer `{ …fields }` on success or `{ errorTag }` when the operation
18 * fails with a TYPED error — the test asserts the tag is in a route-specific
19 * allowlist, which proves both the binding wiring and the IAM grant. An
20 * untyped error crashes into a 500 instead.
21 */
22 const errorTagged = <A, E extends { _tag: string }, R>(
23 effect: Effect.Effect<A, E, R>,
24 ): Effect.Effect<A | { errorTag: string; errorMessage?: string }, never, R> =>
25 effect.pipe(
26 Effect.map((a): A | { errorTag: string; errorMessage?: string } => a),
27 Effect.catch((e) =>
28 Effect.succeed({
29 errorTag: e._tag,
30 errorMessage: (e as { Message?: string }).Message ?? (e as { message?: string }).message,
31 }),
32 ),
33 );
34
35 // One binding per exercised Security Hub capability. Every SecurityHub
36 // binding shares the single account-level scaffolding shape (the request
37 // passes through as-is), so a representative spread across the thematic
38 // groups proves the scaffold; org/member writes with cross-account side
39 // effects (CreateMembers, EnableOrganizationAdminAccount, …) use the same
40 // builder and are not re-proven here.
41 export default SecurityHubTestFunction.make(
42 {
43 main,
44 functionUrl: true,
45 timeout: Duration.seconds(30),
46 },
47 Effect.gen(function* () {
48 // Security Hub must be enabled for every runtime call — the Hub is the
49 // account/region singleton the whole fixture leans on. The Bindings test
50 // only runs when the account had no Hub (capture-and-restore safety).
51 yield* SecurityHub.Hub("BindingsHub", { enableDefaultStandards: false });
52
53 // Findings triage loop
54 const getFindings = yield* SecurityHub.GetFindings();
55 const getFindingHistory = yield* SecurityHub.GetFindingHistory();
56 const batchImportFindings = yield* SecurityHub.BatchImportFindings();
57 const batchUpdateFindings = yield* SecurityHub.BatchUpdateFindings();
58
59 // Insights
60 const getInsights = yield* SecurityHub.GetInsights();
61
62 // Standards & controls
63 const describeStandards = yield* SecurityHub.DescribeStandards();
64 const getEnabledStandards = yield* SecurityHub.GetEnabledStandards();
65 const listSecurityControlDefinitions = yield* SecurityHub.ListSecurityControlDefinitions();
66 const getSecurityControlDefinition = yield* SecurityHub.GetSecurityControlDefinition();
67
68 // Product integrations
69 const describeProducts = yield* SecurityHub.DescribeProducts();
70 const listEnabledProductsForImport = yield* SecurityHub.ListEnabledProductsForImport();
71
72 // Custom actions, automation rules & aggregation reads
73 const describeActionTargets = yield* SecurityHub.DescribeActionTargets();
74 const listAutomationRules = yield* SecurityHub.ListAutomationRules();
75 const listFindingAggregators = yield* SecurityHub.ListFindingAggregators();
76
77 // Members & organization
78 const listMembers = yield* SecurityHub.ListMembers();
79 const listInvitations = yield* SecurityHub.ListInvitations();
80 const getInvitationsCount = yield* SecurityHub.GetInvitationsCount();
81 const getAdministratorAccount = yield* SecurityHub.GetAdministratorAccount();
82 const listOrganizationAdminAccounts = yield* SecurityHub.ListOrganizationAdminAccounts();
83 const describeOrganizationConfiguration =
84 yield* SecurityHub.DescribeOrganizationConfiguration();
85
86 const bound = {
87 getFindings,
88 getFindingHistory,
89 batchImportFindings,
90 batchUpdateFindings,
91 getInsights,
92 describeStandards,
93 getEnabledStandards,
94 listSecurityControlDefinitions,
95 getSecurityControlDefinition,
96 describeProducts,
97 listEnabledProductsForImport,
98 describeActionTargets,
99 listAutomationRules,
100 listFindingAggregators,
101 listMembers,
102 listInvitations,
103 getInvitationsCount,
104 getAdministratorAccount,
105 listOrganizationAdminAccounts,
106 describeOrganizationConfiguration,
107 };
108
109 return {
110 fetch: Effect.gen(function* () {
111 const request = yield* HttpServerRequest;
112 const url = new URL(request.originalUrl);
113 const pathname = url.pathname;
114
115 if (request.method === "GET" && pathname === "/bindings") {
116 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
117 }
118
119 // Imports a synthetic ASFF finding through the account's default
120 // product — the documented way to exercise a findings pipeline. The
121 // test computes id/account/region out-of-band and passes them in.
122 if (request.method === "POST" && pathname === "/import") {
123 const id = url.searchParams.get("id");
124 const accountId = url.searchParams.get("account");
125 const region = url.searchParams.get("region");
126 if (!id || !accountId || !region) {
127 return yield* HttpServerResponse.json(
128 { error: "missing id/account/region" },
129 { status: 400 },
130 );
131 }
132 const productArn = `arn:aws:securityhub:${region}:${accountId}:product/${accountId}/default`;
133 const now = new Date().toISOString();
134 const result = yield* batchImportFindings({
135 Findings: [
136 {
137 SchemaVersion: "2018-10-08",
138 Id: id,
139 ProductArn: productArn,
140 GeneratorId: "alchemy-bindings-test",
141 AwsAccountId: accountId,
142 Types: ["Software and Configuration Checks"],
143 CreatedAt: now,
144 UpdatedAt: now,
145 Severity: { Label: "INFORMATIONAL" },
146 Title: "Alchemy SecurityHub bindings test finding",
147 Description: "Synthetic finding imported by the alchemy SecurityHub bindings test.",
148 Resources: [
149 {
150 Type: "Other",
151 Id: "alchemy-bindings-test-resource",
152 Partition: "aws",
153 Region: region,
154 },
155 ],
156 },
157 ],
158 });
159 return yield* HttpServerResponse.json({
160 success: Number(result.SuccessCount ?? 0),
161 failed: Number(result.FailedCount ?? 0),
162 });
163 }
164
165 if (request.method === "GET" && pathname === "/findings") {
166 const id = url.searchParams.get("id");
167 const { Findings } = yield* getFindings({
168 ...(id
169 ? { Filters: { Id: [{ Value: id, Comparison: "EQUALS" }] } }
170 : { MaxResults: 10 }),
171 });
172 return yield* HttpServerResponse.json({
173 count: (Findings ?? []).length,
174 workflow: Findings?.[0]?.Workflow?.Status,
175 title: Findings?.[0]?.Title,
176 });
177 }
178
179 // Updates customer-editable fields on the imported finding.
180 if (request.method === "POST" && pathname === "/resolve") {
181 const id = url.searchParams.get("id");
182 const productArn = url.searchParams.get("productArn");
183 if (!id || !productArn) {
184 return yield* HttpServerResponse.json(
185 { error: "missing id/productArn" },
186 { status: 400 },
187 );
188 }
189 const result = yield* batchUpdateFindings({
190 FindingIdentifiers: [{ Id: id, ProductArn: productArn }],
191 Workflow: { Status: "NOTIFIED" },
192 Note: {
193 Text: "acknowledged by the alchemy bindings test",
194 UpdatedBy: "alchemy",
195 },
196 });
197 return yield* HttpServerResponse.json({
198 processed: (result.ProcessedFindings ?? []).length,
199 unprocessed: (result.UnprocessedFindings ?? []).length,
200 });
201 }
202
203 // Finding history may lag the import — a typed ResourceNotFound is an
204 // acceptable outcome that still proves the binding + IAM wiring.
205 if (request.method === "GET" && pathname === "/history") {
206 const id = url.searchParams.get("id");
207 const productArn = url.searchParams.get("productArn");
208 if (!id || !productArn) {
209 return yield* HttpServerResponse.json(
210 { error: "missing id/productArn" },
211 { status: 400 },
212 );
213 }
214 const result = yield* errorTagged(
215 getFindingHistory({
216 FindingIdentifier: { Id: id, ProductArn: productArn },
217 }).pipe(Effect.map((r) => ({ records: (r.Records ?? []).length }))),
218 );
219 return yield* HttpServerResponse.json(result);
220 }
221
222 if (request.method === "GET" && pathname === "/insights") {
223 const { Insights } = yield* getInsights();
224 return yield* HttpServerResponse.json({
225 count: (Insights ?? []).length,
226 });
227 }
228
229 if (request.method === "GET" && pathname === "/standards") {
230 const { Standards } = yield* describeStandards();
231 return yield* HttpServerResponse.json({
232 count: (Standards ?? []).length,
233 });
234 }
235
236 if (request.method === "GET" && pathname === "/enabled-standards") {
237 const { StandardsSubscriptions } = yield* getEnabledStandards();
238 return yield* HttpServerResponse.json({
239 count: (StandardsSubscriptions ?? []).length,
240 });
241 }
242
243 if (request.method === "GET" && pathname === "/control-definitions") {
244 const { SecurityControlDefinitions } = yield* listSecurityControlDefinitions({
245 MaxResults: 10,
246 });
247 return yield* HttpServerResponse.json({
248 count: (SecurityControlDefinitions ?? []).length,
249 });
250 }
251
252 if (request.method === "GET" && pathname === "/control") {
253 const { SecurityControlDefinition } = yield* getSecurityControlDefinition({
254 SecurityControlId: "IAM.1",
255 });
256 return yield* HttpServerResponse.json({
257 id: SecurityControlDefinition?.SecurityControlId ?? null,
258 severity: SecurityControlDefinition?.SeverityRating ?? null,
259 });
260 }
261
262 if (request.method === "GET" && pathname === "/products") {
263 const { Products } = yield* describeProducts({ MaxResults: 10 });
264 return yield* HttpServerResponse.json({
265 count: (Products ?? []).length,
266 });
267 }
268
269 if (request.method === "GET" && pathname === "/enabled-products") {
270 const { ProductSubscriptions } = yield* listEnabledProductsForImport();
271 return yield* HttpServerResponse.json({
272 count: (ProductSubscriptions ?? []).length,
273 });
274 }
275
276 if (request.method === "GET" && pathname === "/action-targets") {
277 const { ActionTargets } = yield* describeActionTargets();
278 return yield* HttpServerResponse.json({
279 count: (ActionTargets ?? []).length,
280 });
281 }
282
283 if (request.method === "GET" && pathname === "/automation-rules") {
284 const { AutomationRulesMetadata } = yield* listAutomationRules();
285 return yield* HttpServerResponse.json({
286 count: (AutomationRulesMetadata ?? []).length,
287 });
288 }
289
290 if (request.method === "GET" && pathname === "/aggregators") {
291 const { FindingAggregators } = yield* listFindingAggregators();
292 return yield* HttpServerResponse.json({
293 count: (FindingAggregators ?? []).length,
294 });
295 }
296
297 if (request.method === "GET" && pathname === "/members") {
298 const { Members } = yield* listMembers();
299 return yield* HttpServerResponse.json({
300 count: (Members ?? []).length,
301 });
302 }
303
304 if (request.method === "GET" && pathname === "/invitations") {
305 const { Invitations } = yield* listInvitations();
306 return yield* HttpServerResponse.json({
307 count: (Invitations ?? []).length,
308 });
309 }
310
311 if (request.method === "GET" && pathname === "/invitations-count") {
312 const { InvitationsCount } = yield* getInvitationsCount();
313 return yield* HttpServerResponse.json({
314 count: Number(InvitationsCount ?? 0),
315 });
316 }
317
318 // A standalone account has no administrator — Security Hub answers
319 // with an empty document or a typed error.
320 if (request.method === "GET" && pathname === "/admin") {
321 const result = yield* errorTagged(
322 getAdministratorAccount().pipe(
323 Effect.map((r) => ({
324 administrator: r.Administrator?.AccountId ?? null,
325 })),
326 ),
327 );
328 return yield* HttpServerResponse.json(result);
329 }
330
331 // Organization administration: for a standalone (non-management)
332 // account Security Hub answers with a typed error — asserting the tag
333 // proves the binding + IAM wiring end-to-end.
334 if (request.method === "GET" && pathname === "/org-admins") {
335 const result = yield* errorTagged(
336 listOrganizationAdminAccounts().pipe(
337 Effect.map((r) => ({ admins: (r.AdminAccounts ?? []).length })),
338 ),
339 );
340 return yield* HttpServerResponse.json(result);
341 }
342
343 if (request.method === "GET" && pathname === "/org-config") {
344 const result = yield* errorTagged(
345 describeOrganizationConfiguration().pipe(
346 Effect.map((r) => ({ autoEnable: r.AutoEnable ?? false })),
347 ),
348 );
349 return yield* HttpServerResponse.json(result);
350 }
351
352 return yield* HttpServerResponse.json(
353 { error: "Not found", method: request.method, pathname },
354 { status: 404 },
355 );
356 }).pipe(
357 // Surface typed operation errors as JSON so live-test failures carry
358 // the tag + message instead of an opaque 500 (routes that expect a
359 // typed error use `errorTagged` above and never reach this).
360 Effect.catch((e) =>
361 HttpServerResponse.json(
362 {
363 errorTag: (e as { _tag?: string })._tag ?? "UnknownError",
364 errorMessage:
365 (e as { message?: string }).message ?? (e as { Message?: string }).Message,
366 },
367 { status: 500 },
368 ),
369 ),
370 Effect.orDie,
371 ),
372 };
373 }).pipe(
374 Effect.provide(
375 Layer.mergeAll(
376 SecurityHub.BatchImportFindingsHttp,
377 SecurityHub.BatchUpdateFindingsHttp,
378 SecurityHub.DescribeActionTargetsHttp,
379 SecurityHub.DescribeOrganizationConfigurationHttp,
380 SecurityHub.DescribeProductsHttp,
381 SecurityHub.DescribeStandardsHttp,
382 SecurityHub.GetAdministratorAccountHttp,
383 SecurityHub.GetEnabledStandardsHttp,
384 SecurityHub.GetFindingHistoryHttp,
385 SecurityHub.GetFindingsHttp,
386 SecurityHub.GetInsightsHttp,
387 SecurityHub.GetInvitationsCountHttp,
388 SecurityHub.GetSecurityControlDefinitionHttp,
389 SecurityHub.ListAutomationRulesHttp,
390 SecurityHub.ListEnabledProductsForImportHttp,
391 SecurityHub.ListFindingAggregatorsHttp,
392 SecurityHub.ListInvitationsHttp,
393 SecurityHub.ListMembersHttp,
394 SecurityHub.ListOrganizationAdminAccountsHttp,
395 SecurityHub.ListSecurityControlDefinitionsHttp,
396 ),
397 ),
398 ),
399 );