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

main
ts 187 lines 7.79 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import {
3 Trail,
4 type TrailAdvancedEventSelector,
5 type TrailInsightSelector,
6 } from "@alchemy.run/aws/CloudTrail";
7 import { AWSEnvironment } from "@alchemy.run/aws/Environment";
8 import { Bucket } from "@alchemy.run/aws/S3/Bucket";
9 import { expect } from "@alchemy.run/test";
10 import * as Test from "@alchemy.run/test/Alchemy";
11 import * as cloudtrail from "@distilled.cloud/aws/cloudtrail";
12 import * as Effect from "effect/Effect";
13
14 const { test } = Test.make({ providers: AWS.providers() });
15
16 // Ungated typed-error probe: prove the distilled error union carries the
17 // not-found tag this provider's read/delete paths depend on. Runs in every
18 // CI pass at near-zero cost.
19 test.provider(
20 "getTrail on a nonexistent trail fails with TrailNotFoundException",
21 () =>
22 Effect.gen(function* () {
23 const error = yield* Effect.flip(
24 cloudtrail.getTrail({ Name: "alchemy-nonexistent-trail-probe" }),
25 );
26 expect(error._tag).toBe("TrailNotFoundException");
27 }),
28 { tags: ["provider:aws", "provider:aws:cloudtrail", "live"] },
29 );
30
31 const TRAIL_NAME = "alchemy-test-cloudtrail-trail";
32
33 test.provider(
34 "create trail with S3 bucket + policy, update settings and logging, delete",
35 (stack) =>
36 Effect.gen(function* () {
37 yield* stack.destroy();
38
39 const { accountId, region } = yield* AWSEnvironment.current;
40 // Bucket names are globally unique — key ours to the account. The
41 // trail ARN is deterministic, so the bucket policy can reference it
42 // before the trail exists (no circular dependency).
43 const bucketName = `alchemy-test-cloudtrail-logs-${accountId}`;
44 const trailArn = `arn:aws:cloudtrail:${region}:${accountId}:trail/${TRAIL_NAME}`;
45
46 const make = (props: {
47 isLogging?: boolean;
48 includeGlobalServiceEvents?: boolean;
49 s3KeyPrefix?: string;
50 tags?: Record<string, string>;
51 advancedEventSelectors?: TrailAdvancedEventSelector[];
52 insightSelectors?: TrailInsightSelector[];
53 }) =>
54 Effect.gen(function* () {
55 const bucket = yield* Bucket("TrailLogs", {
56 bucketName,
57 forceDestroy: true,
58 policy: [
59 {
60 Effect: "Allow",
61 Principal: { Service: "cloudtrail.amazonaws.com" },
62 Action: ["s3:GetBucketAcl"],
63 Resource: `arn:aws:s3:::${bucketName}`,
64 Condition: { StringEquals: { "aws:SourceArn": trailArn } },
65 },
66 {
67 Effect: "Allow",
68 Principal: { Service: "cloudtrail.amazonaws.com" },
69 Action: ["s3:PutObject"],
70 // Cover both the default `AWSLogs/...` path and the
71 // `audit/AWSLogs/...` path used after the s3KeyPrefix
72 // update below. Still constrained by aws:SourceArn.
73 Resource: [
74 `arn:aws:s3:::${bucketName}/AWSLogs/${accountId}/*`,
75 `arn:aws:s3:::${bucketName}/audit/AWSLogs/${accountId}/*`,
76 ],
77 Condition: {
78 StringEquals: {
79 "s3:x-amz-acl": "bucket-owner-full-control",
80 "aws:SourceArn": trailArn,
81 },
82 },
83 },
84 ],
85 });
86 const trail = yield* Trail("Audit", {
87 trailName: TRAIL_NAME,
88 s3BucketName: bucket.bucketName,
89 ...props,
90 });
91 return { trail };
92 });
93
94 // 1. Create — logging on by default.
95 const { trail } = yield* stack.deploy(make({ tags: { fixture: "cloudtrail-trail" } }));
96 expect(trail.trailName).toBe(TRAIL_NAME);
97 expect(trail.trailArn).toBe(trailArn);
98 expect(trail.homeRegion).toBe(region);
99 expect(trail.s3BucketName).toBe(bucketName);
100 expect(trail.isLogging).toBe(true);
101
102 // Out-of-band verification via distilled.
103 const observed = yield* cloudtrail.getTrail({ Name: TRAIL_NAME });
104 expect(observed.Trail?.TrailARN).toBe(trailArn);
105 expect(observed.Trail?.S3BucketName).toBe(bucketName);
106 expect(observed.Trail?.IncludeGlobalServiceEvents).toBe(true);
107 expect(observed.Trail?.IsMultiRegionTrail).toBe(false);
108 const status = yield* cloudtrail.getTrailStatus({ Name: trailArn });
109 expect(status.IsLogging).toBe(true);
110 const tags = yield* cloudtrail.listTags({ ResourceIdList: [trailArn] });
111 const tagRecord = Object.fromEntries(
112 (tags.ResourceTagList?.[0]?.TagsList ?? []).map((t) => [t.Key, t.Value]),
113 );
114 expect(tagRecord.fixture).toBe("cloudtrail-trail");
115 expect(tagRecord["alchemy::id"]).toBe("Audit");
116
117 // 2. Sync event + Insights selectors while logging is still on.
118 const { trail: withSelectors } = yield* stack.deploy(
119 make({
120 tags: { fixture: "cloudtrail-trail" },
121 advancedEventSelectors: [
122 {
123 name: "Management events",
124 fieldSelectors: [{ field: "eventCategory", equals: ["Management"] }],
125 },
126 ],
127 insightSelectors: [{ insightType: "ApiCallRateInsight" }],
128 }),
129 );
130 expect(withSelectors.trailArn).toBe(trailArn);
131 const selectors = yield* cloudtrail.getEventSelectors({ TrailName: trailArn });
132 expect(selectors.AdvancedEventSelectors?.[0]?.Name).toBe("Management events");
133 const insights = yield* cloudtrail.getInsightSelectors({ TrailName: trailArn });
134 expect((insights.InsightSelectors ?? []).map((s) => s.InsightType)).toContain(
135 "ApiCallRateInsight",
136 );
137
138 // 3. Update in place — stop logging, flip settings, swap tags,
139 // disable Insights (`[]`). Omitted event selectors stay untouched.
140 const { trail: updated } = yield* stack.deploy(
141 make({
142 isLogging: false,
143 includeGlobalServiceEvents: false,
144 s3KeyPrefix: "audit",
145 tags: { team: "security" },
146 insightSelectors: [],
147 }),
148 );
149 expect(updated.trailArn).toBe(trail.trailArn);
150 expect(updated.isLogging).toBe(false);
151
152 const observedAfter = yield* cloudtrail.getTrail({ Name: TRAIL_NAME });
153 expect(observedAfter.Trail?.IncludeGlobalServiceEvents).toBe(false);
154 expect(observedAfter.Trail?.S3KeyPrefix).toBe("audit");
155 const statusAfter = yield* cloudtrail.getTrailStatus({ Name: trailArn });
156 expect(statusAfter.IsLogging).toBe(false);
157 const tagsAfter = yield* cloudtrail.listTags({ ResourceIdList: [trailArn] });
158 const tagRecordAfter = Object.fromEntries(
159 (tagsAfter.ResourceTagList?.[0]?.TagsList ?? []).map((t) => [t.Key, t.Value]),
160 );
161 expect(tagRecordAfter.team).toBe("security");
162 expect(tagRecordAfter.fixture).toBeUndefined();
163 expect(tagRecordAfter["alchemy::id"]).toBe("Audit");
164
165 // Insights disabled: reads back as the typed InsightNotEnabledException
166 // (or an empty list, depending on propagation).
167 const insightsAfter = yield* cloudtrail.getInsightSelectors({ TrailName: trailArn }).pipe(
168 Effect.map((r) => r.InsightSelectors ?? []),
169 Effect.catchTag("InsightNotEnabledException", () =>
170 Effect.succeed([] as cloudtrail.InsightSelector[]),
171 ),
172 );
173 expect(insightsAfter).toEqual([]);
174 // Omitted event selectors were left untouched by the update.
175 const selectorsAfter = yield* cloudtrail.getEventSelectors({ TrailName: trailArn });
176 expect(selectorsAfter.AdvancedEventSelectors?.[0]?.Name).toBe("Management events");
177
178 // 4. Delete — trail deletion is synchronous.
179 yield* stack.destroy();
180 const gone = yield* Effect.flip(cloudtrail.getTrail({ Name: TRAIL_NAME }));
181 expect(gone._tag).toBe("TrailNotFoundException");
182 }),
183 {
184 tags: ["provider:aws", "provider:aws:cloudtrail", "provider:aws:s3", "live"],
185 timeout: 240_000,
186 },
187 );