@devries-cameron20 / t3code Mirror · read-only
Fork 0

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

Mirrored from https://github.com/Camo67/t3code.git

Synced Nov 21, 06:00 UTC

main
ts 372 lines 14.2 KB
Raw
1 import * as Lambda from "@alchemy.run/aws/Lambda";
2 import * as Macie2 from "@alchemy.run/aws/Macie2";
3 import * as Duration from "effect/Duration";
4 import * as Effect from "effect/Effect";
5 import { HttpServerRequest } from "effect/http/HttpServerRequest";
6 import * as HttpServerResponse from "effect/http/HttpServerResponse";
7 import * as Layer from "effect/Layer";
8 import path from "pathe";
9
10 const main = path.resolve(import.meta.dirname, "handler.ts");
11
12 export class Macie2TestFunction extends Lambda.Function<Lambda.Function>()("Macie2TestFunction") {}
13
14 /**
15 * Routes answer `{ …fields }` on success or `{ errorTag }` when the operation
16 * fails with a TYPED error — the test asserts the tag is in a route-specific
17 * allowlist, which proves both the binding wiring and the IAM grant. An
18 * untyped error crashes into a 500 instead.
19 */
20 const errorTagged = <A, E extends { _tag: string }, R>(
21 effect: Effect.Effect<A, E, R>,
22 ): Effect.Effect<A | { errorTag: string; errorMessage?: string }, never, R> =>
23 effect.pipe(
24 Effect.map((a): A | { errorTag: string; errorMessage?: string } => a),
25 Effect.catch((e) =>
26 Effect.succeed({
27 errorTag: e._tag,
28 errorMessage: (e as { Message?: string }).Message ?? (e as { message?: string }).message,
29 }),
30 ),
31 );
32
33 // One binding per exercised Macie capability. Every Macie2 binding shares the
34 // single account-level scaffolding shape (the request passes through as-is),
35 // so a representative spread across the thematic groups proves the scaffold;
36 // org/member writes with cross-account side effects (CreateMember,
37 // EnableOrganizationAdminAccount, …) use the same builder and are not
38 // re-proven here.
39 export default Macie2TestFunction.make(
40 {
41 main,
42 functionUrl: true,
43 timeout: Duration.seconds(30),
44 },
45 Effect.gen(function* () {
46 // Macie must be enabled for every runtime call — the session is the
47 // account/region singleton the whole fixture leans on. The Bindings test
48 // only runs when the account had no session (capture-and-restore safety).
49 yield* Macie2.Session("BindingsSession", {
50 status: "ENABLED",
51 findingPublishingFrequency: "FIFTEEN_MINUTES",
52 });
53
54 // Findings triage loop
55 const createSampleFindings = yield* Macie2.CreateSampleFindings();
56 const listFindings = yield* Macie2.ListFindings();
57 const getFindings = yield* Macie2.GetFindings();
58 const getFindingStatistics = yield* Macie2.GetFindingStatistics();
59
60 // S3 bucket inventory
61 const getBucketStatistics = yield* Macie2.GetBucketStatistics();
62 const searchResources = yield* Macie2.SearchResources();
63
64 // Identifiers & lists
65 const listManagedDataIdentifiers = yield* Macie2.ListManagedDataIdentifiers();
66 const testCustomDataIdentifier = yield* Macie2.TestCustomDataIdentifier();
67 const listAllowLists = yield* Macie2.ListAllowLists();
68 const listFindingsFilters = yield* Macie2.ListFindingsFilters();
69
70 // Jobs, export & usage
71 const listClassificationJobs = yield* Macie2.ListClassificationJobs();
72 const getClassificationExportConfiguration =
73 yield* Macie2.GetClassificationExportConfiguration();
74 const getUsageTotals = yield* Macie2.GetUsageTotals();
75
76 // Automated discovery & reveal
77 const getAutomatedDiscoveryConfiguration = yield* Macie2.GetAutomatedDiscoveryConfiguration();
78 const listClassificationScopes = yield* Macie2.ListClassificationScopes();
79 const getRevealConfiguration = yield* Macie2.GetRevealConfiguration();
80
81 // Administrator, invitations & organization
82 const getAdministratorAccount = yield* Macie2.GetAdministratorAccount();
83 const getInvitationsCount = yield* Macie2.GetInvitationsCount();
84 const listInvitations = yield* Macie2.ListInvitations();
85 const listMembers = yield* Macie2.ListMembers();
86 const listOrganizationAdminAccounts = yield* Macie2.ListOrganizationAdminAccounts();
87 const describeOrganizationConfiguration = yield* Macie2.DescribeOrganizationConfiguration();
88
89 const bound = {
90 createSampleFindings,
91 listFindings,
92 getFindings,
93 getFindingStatistics,
94 getBucketStatistics,
95 searchResources,
96 listManagedDataIdentifiers,
97 testCustomDataIdentifier,
98 listAllowLists,
99 listFindingsFilters,
100 listClassificationJobs,
101 getClassificationExportConfiguration,
102 getUsageTotals,
103 getAutomatedDiscoveryConfiguration,
104 listClassificationScopes,
105 getRevealConfiguration,
106 getAdministratorAccount,
107 getInvitationsCount,
108 listInvitations,
109 listMembers,
110 listOrganizationAdminAccounts,
111 describeOrganizationConfiguration,
112 };
113
114 return {
115 fetch: Effect.gen(function* () {
116 const request = yield* HttpServerRequest;
117 const url = new URL(request.originalUrl);
118 const pathname = url.pathname;
119
120 if (request.method === "GET" && pathname === "/bindings") {
121 return yield* HttpServerResponse.json({ bound: Object.keys(bound) });
122 }
123
124 // Generates sample findings — the documented way to exercise a
125 // findings pipeline without staging real sensitive data.
126 if (request.method === "POST" && pathname === "/sample") {
127 yield* createSampleFindings({});
128 return yield* HttpServerResponse.json({ ok: true });
129 }
130
131 if (request.method === "GET" && pathname === "/findings") {
132 const { findingIds } = yield* listFindings();
133 return yield* HttpServerResponse.json({
134 count: (findingIds ?? []).length,
135 ids: (findingIds ?? []).slice(0, 5),
136 });
137 }
138
139 if (request.method === "GET" && pathname === "/finding-detail") {
140 const id = url.searchParams.get("id");
141 if (!id) {
142 return yield* HttpServerResponse.json({ error: "missing id" }, { status: 400 });
143 }
144 const { findings } = yield* getFindings({ findingIds: [id] });
145 return yield* HttpServerResponse.json({
146 count: (findings ?? []).length,
147 type: findings?.[0]?.type,
148 sample: findings?.[0]?.sample ?? false,
149 });
150 }
151
152 if (request.method === "GET" && pathname === "/finding-stats") {
153 const { countsByGroup } = yield* getFindingStatistics({
154 groupBy: "severity.description",
155 });
156 return yield* HttpServerResponse.json({
157 groups: (countsByGroup ?? []).length,
158 });
159 }
160
161 if (request.method === "GET" && pathname === "/buckets") {
162 const stats = yield* getBucketStatistics({});
163 return yield* HttpServerResponse.json({
164 bucketCount: Number(stats.bucketCount ?? 0),
165 });
166 }
167
168 if (request.method === "GET" && pathname === "/search") {
169 // SearchResources requires bucket criteria — exclude a bucket that
170 // cannot exist, i.e. match everything.
171 const { matchingResources } = yield* searchResources({
172 bucketCriteria: {
173 excludes: {
174 and: [
175 {
176 simpleCriterion: {
177 comparator: "EQ",
178 key: "S3_BUCKET_NAME",
179 values: ["macie2-bindings-nonexistent-bucket"],
180 },
181 },
182 ],
183 },
184 },
185 });
186 return yield* HttpServerResponse.json({
187 matches: (matchingResources ?? []).length,
188 });
189 }
190
191 if (request.method === "GET" && pathname === "/managed-identifiers") {
192 const { items } = yield* listManagedDataIdentifiers();
193 return yield* HttpServerResponse.json({
194 count: (items ?? []).length,
195 });
196 }
197
198 // A real detection round-trip that needs no cloud state at all.
199 if (request.method === "POST" && pathname === "/test-identifier") {
200 const { matchCount } = yield* testCustomDataIdentifier({
201 regex: "EMP-[0-9]{8}",
202 sampleText: "ids EMP-12345678 and EMP-87654321 but not EMP-123",
203 });
204 return yield* HttpServerResponse.json({ matchCount });
205 }
206
207 if (request.method === "GET" && pathname === "/allow-lists") {
208 const { allowLists } = yield* listAllowLists();
209 return yield* HttpServerResponse.json({
210 count: (allowLists ?? []).length,
211 });
212 }
213
214 if (request.method === "GET" && pathname === "/findings-filters") {
215 const { findingsFilterListItems } = yield* listFindingsFilters();
216 return yield* HttpServerResponse.json({
217 count: (findingsFilterListItems ?? []).length,
218 });
219 }
220
221 if (request.method === "GET" && pathname === "/jobs") {
222 const { items } = yield* listClassificationJobs();
223 return yield* HttpServerResponse.json({
224 count: (items ?? []).length,
225 });
226 }
227
228 // A fresh session has no export configuration — an empty document.
229 if (request.method === "GET" && pathname === "/export-config") {
230 const { configuration } = yield* getClassificationExportConfiguration();
231 return yield* HttpServerResponse.json({
232 configured: configuration?.s3Destination !== undefined,
233 });
234 }
235
236 if (request.method === "GET" && pathname === "/usage") {
237 const { usageTotals } = yield* getUsageTotals();
238 return yield* HttpServerResponse.json({
239 totals: (usageTotals ?? []).length,
240 });
241 }
242
243 if (request.method === "GET" && pathname === "/auto-discovery") {
244 const { status } = yield* getAutomatedDiscoveryConfiguration();
245 return yield* HttpServerResponse.json({ status: status ?? null });
246 }
247
248 if (request.method === "GET" && pathname === "/scopes") {
249 const { classificationScopes } = yield* listClassificationScopes();
250 return yield* HttpServerResponse.json({
251 count: (classificationScopes ?? []).length,
252 });
253 }
254
255 // A fresh session rejects the reveal-configuration read with a typed
256 // AccessDeniedException until sample retrieval is set up.
257 if (request.method === "GET" && pathname === "/reveal") {
258 const result = yield* errorTagged(
259 getRevealConfiguration().pipe(
260 Effect.map((r) => ({
261 status: r.configuration?.status ?? null,
262 })),
263 ),
264 );
265 return yield* HttpServerResponse.json(result);
266 }
267
268 // A standalone account has no administrator — Macie answers with an
269 // empty document or a typed error.
270 if (request.method === "GET" && pathname === "/admin") {
271 const result = yield* errorTagged(
272 getAdministratorAccount().pipe(
273 Effect.map((r) => ({
274 administrator: r.administrator?.accountId ?? null,
275 })),
276 ),
277 );
278 return yield* HttpServerResponse.json(result);
279 }
280
281 if (request.method === "GET" && pathname === "/invitations-count") {
282 const { invitationsCount } = yield* getInvitationsCount();
283 return yield* HttpServerResponse.json({
284 count: Number(invitationsCount ?? 0),
285 });
286 }
287
288 if (request.method === "GET" && pathname === "/invitations") {
289 const { invitations } = yield* listInvitations();
290 return yield* HttpServerResponse.json({
291 count: (invitations ?? []).length,
292 });
293 }
294
295 if (request.method === "GET" && pathname === "/members") {
296 const { members } = yield* listMembers();
297 return yield* HttpServerResponse.json({
298 count: (members ?? []).length,
299 });
300 }
301
302 // Organization administration: for a standalone (non-management)
303 // account Macie answers with a typed error — asserting the tag proves
304 // the binding + IAM wiring end-to-end.
305 if (request.method === "GET" && pathname === "/org-admins") {
306 const result = yield* errorTagged(
307 listOrganizationAdminAccounts().pipe(
308 Effect.map((r) => ({ admins: (r.adminAccounts ?? []).length })),
309 ),
310 );
311 return yield* HttpServerResponse.json(result);
312 }
313
314 if (request.method === "GET" && pathname === "/org-config") {
315 const result = yield* errorTagged(
316 describeOrganizationConfiguration().pipe(
317 Effect.map((r) => ({ autoEnable: r.autoEnable ?? false })),
318 ),
319 );
320 return yield* HttpServerResponse.json(result);
321 }
322
323 return yield* HttpServerResponse.json(
324 { error: "Not found", method: request.method, pathname },
325 { status: 404 },
326 );
327 }).pipe(
328 // Surface typed operation errors as JSON so live-test failures carry
329 // the tag + message instead of an opaque 500 (routes that expect a
330 // typed error use `errorTagged` above and never reach this).
331 Effect.catch((e) =>
332 HttpServerResponse.json(
333 {
334 errorTag: (e as { _tag?: string })._tag ?? "UnknownError",
335 errorMessage:
336 (e as { message?: string }).message ?? (e as { Message?: string }).Message,
337 },
338 { status: 500 },
339 ),
340 ),
341 Effect.orDie,
342 ),
343 };
344 }).pipe(
345 Effect.provide(
346 Layer.mergeAll(
347 Macie2.CreateSampleFindingsHttp,
348 Macie2.DescribeOrganizationConfigurationHttp,
349 Macie2.GetAdministratorAccountHttp,
350 Macie2.GetAutomatedDiscoveryConfigurationHttp,
351 Macie2.GetBucketStatisticsHttp,
352 Macie2.GetClassificationExportConfigurationHttp,
353 Macie2.GetFindingStatisticsHttp,
354 Macie2.GetFindingsHttp,
355 Macie2.GetInvitationsCountHttp,
356 Macie2.GetRevealConfigurationHttp,
357 Macie2.GetUsageTotalsHttp,
358 Macie2.ListAllowListsHttp,
359 Macie2.ListClassificationJobsHttp,
360 Macie2.ListClassificationScopesHttp,
361 Macie2.ListFindingsFiltersHttp,
362 Macie2.ListFindingsHttp,
363 Macie2.ListInvitationsHttp,
364 Macie2.ListManagedDataIdentifiersHttp,
365 Macie2.ListMembersHttp,
366 Macie2.ListOrganizationAdminAccountsHttp,
367 Macie2.SearchResourcesHttp,
368 Macie2.TestCustomDataIdentifierHttp,
369 ),
370 ),
371 ),
372 );