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

main
ts 180 lines 6.68 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { expect } from "@alchemy.run/test";
3 import * as ag from "@distilled.cloud/aws/api-gateway";
4 import * as Duration from "effect/Duration";
5 import * as Effect from "effect/Effect";
6 import * as HttpClient from "effect/http/HttpClient";
7 import * as HttpClientRequest from "effect/http/HttpClientRequest";
8 import * as Schedule from "effect/Schedule";
9 import * as Stream from "effect/Stream";
10 import { assertApiKeyDeleted } from "./assertions.ts";
11 import ApiGatewayBindingsFunctionLive, {
12 ApiGatewayBindingsFunction,
13 } from "./fixtures/bindings-handler.ts";
14 import * as Test from "./Test.ts";
15
16 const { test } = Test.make({ providers: AWS.providers() });
17
18 const keyName = "alchemy-ag-bindings-test-key";
19
20 // The API key under test is created at RUNTIME through the deployed
21 // Lambda's binding — it is not a stack resource, so `stack.destroy()`
22 // can't clean it up if the test dies between `/keys` and `/key` DELETE.
23 // Reap strays by their constant name (pre-clean + ensuring finalizer).
24 const reapApiKeys = ag.getApiKeys.pages({ nameQuery: keyName }).pipe(
25 Stream.runCollect,
26 Effect.map((chunk) =>
27 Array.from(chunk).flatMap((page) =>
28 (page.items ?? []).filter(
29 (key): key is ag.ApiKey & { id: string } => key.id != null && key.name === keyName,
30 ),
31 ),
32 ),
33 Effect.flatMap(
34 Effect.forEach((key) =>
35 ag
36 .deleteApiKey({ apiKey: key.id })
37 .pipe(Effect.catchTag("NotFoundException", () => Effect.void)),
38 ),
39 ),
40 Effect.asVoid,
41 // Finalizer contract: the error channel must be `never`.
42 Effect.orDie,
43 );
44
45 // Fresh Lambda function URLs return transient errors for the first
46 // 30–90s (DNS, IAM propagation, cold init). Poll at a steady cadence.
47 const readinessSchedule = Schedule.max([
48 Schedule.exponential(500).pipe(
49 Schedule.modifyDelay(({ duration: d }) =>
50 Effect.succeed(Duration.isGreaterThan(d, Duration.seconds(10)) ? Duration.seconds(10) : d),
51 ),
52 ),
53 Schedule.recurs(20),
54 ]);
55
56 const getJson = (url: string) =>
57 HttpClient.get(url).pipe(
58 Effect.flatMap((response) =>
59 response.status === 200
60 ? response.json
61 : Effect.fail(new Error(`GET ${url} returned ${response.status}`)),
62 ),
63 );
64
65 const sendJson = (method: "POST" | "DELETE", url: string, body?: unknown) =>
66 HttpClient.execute(
67 body === undefined
68 ? HttpClientRequest.make(method)(url)
69 : HttpClientRequest.make(method)(url).pipe(HttpClientRequest.bodyJsonUnsafe(body)),
70 ).pipe(
71 Effect.flatMap((response) =>
72 response.status === 200
73 ? response.json
74 : Effect.fail(new Error(`${method} ${url} returned ${response.status}`)),
75 ),
76 );
77
78 test.provider.skipIf(!!process.env.FAST)(
79 "ApiGateway bindings issue, meter, and manage API keys from a Lambda",
80 (stack) =>
81 Effect.gen(function* () {
82 yield* stack.destroy();
83 yield* reapApiKeys;
84
85 const { functionUrl } = yield* stack.deploy(
86 Effect.gen(function* () {
87 return yield* ApiGatewayBindingsFunction;
88 }).pipe(Effect.provide(ApiGatewayBindingsFunctionLive)),
89 );
90 expect(functionUrl).toBeTruthy();
91 const baseUrl = functionUrl!.replace(/\/+$/, "");
92
93 // CreateApiKey + CreateUsagePlanKey — retried through cold start.
94 const created = (yield* sendJson("POST", `${baseUrl}/keys`, {
95 name: keyName,
96 }).pipe(Effect.retry({ schedule: readinessSchedule }))) as {
97 id: string;
98 valueRedacted: boolean;
99 };
100 expect(created.id).toBeTruthy();
101 // The distilled response decodes the key material to Redacted.
102 expect(created.valueRedacted).toBe(true);
103
104 // GetApiKey
105 const single = (yield* getJson(`${baseUrl}/key?id=${created.id}`)) as {
106 id: string;
107 name: string;
108 enabled: boolean;
109 };
110 expect(single.id).toEqual(created.id);
111 expect(single.name).toEqual(keyName);
112 expect(single.enabled).toBe(true);
113
114 // GetApiKeys
115 const listed = (yield* getJson(`${baseUrl}/keys?nameQuery=${keyName}`)) as { ids: string[] };
116 expect(listed.ids).toContain(created.id);
117
118 // GetUsagePlanKey / GetUsagePlanKeys — enrollment is visible.
119 const enrollment = (yield* getJson(`${baseUrl}/plan-key?id=${created.id}`)) as {
120 enrolled: boolean;
121 };
122 expect(enrollment.enrolled).toBe(true);
123 const planKeys = (yield* getJson(`${baseUrl}/plan-keys`)) as {
124 ids: string[];
125 };
126 expect(planKeys.ids).toContain(created.id);
127
128 // GetUsage — empty usage window is a valid, IAM-exercising read.
129 const today = new Date().toISOString().slice(0, 10);
130 const usage = (yield* getJson(`${baseUrl}/usage?startDate=${today}&endDate=${today}`)) as {
131 items: Record<string, unknown>;
132 };
133 expect(usage.items).toBeDefined();
134
135 // UpdateUsage — the plan has no quota, so the API answers with a
136 // typed BadRequest (extended: false). An IAM failure would be an
137 // (uncaught) auth error and fail the route with a 500.
138 const extended = (yield* sendJson("POST", `${baseUrl}/extend`, {
139 keyId: created.id,
140 })) as { extended: boolean };
141 expect(typeof extended.extended).toBe("boolean");
142
143 // UpdateApiKey — disable the key.
144 const disabled = (yield* sendJson("POST", `${baseUrl}/disable`, {
145 id: created.id,
146 })) as { enabled: boolean };
147 expect(disabled.enabled).toBe(false);
148
149 // FlushStageCache / FlushStageAuthorizersCache — no cache cluster on
150 // the stage, so the API answers with typed BadRequest/NotFound; the
151 // route reports the flush outcome instead of failing on auth.
152 const flushed = (yield* sendJson("POST", `${baseUrl}/flush`)) as {
153 cache: boolean;
154 authorizers: boolean;
155 };
156 expect(typeof flushed.cache).toBe("boolean");
157 expect(typeof flushed.authorizers).toBe("boolean");
158
159 // DeleteUsagePlanKey + DeleteApiKey — cleanup through the bindings.
160 const deleted = (yield* sendJson("DELETE", `${baseUrl}/key?id=${created.id}`)) as {
161 deleted: boolean;
162 };
163 expect(deleted.deleted).toBe(true);
164 const afterDelete = (yield* getJson(`${baseUrl}/keys?nameQuery=${keyName}`)) as {
165 ids: string[];
166 };
167 expect(afterDelete.ids).not.toContain(created.id);
168
169 yield* stack.destroy();
170
171 // The list endpoint can briefly return a deleted key after GetApiKeys
172 // has already observed the deletion. Prove the runtime-created key is
173 // gone by its stable ID through the bounded typed NotFound assertion.
174 yield* assertApiKeyDeleted(created.id);
175 }).pipe(Effect.ensuring(reapApiKeys)),
176 {
177 tags: ["provider:aws", "provider:aws:apigateway", "provider:aws:lambda", "live"],
178 timeout: 600_000,
179 },
180 );