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

main
ts 247 lines 9.3 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 tokenValidation from "@distilled.cloud/cloudflare/token-validation";
7 import * as Output from "alchemy/Output";
8 import * as Provider from "alchemy/Provider";
9 import * as Effect from "effect/Effect";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import { JWKS_KEY_1, JWKS_KEY_2 } from "./fixtures/jwks.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 // JWT validation (API Shield) is entitlement-gated — on the standard testing
21 // account every token_validation call fails with "You are not entitled for
22 // this service" (code 10403), surfaced as the typed
23 // `TokenValidationNotEntitled` error. The full lifecycle test below is gated
24 // behind an entitled zone id supplied via env.
25 const entitledZoneId = process.env.CLOUDFLARE_TEST_TOKEN_VALIDATION_ZONE_ID;
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 // A freshly minted scoped token propagates eventually-consistently across
37 // Cloudflare's edge — retry the typed `Forbidden` blips on out-of-band calls.
38 const forbiddenRetrySchedule = Schedule.exponential("500 millis");
39
40 const listConfigurations = (zoneId: string) =>
41 tokenValidation.listConfigurations({ zoneId }).pipe(
42 Effect.retry({
43 while: (e) => e._tag === "Forbidden",
44 schedule: forbiddenRetrySchedule,
45 times: 8,
46 }),
47 );
48
49 const getConfiguration = (zoneId: string, configId: string) =>
50 tokenValidation.getConfiguration({ zoneId, configId }).pipe(
51 Effect.retry({
52 while: (e) => e._tag === "Forbidden",
53 schedule: forbiddenRetrySchedule,
54 times: 8,
55 }),
56 );
57
58 const getRule = (zoneId: string, ruleId: string) =>
59 tokenValidation.getRule({ zoneId, ruleId }).pipe(
60 Effect.retry({
61 while: (e) => e._tag === "Forbidden",
62 schedule: forbiddenRetrySchedule,
63 times: 8,
64 }),
65 );
66
67 test.provider(
68 "surfaces the typed TokenValidationNotEntitled error on unentitled accounts",
69 (stack) =>
70 Effect.gen(function* () {
71 const zoneId = yield* resolveZoneId;
72
73 yield* stack.destroy();
74
75 // The testing account lacks the API Shield JWT validation
76 // entitlement — every distilled call must fail with the typed
77 // entitlement tag (never the catch-all
78 // `Forbidden`/`UnknownCloudflareError`).
79 const listError = yield* listConfigurations(zoneId).pipe(Effect.flip);
80 expect(listError._tag).toEqual("TokenValidationNotEntitled");
81
82 const getError = yield* getConfiguration(zoneId, "00000000-0000-0000-0000-000000000000").pipe(
83 Effect.flip,
84 );
85 expect(getError._tag).toEqual("TokenValidationNotEntitled");
86
87 const ruleError = yield* getRule(zoneId, "00000000-0000-0000-0000-000000000000").pipe(
88 Effect.flip,
89 );
90 expect(ruleError._tag).toEqual("TokenValidationNotEntitled");
91
92 yield* stack.destroy();
93 }).pipe(logLevel),
94 {
95 tags: [
96 "provider:cloudflare",
97 "provider:cloudflare:tokenvalidation",
98 "provider:cloudflare:zone",
99 "live",
100 ],
101 timeout: 120_000,
102 },
103 );
104
105 // Canonical `list()` test (zone-scoped collection): configurations live
106 // inside a zone and the list op is keyed per zone, so `list()` enumerates
107 // every zone via `listAllZones` and fans out the per-zone list, skipping
108 // zones that reject with the typed `TokenValidationNotEntitled` / `Forbidden`
109 // tags. On the unentitled testing account every zone is skipped, so the
110 // result is an empty array — the assertion is that `list()` resolves to an
111 // array (proving the typed skip path) rather than throwing. Presence of a
112 // deployed configuration is asserted only on an entitled account (env-gated).
113 test.provider(
114 "list enumerates configurations across all zones",
115 (stack) =>
116 Effect.gen(function* () {
117 const provider = yield* Provider.findProvider(Cloudflare.TokenValidation.TokenConfiguration);
118
119 if (!entitledZoneId) {
120 const all = yield* provider.list();
121 expect(Array.isArray(all)).toBe(true);
122 yield* stack.destroy();
123 return;
124 }
125
126 const zoneId = entitledZoneId;
127 yield* stack.destroy();
128
129 const deployed = yield* stack.deploy(
130 Effect.gen(function* () {
131 return yield* Cloudflare.TokenValidation.TokenConfiguration("JwtConfigList", {
132 zoneId,
133 tokenSources: ['http.request.headers["authorization"][0]'],
134 keys: [JWKS_KEY_1],
135 });
136 }),
137 );
138
139 const all = yield* provider.list();
140 expect(all.some((c) => c.configId === deployed.configId)).toBe(true);
141
142 yield* stack.destroy();
143 }).pipe(logLevel),
144 {
145 tags: ["provider:cloudflare", "provider:cloudflare:tokenvalidation", "live"],
146 timeout: 120_000,
147 },
148 );
149
150 test.provider.skipIf(!entitledZoneId)(
151 "configuration + rule lifecycle: create, update in place, rotate keys, destroy",
152 (stack) =>
153 Effect.gen(function* () {
154 const zoneId = entitledZoneId!;
155
156 yield* stack.destroy();
157
158 // -- Create: configuration with one key, rule that logs ------------
159 const created = yield* stack.deploy(
160 Effect.gen(function* () {
161 const config = yield* Cloudflare.TokenValidation.TokenConfiguration("JwtConfig", {
162 zoneId,
163 description: "v1",
164 tokenSources: ['http.request.headers["authorization"][0]'],
165 keys: [JWKS_KEY_1],
166 });
167 const rule = yield* Cloudflare.TokenValidation.Rule("JwtRule", {
168 zoneId,
169 description: "v1",
170 action: "log",
171 expression: Output.interpolate`is_jwt_valid("${config.configId}")`,
172 selector: { include: [{ host: [zoneName] }] },
173 });
174 return { config, rule };
175 }),
176 );
177
178 expect(created.config.configId).toBeDefined();
179 expect(created.config.zoneId).toEqual(zoneId);
180 expect(created.config.tokenType).toEqual("JWT");
181 expect(created.config.keys.map((k) => k.kid)).toEqual([JWKS_KEY_1.kid]);
182 expect(created.rule.ruleId).toBeDefined();
183 expect(created.rule.action).toEqual("log");
184 expect(created.rule.enabled).toEqual(true);
185 expect(created.rule.expression).toContain(created.config.configId);
186
187 // Out-of-band verification via the distilled API.
188 const liveConfig = yield* getConfiguration(zoneId, created.config.configId);
189 expect(liveConfig.credentials.keys.map((k) => k.kid)).toEqual([JWKS_KEY_1.kid]);
190 const liveRule = yield* getRule(zoneId, created.rule.ruleId);
191 expect(liveRule.action).toEqual("log");
192
193 // -- Update in place: patch metadata, rotate keys, flip the rule ---
194 const updated = yield* stack.deploy(
195 Effect.gen(function* () {
196 const config = yield* Cloudflare.TokenValidation.TokenConfiguration("JwtConfig", {
197 zoneId,
198 description: "v2",
199 tokenSources: [
200 'http.request.headers["authorization"][0]',
201 'http.request.uri.args["token"][0]',
202 ],
203 keys: [JWKS_KEY_1, JWKS_KEY_2],
204 });
205 const rule = yield* Cloudflare.TokenValidation.Rule("JwtRule", {
206 zoneId,
207 description: "v2",
208 enabled: false,
209 action: "block",
210 expression: Output.interpolate`is_jwt_valid("${config.configId}")`,
211 selector: { include: [{ host: [zoneName] }] },
212 });
213 return { config, rule };
214 }),
215 );
216
217 // Same physical resources — patched in place, not replaced.
218 expect(updated.config.configId).toEqual(created.config.configId);
219 expect(updated.config.description).toEqual("v2");
220 expect(updated.config.tokenSources).toHaveLength(2);
221 expect(updated.config.keys.map((k) => k.kid).sort()).toEqual([
222 JWKS_KEY_1.kid,
223 JWKS_KEY_2.kid,
224 ]);
225 expect(updated.rule.ruleId).toEqual(created.rule.ruleId);
226 expect(updated.rule.action).toEqual("block");
227 expect(updated.rule.enabled).toEqual(false);
228
229 const rotated = yield* getConfiguration(zoneId, updated.config.configId);
230 expect(rotated.credentials.keys).toHaveLength(2);
231
232 // -- Destroy: rule first (it references the config), then config ---
233 yield* stack.destroy();
234
235 const configGone = yield* getConfiguration(zoneId, updated.config.configId).pipe(Effect.flip);
236 expect(configGone._tag).toEqual("TokenConfigurationNotFound");
237 const ruleGone = yield* getRule(zoneId, updated.rule.ruleId).pipe(Effect.flip);
238 expect(ruleGone._tag).toEqual("TokenValidationRuleNotFound");
239
240 // Destroy is idempotent.
241 yield* stack.destroy();
242 }).pipe(logLevel),
243 {
244 tags: ["provider:cloudflare", "provider:cloudflare:tokenvalidation", "live"],
245 timeout: 120_000,
246 },
247 );