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

main
ts 353 lines 12.5 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { findZoneByName } from "@alchemy.run/cloudflare/Zone/lookup";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as originTls from "@distilled.cloud/cloudflare/origin-tls-client-auth";
7 import * as Provider from "alchemy/Provider";
8 import { isResourceState, State, type ResourceState } from "alchemy/State";
9 import * as Effect from "effect/Effect";
10 import * as Redacted from "effect/Redacted";
11 import { MinimumLogLevel } from "effect/References";
12 import * as Schedule from "effect/Schedule";
13 import {
14 CERT_2,
15 CERT_3,
16 CERT_4,
17 CERT_8,
18 CERT_9,
19 KEY_2,
20 KEY_3,
21 KEY_4,
22 KEY_8,
23 KEY_9,
24 } from "./fixtures/certs.ts";
25
26 const { test } = Test.make({ providers: Cloudflare.providers() });
27
28 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
29
30 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
31
32 const resolveZoneId = Effect.gen(function* () {
33 const { accountId } = yield* yield* CloudflareEnvironment;
34 const zone = yield* findZoneByName({ accountId, name: zoneName });
35 if (!zone) {
36 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
37 }
38 return zone.id;
39 });
40
41 // The scoped API token the test harness mints propagates eventually-
42 // consistently across Cloudflare's edge — a fresh token intermittently 403s
43 // with "Unable to authenticate request". Ride out the blips on the test's
44 // own out-of-band calls by retrying the typed `Forbidden` error (part of
45 // each operation's error union via distilled patches).
46 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
47
48 const getCertificate = (zoneId: string, certificateId: string) =>
49 originTls.getHostnameCertificate({ zoneId, certificateId }).pipe(
50 Effect.retry({
51 while: (e) => e._tag === "Forbidden",
52 schedule: forbiddenRetrySchedule,
53 times: 8,
54 }),
55 );
56
57 // Re-uploading a PEM that collides with a not-yet-cleared tombstone (a prior
58 // run's `pending_deletion` cert for the same PEM) resurrects it under the same
59 // id, and the certificate can briefly read back as `pending_deletion` before
60 // transitioning to a live status. Poll until it settles, bounded.
61 const waitForLive = (zoneId: string, certificateId: string) =>
62 getCertificate(zoneId, certificateId).pipe(
63 Effect.flatMap((cert) =>
64 cert.status !== "pending_deletion" && cert.status !== "deleted"
65 ? Effect.succeed(cert)
66 : Effect.fail({ _tag: "CertificateNotLive" } as const),
67 ),
68 Effect.retry({
69 while: (e) => e._tag === "CertificateNotLive",
70 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(15)]),
71 }),
72 );
73
74 // Cloudflare keeps deleted hostname client certificates readable by id as
75 // `pending_deletion` / `deleted` tombstones, so "gone" means tombstoned or
76 // 404.
77 const waitForGone = (zoneId: string, certificateId: string) =>
78 getCertificate(zoneId, certificateId).pipe(
79 Effect.flatMap((cert) =>
80 cert.status === "pending_deletion" || cert.status === "deleted"
81 ? Effect.void
82 : Effect.fail({ _tag: "CertificateNotDeleted" } as const),
83 ),
84 Effect.catchTag("HostnameCertificateNotFound", () => Effect.void),
85 Effect.retry({
86 while: (e) => e._tag === "CertificateNotDeleted",
87 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
88 }),
89 );
90
91 // Purge any live hostname client certificates with this suite's fixture PEMs
92 // left behind by interrupted runs. Filtering by PEM content keeps the purge
93 // scoped to this file — other suites in the directory own other fixtures.
94 const purgeCertificates = (zoneId: string, pems: string[]) =>
95 Effect.gen(function* () {
96 const list = yield* originTls.listHostnameCertificates({ zoneId }).pipe(
97 Effect.retry({
98 while: (e) => e._tag === "Forbidden",
99 schedule: forbiddenRetrySchedule,
100 times: 8,
101 }),
102 );
103 const targets = pems.map((p) => p.trim());
104 yield* Effect.forEach(
105 list.result.filter(
106 (c) =>
107 c.id &&
108 c.status !== "deleted" &&
109 c.status !== "pending_deletion" &&
110 targets.includes((c.certificate ?? "").trim()),
111 ),
112 (c) =>
113 originTls.deleteHostnameCertificate({ zoneId, certificateId: c.id! }).pipe(
114 Effect.retry({
115 while: (e) => e._tag === "CertificatePendingDeployment",
116 schedule: Schedule.spaced("5 seconds"),
117 times: 10,
118 }),
119 Effect.catchTag(
120 ["HostnameCertificateNotFound", "CertificatePendingDeletion"],
121 () => Effect.void,
122 ),
123 ),
124 );
125 });
126
127 test.provider(
128 "uploads and deletes a hostname client certificate",
129 (stack) =>
130 Effect.gen(function* () {
131 const zoneId = yield* resolveZoneId;
132
133 // Dedicated PEM (CERT_9): the sibling "replaces" test churns CERT_3
134 // concurrently under the global concurrent config, and its
135 // `pending_deletion` tombstone for CERT_3 would otherwise collide here
136 // (a re-upload resurrects the half-deleted cert, which never goes live).
137 yield* stack.destroy();
138 yield* purgeCertificates(zoneId, [CERT_9]);
139
140 const cert = yield* stack.deploy(
141 Cloudflare.OriginTlsClientAuth.HostnameCertificate("AopHostCert", {
142 zoneId,
143 certificate: CERT_9,
144 privateKey: Redacted.make(KEY_9),
145 }),
146 );
147
148 expect(cert.certificateId).toBeDefined();
149 expect(cert.zoneId).toEqual(zoneId);
150 expect(cert.status).toBeDefined();
151 expect(cert.issuer).toContain("Alchemy AOP Test Cert 9");
152
153 const actual = yield* waitForLive(zoneId, cert.certificateId);
154 expect(actual.id).toEqual(cert.certificateId);
155 expect(actual.status).not.toEqual("deleted");
156 expect(actual.status).not.toEqual("pending_deletion");
157
158 yield* stack.destroy();
159
160 yield* waitForGone(zoneId, cert.certificateId);
161 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
162 {
163 tags: [
164 "provider:cloudflare",
165 "provider:cloudflare:origintlsclientauth",
166 "provider:cloudflare:zone",
167 "live",
168 ],
169 timeout: 120_000,
170 },
171 );
172
173 test.provider(
174 "replaces the hostname certificate when the PEM changes",
175 (stack) =>
176 Effect.gen(function* () {
177 const zoneId = yield* resolveZoneId;
178
179 yield* stack.destroy();
180 yield* purgeCertificates(zoneId, [CERT_3, CERT_4]);
181
182 const original = yield* stack.deploy(
183 Cloudflare.OriginTlsClientAuth.HostnameCertificate("ReplaceHostCert", {
184 zoneId,
185 certificate: CERT_3,
186 privateKey: Redacted.make(KEY_3),
187 }),
188 );
189
190 const replaced = yield* stack.deploy(
191 Cloudflare.OriginTlsClientAuth.HostnameCertificate("ReplaceHostCert", {
192 zoneId,
193 certificate: CERT_4,
194 privateKey: Redacted.make(KEY_4),
195 }),
196 );
197
198 expect(replaced.certificateId).toBeDefined();
199 expect(replaced.certificateId).not.toEqual(original.certificateId);
200 expect(replaced.issuer).toContain("Alchemy AOP Test Cert 4");
201
202 // The old certificate must be gone after the replacement completes.
203 yield* waitForGone(zoneId, original.certificateId);
204
205 const actual = yield* getCertificate(zoneId, replaced.certificateId);
206 expect(actual.id).toEqual(replaced.certificateId);
207
208 yield* stack.destroy();
209
210 yield* waitForGone(zoneId, replaced.certificateId);
211 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
212 {
213 tags: [
214 "provider:cloudflare",
215 "provider:cloudflare:origintlsclientauth",
216 "provider:cloudflare:zone",
217 "live",
218 ],
219 timeout: 120_000,
220 },
221 );
222
223 test.provider(
224 "recovers a creating-state row whose Output-valued certificate was lost (#736)",
225 (stack) =>
226 Effect.gen(function* () {
227 const zoneId = yield* resolveZoneId;
228
229 // Dedicated PEM (CERT_2): the other hostname-certificate tests own
230 // CERT_3/4/8/9; CERT_2 is otherwise only used by the *zone-level*
231 // Certificate suite, which is a separate Cloudflare collection.
232 yield* stack.destroy();
233 yield* purgeCertificates(zoneId, [CERT_2]);
234
235 const deployCert = () =>
236 stack.deploy(
237 Cloudflare.OriginTlsClientAuth.HostnameCertificate("WedgedHostCert", {
238 zoneId,
239 certificate: CERT_2,
240 privateKey: Redacted.make(KEY_2),
241 }),
242 );
243
244 const created = yield* deployCert();
245 expect(created.certificateId).toBeDefined();
246
247 // Rewrite the persisted row into the wedged shape an interrupted deploy
248 // leaves behind when `certificate` was Output-valued: `creating`, no
249 // attributes, and the certificate lost in the round-trip (#736).
250 const state = yield* yield* State;
251 const stage = stack.stage;
252 const fqns = yield* state.list({ stack: stack.name, stage });
253 const rows = yield* Effect.forEach(fqns, (fqn) =>
254 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
255 );
256 const wedged = rows.find(
257 (r): r is { fqn: string; row: ResourceState } =>
258 isResourceState(r.row) &&
259 r.row.resourceType === "Cloudflare.OriginTlsClientAuth.HostnameCertificate",
260 );
261 if (!wedged) {
262 return yield* Effect.die(new Error("no HostnameCertificate state row found after deploy"));
263 }
264 yield* state.set({
265 stack: stack.name,
266 stage,
267 fqn: wedged.fqn,
268 value: {
269 ...wedged.row,
270 status: "creating",
271 attr: undefined,
272 props: { ...wedged.row.props, certificate: undefined },
273 },
274 });
275
276 // `read` cannot content-match without `olds.certificate`, so planning
277 // falls through to `diff` with the junk olds. Before the fix this
278 // crashed with `TypeError: undefined is not an object (evaluating
279 // 'pem.trim')` in normalizePem; after it, diff falls through and
280 // reconcile re-adopts the live certificate by PEM content.
281 const recovered = yield* deployCert();
282 expect(recovered.certificateId).toEqual(created.certificateId);
283
284 yield* stack.destroy();
285
286 yield* waitForGone(zoneId, recovered.certificateId);
287 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
288 {
289 tags: [
290 "provider:cloudflare",
291 "provider:cloudflare:origintlsclientauth",
292 "provider:cloudflare:zone",
293 "live",
294 ],
295 timeout: 120_000,
296 },
297 );
298
299 test.provider(
300 "list enumerates the deployed hostname certificate",
301 (stack) =>
302 Effect.gen(function* () {
303 const zoneId = yield* resolveZoneId;
304
305 yield* stack.destroy();
306 yield* purgeCertificates(zoneId, [CERT_8]);
307
308 const cert = yield* stack.deploy(
309 Cloudflare.OriginTlsClientAuth.HostnameCertificate("ListHostCert", {
310 zoneId,
311 // Dedicated PEM (see fixtures/certs.ts): keeps this certificate out
312 // of the upload/delete churn the sibling tests put CERT_3 through,
313 // so it appears in the eventually-consistent list promptly.
314 certificate: CERT_8,
315 privateKey: Redacted.make(KEY_8),
316 }),
317 );
318
319 const provider = yield* Provider.findProvider(
320 Cloudflare.OriginTlsClientAuth.HostnameCertificate,
321 );
322 // A freshly uploaded certificate can lag the zone list endpoint by
323 // tens of seconds — especially when the same PEM was recently deleted
324 // and re-created (the prior suites churn CERT_3), so the list endpoint
325 // keeps serving the stale "gone" view for a while. Poll list() until it
326 // appears, bounded to ~60s.
327 const found = yield* provider.list().pipe(
328 Effect.map((all) => all.find((c) => c.certificateId === cert.certificateId)),
329 Effect.flatMap((match) =>
330 match ? Effect.succeed(match) : Effect.fail({ _tag: "CertificateNotListed" } as const),
331 ),
332 Effect.retry({
333 while: (e) => e._tag === "CertificateNotListed",
334 schedule: Schedule.spaced("3 seconds"),
335 times: 20,
336 }),
337 );
338 expect(found.zoneId).toEqual(zoneId);
339
340 yield* stack.destroy();
341
342 yield* waitForGone(zoneId, cert.certificateId);
343 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
344 {
345 tags: [
346 "provider:cloudflare",
347 "provider:cloudflare:origintlsclientauth",
348 "provider:cloudflare:zone",
349 "live",
350 ],
351 timeout: 120_000,
352 },
353 );