@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, 07:15 UTC

main
ts 347 lines 12.7 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import type { InferEnv } from "@alchemy.run/cloudflare/Workers/InferEnv";
4 import { describe, expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as mtls from "@distilled.cloud/cloudflare/mtls-certificates";
7 import * as workers from "@distilled.cloud/cloudflare/workers";
8 import * as Provider from "alchemy/Provider";
9 import { poll } from "alchemy/Util/poll";
10 import * as Effect from "effect/Effect";
11 import * as Redacted from "effect/Redacted";
12 import { MinimumLogLevel } from "effect/References";
13 import * as Schedule from "effect/Schedule";
14 import { expectUrlContains } from "../Utils/Http.ts";
15 import { waitForWorkerToBeDeleted } from "../Utils/Worker.ts";
16 import { CA_CERT_1, CA_CERT_2, LEAF_CERT, LEAF_KEY } from "./fixtures/certs.ts";
17 import MtlsFetchWorker, { FetchCert } from "./fixtures/fetch-worker.ts";
18
19 const { test } = Test.make({ providers: Cloudflare.providers() });
20
21 // Compile-time: an MtlsCertificate in `env` is typed as a Fetcher.
22 type CertEnv = InferEnv<{ CERT: Cloudflare.MtlsCertificate.MtlsCertificate }>;
23 const _certIsFetcher: CertEnv["CERT"] extends Fetcher ? true : never = true;
24 void _certIsFetcher;
25
26 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
27
28 // Cloudflare dedups mTLS certificates by PEM content account-wide and rejects
29 // a duplicate upload with `CertificateAlreadyExists` (code 1471). Three of
30 // these cases upload the same `CA_CERT_1`, so under the suite's default
31 // concurrent execution they collide on identical content (and the
32 // adopt-by-content recovery races a sibling that is mid-create or mid-delete).
33 // `describe.sequential` runs them one at a time so each create→…→destroy owns
34 // the content exclusively.
35 describe.sequential(
36 "MtlsCertificate",
37 { tags: ["provider:cloudflare", "provider:cloudflare:mtlscertificate", "live"] },
38 () => {
39 test.provider("create and delete a CA certificate", (stack) =>
40 Effect.gen(function* () {
41 const { accountId } = yield* yield* CloudflareEnvironment;
42
43 yield* stack.destroy();
44
45 const cert = yield* stack.deploy(
46 Cloudflare.MtlsCertificate.MtlsCertificate("CaCert", {
47 ca: true,
48 certificates: CA_CERT_1,
49 }),
50 );
51
52 expect(cert.mtlsCertificateId).toBeDefined();
53 expect(cert.ca).toEqual(true);
54 expect(cert.name).toBeDefined();
55 expect(cert.expiresOn).toBeDefined();
56
57 const actual = yield* mtls.getMtlsCertificate({
58 accountId,
59 mtlsCertificateId: cert.mtlsCertificateId,
60 });
61 expect(actual.id).toEqual(cert.mtlsCertificateId);
62 expect(actual.ca).toEqual(true);
63 expect(actual.name).toEqual(cert.name);
64
65 yield* stack.destroy();
66
67 yield* waitForDelete(accountId, cert.mtlsCertificateId);
68 }).pipe(logLevel),
69 );
70
71 test.provider("create and delete a leaf certificate with private key", (stack) =>
72 Effect.gen(function* () {
73 const { accountId } = yield* yield* CloudflareEnvironment;
74
75 yield* stack.destroy();
76
77 const cert = yield* stack.deploy(
78 Cloudflare.MtlsCertificate.MtlsCertificate("LeafCert", {
79 ca: false,
80 certificates: LEAF_CERT,
81 privateKey: Redacted.make(LEAF_KEY),
82 }),
83 );
84
85 expect(cert.mtlsCertificateId).toBeDefined();
86 expect(cert.ca).toEqual(false);
87
88 const actual = yield* mtls.getMtlsCertificate({
89 accountId,
90 mtlsCertificateId: cert.mtlsCertificateId,
91 });
92 expect(actual.id).toEqual(cert.mtlsCertificateId);
93 expect(actual.ca).toEqual(false);
94
95 yield* stack.destroy();
96
97 yield* waitForDelete(accountId, cert.mtlsCertificateId);
98 }).pipe(logLevel),
99 );
100
101 test.provider("replaces the certificate when the PEM changes", (stack) =>
102 Effect.gen(function* () {
103 const { accountId } = yield* yield* CloudflareEnvironment;
104
105 yield* stack.destroy();
106
107 const original = yield* stack.deploy(
108 Cloudflare.MtlsCertificate.MtlsCertificate("ReplaceCert", {
109 ca: true,
110 certificates: CA_CERT_1,
111 }),
112 );
113
114 const replaced = yield* stack.deploy(
115 Cloudflare.MtlsCertificate.MtlsCertificate("ReplaceCert", {
116 ca: true,
117 certificates: CA_CERT_2,
118 }),
119 );
120
121 expect(replaced.mtlsCertificateId).toBeDefined();
122 expect(replaced.mtlsCertificateId).not.toEqual(original.mtlsCertificateId);
123 expect(replaced.serialNumber).not.toEqual(original.serialNumber);
124
125 // The old certificate must be gone after the replacement completes.
126 yield* waitForDelete(accountId, original.mtlsCertificateId);
127
128 const actual = yield* mtls.getMtlsCertificate({
129 accountId,
130 mtlsCertificateId: replaced.mtlsCertificateId,
131 });
132 expect(actual.id).toEqual(replaced.mtlsCertificateId);
133
134 yield* stack.destroy();
135
136 yield* waitForDelete(accountId, replaced.mtlsCertificateId);
137 }).pipe(logLevel),
138 );
139
140 // Regression for #2359: with an explicit name the replacement shares the
141 // old certificate's name. Cloudflare rejects duplicate names, so the
142 // replacement deletes first and uploads the new PEM instead of adopting
143 // the old certificate by name.
144 test.provider("replaces a named certificate when the PEM changes", (stack) =>
145 Effect.gen(function* () {
146 const { accountId } = yield* yield* CloudflareEnvironment;
147 const name = `alchemy-mtls-named-${stack.stage}`.toLowerCase();
148
149 yield* stack.destroy();
150
151 const original = yield* stack.deploy(
152 Cloudflare.MtlsCertificate.MtlsCertificate("NamedReplaceCert", {
153 name,
154 ca: true,
155 certificates: CA_CERT_1,
156 }),
157 );
158
159 const replacePlan = yield* stack.plan(
160 Cloudflare.MtlsCertificate.MtlsCertificate("NamedReplaceCert", {
161 name,
162 ca: true,
163 certificates: CA_CERT_2,
164 }),
165 );
166 const replaceChange = replacePlan.resources.NamedReplaceCert!;
167 expect(replaceChange.action).toEqual("replace");
168 if (replaceChange.action === "replace") expect(replaceChange.deleteFirst).toBe(true);
169
170 const replaced = yield* stack.deploy(
171 Cloudflare.MtlsCertificate.MtlsCertificate("NamedReplaceCert", {
172 name,
173 ca: true,
174 certificates: CA_CERT_2,
175 }),
176 );
177
178 expect(replaced.name).toEqual(name);
179 expect(replaced.mtlsCertificateId).not.toEqual(original.mtlsCertificateId);
180 expect(replaced.serialNumber).not.toEqual(original.serialNumber);
181
182 yield* waitForDelete(accountId, original.mtlsCertificateId);
183
184 const actual = yield* mtls.getMtlsCertificate({
185 accountId,
186 mtlsCertificateId: replaced.mtlsCertificateId,
187 });
188 expect(actual.certificates?.trim()).toEqual(CA_CERT_2.trim());
189
190 // State now matches the cloud, so a redeploy is a noop.
191 const plan = yield* stack.plan(
192 Cloudflare.MtlsCertificate.MtlsCertificate("NamedReplaceCert", {
193 name,
194 ca: true,
195 certificates: CA_CERT_2,
196 }),
197 );
198 expect(plan.resources.NamedReplaceCert!.action).toEqual("noop");
199
200 yield* stack.destroy();
201
202 yield* waitForDelete(accountId, replaced.mtlsCertificateId);
203 }).pipe(logLevel),
204 );
205
206 // A certificate passed in a Worker's `env` becomes an `mtls_certificate`
207 // binding, exposed to the Worker as a Fetcher (#2048). On destroy,
208 // right after the Worker is deleted, Cloudflare still rejects the
209 // certificate delete with "Certificate cannot be deleted while in use."
210 // Destroy must ride that out (#2080).
211 test.provider(
212 "binds a certificate in Worker env and destroys it after the Worker",
213 (stack) =>
214 Effect.gen(function* () {
215 const { accountId } = yield* yield* CloudflareEnvironment;
216
217 yield* stack.destroy();
218
219 const { cert, worker } = yield* stack.deploy(
220 Effect.gen(function* () {
221 const cert = yield* Cloudflare.MtlsCertificate.MtlsCertificate("BoundCert", {
222 ca: false,
223 certificates: LEAF_CERT,
224 privateKey: Redacted.make(LEAF_KEY),
225 });
226 const worker = yield* Cloudflare.Worker("MtlsBoundWorker", {
227 script: `export default {
228 fetch: (_request, env) => new Response("cert-fetch:" + typeof env.CERT?.fetch),
229 };`,
230 env: { CERT: cert },
231 });
232 return { cert, worker };
233 }),
234 );
235
236 const settings = yield* workers.getScriptScriptAndVersionSetting({
237 accountId,
238 scriptName: worker.workerName,
239 });
240 expect(
241 (settings.bindings ?? []).some(
242 (b) => b.type === "mtls_certificate" && b.certificateId === cert.mtlsCertificateId,
243 ),
244 ).toBe(true);
245 // The runtime hands the Worker a Fetcher for the binding.
246 yield* expectUrlContains(worker.url!, "cert-fetch:function", {
247 timeout: "60 seconds",
248 label: "mtls_certificate binding is a Fetcher",
249 });
250
251 yield* stack.destroy();
252
253 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
254 yield* waitForDelete(accountId, cert.mtlsCertificateId);
255 }).pipe(logLevel),
256 { timeout: 180_000 },
257 );
258
259 // `Cloudflare.MtlsCertificate.Fetch` binds the certificate from an Effect
260 // Worker and sends requests through it.
261 test.provider(
262 "an Effect Worker sends requests through the Fetch binding",
263 (stack) =>
264 Effect.gen(function* () {
265 const { accountId } = yield* yield* CloudflareEnvironment;
266
267 yield* stack.destroy();
268
269 const { cert, worker } = yield* stack.deploy(
270 Effect.gen(function* () {
271 const worker = yield* MtlsFetchWorker;
272 const cert = yield* FetchCert;
273 return { cert, worker };
274 }),
275 );
276
277 const settings = yield* workers.getScriptScriptAndVersionSetting({
278 accountId,
279 scriptName: worker.workerName,
280 });
281 expect(
282 (settings.bindings ?? []).some(
283 (b) =>
284 b.type === "mtls_certificate" &&
285 b.name === "FetchCert" &&
286 b.certificateId === cert.mtlsCertificateId,
287 ),
288 ).toBe(true);
289 yield* expectUrlContains(worker.url!, "origin-status:200", {
290 timeout: "60 seconds",
291 label: "request sent through the mTLS Fetch binding",
292 });
293
294 yield* stack.destroy();
295
296 yield* waitForWorkerToBeDeleted(worker.workerName, accountId);
297 yield* waitForDelete(accountId, cert.mtlsCertificateId);
298 }).pipe(logLevel),
299 { timeout: 180_000 },
300 );
301
302 test.provider("list enumerates the deployed mTLS certificate", (stack) =>
303 Effect.gen(function* () {
304 const { accountId } = yield* yield* CloudflareEnvironment;
305
306 yield* stack.destroy();
307
308 const cert = yield* stack.deploy(
309 Cloudflare.MtlsCertificate.MtlsCertificate("ListCert", {
310 ca: true,
311 certificates: CA_CERT_1,
312 }),
313 );
314
315 const provider = yield* Provider.findProvider(Cloudflare.MtlsCertificate.MtlsCertificate);
316
317 // A freshly-deployed certificate is eventually consistent in the
318 // account-wide list(); poll until it appears before asserting.
319 const all = yield* poll({
320 description: "list() includes the deployed mTLS certificate",
321 effect: provider.list(),
322 predicate: (all) => all.some((c) => c.mtlsCertificateId === cert.mtlsCertificateId),
323 });
324
325 expect(all.some((c) => c.mtlsCertificateId === cert.mtlsCertificateId)).toBe(true);
326
327 yield* stack.destroy();
328
329 yield* waitForDelete(accountId, cert.mtlsCertificateId);
330 }).pipe(logLevel),
331 );
332 },
333 );
334
335 const waitForDelete = (accountId: string, mtlsCertificateId: string) =>
336 mtls.getMtlsCertificate({ accountId, mtlsCertificateId }).pipe(
337 Effect.flatMap((cert) =>
338 cert.id === mtlsCertificateId
339 ? Effect.fail({ _tag: "CertificateNotDeleted" } as const)
340 : Effect.void,
341 ),
342 Effect.catchTag("CertificateNotFound", () => Effect.void),
343 Effect.retry({
344 while: (e) => e._tag === "CertificateNotDeleted",
345 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
346 }),
347 );