| 1 | import * as AWS from "@/AWS"; |
| 2 | import * as Core from "@/Test/Core"; |
| 3 | import * as Test from "@/Test/Alchemy"; |
| 4 | import * as macie2 from "@distilled.cloud/aws/macie2"; |
| 5 | import { describe, expect } from "alchemy-test"; |
| 6 | import * as Data from "effect/Data"; |
| 7 | import * as Effect from "effect/Effect"; |
| 8 | import * as Schedule from "effect/Schedule"; |
| 9 | import * as HttpClient from "effect/http/HttpClient"; |
| 10 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 11 | import Macie2TestFunctionLive, { Macie2TestFunction } from "./handler"; |
| 12 | import { makeMacie2TestLease } from "./TestLease.ts"; |
| 13 | |
| 14 | const testOptions = { providers: AWS.providers() }; |
| 15 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 16 | const sharedStack = Core.scratchStack(testOptions, "Macie2Bindings"); |
| 17 | const testLease = makeMacie2TestLease(); |
| 18 | |
| 19 | // This budget covers waiting behind the other Macie files, not an AWS API |
| 20 | // operation. Bindings can legitimately hold the singleton lease for several |
| 21 | // minutes under a full parallel sweep (setup + sample-finding poll + cleanup). |
| 22 | beforeAll(testLease.acquire, { timeout: 3_600_000 }); |
| 23 | afterAll(testLease.release); |
| 24 | |
| 25 | // Lambda function URL cold-start (DNS, IAM propagation, init) can take well |
| 26 | // over 60s on a fresh deploy. |
| 27 | const readinessPolicy = Schedule.max([ |
| 28 | Schedule.fixed("2 seconds"), |
| 29 | Schedule.recurs(75), |
| 30 | ]); |
| 31 | |
| 32 | let baseUrl: string; |
| 33 | // The Macie session is an account/region singleton with no tags, so ownership |
| 34 | // cannot be verified from the cloud. If the account already runs a session |
| 35 | // this suite did not create, deploying the fixture would adopt (and later |
| 36 | // DISABLE) it — so every test degrades to a logged no-op instead |
| 37 | // (capture-and-restore safety, mirroring Session.test.ts). |
| 38 | let foreignSession = false; |
| 39 | |
| 40 | class TransientUpstream extends Data.TaggedError("TransientUpstream")<{ |
| 41 | readonly status: number; |
| 42 | readonly body: string; |
| 43 | }> {} |
| 44 | |
| 45 | // The shared Lambda fixture occasionally answers a transient 5xx under load |
| 46 | // (cold re-init, IAM propagation on the freshly attached policy that the |
| 47 | // handler's `Effect.orDie` surfaces as a 500). Retry only 5xx; a genuine |
| 48 | // 4xx/assertion failure surfaces immediately. |
| 49 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 50 | HttpClient.execute(request).pipe( |
| 51 | Effect.flatMap((response) => |
| 52 | response.status >= 500 |
| 53 | ? response.text.pipe( |
| 54 | Effect.flatMap((body) => |
| 55 | Effect.fail( |
| 56 | new TransientUpstream({ status: response.status, body }), |
| 57 | ), |
| 58 | ), |
| 59 | ) |
| 60 | : Effect.succeed(response), |
| 61 | ), |
| 62 | Effect.retry({ |
| 63 | while: (e) => e._tag === "TransientUpstream", |
| 64 | schedule: Schedule.max([ |
| 65 | Schedule.exponential("500 millis"), |
| 66 | Schedule.recurs(6), |
| 67 | ]), |
| 68 | }), |
| 69 | ); |
| 70 | |
| 71 | const getJson = (path: string) => |
| 72 | send(HttpClientRequest.get(`${baseUrl}${path}`)).pipe( |
| 73 | Effect.flatMap((r) => r.json), |
| 74 | ); |
| 75 | |
| 76 | const postJson = (path: string) => |
| 77 | send(HttpClientRequest.post(`${baseUrl}${path}`)).pipe( |
| 78 | Effect.flatMap((r) => r.json), |
| 79 | ); |
| 80 | |
| 81 | // beforeAll/afterAll hooks run outside `test.provider`'s layer, so raw |
| 82 | // distilled calls need the provider layer (credentials, region) supplied |
| 83 | // explicitly. |
| 84 | const aws = <A, E, R>(effect: Effect.Effect<A, E, R>) => |
| 85 | Core.withProviders(effect, testOptions, sharedStack.name); |
| 86 | |
| 87 | const getSession = macie2.getMacieSession({}).pipe( |
| 88 | Effect.map((s) => s as macie2.GetMacieSessionResponse | undefined), |
| 89 | Effect.catchTag("AccessDeniedException", () => Effect.succeed(undefined)), |
| 90 | Effect.catchTag("ResourceNotFoundException", () => Effect.succeed(undefined)), |
| 91 | ); |
| 92 | |
| 93 | const skipForeign = () => |
| 94 | foreignSession |
| 95 | ? Effect.logInfo( |
| 96 | "Macie is already enabled by someone else — skipping", |
| 97 | ).pipe(Effect.as(true)) |
| 98 | : Effect.succeed(false); |
| 99 | |
| 100 | describe.sequential( |
| 101 | "Macie2 Bindings", |
| 102 | { |
| 103 | tags: [ |
| 104 | "provider:aws", |
| 105 | "provider:aws:lambda", |
| 106 | "provider:aws:macie2", |
| 107 | "live", |
| 108 | ], |
| 109 | }, |
| 110 | () => { |
| 111 | beforeAll( |
| 112 | Effect.gen(function* () { |
| 113 | // Destroy OUR previous resources first — a crashed prior run leaves the |
| 114 | // fixture's own session enabled, which must not be mistaken for a |
| 115 | // foreign one. Destroying the scratch stack disables Macie only if the |
| 116 | // session is tracked in our state. |
| 117 | yield* Effect.logInfo( |
| 118 | "Macie2 test setup: destroying previous resources", |
| 119 | ); |
| 120 | yield* sharedStack.destroy(); |
| 121 | |
| 122 | // Never take over a Macie session this fixture did not create — any |
| 123 | // session that remains after our own destroy is foreign. |
| 124 | const preexisting = yield* aws(getSession); |
| 125 | if (preexisting) { |
| 126 | foreignSession = true; |
| 127 | yield* Effect.logInfo( |
| 128 | "Macie2 test setup: Macie already enabled — suite degrades to no-op", |
| 129 | ); |
| 130 | return; |
| 131 | } |
| 132 | |
| 133 | yield* Effect.logInfo("Macie2 test setup: deploying fixture"); |
| 134 | const attrs = yield* sharedStack.deploy( |
| 135 | Effect.gen(function* () { |
| 136 | return yield* Macie2TestFunction; |
| 137 | }).pipe(Effect.provide(Macie2TestFunctionLive)), |
| 138 | ); |
| 139 | |
| 140 | expect(attrs.functionUrl).toBeTruthy(); |
| 141 | baseUrl = attrs.functionUrl!.replace(/\/+$/, ""); |
| 142 | |
| 143 | const readinessUrl = `${baseUrl}/bindings`; |
| 144 | yield* Effect.logInfo( |
| 145 | `Macie2 test setup: probing readiness at ${readinessUrl}`, |
| 146 | ); |
| 147 | yield* HttpClient.get(readinessUrl).pipe( |
| 148 | Effect.flatMap((response) => |
| 149 | response.status === 200 |
| 150 | ? Effect.succeed(response) |
| 151 | : Effect.fail( |
| 152 | new Error(`Function not ready: ${response.status}`), |
| 153 | ), |
| 154 | ), |
| 155 | Effect.tapError((error) => |
| 156 | Effect.logWarning( |
| 157 | `Macie2 test setup: fixture not ready yet (${String(error)})`, |
| 158 | ), |
| 159 | ), |
| 160 | Effect.retry({ schedule: readinessPolicy }), |
| 161 | ); |
| 162 | }), |
| 163 | { timeout: 300_000 }, |
| 164 | ); |
| 165 | |
| 166 | afterAll( |
| 167 | Effect.gen(function* () { |
| 168 | if (foreignSession) return; |
| 169 | yield* sharedStack.destroy(); |
| 170 | // Destroying the stack disables Macie for the account — zero orphans. |
| 171 | const after = yield* aws(getSession); |
| 172 | expect(after).toBeUndefined(); |
| 173 | }), |
| 174 | { timeout: 180_000 }, |
| 175 | ); |
| 176 | |
| 177 | describe("binding registration", () => { |
| 178 | test.provider("all 22 capabilities initialize in the runtime", (_stack) => |
| 179 | Effect.gen(function* () { |
| 180 | if (yield* skipForeign()) return; |
| 181 | const response = (yield* getJson("/bindings")) as { bound: string[] }; |
| 182 | expect(response.bound).toHaveLength(22); |
| 183 | expect(response.bound).toContain("createSampleFindings"); |
| 184 | expect(response.bound).toContain("listFindings"); |
| 185 | expect(response.bound).toContain("testCustomDataIdentifier"); |
| 186 | }), |
| 187 | ); |
| 188 | }); |
| 189 | |
| 190 | describe("TestCustomDataIdentifier", () => { |
| 191 | test.provider( |
| 192 | "a detection regex round-trips with match counts", |
| 193 | (_stack) => |
| 194 | Effect.gen(function* () { |
| 195 | if (yield* skipForeign()) return; |
| 196 | const response = (yield* postJson("/test-identifier")) as { |
| 197 | matchCount: number; |
| 198 | }; |
| 199 | expect(response.matchCount).toBe(2); |
| 200 | }), |
| 201 | ); |
| 202 | }); |
| 203 | |
| 204 | describe("CreateSampleFindings + ListFindings + GetFindings + GetFindingStatistics", () => { |
| 205 | test.provider( |
| 206 | "sample findings flow through the triage loop", |
| 207 | (_stack) => |
| 208 | Effect.gen(function* () { |
| 209 | if (yield* skipForeign()) return; |
| 210 | |
| 211 | // Generate sample findings. |
| 212 | const sample = (yield* postJson("/sample")) as { ok: boolean }; |
| 213 | expect(sample.ok).toBe(true); |
| 214 | |
| 215 | // Sample findings surface asynchronously (documented up to ~5 |
| 216 | // minutes) — poll bounded to ~60s; the writes above already proved |
| 217 | // the binding + IAM wiring, so a slow surface is not a failure. |
| 218 | const findings = (yield* getJson("/findings").pipe( |
| 219 | Effect.repeat({ |
| 220 | schedule: Schedule.spaced("3 seconds"), |
| 221 | until: (r): boolean => (r as { count: number }).count > 0, |
| 222 | times: 20, |
| 223 | }), |
| 224 | )) as { count: number; ids: string[] }; |
| 225 | |
| 226 | if (findings.count > 0) { |
| 227 | // Hydrate the full finding document. |
| 228 | const detail = (yield* getJson( |
| 229 | `/finding-detail?id=${encodeURIComponent(findings.ids[0]!)}`, |
| 230 | )) as { count: number; type?: string; sample: boolean }; |
| 231 | expect(detail.count).toBe(1); |
| 232 | expect(detail.sample).toBe(true); |
| 233 | } else { |
| 234 | yield* Effect.logWarning( |
| 235 | "Macie sample findings did not surface within the bounded poll — continuing (writes succeeded)", |
| 236 | ); |
| 237 | } |
| 238 | |
| 239 | // Statistics grouped by severity answer either way. |
| 240 | const stats = (yield* getJson("/finding-stats")) as { |
| 241 | groups: number; |
| 242 | }; |
| 243 | expect(stats.groups).toBeGreaterThanOrEqual(0); |
| 244 | }), |
| 245 | { timeout: 150_000 }, |
| 246 | ); |
| 247 | }); |
| 248 | |
| 249 | describe("GetBucketStatistics + SearchResources", () => { |
| 250 | test.provider("reads Macie's S3 inventory", (_stack) => |
| 251 | Effect.gen(function* () { |
| 252 | if (yield* skipForeign()) return; |
| 253 | const buckets = (yield* getJson("/buckets")) as { |
| 254 | bucketCount: number; |
| 255 | }; |
| 256 | expect(buckets.bucketCount).toBeGreaterThanOrEqual(0); |
| 257 | |
| 258 | const search = (yield* getJson("/search")) as { matches: number }; |
| 259 | expect(search.matches).toBeGreaterThanOrEqual(0); |
| 260 | }), |
| 261 | ); |
| 262 | }); |
| 263 | |
| 264 | describe("ListManagedDataIdentifiers", () => { |
| 265 | test.provider("lists Macie's managed data identifiers", (_stack) => |
| 266 | Effect.gen(function* () { |
| 267 | if (yield* skipForeign()) return; |
| 268 | const response = (yield* getJson("/managed-identifiers")) as { |
| 269 | count: number; |
| 270 | }; |
| 271 | expect(response.count).toBeGreaterThan(0); |
| 272 | }), |
| 273 | ); |
| 274 | }); |
| 275 | |
| 276 | describe("ListAllowLists + ListFindingsFilters + ListClassificationJobs", () => { |
| 277 | test.provider("a fresh session has no user configuration", (_stack) => |
| 278 | Effect.gen(function* () { |
| 279 | if (yield* skipForeign()) return; |
| 280 | const allowLists = (yield* getJson("/allow-lists")) as { |
| 281 | count: number; |
| 282 | }; |
| 283 | expect(allowLists.count).toBe(0); |
| 284 | |
| 285 | const filters = (yield* getJson("/findings-filters")) as { |
| 286 | count: number; |
| 287 | }; |
| 288 | expect(filters.count).toBe(0); |
| 289 | |
| 290 | const jobs = (yield* getJson("/jobs")) as { count: number }; |
| 291 | expect(jobs.count).toBeGreaterThanOrEqual(0); |
| 292 | }), |
| 293 | ); |
| 294 | }); |
| 295 | |
| 296 | describe("GetClassificationExportConfiguration + GetUsageTotals", () => { |
| 297 | test.provider("reads export configuration and usage totals", (_stack) => |
| 298 | Effect.gen(function* () { |
| 299 | if (yield* skipForeign()) return; |
| 300 | const exportConfig = (yield* getJson("/export-config")) as { |
| 301 | configured: boolean; |
| 302 | }; |
| 303 | expect(exportConfig.configured).toBe(false); |
| 304 | |
| 305 | const usage = (yield* getJson("/usage")) as { totals: number }; |
| 306 | expect(usage.totals).toBeGreaterThanOrEqual(0); |
| 307 | }), |
| 308 | ); |
| 309 | }); |
| 310 | |
| 311 | describe("GetAutomatedDiscoveryConfiguration + ListClassificationScopes + GetRevealConfiguration", () => { |
| 312 | test.provider("reads the discovery and reveal configuration", (_stack) => |
| 313 | Effect.gen(function* () { |
| 314 | if (yield* skipForeign()) return; |
| 315 | const discovery = (yield* getJson("/auto-discovery")) as { |
| 316 | status: string | null; |
| 317 | }; |
| 318 | expect(discovery.status).not.toBeUndefined(); |
| 319 | |
| 320 | const scopes = (yield* getJson("/scopes")) as { count: number }; |
| 321 | expect(scopes.count).toBeGreaterThanOrEqual(0); |
| 322 | |
| 323 | const reveal = (yield* getJson("/reveal")) as { |
| 324 | status?: string | null; |
| 325 | errorTag?: string; |
| 326 | }; |
| 327 | if (reveal.errorTag) { |
| 328 | // A fresh session rejects the read until sample retrieval is |
| 329 | // configured — the typed tag proves the binding + IAM wiring. |
| 330 | expect(reveal.errorTag).toBe("AccessDeniedException"); |
| 331 | } else { |
| 332 | expect(["ENABLED", "DISABLED", null]).toContain(reveal.status); |
| 333 | } |
| 334 | }), |
| 335 | ); |
| 336 | }); |
| 337 | |
| 338 | describe("GetAdministratorAccount", () => { |
| 339 | test.provider( |
| 340 | "a standalone account has no administrator (typed outcome either way)", |
| 341 | (_stack) => |
| 342 | Effect.gen(function* () { |
| 343 | if (yield* skipForeign()) return; |
| 344 | const response = (yield* getJson("/admin")) as { |
| 345 | administrator?: string | null; |
| 346 | errorTag?: string; |
| 347 | }; |
| 348 | if (response.errorTag) { |
| 349 | expect([ |
| 350 | "ResourceNotFoundException", |
| 351 | "AccessDeniedException", |
| 352 | ]).toContain(response.errorTag); |
| 353 | } else { |
| 354 | expect(response.administrator ?? null).toBeNull(); |
| 355 | } |
| 356 | }), |
| 357 | ); |
| 358 | }); |
| 359 | |
| 360 | describe("GetInvitationsCount + ListInvitations + ListMembers", () => { |
| 361 | test.provider("reads this account's membership state", (_stack) => |
| 362 | Effect.gen(function* () { |
| 363 | if (yield* skipForeign()) return; |
| 364 | const count = (yield* getJson("/invitations-count")) as { |
| 365 | count: number; |
| 366 | }; |
| 367 | expect(count.count).toBeGreaterThanOrEqual(0); |
| 368 | |
| 369 | const invitations = (yield* getJson("/invitations")) as { |
| 370 | count: number; |
| 371 | }; |
| 372 | expect(invitations.count).toBeGreaterThanOrEqual(0); |
| 373 | |
| 374 | const members = (yield* getJson("/members")) as { count: number }; |
| 375 | expect(members.count).toBe(0); |
| 376 | }), |
| 377 | ); |
| 378 | }); |
| 379 | |
| 380 | describe("ListOrganizationAdminAccounts + DescribeOrganizationConfiguration", () => { |
| 381 | test.provider( |
| 382 | "answers (or rejects with a typed error outside the management account)", |
| 383 | (_stack) => |
| 384 | Effect.gen(function* () { |
| 385 | if (yield* skipForeign()) return; |
| 386 | const admins = (yield* getJson("/org-admins")) as { |
| 387 | admins?: number; |
| 388 | errorTag?: string; |
| 389 | }; |
| 390 | if (admins.errorTag) { |
| 391 | expect([ |
| 392 | "AccessDeniedException", |
| 393 | "ValidationException", |
| 394 | ]).toContain(admins.errorTag); |
| 395 | } else { |
| 396 | expect(admins.admins).toBeGreaterThanOrEqual(0); |
| 397 | } |
| 398 | |
| 399 | const orgConfig = (yield* getJson("/org-config")) as { |
| 400 | autoEnable?: boolean; |
| 401 | errorTag?: string; |
| 402 | }; |
| 403 | if (orgConfig.errorTag) { |
| 404 | expect([ |
| 405 | "AccessDeniedException", |
| 406 | "ValidationException", |
| 407 | ]).toContain(orgConfig.errorTag); |
| 408 | } else { |
| 409 | expect(typeof orgConfig.autoEnable).toBe("boolean"); |
| 410 | } |
| 411 | }), |
| 412 | ); |
| 413 | }); |
| 414 | }, |
| 415 | ); |