@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 265 lines 11.1 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 { describe, 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 * as Effect from "effect/Effect";
9 import * as Redacted from "effect/Redacted";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import { CERT_1, CERT_2, CERT_7, KEY_1, KEY_2, KEY_7 } from "./fixtures/certs.ts";
13
14 const { test } = Test.make({ providers: Cloudflare.providers() });
15
16 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
17
18 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
19
20 const resolveZoneId = Effect.gen(function* () {
21 const { accountId } = yield* yield* CloudflareEnvironment;
22 const zone = yield* findZoneByName({ accountId, name: zoneName });
23 if (!zone) {
24 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
25 }
26 return zone.id;
27 });
28
29 // The scoped API token the test harness mints propagates eventually-
30 // consistently across Cloudflare's edge — a fresh token intermittently 403s
31 // with "Unable to authenticate request". Ride out the blips on the test's
32 // own out-of-band calls by retrying the typed `Forbidden` error (part of
33 // each operation's error union via distilled patches).
34 //
35 // CAPPED at 3s: a bare `Schedule.exponential("500 millis")` reaches a 64s
36 // single delay by the 8th retry (~127s total), so a token blip would sleep
37 // for over a minute between attempts and blow the test budget even though the
38 // blip itself clears in seconds. Capping keeps the cadence steady.
39 const forbiddenRetrySchedule = Schedule.min([
40 Schedule.exponential("500 millis"),
41 Schedule.spaced("3 seconds"),
42 ]);
43
44 const getCertificate = (zoneId: string, certificateId: string) =>
45 originTls.getOriginTlsClientAuth({ zoneId, certificateId }).pipe(
46 Effect.retry({
47 while: (e) => e._tag === "Forbidden",
48 schedule: forbiddenRetrySchedule,
49 times: 8,
50 }),
51 );
52
53 // Cloudflare keeps deleted zone client certificates readable by id as
54 // `pending_deletion` / `deleted` tombstones (and excludes them from list),
55 // so "gone" means tombstoned or 404.
56 const waitForGone = (zoneId: string, certificateId: string) =>
57 getCertificate(zoneId, certificateId).pipe(
58 Effect.flatMap((cert) =>
59 cert.status === "pending_deletion" || cert.status === "deleted"
60 ? Effect.void
61 : Effect.fail({ _tag: "CertificateNotDeleted" } as const),
62 ),
63 Effect.catchTag("CertificateNotFound", () => Effect.void),
64 Effect.retry({
65 while: (e) => e._tag === "CertificateNotDeleted",
66 // STEADY 3s cadence, bounded ~60s. The previous
67 // `Schedule.exponential("500 millis")` (capped only by `recurs(10)`)
68 // ramped to 64s/128s/256s single delays — so once a tombstone lagged a
69 // little, the poll would *sleep* far past the deadline before noticing
70 // the cert was already gone. That overshoot — not genuinely-slow CF —
71 // was what blew the test budget. A fixed interval detects the tombstone
72 // within one poll of it actually happening.
73 schedule: Schedule.max([Schedule.spaced("3 seconds"), Schedule.recurs(45)]),
74 }),
75 );
76
77 // Purge any live zone client certificates left behind by interrupted runs so
78 // each test starts from a clean slate (the zone-level cert store is only
79 // exercised by this suite).
80 const purgeCertificates = (zoneId: string) =>
81 Effect.gen(function* () {
82 const list = yield* originTls.listOriginTlsClientAuths({ zoneId }).pipe(
83 Effect.retry({
84 while: (e) => e._tag === "Forbidden",
85 schedule: forbiddenRetrySchedule,
86 times: 8,
87 }),
88 );
89 yield* Effect.forEach(
90 (list.result ?? []).filter(
91 (c) => c.id && c.status !== "deleted" && c.status !== "pending_deletion",
92 ),
93 (c) =>
94 originTls.deleteOriginTlsClientAuth({ zoneId, certificateId: c.id! }).pipe(
95 // A leftover cert still propagating its initial deployment rejects
96 // the delete with code 1434 (pending deployment); ride it out so
97 // the purge actually clears the slate instead of cascading. A
98 // delete racing a sibling per-zone mutation is rejected with HTTP
99 // 409 (`ZoneClientCertConflict`) — retry that too.
100 Effect.retry({
101 while: (e) =>
102 e._tag === "CertificatePendingDeployment" || e._tag === "ZoneClientCertConflict",
103 schedule: Schedule.spaced("5 seconds"),
104 times: 12,
105 }),
106 // Deletion is idempotent: a cert that flipped into (or past)
107 // deletion between the list and this call answers HTTP 400
108 // "Certificate is already deleted." — both mean it is gone.
109 Effect.catchTag(["CertificateNotFound", "CertificateAlreadyDeleted"], () => Effect.void),
110 ),
111 );
112 });
113
114 // The zone client-certificate store dedups by PEM content and the upload /
115 // delete lifecycle is eventually consistent, so two cases uploading the same
116 // `CERT_1` concurrently churn each other (collisions + stale list views).
117 // Run the cases one at a time so each owns its certificate content.
118 describe.sequential(
119 "Certificate",
120 {
121 tags: [
122 "provider:cloudflare",
123 "provider:cloudflare:origintlsclientauth",
124 "provider:cloudflare:zone",
125 "live",
126 ],
127 },
128 () => {
129 test.provider(
130 "uploads and deletes a zone client certificate",
131 (stack) =>
132 Effect.gen(function* () {
133 const zoneId = yield* resolveZoneId;
134
135 yield* stack.destroy();
136 yield* purgeCertificates(zoneId);
137
138 const cert = yield* stack.deploy(
139 Cloudflare.OriginTlsClientAuth.Certificate("AopCert", {
140 zoneId,
141 certificate: CERT_1,
142 privateKey: Redacted.make(KEY_1),
143 }),
144 );
145
146 expect(cert.certificateId).toBeDefined();
147 expect(cert.zoneId).toEqual(zoneId);
148 expect(cert.status).toBeDefined();
149 expect(cert.expiresOn).toBeDefined();
150 expect(cert.issuer).toContain("Alchemy AOP Test Cert 1");
151
152 const actual = yield* getCertificate(zoneId, cert.certificateId);
153 expect(actual.id).toEqual(cert.certificateId);
154 expect(actual.status).not.toEqual("deleted");
155 expect(actual.status).not.toEqual("pending_deletion");
156
157 yield* stack.destroy();
158
159 yield* waitForGone(zoneId, cert.certificateId);
160 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
161 { timeout: 200_000 },
162 );
163
164 test.provider(
165 "replaces the certificate when the PEM changes",
166 (stack) =>
167 Effect.gen(function* () {
168 const zoneId = yield* resolveZoneId;
169
170 yield* stack.destroy();
171 yield* purgeCertificates(zoneId);
172
173 const original = yield* stack.deploy(
174 Cloudflare.OriginTlsClientAuth.Certificate("ReplaceCert", {
175 zoneId,
176 certificate: CERT_1,
177 privateKey: Redacted.make(KEY_1),
178 }),
179 );
180
181 const replaced = yield* stack.deploy(
182 Cloudflare.OriginTlsClientAuth.Certificate("ReplaceCert", {
183 zoneId,
184 certificate: CERT_2,
185 privateKey: Redacted.make(KEY_2),
186 }),
187 );
188
189 expect(replaced.certificateId).toBeDefined();
190 expect(replaced.certificateId).not.toEqual(original.certificateId);
191 expect(replaced.issuer).toContain("Alchemy AOP Test Cert 2");
192
193 // The old certificate must be gone after the replacement completes.
194 yield* waitForGone(zoneId, original.certificateId);
195
196 const actual = yield* getCertificate(zoneId, replaced.certificateId);
197 expect(actual.id).toEqual(replaced.certificateId);
198
199 yield* stack.destroy();
200
201 yield* waitForGone(zoneId, replaced.certificateId);
202 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
203 { timeout: 200_000 },
204 );
205
206 // Canonical `list()` test (zone-scoped collection): `list()` fans out over
207 // every zone via `listAllZones` and enumerates the per-zone certificate store,
208 // hydrating each into the same `read` Attributes shape. Deploy a certificate
209 // to the standing test zone and assert it appears in the exhaustive result.
210 test.provider(
211 "list enumerates the deployed zone client certificate",
212 (stack) =>
213 Effect.gen(function* () {
214 const zoneId = yield* resolveZoneId;
215
216 yield* stack.destroy();
217 yield* purgeCertificates(zoneId);
218
219 const cert = yield* stack.deploy(
220 Cloudflare.OriginTlsClientAuth.Certificate("ListCert", {
221 zoneId,
222 // Dedicated PEM (see fixtures/certs.ts): keeps this certificate out
223 // of the upload/delete churn the sibling tests put CERT_1 through,
224 // so it appears in the eventually-consistent list promptly.
225 certificate: CERT_7,
226 privateKey: Redacted.make(KEY_7),
227 }),
228 );
229
230 const provider = yield* Provider.findProvider(Cloudflare.OriginTlsClientAuth.Certificate);
231 // A freshly uploaded certificate can lag the zone list endpoint by tens
232 // of seconds — especially when the same PEM was recently deleted and
233 // re-created (the sibling tests churn CERT_1), so the list endpoint
234 // keeps serving the stale "gone" view for a while. Poll list() until it
235 // appears, bounded to ~60s, rather than asserting on a single read.
236 const found = yield* provider.list().pipe(
237 Effect.map((all) => all.find((c) => c.certificateId === cert.certificateId)),
238 Effect.flatMap((match) =>
239 match
240 ? Effect.succeed(match)
241 : Effect.fail({ _tag: "CertificateNotListed" } as const),
242 ),
243 Effect.retry({
244 while: (e) => e._tag === "CertificateNotListed",
245 schedule: Schedule.spaced("3 seconds"),
246 times: 20,
247 }),
248 );
249 expect(found.zoneId).toEqual(zoneId);
250
251 yield* stack.destroy();
252
253 yield* waitForGone(zoneId, cert.certificateId);
254 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
255 // With the poll backoffs now CAPPED (steady cadence, see
256 // `waitForGone`/`forbiddenRetrySchedule`), this test's three sequential
257 // eventual-consistency waits are each bounded to ~60s — the list-appear
258 // poll, the destroy's pending-deployment delete retry, and `waitForGone` —
259 // for a deterministic worst case of ~200s. The timeout matches that bound;
260 // 120s was below the legitimate maximum (the acute flake was the old
261 // uncapped exponential sleeping past the deadline, now fixed).
262 { timeout: 240_000 },
263 );
264 },
265 );