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

main
ts 234 lines 8.29 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import type { CertificateAttributes } from "@alchemy.run/cloudflare/Gateway/Certificate";
4 import { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
7 import * as Provider from "alchemy/Provider";
8 import * as Cause from "effect/Cause";
9 import * as Effect from "effect/Effect";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12
13 const { test } = Test.make({ providers: Cloudflare.providers() });
14
15 // Cloudflare caps Zero Trust certificate *generation* at 3 per 24h per account
16 // and does NOT refund that rolling counter on delete (it is separate from the
17 // "10 active certificates" count limit), so neither `stack.destroy()` nor
18 // `bun nuke` can reclaim budget. The replacement test mints two certificates
19 // per run, so it exhausts the quota fastest — skip it by default. Set
20 // RUN_GATEWAY_CERT_TESTS=1 to run it against an account with fresh daily budget.
21 const runGatewayCertTests = !!process.env.RUN_GATEWAY_CERT_TESTS;
22
23 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
24
25 // Ride out 403 blips (`Forbidden`) while the harness-minted token
26 // propagates across Cloudflare's edge.
27 const getCertificate = (accountId: string, certificateId: string) =>
28 zeroTrust.getGatewayCertificate({ accountId, certificateId }).pipe(
29 Effect.retry({
30 while: (e) => e._tag === "Forbidden",
31 schedule: Schedule.exponential("500 millis"),
32 times: 8,
33 }),
34 );
35
36 // A deleted certificate surfaces as `GatewayCertificateNotFound`
37 // (Cloudflare code 2027, "Certificate not found in SSL store").
38 const expectGone = (accountId: string, certificateId: string) =>
39 getCertificate(accountId, certificateId).pipe(
40 Effect.flatMap(() => Effect.fail({ _tag: "CertificateNotDeleted" } as const)),
41 Effect.catchTag("GatewayCertificateNotFound", () => Effect.void),
42 Effect.retry({
43 while: (e) => e._tag === "CertificateNotDeleted",
44 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
45 }),
46 );
47
48 /**
49 * Pull the typed {@link zeroTrust.GatewayCertificateQuotaReached} value out of
50 * a Cause regardless of whether the engine raised it as a failure or a defect.
51 */
52 const findQuotaError = (
53 cause: Cause.Cause<unknown>,
54 ): zeroTrust.GatewayCertificateQuotaReached | undefined =>
55 cause.reasons
56 .map((reason) =>
57 Cause.isFailReason(reason)
58 ? reason.error
59 : Cause.isDieReason(reason)
60 ? reason.defect
61 : undefined,
62 )
63 .find(
64 (value): value is zeroTrust.GatewayCertificateQuotaReached =>
65 value instanceof zeroTrust.GatewayCertificateQuotaReached,
66 );
67
68 /**
69 * Deploy, but converge a `GatewayCertificateQuotaReached` failure (Cloudflare
70 * caps gateway certificate creation at 3 per 24 hours per account) to
71 * `undefined` so the calling test can skip its assertions gracefully instead
72 * of failing on same-day reruns.
73 */
74 const deployUnlessQuotaReached = (
75 stack: Test.ScratchStack,
76 eff: Effect.Effect<any, any, any>,
77 ): Effect.Effect<CertificateAttributes | undefined, any, any> =>
78 stack
79 .deploy(eff)
80 .pipe(
81 Effect.catchCause((cause): Effect.Effect<CertificateAttributes | undefined, any, never> =>
82 findQuotaError(cause) ? Effect.succeed(undefined) : Effect.failCause(cause),
83 ),
84 );
85
86 const logQuotaSkip = (what: string) =>
87 Effect.logWarning(
88 `skipping ${what}: Cloudflare's 3-per-24h gateway certificate creation quota is exhausted (GatewayCertificateQuotaReached)`,
89 );
90
91 test.provider(
92 "create an activated certificate, deactivate in place, destroy",
93 (stack) =>
94 Effect.gen(function* () {
95 const { accountId } = yield* yield* CloudflareEnvironment;
96
97 yield* stack.destroy();
98
99 const cert = yield* deployUnlessQuotaReached(
100 stack,
101 Cloudflare.Gateway.Certificate("InspectionCa", {
102 validityPeriodDays: 30,
103 }),
104 );
105 if (cert === undefined) {
106 yield* logQuotaSkip("activate/deactivate assertions");
107 yield* stack.destroy();
108 return;
109 }
110
111 expect(cert.certificateId).toBeTruthy();
112 expect(cert.accountId).toEqual(accountId);
113 expect(cert.certificateType).toEqual("gateway_managed");
114 expect(cert.certificate).toContain("BEGIN CERTIFICATE");
115 expect(cert.fingerprint).toBeTruthy();
116 // Activation settles within seconds; the provider waits for it.
117 expect(cert.bindingStatus).toEqual("available");
118
119 const live = yield* getCertificate(accountId, cert.certificateId);
120 expect(live.bindingStatus).toEqual("available");
121 expect(live.fingerprint).toEqual(cert.fingerprint);
122
123 // Deactivate in place — same certificate, new binding status.
124 const deactivated = yield* stack.deploy(
125 Cloudflare.Gateway.Certificate("InspectionCa", {
126 validityPeriodDays: 30,
127 activate: false,
128 }),
129 );
130 expect(deactivated.certificateId).toEqual(cert.certificateId);
131 expect(deactivated.bindingStatus).toEqual("inactive");
132
133 yield* stack.destroy();
134 yield* expectGone(accountId, cert.certificateId);
135 }).pipe(logLevel),
136 {
137 tags: ["provider:cloudflare", "provider:cloudflare:gateway", "live"],
138 timeout: 120_000,
139 },
140 );
141
142 test.provider.skipIf(!runGatewayCertTests)(
143 "changing the validity period replaces the certificate",
144 (stack) =>
145 Effect.gen(function* () {
146 const { accountId } = yield* yield* CloudflareEnvironment;
147
148 yield* stack.destroy();
149
150 // Keep both generations inactive so the test stays fast — no edge
151 // activation round-trips.
152 const first = yield* deployUnlessQuotaReached(
153 stack,
154 Cloudflare.Gateway.Certificate("ShortCa", {
155 validityPeriodDays: 30,
156 activate: false,
157 }),
158 );
159 if (first === undefined) {
160 yield* logQuotaSkip("replacement assertions");
161 yield* stack.destroy();
162 return;
163 }
164 expect(first.bindingStatus).toEqual("inactive");
165
166 const second = yield* deployUnlessQuotaReached(
167 stack,
168 Cloudflare.Gateway.Certificate("ShortCa", {
169 validityPeriodDays: 60,
170 activate: false,
171 }),
172 );
173 if (second === undefined) {
174 yield* logQuotaSkip("replacement assertions (second generation)");
175 yield* stack.destroy();
176 return;
177 }
178 // The validity period is immutable — a new certificate is minted
179 // and the old one deleted.
180 expect(second.certificateId).not.toEqual(first.certificateId);
181 yield* expectGone(accountId, first.certificateId);
182
183 yield* stack.destroy();
184 yield* expectGone(accountId, second.certificateId);
185 }).pipe(logLevel),
186 {
187 tags: ["provider:cloudflare", "provider:cloudflare:gateway", "live"],
188 timeout: 120_000,
189 },
190 );
191
192 test.provider(
193 "list enumerates the deployed gateway certificate",
194 (stack) =>
195 Effect.gen(function* () {
196 const { accountId } = yield* yield* CloudflareEnvironment;
197
198 yield* stack.destroy();
199
200 const cert = yield* deployUnlessQuotaReached(
201 stack,
202 Cloudflare.Gateway.Certificate("ListCa", {
203 validityPeriodDays: 30,
204 activate: false,
205 }),
206 );
207
208 const provider = yield* Provider.findProvider(Cloudflare.Gateway.Certificate);
209 const all = yield* provider.list();
210
211 // Always a well-typed array of Attributes scoped to this account.
212 expect(Array.isArray(all)).toBe(true);
213 expect(all.every((c) => c.accountId === accountId)).toBe(true);
214
215 if (cert === undefined) {
216 // Same-day reruns can exhaust the 3-per-24h creation quota; the
217 // read-only list assertion above still proves enumeration works.
218 yield* logQuotaSkip("list presence assertion");
219 yield* stack.destroy();
220 return;
221 }
222
223 const found = all.find((c) => c.certificateId === cert.certificateId);
224 expect(found).toBeDefined();
225 expect(found?.accountId).toEqual(accountId);
226
227 yield* stack.destroy();
228 yield* expectGone(accountId, cert.certificateId);
229 }).pipe(logLevel),
230 {
231 tags: ["provider:cloudflare", "provider:cloudflare:gateway", "live"],
232 timeout: 120_000,
233 },
234 );