| 1 | import * as AWS from "@/AWS"; |
| 2 | import { Trail } from "@/AWS/CloudTrail"; |
| 3 | import { AWSEnvironment } from "@/AWS/Environment.ts"; |
| 4 | import { Bucket } from "@/AWS/S3/Bucket.ts"; |
| 5 | import * as Core from "@/Test/Core"; |
| 6 | import * as Test from "@/Test/Alchemy"; |
| 7 | import * as s3 from "@distilled.cloud/aws/s3"; |
| 8 | import { describe, expect } from "alchemy-test"; |
| 9 | import * as Data from "effect/Data"; |
| 10 | import * as Effect from "effect/Effect"; |
| 11 | import * as Schedule from "effect/Schedule"; |
| 12 | import * as HttpClient from "effect/http/HttpClient"; |
| 13 | import * as HttpClientRequest from "effect/http/HttpClientRequest"; |
| 14 | import CloudTrailTestFunctionLive, { CloudTrailTestFunction } from "./handler"; |
| 15 | |
| 16 | const testOptions = { providers: AWS.providers() }; |
| 17 | const { test, beforeAll, afterAll } = Test.make(testOptions); |
| 18 | const sharedStack = Core.scratchStack(testOptions, "CloudTrailBindings"); |
| 19 | |
| 20 | // Lambda function URL cold-start (DNS, IAM propagation, init) can take well |
| 21 | // over 60s on a fresh deploy under parallel-suite load. |
| 22 | const readinessPolicy = Schedule.max([ |
| 23 | Schedule.fixed("2 seconds"), |
| 24 | Schedule.recurs(75), |
| 25 | ]); |
| 26 | |
| 27 | let baseUrl: string; |
| 28 | |
| 29 | class TransientUpstream extends Data.TaggedError("TransientUpstream")<{ |
| 30 | readonly status: number; |
| 31 | readonly body: string; |
| 32 | }> {} |
| 33 | |
| 34 | // Retry transient 5xx from the shared Lambda fixture (cold re-init, IAM |
| 35 | // propagation on the freshly attached cloudtrail policy surfaced as a 500 by |
| 36 | // the handler's `Effect.orDie`). Genuine 4xx/assertion failures return |
| 37 | // immediately. |
| 38 | const send = (request: HttpClientRequest.HttpClientRequest) => |
| 39 | HttpClient.execute(request).pipe( |
| 40 | Effect.flatMap((response) => |
| 41 | response.status >= 500 |
| 42 | ? response.text.pipe( |
| 43 | Effect.flatMap((body) => |
| 44 | Effect.fail( |
| 45 | new TransientUpstream({ status: response.status, body }), |
| 46 | ), |
| 47 | ), |
| 48 | ) |
| 49 | : Effect.succeed(response), |
| 50 | ), |
| 51 | Effect.retry({ |
| 52 | while: (e) => e._tag === "TransientUpstream", |
| 53 | schedule: Schedule.max([ |
| 54 | Schedule.exponential("500 millis"), |
| 55 | Schedule.recurs(6), |
| 56 | ]), |
| 57 | }), |
| 58 | ); |
| 59 | |
| 60 | const getJson = (url: string) => |
| 61 | send(HttpClientRequest.get(url)).pipe(Effect.flatMap((r) => r.json)); |
| 62 | |
| 63 | describe.sequential( |
| 64 | "CloudTrail Bindings", |
| 65 | { |
| 66 | tags: [ |
| 67 | "provider:aws", |
| 68 | "provider:aws:cloudtrail", |
| 69 | "provider:aws:lambda", |
| 70 | "provider:aws:s3", |
| 71 | "live", |
| 72 | ], |
| 73 | }, |
| 74 | () => { |
| 75 | beforeAll( |
| 76 | Effect.gen(function* () { |
| 77 | yield* Effect.logInfo( |
| 78 | "CloudTrail test setup: destroying previous resources", |
| 79 | ); |
| 80 | yield* sharedStack.destroy(); |
| 81 | |
| 82 | yield* Effect.logInfo("CloudTrail test setup: deploying fixture"); |
| 83 | // EventBridge only publishes `AWS API Call via CloudTrail` events |
| 84 | // while at least one trail with logging enabled exists in the region |
| 85 | // — deploy one next to the fixture function. The trail ARN is |
| 86 | // deterministic, so the log bucket's policy can reference it before |
| 87 | // the trail exists. |
| 88 | const { accountId, region } = yield* Core.withProviders( |
| 89 | AWSEnvironment.current, |
| 90 | testOptions, |
| 91 | sharedStack.name, |
| 92 | ); |
| 93 | const trailName = "alchemy-test-cloudtrail-bindings"; |
| 94 | const logBucketName = `alchemy-test-cloudtrail-bindings-logs-${accountId}`; |
| 95 | const trailArn = `arn:aws:cloudtrail:${region}:${accountId}:trail/${trailName}`; |
| 96 | const { functionUrl } = yield* sharedStack.deploy( |
| 97 | Effect.gen(function* () { |
| 98 | const logBucket = yield* Bucket("BindingsTrailLogs", { |
| 99 | bucketName: logBucketName, |
| 100 | forceDestroy: true, |
| 101 | policy: [ |
| 102 | { |
| 103 | Effect: "Allow", |
| 104 | Principal: { Service: "cloudtrail.amazonaws.com" }, |
| 105 | Action: ["s3:GetBucketAcl"], |
| 106 | Resource: `arn:aws:s3:::${logBucketName}`, |
| 107 | Condition: { StringEquals: { "aws:SourceArn": trailArn } }, |
| 108 | }, |
| 109 | { |
| 110 | Effect: "Allow", |
| 111 | Principal: { Service: "cloudtrail.amazonaws.com" }, |
| 112 | Action: ["s3:PutObject"], |
| 113 | Resource: `arn:aws:s3:::${logBucketName}/AWSLogs/${accountId}/*`, |
| 114 | Condition: { |
| 115 | StringEquals: { |
| 116 | "s3:x-amz-acl": "bucket-owner-full-control", |
| 117 | "aws:SourceArn": trailArn, |
| 118 | }, |
| 119 | }, |
| 120 | }, |
| 121 | ], |
| 122 | }); |
| 123 | yield* Trail("BindingsTrail", { |
| 124 | trailName, |
| 125 | s3BucketName: logBucket.bucketName, |
| 126 | }); |
| 127 | return yield* CloudTrailTestFunction; |
| 128 | }).pipe(Effect.provide(CloudTrailTestFunctionLive)), |
| 129 | ); |
| 130 | |
| 131 | expect(functionUrl).toBeTruthy(); |
| 132 | baseUrl = functionUrl!.replace(/\/+$/, ""); |
| 133 | const readinessUrl = `${baseUrl}/info`; |
| 134 | |
| 135 | yield* Effect.logInfo( |
| 136 | `CloudTrail test setup: probing readiness at ${readinessUrl}`, |
| 137 | ); |
| 138 | yield* HttpClient.get(readinessUrl).pipe( |
| 139 | Effect.flatMap((response) => |
| 140 | response.status === 200 |
| 141 | ? Effect.succeed(response) |
| 142 | : Effect.fail( |
| 143 | new Error(`Function not ready: ${response.status}`), |
| 144 | ), |
| 145 | ), |
| 146 | Effect.retry({ schedule: readinessPolicy }), |
| 147 | ); |
| 148 | }), |
| 149 | { timeout: 300_000 }, |
| 150 | ); |
| 151 | |
| 152 | afterAll.skipIf(!!process.env.NO_DESTROY)(sharedStack.destroy(), { |
| 153 | timeout: 240_000, |
| 154 | }); |
| 155 | |
| 156 | describe("LookupEvents", () => { |
| 157 | test.provider("reads the 90-day management event history", () => |
| 158 | Effect.gen(function* () { |
| 159 | const body = (yield* getJson(`${baseUrl}/lookup`)) as any; |
| 160 | |
| 161 | // An active test account always has recent management events. |
| 162 | expect(Array.isArray(body.names)).toBe(true); |
| 163 | expect(body.count).toBeGreaterThan(0); |
| 164 | }), |
| 165 | ); |
| 166 | }); |
| 167 | |
| 168 | describe("ListPublicKeys", () => { |
| 169 | test.provider("lists digest public keys (possibly none)", () => |
| 170 | Effect.gen(function* () { |
| 171 | const body = (yield* getJson(`${baseUrl}/public-keys`)) as any; |
| 172 | |
| 173 | // Keys only exist while a log-file-validated trail has been |
| 174 | // delivering digests — the call succeeding proves the IAM + binding |
| 175 | // wiring either way. |
| 176 | expect(Array.isArray(body.fingerprints)).toBe(true); |
| 177 | }), |
| 178 | ); |
| 179 | }); |
| 180 | |
| 181 | describe("ListInsightsMetricData", () => { |
| 182 | test.provider("reads an Insights metric series (empty is fine)", () => |
| 183 | Effect.gen(function* () { |
| 184 | const body = (yield* getJson(`${baseUrl}/insights-metric`)) as any; |
| 185 | |
| 186 | // No Insights are enabled in the test account, so the series is |
| 187 | // empty — success proves the wiring; a rejection must be TYPED. |
| 188 | if (body.errorTag !== undefined) { |
| 189 | expect(typeof body.errorTag).toBe("string"); |
| 190 | expect(body.errorTag.length).toBeGreaterThan(0); |
| 191 | } else { |
| 192 | expect(body.timestamps).toBeGreaterThanOrEqual(0); |
| 193 | expect(body.values).toBeGreaterThanOrEqual(0); |
| 194 | } |
| 195 | }), |
| 196 | ); |
| 197 | }); |
| 198 | |
| 199 | describe("ListInsightsData", () => { |
| 200 | test.provider("reads raw Insights events (empty is fine)", () => |
| 201 | Effect.gen(function* () { |
| 202 | const body = (yield* getJson(`${baseUrl}/insights-data`)) as any; |
| 203 | |
| 204 | // No Insights are enabled in the test account, so the list is |
| 205 | // empty — success proves the wiring; a rejection must be TYPED. |
| 206 | if (body.errorTag !== undefined) { |
| 207 | expect(typeof body.errorTag).toBe("string"); |
| 208 | expect(body.errorTag.length).toBeGreaterThan(0); |
| 209 | } else { |
| 210 | expect(body.events).toBeGreaterThanOrEqual(0); |
| 211 | } |
| 212 | }), |
| 213 | ); |
| 214 | }); |
| 215 | |
| 216 | describe("ApiCallEventSource", () => { |
| 217 | test.provider( |
| 218 | "delivers a mutating management API call to the handler", |
| 219 | () => |
| 220 | Effect.gen(function* () { |
| 221 | const info = (yield* getJson(`${baseUrl}/info`)) as any; |
| 222 | const bucketName = info.bucketName as string; |
| 223 | expect(bucketName).toBeTruthy(); |
| 224 | |
| 225 | // Each probe iteration re-fires a PutBucketTagging call (riding |
| 226 | // out fresh-rule propagation on the default bus), preserving the |
| 227 | // bucket's existing tags, then checks for the marker the event |
| 228 | // handler wrote to S3. |
| 229 | const probe = Effect.gen(function* () { |
| 230 | const existing = yield* s3 |
| 231 | .getBucketTagging({ Bucket: bucketName }) |
| 232 | .pipe( |
| 233 | Effect.map((r) => r.TagSet ?? []), |
| 234 | Effect.catchTag("NoSuchTagSet", () => Effect.succeed([])), |
| 235 | ); |
| 236 | yield* s3.putBucketTagging({ |
| 237 | Bucket: bucketName, |
| 238 | Tagging: { |
| 239 | TagSet: [ |
| 240 | ...existing.filter((t) => t.Key !== "cloudtrail-probe"), |
| 241 | { Key: "cloudtrail-probe", Value: "1" }, |
| 242 | ], |
| 243 | }, |
| 244 | }); |
| 245 | yield* Effect.sleep("5 seconds"); |
| 246 | const body = (yield* getJson( |
| 247 | `${baseUrl}/events/check?bucket=${bucketName}`, |
| 248 | )) as any; |
| 249 | return body.seen as boolean; |
| 250 | }); |
| 251 | |
| 252 | // A freshly created trail warms up the CloudTrail→EventBridge |
| 253 | // pipeline on its first events — budget accordingly (bounded). |
| 254 | const seen = yield* probe.pipe( |
| 255 | Effect.repeat({ |
| 256 | schedule: Schedule.spaced("3 seconds"), |
| 257 | until: (s): boolean => s, |
| 258 | times: 22, |
| 259 | }), |
| 260 | ); |
| 261 | expect(seen).toBe(true); |
| 262 | }), |
| 263 | { timeout: 300_000 }, |
| 264 | ); |
| 265 | }); |
| 266 | }, |
| 267 | ); |