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

main
ts 279 lines 10.8 KB
Raw
1 import * as AWS from "@alchemy.run/aws";
2 import { describe, expect } from "@alchemy.run/test";
3 import * as Test from "@alchemy.run/test/Alchemy";
4 import * as Core from "@alchemy.run/test/Core";
5 import * as acm from "@distilled.cloud/aws/acm";
6 import { Region as AwsRegion } from "@distilled.cloud/aws/Region";
7 import * as Data from "effect/Data";
8 import * as Effect from "effect/Effect";
9 import * as HttpClient from "effect/http/HttpClient";
10 import * as HttpClientRequest from "effect/http/HttpClientRequest";
11 import * as Schedule from "effect/Schedule";
12 import AcmTestFunctionLive, { AcmTestFunction, FIXTURE_DOMAIN } from "./handler";
13
14 const testOptions = { providers: AWS.providers() };
15 const { test, beforeAll, afterAll } = Test.make(testOptions);
16 const sharedStack = Core.scratchStack(testOptions, "ACMBindings");
17
18 // ACM operations (and the bindings) are pinned to us-east-1, matching where
19 // the Certificate resource provider requests certificates. Every out-of-band
20 // ACM call in this file must target the same region.
21 const withUsEast1 = <A, E, R>(effect: Effect.Effect<A, E, R>) =>
22 effect.pipe(Effect.provideService(AwsRegion, Effect.succeed("us-east-1")));
23
24 // Lambda function URL cold-start (DNS, IAM propagation, init) can take well
25 // over 60s on a fresh deploy under parallel-suite load.
26 const readinessPolicy = Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(75)]);
27
28 let baseUrl: string;
29
30 class TransientUpstream extends Data.TaggedError("TransientUpstream")<{
31 readonly status: number;
32 readonly body: string;
33 }> {}
34
35 // Retry transient 5xx from the shared Lambda fixture (cold re-init, IAM
36 // propagation on the freshly attached acm policy surfaced as a 500 by the
37 // handler's `Effect.orDie`). Genuine 4xx/assertion failures return
38 // immediately.
39 const send = (request: HttpClientRequest.HttpClientRequest) =>
40 HttpClient.execute(request).pipe(
41 Effect.flatMap((response) =>
42 response.status >= 500
43 ? response.text.pipe(
44 Effect.flatMap((body) =>
45 Effect.fail(new TransientUpstream({ status: response.status, body })),
46 ),
47 )
48 : Effect.succeed(response),
49 ),
50 Effect.retry({
51 while: (e) => e._tag === "TransientUpstream",
52 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(6)]),
53 }),
54 );
55
56 // The revoke probe below mutates shared fixture state if it were ever to
57 // succeed, and list/search are eventually consistent against the fixture
58 // certificate — run the file sequentially.
59 describe.sequential(
60 "ACM Bindings",
61 { tags: ["provider:aws", "provider:aws:acm", "provider:aws:lambda", "live"] },
62 () => {
63 beforeAll(
64 Effect.gen(function* () {
65 yield* Effect.logInfo("ACM test setup: destroying previous resources");
66 yield* sharedStack.destroy();
67
68 yield* Effect.logInfo("ACM test setup: deploying fixture");
69 const { functionUrl } = yield* sharedStack.deploy(
70 Effect.gen(function* () {
71 return yield* AcmTestFunction;
72 }).pipe(Effect.provide(AcmTestFunctionLive)),
73 );
74
75 expect(functionUrl).toBeTruthy();
76 baseUrl = functionUrl!.replace(/\/+$/, "");
77 const readinessUrl = `${baseUrl}/describe`;
78
79 yield* Effect.logInfo(`ACM test setup: probing readiness at ${readinessUrl}`);
80 yield* HttpClient.get(readinessUrl).pipe(
81 Effect.flatMap((response) =>
82 response.status === 200
83 ? Effect.succeed(response)
84 : Effect.fail(new Error(`Function not ready: ${response.status}`)),
85 ),
86 Effect.retry({ schedule: readinessPolicy }),
87 );
88 }),
89 { timeout: 240_000 },
90 );
91
92 afterAll(sharedStack.destroy(), { timeout: 120_000 });
93
94 describe("DescribeCertificate", () => {
95 test.provider("reads the bound certificate's metadata", (_stack) =>
96 Effect.gen(function* () {
97 const body = (yield* send(HttpClientRequest.get(`${baseUrl}/describe`)).pipe(
98 Effect.flatMap((r) => r.json),
99 )) as any;
100
101 expect(body.arn).toContain("arn:aws:acm:us-east-1:");
102 expect(body.domainName).toBe(FIXTURE_DOMAIN);
103 // example.com is not ours — the DNS-validated fixture certificate
104 // stays pending forever.
105 expect(body.status).toBe("PENDING_VALIDATION");
106 }),
107 );
108 });
109
110 describe("GetCertificate", () => {
111 test.provider("fails with the typed RequestInProgressException while pending", (_stack) =>
112 Effect.gen(function* () {
113 const body = (yield* send(HttpClientRequest.get(`${baseUrl}/get`)).pipe(
114 Effect.flatMap((r) => r.json),
115 )) as any;
116
117 expect(body.errorTag).toBe("RequestInProgressException");
118 }),
119 );
120 });
121
122 describe("ListCertificates", () => {
123 test.provider("lists the bound certificate", (_stack) =>
124 Effect.gen(function* () {
125 const described = (yield* send(HttpClientRequest.get(`${baseUrl}/describe`)).pipe(
126 Effect.flatMap((r) => r.json),
127 )) as any;
128
129 // ListCertificates is eventually consistent for fresh requests.
130 const body = yield* fetchUntil(
131 send(HttpClientRequest.get(`${baseUrl}/list`)).pipe(Effect.flatMap((r) => r.json)),
132 (b) => Array.isArray(b?.arns) && b.arns.includes(described.arn),
133 );
134
135 expect((body as any).arns).toContain(described.arn);
136 }),
137 );
138 });
139
140 describe("SearchCertificates", () => {
141 test.provider("finds the bound certificate by ARN filter", (_stack) =>
142 Effect.gen(function* () {
143 const described = (yield* send(HttpClientRequest.get(`${baseUrl}/describe`)).pipe(
144 Effect.flatMap((r) => r.json),
145 )) as any;
146
147 const body = yield* fetchUntil(
148 send(HttpClientRequest.get(`${baseUrl}/search`)).pipe(Effect.flatMap((r) => r.json)),
149 (b) => Array.isArray(b?.arns) && b.arns.includes(described.arn),
150 );
151
152 expect((body as any).arns).toContain(described.arn);
153 }),
154 );
155 });
156
157 describe("ExportCertificate", () => {
158 test.provider("fails with a typed error on a non-exportable pending certificate", (_stack) =>
159 Effect.gen(function* () {
160 const body = (yield* send(HttpClientRequest.post(`${baseUrl}/export`)).pipe(
161 Effect.flatMap((r) => r.json),
162 )) as any;
163
164 // The fixture certificate is pending and was not requested with
165 // `export: "ENABLED"` — the export must be rejected with a TYPED
166 // tag (an untyped catch-all would crash the handler into a 500).
167 expect(typeof body.errorTag).toBe("string");
168 expect(body.errorTag.length).toBeGreaterThan(0);
169 }),
170 );
171 });
172
173 describe("RenewCertificate", () => {
174 test.provider("fails with a typed error on a pending certificate", (_stack) =>
175 Effect.gen(function* () {
176 const body = (yield* send(HttpClientRequest.post(`${baseUrl}/renew`)).pipe(
177 Effect.flatMap((r) => r.json),
178 )) as any;
179
180 expect(typeof body.errorTag).toBe("string");
181 expect(body.errorTag.length).toBeGreaterThan(0);
182 }),
183 );
184 });
185
186 describe("ResendValidationEmail", () => {
187 test.provider("fails with a typed error on a DNS-validated certificate", (_stack) =>
188 Effect.gen(function* () {
189 const body = (yield* send(HttpClientRequest.post(`${baseUrl}/resend-email`)).pipe(
190 Effect.flatMap((r) => r.json),
191 )) as any;
192
193 // Email validation cannot be (re)sent for a DNS-validated
194 // certificate; ACM reports the invalid state with a typed tag.
195 expect(typeof body.errorTag).toBe("string");
196 expect(body.errorTag.length).toBeGreaterThan(0);
197 }),
198 );
199 });
200
201 describe("RevokeCertificate", () => {
202 test.provider("fails with a typed error on a never-exported certificate", (_stack) =>
203 Effect.gen(function* () {
204 const body = (yield* send(HttpClientRequest.post(`${baseUrl}/revoke`)).pipe(
205 Effect.flatMap((r) => r.json),
206 )) as any;
207
208 // Only previously exported certificates can be revoked — the
209 // pending fixture must be rejected with a typed tag.
210 expect(typeof body.errorTag).toBe("string");
211 expect(body.errorTag.length).toBeGreaterThan(0);
212 }),
213 );
214 });
215
216 describe("ImportCertificate", () => {
217 test.provider(
218 "imports and rotates an externally issued certificate",
219 (_stack) =>
220 Effect.gen(function* () {
221 const imported = (yield* send(
222 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/import`), {}),
223 ).pipe(Effect.flatMap((r) => r.json))) as any;
224
225 expect(imported.arn).toContain("arn:aws:acm:us-east-1:");
226 expect(imported.arn).toContain(":certificate/");
227
228 // The imported certificate is created outside IaC management —
229 // reclaim it even if the assertions below fail.
230 yield* Effect.addFinalizer(() =>
231 withUsEast1(acm.deleteCertificate({ CertificateArn: imported.arn })).pipe(
232 Effect.ignore,
233 ),
234 );
235
236 // Rotation path: re-importing over the existing ARN keeps the ARN.
237 const reimported = (yield* send(
238 HttpClientRequest.bodyJsonUnsafe(HttpClientRequest.post(`${baseUrl}/import`), {
239 reimportArn: imported.arn,
240 }),
241 ).pipe(Effect.flatMap((r) => r.json))) as any;
242
243 expect(reimported.arn).toBe(imported.arn);
244
245 // Deleting a freshly imported certificate can hit eventual
246 // consistency; retry the typed conflict, tolerate already-gone.
247 yield* withUsEast1(
248 acm.deleteCertificate({ CertificateArn: imported.arn }).pipe(
249 Effect.retry({
250 while: (e) => e._tag === "ConflictException",
251 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(10)]),
252 }),
253 Effect.catchTag("ResourceNotFoundException", () => Effect.void),
254 ),
255 );
256 }),
257 { timeout: 120_000 },
258 );
259 });
260 },
261 );
262
263 // A request observed not-yet-consistent control-plane state (ListCertificates
264 // lags fresh requests by a few seconds). Retry, bounded.
265 class BindingNotConsistent extends Data.TaggedError("BindingNotConsistent") {}
266
267 const fetchUntil = <A>(
268 fetch: Effect.Effect<unknown, any, HttpClient.HttpClient>,
269 ready: (body: any) => boolean,
270 ) =>
271 fetch.pipe(
272 Effect.flatMap((body) =>
273 ready(body) ? Effect.succeed(body as A) : Effect.fail(new BindingNotConsistent()),
274 ),
275 Effect.retry({
276 while: (e) => e._tag === "BindingNotConsistent",
277 schedule: Schedule.max([Schedule.fixed("2 seconds"), Schedule.recurs(20)]),
278 }),
279 );