@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 421 lines 16.5 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 rulesets from "@distilled.cloud/cloudflare/rulesets";
7 import * as AdoptPolicy from "alchemy/AdoptPolicy";
8 import * as Provider from "alchemy/Provider";
9 import * as RemovalPolicy from "alchemy/RemovalPolicy";
10 import { isResourceState, State, type ResourceState } from "alchemy/State";
11 import * as Cause from "effect/Cause";
12 import * as Effect from "effect/Effect";
13 import * as Predicate from "effect/Predicate";
14 import { MinimumLogLevel } from "effect/References";
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 // Cloudflare intermittently blocks *all* zone creation on an account with
18 // error 1052 ("An error(zone setup) has occurred and it has been logged");
19 // the block is account-level and can persist for hours. The unresolved-zone
20 // test below provisions a fresh zone, so soft-skip it while the account is in
21 // that state; every other failure propagates unchanged.
22 const softSkipWhenZoneCreationBlocked = <A, E, R>(
23 effect: Effect.Effect<A, E, R>,
24 ): Effect.Effect<A | undefined, E, R> =>
25 effect.pipe(
26 Effect.catchCause((cause) => {
27 // Match by tag rather than `instanceof zones.ZoneCreationBlocked`: the
28 // error is constructed inside the provider's copy of the distilled
29 // module, which vitest resolves as a separate module instance from this
30 // test's import, so `instanceof` across that boundary is always false.
31 const blocked = cause.reasons
32 .map((reason) =>
33 Cause.isFailReason(reason)
34 ? reason.error
35 : Cause.isDieReason(reason)
36 ? reason.defect
37 : undefined,
38 )
39 .some(
40 (value) => Predicate.hasProperty(value, "_tag") && value._tag === "ZoneCreationBlocked",
41 );
42 return blocked
43 ? Effect.logWarning(
44 "Cloudflare has zone creation blocked on this account (error 1052) — skipping zone-provisioning ruleset assertions",
45 ).pipe(Effect.as(undefined))
46 : Effect.failCause(cause);
47 }),
48 );
49
50 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
51
52 const zoneName = process.env.CLOUDFLARE_TEST_RULESET_ZONE_NAME ?? "alchemy-test-2.us";
53 // The unresolved-zone test owns a phase entrypoint on a *separate* zone so it
54 // never clobbers the CRUD test's rules.
55 const unresolvedZoneName =
56 process.env.CLOUDFLARE_TEST_RULESET_ZONE_NAME_2 ?? "alchemy-test-unresolved.us";
57 const phase = "http_request_firewall_custom";
58 type TestRulesetPhase = typeof phase;
59
60 // The CRUD test and the `list` test both manage the same zone+phase entrypoint
61 // on `alchemy-test-2.us`; run them serially so they can't clobber each other
62 // under the global concurrent test config.
63 describe.sequential(
64 "Ruleset",
65 {
66 tags: [
67 "provider:cloudflare",
68 "provider:cloudflare:ruleset",
69 "provider:cloudflare:zone",
70 "live",
71 ],
72 },
73 () => {
74 test.provider("creates, updates, and deletes a zone phase entrypoint ruleset", (stack) =>
75 Effect.gen(function* () {
76 yield* stack.destroy();
77
78 const initial = yield* stack.deploy(
79 Effect.gen(function* () {
80 const zone = yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(
81 AdoptPolicy.adopt(true),
82 );
83 return yield* Cloudflare.Ruleset.Ruleset("TestRuleset", {
84 zone,
85 phase,
86 rules: [
87 {
88 description: "Alchemy test rule",
89 expression: 'http.request.uri.path eq "/__alchemy_ruleset_test__"',
90 action: "block",
91 },
92 ],
93 });
94 }),
95 );
96
97 expect(initial.phase).toEqual(phase);
98 expect(initial.rules).toHaveLength(1);
99
100 // Verify the rule actually exists in Cloudflare, not just in the
101 // stack output.
102 const createdRules = yield* getPhaseRules(initial.zoneId, phase);
103 expect(createdRules).toHaveLength(1);
104 expect(createdRules[0]).toMatchObject({
105 description: "Alchemy test rule",
106 action: "block",
107 expression: 'http.request.uri.path eq "/__alchemy_ruleset_test__"',
108 });
109
110 const updated = yield* stack.deploy(
111 Effect.gen(function* () {
112 const zone = yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(
113 AdoptPolicy.adopt(true),
114 );
115 return yield* Cloudflare.Ruleset.Ruleset("TestRuleset", {
116 zone,
117 phase,
118 rules: [
119 {
120 description: "Updated Alchemy test rule",
121 expression: 'http.request.uri.path eq "/__alchemy_ruleset_test__"',
122 action: "managed_challenge",
123 },
124 ],
125 });
126 }),
127 );
128
129 expect(updated.zoneId).toEqual(initial.zoneId);
130 expect(updated.rules[0]?.description).toEqual("Updated Alchemy test rule");
131 expect(updated.rules[0]?.action).toEqual("managed_challenge");
132
133 // Verify the update landed in Cloudflare itself.
134 const updatedRules = yield* getPhaseRules(initial.zoneId, phase);
135 expect(updatedRules).toHaveLength(1);
136 expect(updatedRules[0]).toMatchObject({
137 description: "Updated Alchemy test rule",
138 action: "managed_challenge",
139 });
140
141 yield* stack.destroy();
142
143 // Confirm the phase entrypoint was emptied in Cloudflare on destroy.
144 const actualRules = yield* getPhaseRules(initial.zoneId, phase);
145 expect(actualRules).toEqual([]);
146 }).pipe(logLevel),
147 );
148
149 test.provider("destroy removes only its own rules and keeps the entrypoint", (stack) =>
150 Effect.gen(function* () {
151 yield* stack.destroy();
152
153 const deployed = yield* stack.deploy(
154 Effect.gen(function* () {
155 const zone = yield* Cloudflare.Zone.Zone("TestZone", {
156 name: zoneName,
157 }).pipe(AdoptPolicy.adopt(true));
158 return yield* Cloudflare.Ruleset.Ruleset("OwnedRules", {
159 zone,
160 phase,
161 rules: [
162 {
163 description: "Alchemy owned rule",
164 expression: 'http.request.uri.path eq "/__alchemy_ruleset_owned__"',
165 action: "block",
166 },
167 ],
168 });
169 }),
170 );
171
172 // A rule added outside this stack after the deploy. Remove it
173 // even when an assertion below fails.
174 const withForeign = yield* rulesets.createRuleForZone({
175 zoneId: deployed.zoneId,
176 rulesetId: deployed.rulesetId,
177 body: {
178 description: "Foreign rule",
179 expression: 'http.request.uri.path eq "/__alchemy_ruleset_foreign__"',
180 action: "block",
181 },
182 });
183 const foreignId = withForeign.rules.find((r) => r.description === "Foreign rule")?.id;
184 expect(foreignId).toBeTruthy();
185 yield* Effect.addFinalizer(() =>
186 rulesets
187 .deleteRuleForZone({
188 zoneId: deployed.zoneId,
189 rulesetId: deployed.rulesetId,
190 ruleId: foreignId!,
191 })
192 .pipe(Effect.ignore),
193 );
194
195 yield* stack.destroy();
196
197 // The entrypoint survives with only the foreign rule left in it.
198 const entrypoint = yield* rulesets.getPhasForZone({
199 zoneId: deployed.zoneId,
200 rulesetPhase: phase,
201 });
202 expect(entrypoint.id).toEqual(deployed.rulesetId);
203 expect(entrypoint.rules.map((r) => r.id)).toEqual([foreignId]);
204 }).pipe(logLevel),
205 );
206
207 // Skipped: provisioning a zone fails with `ZoneQuotaExceeded` on the testing
208 // account (see test/Cloudflare/Zone/Zone.test.ts).
209 test.provider.skip(
210 "creates and tears down a ruleset whose zone is provisioned in the same deploy",
211 (stack) =>
212 Effect.gen(function* () {
213 // Start from a clean slate so a leftover zone/ruleset from an
214 // interrupted run can't mask a regression.
215 yield* stack.destroy();
216
217 // The zone is created in the same deploy as the ruleset, so its `zoneId`
218 // is an unresolved Output while the ruleset is planned. `adopt(true)`
219 // takes over a leftover zone from a prior run; `destroy()` overrides the
220 // zone's default `retain` so it is actually deleted on teardown.
221 const initial = yield* stack.deploy(
222 Effect.gen(function* () {
223 const zone = yield* Cloudflare.Zone.Zone("TestZone", {
224 name: unresolvedZoneName,
225 }).pipe(AdoptPolicy.adopt(true), RemovalPolicy.destroy());
226 return yield* Cloudflare.Ruleset.Ruleset("TestRuleset", {
227 zone,
228 phase,
229 rules: [
230 {
231 description: "Unresolved zone rule v1",
232 expression: 'http.request.uri.path eq "/__alchemy_ruleset_unresolved__"',
233 action: "block",
234 },
235 ],
236 });
237 }),
238 );
239
240 const createdRules = yield* getPhaseRules(initial.zoneId, phase);
241 expect(createdRules).toHaveLength(1);
242 expect(createdRules[0]).toMatchObject({
243 description: "Unresolved zone rule v1",
244 action: "block",
245 });
246
247 // Re-deploy with changed rules; the ruleset must update in place.
248 const updated = yield* stack.deploy(
249 Effect.gen(function* () {
250 const zone = yield* Cloudflare.Zone.Zone("TestZone", {
251 name: unresolvedZoneName,
252 }).pipe(AdoptPolicy.adopt(true), RemovalPolicy.destroy());
253 return yield* Cloudflare.Ruleset.Ruleset("TestRuleset", {
254 zone,
255 phase,
256 rules: [
257 {
258 description: "Unresolved zone rule v2",
259 expression: 'http.request.uri.path eq "/__alchemy_ruleset_unresolved__"',
260 action: "managed_challenge",
261 },
262 ],
263 });
264 }),
265 );
266
267 expect(updated.zoneId).toEqual(initial.zoneId);
268 const updatedRules = yield* getPhaseRules(updated.zoneId, phase);
269 expect(updatedRules).toHaveLength(1);
270 expect(updatedRules[0]).toMatchObject({
271 description: "Unresolved zone rule v2",
272 action: "managed_challenge",
273 });
274
275 yield* stack.destroy();
276
277 // The zone itself is deleted (destroy, not retain) — assert it's gone in
278 // Cloudflare. (Querying the phase entrypoint here is meaningless: the
279 // zone no longer exists, so Cloudflare answers Unauthorized, not 404.)
280 const { accountId } = yield* yield* CloudflareEnvironment;
281 const zoneAfter = yield* findZoneByName({ accountId, name: unresolvedZoneName });
282 expect(zoneAfter).toBeUndefined();
283 }).pipe(softSkipWhenZoneCreationBlocked, logLevel),
284 );
285
286 // A `creating` state row persisted before upstream Outputs resolve cannot
287 // round-trip Output-valued props — the `zone` prop deserializes as
288 // `undefined`. The engine's creating-with-no-attr recovery path then calls
289 // `read` with those junk props as `olds` and `output: undefined`. Before the
290 // #770 guard, `zoneIdOf(olds.zone)` dereferenced `.zoneId` on `undefined`
291 // and crashed the deploy; after it, `read` returns "not found" and
292 // `reconcile` re-converges the phase entrypoint from the resolved news.
293 test.provider(
294 "recovers a half-created ruleset whose creating-state lost the Output-valued zone (#736)",
295 (stack) =>
296 Effect.gen(function* () {
297 yield* stack.destroy();
298
299 const deployRuleset = () =>
300 stack.deploy(
301 Effect.gen(function* () {
302 const zone = yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(
303 AdoptPolicy.adopt(true),
304 );
305 return yield* Cloudflare.Ruleset.Ruleset("WedgedRuleset", {
306 zone,
307 phase,
308 rules: [
309 {
310 description: "Alchemy wedged recovery rule",
311 expression: 'http.request.uri.path eq "/__alchemy_ruleset_wedged__"',
312 action: "block",
313 },
314 ],
315 });
316 }),
317 );
318
319 const created = yield* deployRuleset();
320
321 // Rewrite the ruleset's persisted row into the wedged shape an
322 // interrupted deploy leaves behind: `creating`, no attributes, and the
323 // Output-valued `zone` prop lost in the round-trip.
324 const state = yield* yield* State;
325 const stage = stack.stage;
326 const fqns = yield* state.list({ stack: stack.name, stage });
327 const rows = yield* Effect.forEach(fqns, (fqn) =>
328 state.get({ stack: stack.name, stage, fqn }).pipe(Effect.map((row) => ({ fqn, row }))),
329 );
330 const wedged = rows.find(
331 (r): r is { fqn: string; row: ResourceState } =>
332 isResourceState(r.row) && r.row.resourceType === "Cloudflare.Ruleset.Ruleset",
333 );
334 if (!wedged) {
335 return yield* Effect.die(
336 new Error("no Cloudflare.Ruleset.Ruleset state row found after deploy"),
337 );
338 }
339 yield* state.set({
340 stack: stack.name,
341 stage,
342 fqn: wedged.fqn,
343 value: {
344 ...wedged.row,
345 status: "creating",
346 attr: undefined,
347 props: { ...wedged.row.props, zone: undefined },
348 },
349 });
350
351 // Before the fix this crashed in `read` with
352 // `TypeError: undefined is not an object (evaluating 'zone.zoneId')`.
353 const recovered = yield* deployRuleset();
354 expect(recovered.rulesetId).toEqual(created.rulesetId);
355 expect(recovered.zoneId).toEqual(created.zoneId);
356
357 // The recovered entrypoint converged to the desired rules.
358 const recoveredRules = yield* getPhaseRules(recovered.zoneId, phase);
359 expect(recoveredRules).toHaveLength(1);
360 expect(recoveredRules[0]).toMatchObject({
361 description: "Alchemy wedged recovery rule",
362 action: "block",
363 });
364
365 yield* stack.destroy();
366 }).pipe(logLevel),
367 { timeout: 240_000 },
368 );
369
370 // Canonical `list()` test (zone-scoped collection): enumerate every zone via
371 // `listAllZones`, list each zone's rulesets, keep the phase entrypoints, and
372 // hydrate them. Deploy a ruleset on the standing test zone, then assert it is
373 // present in the exhaustively-paginated result.
374 test.provider("list enumerates the deployed zone phase entrypoint", (stack) =>
375 Effect.gen(function* () {
376 yield* stack.destroy();
377
378 const deployed = yield* stack.deploy(
379 Effect.gen(function* () {
380 const zone = yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(
381 AdoptPolicy.adopt(true),
382 );
383 return yield* Cloudflare.Ruleset.Ruleset("TestRuleset", {
384 zone,
385 phase,
386 rules: [
387 {
388 description: "Alchemy list test rule",
389 expression: 'http.request.uri.path eq "/__alchemy_ruleset_list_test__"',
390 action: "block",
391 },
392 ],
393 });
394 }),
395 );
396
397 const provider = yield* Provider.findProvider(Cloudflare.Ruleset.Ruleset);
398 const all = yield* provider.list();
399
400 expect(all.length).toBeGreaterThan(0);
401 expect(
402 all.some(
403 (r) =>
404 r.rulesetId === deployed.rulesetId &&
405 r.zoneId === deployed.zoneId &&
406 r.phase === phase,
407 ),
408 ).toBe(true);
409
410 yield* stack.destroy();
411 }).pipe(logLevel),
412 );
413 },
414 );
415
416 const getPhaseRules = Effect.fn(function* (zoneId: string, phase: TestRulesetPhase) {
417 return yield* rulesets.getPhasForZone({ zoneId, rulesetPhase: phase }).pipe(
418 Effect.map((ruleset) => ruleset.rules ?? []),
419 Effect.catchTag("RulesetNotFound", () => Effect.succeed([])),
420 );
421 });