1import * as AWS from "@/AWS";
2import * as Core from "@/Test/Core";
3import * as Test from "@/Test/Alchemy";
4import * as guardduty from "@distilled.cloud/aws/guardduty";
5import { describe, expect } from "alchemy-test";
6import * as Data from "effect/Data";
7import * as Effect from "effect/Effect";
8import * as Schedule from "effect/Schedule";
9import * as HttpClient from "effect/http/HttpClient";
10import * as HttpClientRequest from "effect/http/HttpClientRequest";
11import GuardDutyTestFunctionLive, { GuardDutyTestFunction } from "./handler";
12import { makeGuardDutyTestLease } from "./TestLease.ts";
13
14const testOptions = { providers: AWS.providers() };
15const { test, beforeAll, afterAll } = Test.make(testOptions);
16const sharedStack = Core.scratchStack(testOptions, "GuardDutyBindings");
17const testLease = makeGuardDutyTestLease();
18
19beforeAll(testLease.acquire, { timeout: 240_000 });
20afterAll(testLease.release);
21
22// Lambda function URL cold-start (DNS, IAM propagation, init) can take well
23// over 60s on a fresh deploy.
24const readinessPolicy = Schedule.max([
25 Schedule.fixed("2 seconds"),
26 Schedule.recurs(75),
27]);
28
29let baseUrl: string;
30let accountId: string;
31// The GuardDuty detector is an account/region singleton. If the account
32// already runs a detector this suite did not create, deploying the fixture
33// would adopt (and later DELETE) it — so every test degrades to a logged
34// no-op instead (capture-and-restore safety, mirroring Detector.test.ts).
35let foreignDetectorId: string | undefined;
36
37class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
38 readonly status: number;
39 readonly body: string;
40}> {}
41
42// The shared Lambda fixture occasionally answers a transient 5xx under load
43// (cold re-init, IAM propagation on the freshly attached policy that the
44// handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine
45// 4xx/assertion failure surfaces immediately.
46const send = (request: HttpClientRequest.HttpClientRequest) =>
47 HttpClient.execute(request).pipe(
48 Effect.flatMap((response) =>
49 response.status >= 500
50 ? response.text.pipe(
51 Effect.flatMap((body) =>
52 Effect.fail(
53 new TransientUpstream({ status: response.status, body }),
54 ),
55 ),
56 )
57 : Effect.succeed(response),
58 ),
59 Effect.retry({
60 while: (e) => e._tag === "TransientUpstream",
61 schedule: Schedule.max([
62 Schedule.exponential("500 millis"),
63 Schedule.recurs(6),
64 ]),
65 }),
66 );
67
68const getJson = (path: string) =>
69 send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe(
70 Effect.flatMap((r) => r.json),
71 );
72
73const postJson = (path: string) =>
74 send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe(
75 Effect.flatMap((r) => r.json),
76 );
77
78// beforeAll/afterAll hooks run outside `test.provider`'s layer, so raw
79// distilled calls need the provider layer (credentials, region) supplied
80// explicitly.
81const aws = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
82 Core.withProviders(effect, testOptions, sharedStack.name);
83
84const skipForeign = () =>
85 foreignDetectorId
86 ? Effect.logInfo(
87 `GuardDuty detector ${foreignDetectorId} already exists and is not ours — skipping`,
88 ).pipe(Effect.as(true))
89 : Effect.succeed(false);
90
91describe.sequential(
92 "GuardDuty Bindings",
93 {
94 tags: [
95 "provider:aws",
96 "provider:aws:guardduty",
97 "provider:aws:lambda",
98 "live",
99 ],
100 },
101 () => {
102 beforeAll(
103 Effect.gen(function* () {
104 // Never take over a detector this fixture did not create.
105 const preexisting = (yield* aws(guardduty.listDetectors({})))
106 .DetectorIds?.[0];
107 if (preexisting) {
108 const detector = yield* aws(
109 guardduty.getDetector({ DetectorId: preexisting }),
110 );
111 if (detector.Tags?.["fixture"] !== "guardduty-bindings") {
112 foreignDetectorId = preexisting;
113 yield* Effect.logInfo(
114 `GuardDuty test setup: foreign detector ${preexisting} present — suite degrades to no-op`,
115 );
116 return;
117 }
118 }
119
120 yield* Effect.logInfo(
121 "GuardDuty test setup: destroying previous resources",
122 );
123 yield* sharedStack.destroy();
124
125 yield* Effect.logInfo("GuardDuty test setup: deploying fixture");
126 const attrs = yield* sharedStack.deploy(
127 Effect.gen(function* () {
128 return yield* GuardDutyTestFunction;
129 }).pipe(Effect.provide(GuardDutyTestFunctionLive)),
130 );
131
132 expect(attrs.functionUrl).toBeTruthy();
133 baseUrl = attrs.functionUrl!.replace(/\/+$/, "");
134 accountId = attrs.roleArn.split(":")[4]!;
135
136 const readinessUrl = `${baseUrl}/bindings`;
137 yield* Effect.logInfo(
138 `GuardDuty test setup: probing readiness at ${readinessUrl}`,
139 );
140 yield* HttpClient.get(readinessUrl).pipe(
141 Effect.flatMap((response) =>
142 response.status === 200
143 ? Effect.succeed(response)
144 : Effect.fail(
145 new Error(`Function not ready: ${response.status}`),
146 ),
147 ),
148 Effect.tapError((error) =>
149 Effect.logWarning(
150 `GuardDuty test setup: fixture not ready yet (${String(error)})`,
151 ),
152 ),
153 Effect.retry({ schedule: readinessPolicy }),
154 );
155 }),
156 { timeout: 240_000 },
157 );
158
159 afterAll(
160 Effect.gen(function* () {
161 if (foreignDetectorId) return;
162 yield* sharedStack.destroy();
163 }),
164 { timeout: 120_000 },
165 );
166
167 describe("binding registration", () => {
168 test.provider("all 19 capabilities initialize in the runtime", (_stack) =>
169 Effect.gen(function* () {
170 if (yield* skipForeign()) return;
171 const response = (yield* getJson("/bindings")) as { bound: string[] };
172 expect(response.bound).toHaveLength(19);
173 expect(response.bound).toContain("createSampleFindings");
174 expect(response.bound).toContain("listFindings");
175 expect(response.bound).toContain("getInvitationsCount");
176 }),
177 );
178 });
179
180 describe("CreateSampleFindings + ListFindings + GetFindings + ArchiveFindings", () => {
181 test.provider(
182 "sample finding round-trips through the triage loop (injected detector id)",
183 (_stack) =>
184 Effect.gen(function* () {
185 if (yield* skipForeign()) return;
186
187 // Generate a sample finding on our own detector.
188 const sample = (yield* postJson("/sample")) as { ok: boolean };
189 expect(sample.ok).toBe(true);
190
191 // Sample findings surface asynchronously — poll bounded.
192 const findings = (yield* getJson("/findings").pipe(
193 Effect.repeat({
194 schedule: Schedule.spaced("3 seconds"),
195 until: (r): boolean => (r as { count: number }).count > 0,
196 times: 20,
197 }),
198 )) as { count: number; ids: string[] };
199 expect(findings.count).toBeGreaterThan(0);
200
201 // Hydrate the full finding document.
202 const detail = (yield* getJson(
203 `/finding-detail?id=${encodeURIComponent(findings.ids[0]!)}`,
204 )) as { count: number; type?: string; archived: boolean };
205 expect(detail.count).toBe(1);
206 expect(detail.type).toBe("Recon:EC2/PortProbeUnprotectedPort");
207
208 // Statistics can lag behind the finding itself.
209 const stats = (yield* getJson("/stats").pipe(
210 Effect.repeat({
211 schedule: Schedule.spaced("3 seconds"),
212 until: (r): boolean =>
213 (r as { severities: string[] }).severities.length > 0,
214 times: 10,
215 }),
216 )) as { severities: string[] };
217 expect(stats.severities.length).toBeGreaterThan(0);
218
219 // Archive everything we generated — a real write.
220 const archived = (yield* postJson("/archive")) as {
221 archived: number;
222 };
223 expect(archived.archived).toBeGreaterThan(0);
224 }),
225 { timeout: 120_000 },
226 );
227 });
228
229 describe("ListMembers", () => {
230 test.provider("a standalone detector has no members", (_stack) =>
231 Effect.gen(function* () {
232 if (yield* skipForeign()) return;
233 const response = (yield* getJson("/members")) as { count: number };
234 expect(response.count).toBe(0);
235 }),
236 );
237 });
238
239 describe("GetAdministratorAccount", () => {
240 test.provider(
241 "a standalone account has no administrator (typed outcome either way)",
242 (_stack) =>
243 Effect.gen(function* () {
244 if (yield* skipForeign()) return;
245 const response = (yield* getJson("/admin")) as {
246 administrator?: string | null;
247 errorTag?: string;
248 };
249 if (response.errorTag) {
250 // GuardDuty rejects the call outright for a standalone
251 // (non-member) account.
252 expect([
253 "BadRequestException",
254 "AccessDeniedException",
255 ]).toContain(response.errorTag);
256 } else {
257 expect(response.administrator ?? null).toBeNull();
258 }
259 }),
260 );
261 });
262
263 describe("GetMalwareScanSettings", () => {
264 test.provider("reads the detector's malware scan settings", (_stack) =>
265 Effect.gen(function* () {
266 if (yield* skipForeign()) return;
267 const response = (yield* getJson("/malware-settings")) as {
268 ebsSnapshotPreservation?: string | null;
269 errorTag?: string;
270 };
271 if (response.errorTag) {
272 // Malware Protection may not be enabled on a fresh detector.
273 expect(["BadRequestException"]).toContain(response.errorTag);
274 } else {
275 expect(response).toHaveProperty("ebsSnapshotPreservation");
276 }
277 }),
278 );
279 });
280
281 describe("GetUsageStatistics", () => {
282 test.provider("reports usage grouped by data source", (_stack) =>
283 Effect.gen(function* () {
284 if (yield* skipForeign()) return;
285 const response = (yield* getJson("/usage")) as {
286 dataSources: number;
287 };
288 expect(response.dataSources).toBeGreaterThanOrEqual(0);
289 }),
290 );
291 });
292
293 describe("ListCoverage + GetRemainingFreeTrialDays", () => {
294 test.provider("reads coverage and free-trial state", (_stack) =>
295 Effect.gen(function* () {
296 if (yield* skipForeign()) return;
297 const coverage = (yield* getJson("/coverage")) as {
298 resources: number;
299 };
300 expect(coverage.resources).toBeGreaterThanOrEqual(0);
301
302 const freeTrial = (yield* getJson(
303 `/free-trial?account=${accountId}`,
304 )) as {
305 accounts: number;
306 };
307 expect(freeTrial.accounts).toBeGreaterThanOrEqual(0);
308 }),
309 );
310 });
311
312 describe("ListInvestigations", () => {
313 test.provider("a fresh detector has no investigations", (_stack) =>
314 Effect.gen(function* () {
315 if (yield* skipForeign()) return;
316 const response = (yield* getJson("/investigations")) as {
317 count?: number;
318 errorTag?: string;
319 };
320 if (response.errorTag) {
321 // Extended Threat Detection may be unavailable for the account.
322 expect(["BadRequestException", "AccessDeniedException"]).toContain(
323 response.errorTag,
324 );
325 } else {
326 expect(response.count).toBe(0);
327 }
328 }),
329 );
330 });
331
332 describe("DescribeOrganizationConfiguration", () => {
333 test.provider(
334 "answers (or rejects with a typed error for a non-delegated account)",
335 (_stack) =>
336 Effect.gen(function* () {
337 if (yield* skipForeign()) return;
338 const response = (yield* getJson("/org-config")) as {
339 autoEnable?: boolean;
340 errorTag?: string;
341 };
342 if (response.errorTag) {
343 expect([
344 "BadRequestException",
345 "AccessDeniedException",
346 ]).toContain(response.errorTag);
347 } else {
348 expect(typeof response.autoEnable).toBe("boolean");
349 }
350 }),
351 );
352 });
353
354 describe("ListOrganizationAdminAccounts + GetOrganizationStatistics", () => {
355 test.provider(
356 "answers (or rejects with a typed error outside the management account)",
357 (_stack) =>
358 Effect.gen(function* () {
359 if (yield* skipForeign()) return;
360 const admins = (yield* getJson("/org-admins")) as {
361 admins?: number;
362 errorTag?: string;
363 };
364 if (admins.errorTag) {
365 expect([
366 "BadRequestException",
367 "AccessDeniedException",
368 ]).toContain(admins.errorTag);
369 } else {
370 expect(admins.admins).toBeGreaterThanOrEqual(0);
371 }
372
373 const stats = (yield* getJson("/org-stats")) as {
374 activeAccounts?: number;
375 errorTag?: string;
376 };
377 if (stats.errorTag) {
378 expect([
379 "BadRequestException",
380 "AccessDeniedException",
381 ]).toContain(stats.errorTag);
382 } else {
383 expect(stats.activeAccounts).toBeGreaterThanOrEqual(0);
384 }
385 }),
386 );
387 });
388
389 describe("GetInvitationsCount + ListInvitations", () => {
390 test.provider("reads this account's invitation state", (_stack) =>
391 Effect.gen(function* () {
392 if (yield* skipForeign()) return;
393 const count = (yield* getJson("/invitations-count")) as {
394 count: number;
395 };
396 expect(count.count).toBeGreaterThanOrEqual(0);
397
398 const invitations = (yield* getJson("/invitations")) as {
399 count: number;
400 };
401 expect(invitations.count).toBeGreaterThanOrEqual(0);
402 }),
403 );
404 });
405 },
406);