@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 324 lines 12.5 KB
Raw
1 import * as GuardDuty from "@alchemy.run/aws/GuardDuty";
2 import * as Lambda from "@alchemy.run/aws/Lambda";
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 GuardDutyTestFunction extends Lambda.Function<Lambda.Function>()(
13 "GuardDutyTestFunction",
14 ) {}
15
16 /**
17 * Routes answer `{ …fields }` on success or `{ errorTag }` when the
18 * operation fails with a TYPED error — the test asserts the tag is in a
19 * route-specific allowlist, which proves both the binding wiring and the
20 * IAM grant. An 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 GuardDuty capability, spanning both scaffolding
36 // shapes: detector-scoped (DetectorId injected from the bound Detector) and
37 // account-level (request passed as-is). Member/org-admin writes with
38 // cross-account side effects (InviteMembers, EnableOrganizationAdminAccount,
39 // …) share the same two builders and are not re-proven here.
40 export default GuardDutyTestFunction.make(
41 {
42 main,
43 functionUrl: true,
44 timeout: Duration.seconds(30),
45 },
46 Effect.gen(function* () {
47 // The detector every detector-scoped binding is bound to. GuardDuty
48 // allows one detector per account/region — the test account keeps none
49 // deployed between runs (Detector.test.ts is capture-and-restore safe).
50 const detector = yield* GuardDuty.Detector("BindingsDetector", {
51 findingPublishingFrequency: "FIFTEEN_MINUTES",
52 tags: { fixture: "guardduty-bindings" },
53 });
54
55 // Findings triage loop
56 const createSampleFindings = yield* GuardDuty.CreateSampleFindings(detector);
57 const listFindings = yield* GuardDuty.ListFindings(detector);
58 const getFindings = yield* GuardDuty.GetFindings(detector);
59 const getFindingsStatistics = yield* GuardDuty.GetFindingsStatistics(detector);
60 const archiveFindings = yield* GuardDuty.ArchiveFindings(detector);
61 const unarchiveFindings = yield* GuardDuty.UnarchiveFindings(detector);
62 const updateFindingsFeedback = yield* GuardDuty.UpdateFindingsFeedback(detector);
63
64 // Detector-scoped reads
65 const listMembers = yield* GuardDuty.ListMembers(detector);
66 const getAdministratorAccount = yield* GuardDuty.GetAdministratorAccount(detector);
67 const getMalwareScanSettings = yield* GuardDuty.GetMalwareScanSettings(detector);
68 const getUsageStatistics = yield* GuardDuty.GetUsageStatistics(detector);
69 const listCoverage = yield* GuardDuty.ListCoverage(detector);
70 const getRemainingFreeTrialDays = yield* GuardDuty.GetRemainingFreeTrialDays(detector);
71 const listInvestigations = yield* GuardDuty.ListInvestigations(detector);
72 const describeOrganizationConfiguration =
73 yield* GuardDuty.DescribeOrganizationConfiguration(detector);
74
75 // Account-level (invitation flow + org administration)
76 const getInvitationsCount = yield* GuardDuty.GetInvitationsCount();
77 const listInvitations = yield* GuardDuty.ListInvitations();
78 const listOrganizationAdminAccounts = yield* GuardDuty.ListOrganizationAdminAccounts();
79 const getOrganizationStatistics = yield* GuardDuty.GetOrganizationStatistics();
80
81 const bound = {
82 createSampleFindings,
83 listFindings,
84 getFindings,
85 getFindingsStatistics,
86 archiveFindings,
87 unarchiveFindings,
88 updateFindingsFeedback,
89 listMembers,
90 getAdministratorAccount,
91 getMalwareScanSettings,
92 getUsageStatistics,
93 listCoverage,
94 getRemainingFreeTrialDays,
95 listInvestigations,
96 describeOrganizationConfiguration,
97 getInvitationsCount,
98 listInvitations,
99 listOrganizationAdminAccounts,
100 getOrganizationStatistics,
101 };
102
103 return {
104 fetch: Effect.gen(function* () {
105 const request = yield* HttpServerRequest;
106 const url = new URL(request.originalUrl);
107 const pathname = url.pathname;
108
109 if (request.method === "GET" && pathname === "/bindings") {
110 return yield* HttpServerResponse.json({
111 bound: Object.keys(bound),
112 });
113 }
114
115 // Generates sample findings on our own detector — the documented
116 // way to exercise a findings pipeline without staging a threat.
117 if (request.method === "POST" && pathname === "/sample") {
118 yield* createSampleFindings({
119 FindingTypes: ["Recon:EC2/PortProbeUnprotectedPort"],
120 });
121 return yield* HttpServerResponse.json({ ok: true });
122 }
123
124 if (request.method === "GET" && pathname === "/findings") {
125 const { FindingIds } = yield* listFindings();
126 return yield* HttpServerResponse.json({
127 count: (FindingIds ?? []).length,
128 ids: (FindingIds ?? []).slice(0, 5),
129 });
130 }
131
132 if (request.method === "GET" && pathname === "/finding-detail") {
133 const id = url.searchParams.get("id");
134 if (!id) {
135 return yield* HttpServerResponse.json({ error: "missing id" }, { status: 400 });
136 }
137 const { Findings } = yield* getFindings({ FindingIds: [id] });
138 return yield* HttpServerResponse.json({
139 count: (Findings ?? []).length,
140 type: Findings?.[0]?.Type,
141 archived: Findings?.[0]?.Service?.Archived ?? false,
142 });
143 }
144
145 if (request.method === "GET" && pathname === "/stats") {
146 const { FindingStatistics } = yield* getFindingsStatistics({
147 FindingStatisticTypes: ["COUNT_BY_SEVERITY"],
148 });
149 return yield* HttpServerResponse.json({
150 severities: Object.keys(FindingStatistics?.CountBySeverity ?? {}),
151 });
152 }
153
154 // Archive whatever findings currently exist (sample findings from
155 // /sample) — a real write against our own detector.
156 if (request.method === "POST" && pathname === "/archive") {
157 const { FindingIds } = yield* listFindings();
158 if ((FindingIds ?? []).length === 0) {
159 return yield* HttpServerResponse.json({ archived: 0 });
160 }
161 const result = yield* errorTagged(
162 archiveFindings({ FindingIds: FindingIds! }).pipe(
163 Effect.map(() => ({ archived: FindingIds!.length })),
164 ),
165 );
166 return yield* HttpServerResponse.json(result);
167 }
168
169 if (request.method === "GET" && pathname === "/members") {
170 const { Members } = yield* listMembers();
171 return yield* HttpServerResponse.json({
172 count: (Members ?? []).length,
173 });
174 }
175
176 // A standalone account has no administrator — GuardDuty answers
177 // with an empty document or a typed BadRequestException.
178 if (request.method === "GET" && pathname === "/admin") {
179 const result = yield* errorTagged(
180 getAdministratorAccount().pipe(
181 Effect.map((r) => ({
182 administrator: r.Administrator?.AccountId ?? null,
183 })),
184 ),
185 );
186 return yield* HttpServerResponse.json(result);
187 }
188
189 if (request.method === "GET" && pathname === "/malware-settings") {
190 const result = yield* errorTagged(
191 getMalwareScanSettings().pipe(
192 Effect.map((r) => ({
193 ebsSnapshotPreservation: r.EbsSnapshotPreservation ?? null,
194 })),
195 ),
196 );
197 return yield* HttpServerResponse.json(result);
198 }
199
200 if (request.method === "GET" && pathname === "/usage") {
201 const { UsageStatistics } = yield* getUsageStatistics({
202 UsageStatisticType: "SUM_BY_DATA_SOURCE",
203 UsageCriteria: { DataSources: ["FLOW_LOGS"] },
204 });
205 return yield* HttpServerResponse.json({
206 dataSources: (UsageStatistics?.SumByDataSource ?? []).length,
207 });
208 }
209
210 if (request.method === "GET" && pathname === "/coverage") {
211 const { Resources } = yield* listCoverage();
212 return yield* HttpServerResponse.json({
213 resources: (Resources ?? []).length,
214 });
215 }
216
217 if (request.method === "GET" && pathname === "/free-trial") {
218 // The smithy model requires AccountIds — the caller passes its
219 // own account id.
220 const account = url.searchParams.get("account");
221 if (!account) {
222 return yield* HttpServerResponse.json({ error: "missing account" }, { status: 400 });
223 }
224 const { Accounts } = yield* getRemainingFreeTrialDays({
225 AccountIds: [account],
226 });
227 return yield* HttpServerResponse.json({
228 accounts: (Accounts ?? []).length,
229 });
230 }
231
232 if (request.method === "GET" && pathname === "/investigations") {
233 const result = yield* errorTagged(
234 listInvestigations().pipe(
235 Effect.map((r) => ({
236 count: (r.Investigations ?? []).length,
237 })),
238 ),
239 );
240 return yield* HttpServerResponse.json(result);
241 }
242
243 // Org administration: this account is a standalone (non-delegated)
244 // account, so GuardDuty answers with a typed error — asserting the
245 // tag proves the binding + IAM wiring end-to-end.
246 if (request.method === "GET" && pathname === "/org-config") {
247 const result = yield* errorTagged(
248 describeOrganizationConfiguration().pipe(
249 Effect.map((r) => ({ autoEnable: r.AutoEnable ?? false })),
250 ),
251 );
252 return yield* HttpServerResponse.json(result);
253 }
254
255 if (request.method === "GET" && pathname === "/org-admins") {
256 const result = yield* errorTagged(
257 listOrganizationAdminAccounts().pipe(
258 Effect.map((r) => ({
259 admins: (r.AdminAccounts ?? []).length,
260 })),
261 ),
262 );
263 return yield* HttpServerResponse.json(result);
264 }
265
266 if (request.method === "GET" && pathname === "/org-stats") {
267 const result = yield* errorTagged(
268 getOrganizationStatistics().pipe(
269 Effect.map((r) => ({
270 activeAccounts:
271 r.OrganizationDetails?.OrganizationStatistics?.ActiveAccountsCount ?? 0,
272 })),
273 ),
274 );
275 return yield* HttpServerResponse.json(result);
276 }
277
278 // Account-level invitation reads.
279 if (request.method === "GET" && pathname === "/invitations-count") {
280 const { InvitationsCount } = yield* getInvitationsCount();
281 return yield* HttpServerResponse.json({
282 count: InvitationsCount ?? 0,
283 });
284 }
285
286 if (request.method === "GET" && pathname === "/invitations") {
287 const { Invitations } = yield* listInvitations();
288 return yield* HttpServerResponse.json({
289 count: (Invitations ?? []).length,
290 });
291 }
292
293 return yield* HttpServerResponse.json(
294 { error: "Not found", method: request.method, pathname },
295 { status: 404 },
296 );
297 }).pipe(Effect.orDie),
298 };
299 }).pipe(
300 Effect.provide(
301 Layer.mergeAll(
302 GuardDuty.ArchiveFindingsHttp,
303 GuardDuty.CreateSampleFindingsHttp,
304 GuardDuty.DescribeOrganizationConfigurationHttp,
305 GuardDuty.GetAdministratorAccountHttp,
306 GuardDuty.GetFindingsHttp,
307 GuardDuty.GetFindingsStatisticsHttp,
308 GuardDuty.GetInvitationsCountHttp,
309 GuardDuty.GetMalwareScanSettingsHttp,
310 GuardDuty.GetOrganizationStatisticsHttp,
311 GuardDuty.GetRemainingFreeTrialDaysHttp,
312 GuardDuty.GetUsageStatisticsHttp,
313 GuardDuty.ListCoverageHttp,
314 GuardDuty.ListFindingsHttp,
315 GuardDuty.ListInvestigationsHttp,
316 GuardDuty.ListInvitationsHttp,
317 GuardDuty.ListMembersHttp,
318 GuardDuty.ListOrganizationAdminAccountsHttp,
319 GuardDuty.UnarchiveFindingsHttp,
320 GuardDuty.UpdateFindingsFeedbackHttp,
321 ),
322 ),
323 ),
324 );