@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 180 lines 6.52 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { liveEndpoint, s3CredentialsPolicy } from "@alchemy.run/cloudflare/R2/S3CredentialsBinding";
3 import { expect, it } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as Data from "effect/Data";
6 import * as Effect from "effect/Effect";
7 import * as HttpBody from "effect/http/HttpBody";
8 import * as HttpClient from "effect/http/HttpClient";
9 import * as HttpClientRequest from "effect/http/HttpClientRequest";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import * as pathe from "pathe";
13 import PresignRemoteWorker, { PresignRemoteBucket } from "./fixtures/presign/remote-worker.ts";
14 import { presignRoundTrip } from "./fixtures/presign/roundtrip.ts";
15
16 const { test } = Test.make({
17 providers: Cloudflare.providers(),
18 });
19
20 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
21
22 class OtherBucketNotReady extends Data.TaggedError("OtherBucketNotReady")<{
23 status: number;
24 body: string;
25 }> {}
26
27 /**
28 * Seed `key` in the other bucket through the Worker's native binding, then
29 * presign a GET for it with the first bucket's S3 credentials and fetch it.
30 * The token is bucket-scoped, so R2 must answer 403.
31 */
32 const expectOtherBucketDenied = (workerUrl: string, otherBucket: string, key: string) =>
33 Effect.gen(function* () {
34 const client = yield* HttpClient.HttpClient;
35 const okText = (request: HttpClientRequest.HttpClientRequest) =>
36 client.execute(request).pipe(
37 Effect.flatMap((res) =>
38 res.text.pipe(
39 Effect.flatMap((body) =>
40 res.status === 200
41 ? Effect.succeed(body)
42 : Effect.fail(new OtherBucketNotReady({ status: res.status, body })),
43 ),
44 ),
45 ),
46 Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 20 }),
47 );
48
49 yield* okText(
50 HttpClientRequest.post(`${workerUrl}/write-other?key=${encodeURIComponent(key)}`).pipe(
51 HttpClientRequest.setBody(HttpBody.text("other bucket secret")),
52 ),
53 );
54 const { url } = JSON.parse(
55 yield* okText(
56 HttpClientRequest.get(
57 `${workerUrl}/presign-other-bucket?bucket=${encodeURIComponent(otherBucket)}&key=${encodeURIComponent(key)}`,
58 ),
59 ),
60 ) as { url: string };
61 expect(new URL(url).pathname.startsWith(`/${otherBucket}/`)).toBe(true);
62
63 const res = yield* client.execute(HttpClientRequest.get(url));
64 const body = yield* res.text;
65 expect(body).not.toContain("other bucket secret");
66 expect(res.status).toBe(403);
67 });
68
69 /**
70 * Deployed: the Worker mints presigned URLs with S3 credentials derived from
71 * a scoped API token, and an unauthenticated client uploads/downloads
72 * directly against R2's S3 endpoint.
73 */
74 test.provider(
75 "deployed Worker presigns PUT and GET URLs for R2",
76 (stack) =>
77 Effect.gen(function* () {
78 yield* stack.destroy();
79
80 const deployed = yield* stack.deploy(
81 Effect.gen(function* () {
82 const bucket = yield* PresignRemoteBucket;
83 const worker = yield* PresignRemoteWorker;
84 return { bucket, worker };
85 }),
86 );
87
88 const { putUrl, getUrl } = yield* presignRoundTrip(
89 deployed.worker.url!,
90 "uploads/deployed file.txt",
91 );
92 for (const url of [putUrl, getUrl]) {
93 const parsed = new URL(url);
94 expect(parsed.hostname).toMatch(/\.r2\.cloudflarestorage\.com$/);
95 expect(parsed.pathname.startsWith(`/${deployed.bucket.bucketName}/`)).toBe(true);
96 }
97
98 yield* stack.destroy();
99 }).pipe(logLevel),
100 {
101 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
102 timeout: 180_000,
103 },
104 );
105
106 /**
107 * Deployed async Worker: `Cloudflare.R2.S3Credentials` injects token-derived
108 * credentials as a secret, and `aws4fetch` presigns against R2.
109 */
110 test.provider(
111 "deployed async Worker presigns with S3Credentials",
112 (stack) =>
113 Effect.gen(function* () {
114 yield* stack.destroy();
115
116 const deployed = yield* stack.deploy(
117 Effect.gen(function* () {
118 const bucket = yield* Cloudflare.R2.Bucket("PresignAsyncBucket", {
119 forceDestroy: true,
120 });
121 // A second bucket in the same account that the credentials must
122 // NOT reach. The Worker binds it natively only to seed an object.
123 const otherBucket = yield* Cloudflare.R2.Bucket("PresignAsyncOtherBucket", {
124 forceDestroy: true,
125 });
126 const worker = yield* Cloudflare.Worker("PresignAsyncWorker", {
127 main: pathe.resolve(import.meta.dirname, "fixtures/presign/async-worker.ts"),
128 env: {
129 BUCKET: bucket,
130 OTHER_BUCKET: otherBucket,
131 BUCKET_S3: Cloudflare.R2.S3Credentials(bucket, {
132 access: "read-write",
133 }),
134 },
135 });
136 return { bucket, otherBucket, worker };
137 }),
138 );
139
140 const { putUrl } = yield* presignRoundTrip(
141 deployed.worker.url!,
142 "uploads/async deployed.txt",
143 );
144 expect(new URL(putUrl).hostname).toMatch(/\.r2\.cloudflarestorage\.com$/);
145
146 // The token behind the credentials is scoped to BUCKET: an object in
147 // another bucket of the same account is not readable with them.
148 const otherKey = "secret.txt";
149 yield* expectOtherBucketDenied(
150 deployed.worker.url!,
151 deployed.otherBucket.bucketName,
152 otherKey,
153 );
154
155 yield* stack.destroy();
156 }).pipe(logLevel),
157 {
158 tags: ["provider:cloudflare", "provider:cloudflare:r2", "provider:cloudflare:worker", "live"],
159 timeout: 180_000,
160 },
161 );
162
163 // A jurisdictional bucket's token resource carries its jurisdiction; the live
164 // tests above only deploy `default`-jurisdiction buckets.
165 it(
166 "S3Credentials scopes a jurisdictional bucket's token to that jurisdiction",
167 () => {
168 expect(s3CredentialsPolicy("acct", "uploads", "eu", "read").resources).toEqual({
169 "com.cloudflare.edge.r2.bucket.acct_eu_uploads": "*",
170 });
171 expect(s3CredentialsPolicy("acct", "gov", "fedramp", "write").resources).toEqual({
172 "com.cloudflare.edge.r2.bucket.acct_fedramp_gov": "*",
173 });
174 expect(s3CredentialsPolicy("acct", "records", "us", "read").resources).toEqual({
175 "com.cloudflare.edge.r2.bucket.acct_us_records": "*",
176 });
177 expect(liveEndpoint("acct", "us")).toBe("https://acct.us.r2.cloudflarestorage.com");
178 },
179 { tags: ["unit", "provider:cloudflare", "provider:cloudflare:r2", "local"] },
180 );