@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 299 lines 13 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 { testName } from "../../names.ts";
13 import { CERT_5, CERT_6, KEY_5, KEY_6 } from "./fixtures/certs.ts";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
20
21 // Deterministic per-test hostnames. Each test owns a disjoint subdomain so
22 // reruns never collide (never derive names from Date.now()/random).
23 const HOST_LIFECYCLE = `${testName("alchemy-aop-assoc")}.${zoneName}`;
24 const HOST_REPLACE_A = `${testName("alchemy-aop-assoc-replace-a")}.${zoneName}`;
25 const HOST_REPLACE_B = `${testName("alchemy-aop-assoc-replace-b")}.${zoneName}`;
26
27 const resolveZoneId = Effect.gen(function* () {
28 const { accountId } = yield* yield* CloudflareEnvironment;
29 const zone = yield* findZoneByName({ accountId, name: zoneName });
30 if (!zone) {
31 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
32 }
33 return zone.id;
34 });
35
36 // The scoped API token the test harness mints propagates eventually-
37 // consistently across Cloudflare's edge — a fresh token intermittently 403s
38 // with "Unable to authenticate request". Ride out the blips on the test's
39 // own out-of-band calls by retrying the typed `Forbidden` error (part of
40 // each operation's error union via distilled patches).
41 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
42
43 // Read a hostname's association out-of-band; "never configured" (404 / code
44 // 1553) and "voided" (`enabled: null`) both read as undefined.
45 const getAssociation = (zoneId: string, hostname: string) =>
46 originTls.getHostname({ zoneId, hostname }).pipe(
47 Effect.map((assoc) =>
48 assoc.enabled === null || assoc.enabled === undefined ? undefined : assoc,
49 ),
50 Effect.catchTag("HostnameAssociationNotFound", () => Effect.succeed(undefined)),
51 Effect.retry({
52 while: (e) => e._tag === "Forbidden",
53 schedule: forbiddenRetrySchedule,
54 times: 8,
55 }),
56 );
57
58 // Void any association left behind by interrupted runs so the test starts
59 // from a clean slate.
60 const voidAssociation = (zoneId: string, hostname: string) =>
61 Effect.gen(function* () {
62 const observed = yield* getAssociation(zoneId, hostname);
63 if (!observed?.certId) return;
64 yield* originTls
65 .putHostname({ zoneId, config: [{ hostname, certId: observed.certId, enabled: null }] })
66 .pipe(
67 // The pinned certificate may already be gone (code 1415); the
68 // association is inert without it.
69 Effect.catchTag("InvalidHostnameConfig", () => Effect.void),
70 );
71 });
72
73 // Purge any live hostname client certificates with this suite's fixture PEMs
74 // left behind by interrupted runs. Filtering by PEM content keeps the purge
75 // scoped to this file — other suites in the directory own other fixtures.
76 const purgeCertificates = (zoneId: string, pems: string[]) =>
77 Effect.gen(function* () {
78 const list = yield* originTls.listHostnameCertificates({ zoneId }).pipe(
79 Effect.retry({
80 while: (e) => e._tag === "Forbidden",
81 schedule: forbiddenRetrySchedule,
82 times: 8,
83 }),
84 );
85 const targets = pems.map((p) => p.trim());
86 yield* Effect.forEach(
87 list.result.filter(
88 (c) =>
89 c.id &&
90 c.status !== "deleted" &&
91 c.status !== "pending_deletion" &&
92 targets.includes((c.certificate ?? "").trim()),
93 ),
94 (c) =>
95 originTls.deleteHostnameCertificate({ zoneId, certificateId: c.id! }).pipe(
96 Effect.retry({
97 while: (e) =>
98 e._tag === "CertificatePendingDeployment" || e._tag === "HostnameCertificateInUse",
99 schedule: Schedule.spaced("5 seconds"),
100 times: 10,
101 }),
102 Effect.catchTag(
103 ["HostnameCertificateNotFound", "CertificatePendingDeletion"],
104 () => Effect.void,
105 ),
106 ),
107 );
108 });
109
110 // Both certificates stay deployed across every step so updates/replacements
111 // only touch the association itself (replacing a resource while removing its
112 // old dependency in the same deploy is a known engine deadlock).
113 const program = (opts: { zoneId: string; hostname: string; cert: "5" | "6"; enabled: boolean }) =>
114 Effect.gen(function* () {
115 const cert5 = yield* Cloudflare.OriginTlsClientAuth.HostnameCertificate("AssocCert5", {
116 zoneId: opts.zoneId,
117 certificate: CERT_5,
118 privateKey: Redacted.make(KEY_5),
119 });
120 const cert6 = yield* Cloudflare.OriginTlsClientAuth.HostnameCertificate("AssocCert6", {
121 zoneId: opts.zoneId,
122 certificate: CERT_6,
123 privateKey: Redacted.make(KEY_6),
124 });
125 const pinned = opts.cert === "6" ? cert6 : cert5;
126 const association = yield* Cloudflare.OriginTlsClientAuth.HostnameAssociation("AopHost", {
127 zoneId: opts.zoneId,
128 hostname: opts.hostname,
129 certId: pinned.certificateId,
130 enabled: opts.enabled,
131 });
132 return { cert5, cert6, association };
133 });
134
135 describe.skipIf(!!process.env.FAST)(
136 "HostnameAssociation",
137 { tags: ["provider:cloudflare", "provider:cloudflare:origintlsclientauth", "live"] },
138 () => {
139 // Hostname associations are keyed entirely by {zoneId, hostname} and
140 // Cloudflare exposes no endpoint that enumerates which hostnames in a zone
141 // have an AOP association, so `list()` is non-listable and returns []. This
142 // read-only assertion always runs (no cert/hostname deploy required).
143 test.provider("list returns [] for the non-listable association", (stack) =>
144 Effect.gen(function* () {
145 yield* stack.destroy();
146
147 const provider = yield* Provider.findProvider(
148 Cloudflare.OriginTlsClientAuth.HostnameAssociation,
149 );
150 const all = yield* provider.list();
151 expect(all).toEqual([]);
152
153 yield* stack.destroy();
154 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
155 );
156
157 test.provider(
158 "associates a hostname, updates cert and enablement in place, voids on destroy",
159 (stack) =>
160 Effect.gen(function* () {
161 const zoneId = yield* resolveZoneId;
162
163 yield* stack.destroy();
164 yield* voidAssociation(zoneId, HOST_LIFECYCLE);
165 yield* purgeCertificates(zoneId, [CERT_5, CERT_6]);
166
167 // Create — pin cert 5, enabled.
168 const initial = yield* stack.deploy(
169 program({ zoneId, hostname: HOST_LIFECYCLE, cert: "5", enabled: true }),
170 );
171
172 expect(initial.association.zoneId).toEqual(zoneId);
173 expect(initial.association.hostname).toEqual(HOST_LIFECYCLE);
174 expect(initial.association.certId).toEqual(initial.cert5.certificateId);
175 expect(initial.association.enabled).toEqual(true);
176
177 const observed = yield* getAssociation(zoneId, HOST_LIFECYCLE);
178 expect(observed?.certId).toEqual(initial.cert5.certificateId);
179 expect(observed?.enabled).toEqual(true);
180
181 // Update in place — repin to cert 6 and disable enforcement.
182 const updated = yield* stack.deploy(
183 program({ zoneId, hostname: HOST_LIFECYCLE, cert: "6", enabled: false }),
184 );
185
186 expect(updated.association.hostname).toEqual(HOST_LIFECYCLE);
187 expect(updated.association.certId).toEqual(updated.cert6.certificateId);
188 expect(updated.association.enabled).toEqual(false);
189
190 const reobserved = yield* getAssociation(zoneId, HOST_LIFECYCLE);
191 expect(reobserved?.certId).toEqual(updated.cert6.certificateId);
192 expect(reobserved?.enabled).toEqual(false);
193
194 // Destroy — the association is voided (`enabled: null`).
195 yield* stack.destroy();
196
197 const gone = yield* getAssociation(zoneId, HOST_LIFECYCLE).pipe(
198 Effect.flatMap((assoc) =>
199 assoc === undefined
200 ? Effect.void
201 : Effect.fail({ _tag: "AssociationNotVoided" } as const),
202 ),
203 // Frequent, bounded spaced poll (~240s): voiding settles through
204 // edge propagation asynchronously and can occasionally take well
205 // past two minutes, so poll every 5s with a generous bound rather
206 // than backing off exponentially (whose late gaps overshoot).
207 Effect.retry({
208 while: (e) => e._tag === "AssociationNotVoided",
209 schedule: Schedule.spaced("5 seconds"),
210 times: 48,
211 }),
212 Effect.map(() => true),
213 );
214 expect(gone).toEqual(true);
215 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
216 // Two sequential deploys, each uploading two hostname client-certificates
217 // plus the association, on Cloudflare's per-zone-serialized client-cert
218 // API. Under a full concurrent `./test/Cloudflare` run this zone's cert
219 // mutations contend with the sibling Certificate/HostnameCertificate
220 // suites (each create/delete bounded-retries the per-zone 409), then a
221 // ~240s spaced void poll — give real headroom while staying bounded.
222 { tags: ["provider:cloudflare:zone"], timeout: 420_000 },
223 );
224
225 test.provider(
226 "replaces the association when the hostname changes",
227 (stack) =>
228 Effect.gen(function* () {
229 const zoneId = yield* resolveZoneId;
230
231 yield* stack.destroy();
232 yield* voidAssociation(zoneId, HOST_REPLACE_A);
233 yield* voidAssociation(zoneId, HOST_REPLACE_B);
234 yield* purgeCertificates(zoneId, [CERT_5, CERT_6]);
235
236 const initial = yield* stack.deploy(
237 program({ zoneId, hostname: HOST_REPLACE_A, cert: "5", enabled: true }),
238 );
239 expect(initial.association.hostname).toEqual(HOST_REPLACE_A);
240
241 // Changing the hostname is a replacement — the old hostname's
242 // association is voided and the new hostname gets its own entry.
243 const replaced = yield* stack.deploy(
244 program({ zoneId, hostname: HOST_REPLACE_B, cert: "5", enabled: true }),
245 );
246 expect(replaced.association.hostname).toEqual(HOST_REPLACE_B);
247 expect(replaced.association.certId).toEqual(replaced.cert5.certificateId);
248
249 const observedNew = yield* getAssociation(zoneId, HOST_REPLACE_B);
250 expect(observedNew?.enabled).toEqual(true);
251
252 // The old hostname's association must be voided by the replacement.
253 const oldGone = yield* getAssociation(zoneId, HOST_REPLACE_A).pipe(
254 Effect.flatMap((assoc) =>
255 assoc === undefined
256 ? Effect.void
257 : Effect.fail({ _tag: "AssociationNotVoided" } as const),
258 ),
259 // Frequent, bounded spaced poll (~120s): voiding settles through
260 // edge propagation asynchronously, so check every 5s rather than
261 // backing off exponentially (whose late gaps overshoot the timeout).
262 Effect.retry({
263 while: (e) => e._tag === "AssociationNotVoided",
264 schedule: Schedule.spaced("5 seconds"),
265 times: 24,
266 }),
267 Effect.map(() => true),
268 );
269 expect(oldGone).toEqual(true);
270
271 yield* stack.destroy();
272
273 // Voiding is asynchronous (the void PUT settles through edge
274 // propagation) — poll until the association reads as absent rather
275 // than asserting on a single (potentially stale) read.
276 const newGone = yield* getAssociation(zoneId, HOST_REPLACE_B).pipe(
277 Effect.flatMap((assoc) =>
278 assoc === undefined
279 ? Effect.void
280 : Effect.fail({ _tag: "AssociationNotVoided" } as const),
281 ),
282 // Frequent, bounded spaced poll (~120s): voiding settles through
283 // edge propagation asynchronously, so check every 5s rather than
284 // backing off exponentially (whose late gaps overshoot the timeout).
285 Effect.retry({
286 while: (e) => e._tag === "AssociationNotVoided",
287 schedule: Schedule.spaced("5 seconds"),
288 times: 24,
289 }),
290 Effect.map(() => true),
291 );
292 expect(newGone).toEqual(true);
293 }).pipe(Effect.ensuring(stack.destroy().pipe(Effect.orDie).pipe(Effect.ignore)), logLevel),
294 // Same per-zone-serialized client-cert contention as the lifecycle case
295 // above, plus two spaced void polls — give real headroom under load.
296 { tags: ["provider:cloudflare:zone"], timeout: 300_000 },
297 );
298 },
299 );