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

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