@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 356 lines 12.8 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as resourceSharing from "@distilled.cloud/cloudflare/resource-sharing";
6 import * as Provider from "alchemy/Provider";
7 import * as Effect from "effect/Effect";
8 import { MinimumLogLevel } from "effect/References";
9 import * as Result from "effect/Result";
10 import * as Schedule from "effect/Schedule";
11 import { testName } from "../../names.ts";
12
13 const { test } = Test.make({ providers: Cloudflare.providers() });
14
15 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
16
17 // Resource Sharing writes are permission-gated: on the standard testing
18 // account every POST/PUT/DELETE under /accounts/{id}/shares fails with the
19 // typed `Forbidden` error (HTTP 403, Cloudflare code 10000 "Authentication
20 // error") because the token lacks the Resource Sharing Edit permission.
21 // Reads (list/get) succeed. Sharing also requires a *second* account or
22 // organization as recipient. The full lifecycle test below is gated behind
23 // an explicit opt-in env var pointing at a recipient account; the probe
24 // test always runs and pins the typed tags.
25 const recipientAccountId = process.env.CLOUDFLARE_TEST_SHARE_RECIPIENT_ACCOUNT_ID;
26
27 const getShare = (accountId: string, shareId: string) =>
28 resourceSharing.getResourceSharing({ accountId, shareId }).pipe(
29 Effect.retry({
30 while: (e) => e._tag === "Forbidden",
31 schedule: Schedule.exponential("500 millis"),
32 times: 8,
33 }),
34 );
35
36 // Poll until the share is gone after destroy. Deletion is asynchronous —
37 // status walks `active → deleting → deleted`; a fully purged share answers
38 // with the typed `ShareNotFound` (Cloudflare error code 1004).
39 const expectGone = (accountId: string, shareId: string) =>
40 getShare(accountId, shareId).pipe(
41 Effect.flatMap((share) =>
42 share.status === "deleting" || share.status === "deleted"
43 ? Effect.void
44 : Effect.fail({ _tag: "ShareNotDeleted" } as const),
45 ),
46 Effect.catchTag("ShareNotFound", () => Effect.void),
47 Effect.retry({
48 while: (e) => e._tag === "ShareNotDeleted",
49 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
50 }),
51 );
52
53 test.provider(
54 "reads succeed and write-blocked accounts surface the typed Forbidden error",
55 (stack) =>
56 Effect.gen(function* () {
57 const { accountId } = yield* yield* CloudflareEnvironment;
58
59 yield* stack.destroy();
60
61 // Read access works — list the account's sent shares.
62 const shares = yield* resourceSharing.listResourceSharings({
63 accountId,
64 kind: "sent",
65 });
66 expect(Array.isArray(shares.result)).toBe(true);
67
68 // A missing share surfaces as the typed `ShareNotFound`
69 // (Cloudflare error code 1004), not UnknownCloudflareError.
70 const notFound = yield* resourceSharing
71 .getResourceSharing({
72 accountId,
73 shareId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
74 })
75 .pipe(Effect.flip);
76 expect(notFound._tag).toEqual("ShareNotFound");
77
78 // Probe the write path. On the standard testing account this fails
79 // with the typed `Forbidden` — the token lacks Resource Sharing
80 // Edit. On an entitled token the dummy resource id fails validation
81 // instead (a non-Forbidden error) or, at worst, creates a share we
82 // immediately clean up.
83 const probe = yield* resourceSharing
84 .createResourceSharing({
85 accountId,
86 name: "alchemy-share-probe",
87 recipients: [{ accountId }],
88 resources: [
89 {
90 meta: {},
91 resourceAccountId: accountId,
92 resourceId: "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa",
93 resourceType: "gateway-policy",
94 },
95 ],
96 })
97 .pipe(Effect.result);
98
99 if (Result.isSuccess(probe)) {
100 // Safety net: should the account ever become entitled, clean up
101 // the accidental share so the probe stays side-effect free.
102 yield* resourceSharing
103 .deleteResourceSharing({ accountId, shareId: probe.success.id })
104 .pipe(Effect.catchTag("ShareNotFound", () => Effect.void));
105 yield* Effect.logInfo(
106 "account can write shares; run the gated lifecycle tests via CLOUDFLARE_TEST_SHARE_RECIPIENT_ACCOUNT_ID",
107 );
108 return;
109 }
110
111 if (probe.failure._tag !== "Forbidden") {
112 // Entitled token — the dummy resource was rejected by validation
113 // rather than by the permission gate.
114 yield* Effect.logInfo(
115 `share write probe failed with ${probe.failure._tag}; writes are reachable`,
116 );
117 return;
118 }
119
120 // The typed tag — not UnknownCloudflareError, not a status check.
121 expect(probe.failure._tag).toEqual("Forbidden");
122
123 yield* stack.destroy();
124 }).pipe(logLevel),
125 {
126 tags: ["provider:cloudflare", "provider:cloudflare:resourcesharing", "live"],
127 timeout: 120_000,
128 },
129 );
130
131 test.provider(
132 "list enumerates the account's sent shares (typed Attributes), and includes a deployed share when entitled",
133 (stack) =>
134 Effect.gen(function* () {
135 const { accountId } = yield* yield* CloudflareEnvironment;
136
137 yield* stack.destroy();
138
139 const provider = yield* Provider.findProvider(Cloudflare.ResourceSharing.Share);
140
141 // Reads (list) succeed without the Resource Sharing Edit permission,
142 // so the read-only assertion always runs: list() returns the full,
143 // exhaustively-paginated set of sent shares in the read Attributes
144 // shape.
145 const before = yield* provider.list();
146 expect(Array.isArray(before)).toBe(true);
147 for (const share of before) {
148 expect(typeof share.shareId).toBe("string");
149 expect(share.accountId).toEqual(accountId);
150 expect(typeof share.name).toBe("string");
151 // Deleted shares are filtered out — never surfaced by list().
152 expect(share.status).not.toEqual("deleted");
153 }
154
155 // Writes are permission-gated (and need a second recipient account),
156 // so only assert presence of a freshly-deployed share when an entitled
157 // recipient account is provided. On the standard testing token the
158 // deploy would fail with the typed `Forbidden` (HTTP 403, code 10000).
159 if (recipientAccountId) {
160 const policy = yield* stack.deploy(
161 Cloudflare.Gateway.Rule("ListSharePolicy", {
162 action: "block",
163 traffic: 'dns.fqdn == "list-share.alchemy-test.example"',
164 filters: ["dns"],
165 enabled: false,
166 }),
167 );
168 const deployed = yield* stack.deploy(
169 Cloudflare.ResourceSharing.Share("ListShare", {
170 recipients: [{ accountId: recipientAccountId }],
171 resources: [{ resourceType: "gateway-policy", resourceId: policy.ruleId }],
172 }),
173 );
174
175 const all = yield* provider.list();
176 expect(all.some((s) => s.shareId === deployed.shareId)).toBe(true);
177
178 yield* stack.destroy();
179 yield* expectGone(accountId, deployed.shareId);
180 }
181
182 yield* stack.destroy();
183 }).pipe(logLevel),
184 {
185 tags: [
186 "provider:cloudflare",
187 "provider:cloudflare:gateway",
188 "provider:cloudflare:resourcesharing",
189 "live",
190 ],
191 timeout: 180_000,
192 },
193 );
194
195 test.provider.skipIf(!recipientAccountId)(
196 "creates a share with a gateway policy, renames in place, adds and removes a resource, and destroys",
197 (stack) =>
198 Effect.gen(function* () {
199 const { accountId } = yield* yield* CloudflareEnvironment;
200 const recipient = recipientAccountId!;
201
202 yield* stack.destroy();
203
204 // A shareable resource: gateway policies are sharable on the test
205 // account's Zero Trust setup.
206 const policyA = yield* stack.deploy(
207 Cloudflare.Gateway.Rule("SharePolicyA", {
208 action: "block",
209 traffic: 'dns.fqdn == "share-a.alchemy-test.example"',
210 filters: ["dns"],
211 enabled: false,
212 }),
213 );
214 const policyB = yield* stack.deploy(
215 Cloudflare.Gateway.Rule("SharePolicyB", {
216 action: "block",
217 traffic: 'dns.fqdn == "share-b.alchemy-test.example"',
218 filters: ["dns"],
219 enabled: false,
220 }),
221 );
222
223 const share = yield* stack.deploy(
224 Cloudflare.ResourceSharing.Share("Share", {
225 name: testName("alchemy-resource-share"),
226 recipients: [{ accountId: recipient }],
227 resources: [{ resourceType: "gateway-policy", resourceId: policyA.ruleId }],
228 }),
229 );
230 expect(share.shareId).toBeTruthy();
231 expect(share.accountId).toEqual(accountId);
232 expect(share.name).toEqual(testName("alchemy-resource-share"));
233 expect(share.status).toEqual("active");
234 expect(share.kind).toEqual("sent");
235
236 // Out-of-band verification via the distilled API.
237 const live = yield* getShare(accountId, share.shareId);
238 expect(live.name).toEqual(testName("alchemy-resource-share"));
239
240 // Rename in place — same shareId; also converge resources to
241 // include policy B (delta add through the resource sub-API).
242 const renamed = yield* stack.deploy(
243 Cloudflare.ResourceSharing.Share("Share", {
244 name: testName("alchemy-resource-share-v2"),
245 recipients: [{ accountId: recipient }],
246 resources: [
247 { resourceType: "gateway-policy", resourceId: policyA.ruleId },
248 { resourceType: "gateway-policy", resourceId: policyB.ruleId },
249 ],
250 }),
251 );
252 expect(renamed.shareId).toEqual(share.shareId);
253 expect(renamed.name).toEqual(testName("alchemy-resource-share-v2"));
254
255 const resources = yield* resourceSharing.listResources({
256 accountId,
257 shareId: share.shareId,
258 });
259 const liveIds = resources.result
260 .filter((r) => r.status !== "deleted" && r.status !== "deleting")
261 .map((r) => r.resourceId)
262 .sort();
263 expect(liveIds).toEqual([policyA.ruleId, policyB.ruleId].sort());
264
265 // Drop policy B again — delta remove through the resource sub-API.
266 const reduced = yield* stack.deploy(
267 Cloudflare.ResourceSharing.Share("Share", {
268 name: testName("alchemy-resource-share-v2"),
269 recipients: [{ accountId: recipient }],
270 resources: [{ resourceType: "gateway-policy", resourceId: policyA.ruleId }],
271 }),
272 );
273 expect(reduced.shareId).toEqual(share.shareId);
274
275 yield* stack.destroy();
276
277 yield* expectGone(accountId, share.shareId);
278 }).pipe(logLevel),
279 {
280 tags: [
281 "provider:cloudflare",
282 "provider:cloudflare:gateway",
283 "provider:cloudflare:resourcesharing",
284 "live",
285 ],
286 timeout: 180_000,
287 },
288 );
289
290 test.provider.skipIf(!recipientAccountId)(
291 "manages standalone ShareResource and ShareRecipient on an existing share",
292 (stack) =>
293 Effect.gen(function* () {
294 const { accountId } = yield* yield* CloudflareEnvironment;
295 const recipient = recipientAccountId!;
296
297 yield* stack.destroy();
298
299 const policyA = yield* stack.deploy(
300 Cloudflare.Gateway.Rule("ChildPolicyA", {
301 action: "block",
302 traffic: 'dns.fqdn == "child-a.alchemy-test.example"',
303 filters: ["dns"],
304 enabled: false,
305 }),
306 );
307 const policyB = yield* stack.deploy(
308 Cloudflare.Gateway.Rule("ChildPolicyB", {
309 action: "block",
310 traffic: 'dns.fqdn == "child-b.alchemy-test.example"',
311 filters: ["dns"],
312 enabled: false,
313 }),
314 );
315
316 const share = yield* stack.deploy(
317 Cloudflare.ResourceSharing.Share("ChildShare", {
318 recipients: [{ accountId: recipient }],
319 resources: [{ resourceType: "gateway-policy", resourceId: policyA.ruleId }],
320 }),
321 );
322
323 // Standalone resource entry — adds policy B incrementally.
324 const entry = yield* stack.deploy(
325 Cloudflare.ResourceSharing.ShareResource("ChildEntry", {
326 shareId: share.shareId,
327 resourceType: "gateway-policy",
328 resourceId: policyB.ruleId,
329 }),
330 );
331 expect(entry.shareResourceId).toBeTruthy();
332 expect(entry.shareId).toEqual(share.shareId);
333 expect(entry.resourceId).toEqual(policyB.ruleId);
334
335 // Out-of-band verify the entry exists.
336 const liveEntry = yield* resourceSharing.getResource({
337 accountId,
338 shareId: share.shareId,
339 shareResourceId: entry.shareResourceId,
340 });
341 expect(liveEntry.resourceId).toEqual(policyB.ruleId);
342
343 yield* stack.destroy();
344
345 yield* expectGone(accountId, share.shareId);
346 }).pipe(logLevel),
347 {
348 tags: [
349 "provider:cloudflare",
350 "provider:cloudflare:gateway",
351 "provider:cloudflare:resourcesharing",
352 "live",
353 ],
354 timeout: 180_000,
355 },
356 );