@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 325 lines 14.5 KB
Raw
1 import * as Cloudflare from "@alchemy.run/cloudflare";
2 import { CloudflareEnvironment } from "@alchemy.run/cloudflare/CloudflareEnvironment";
3 import { describe, expect } from "@alchemy.run/test";
4 import * as Test from "@alchemy.run/test/Alchemy";
5 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
6 import * as Output from "alchemy/Output";
7 import * as Provider from "alchemy/Provider";
8 import * as Effect from "effect/Effect";
9 import * as FileSystem from "effect/FileSystem";
10 import { MinimumLogLevel } from "effect/References";
11 import * as pathe from "pathe";
12 import { expectUrlContains } from "../Utils/Http.ts";
13 const { test } = Test.make({ providers: Cloudflare.providers() });
14
15 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
16
17 // The Access organization is an account-wide singleton whose auth domain is
18 // allocated once and effectively immutable — the tests adopt the LIVE org
19 // (auth domain read from the account, or CLOUDFLARE_TEST_AUTH_DOMAIN) and
20 // restore every setting they toggle. The standing test account has a Zero
21 // Trust org, so they run by default; set CLOUDFLARE_TEST_ACCESS_ORG=0 to skip
22 // them on an account whose org must not be touched.
23 const skip = process.env.CLOUDFLARE_TEST_ACCESS_ORG === "0";
24
25 const customPagesEntitled = !!process.env.CLOUDFLARE_TEST_ACCESS_CUSTOM_PAGES;
26 const brandingDir = pathe.resolve(import.meta.dirname, "fixtures/branding");
27
28 const resolveAuthDomain = (accountId: string) =>
29 process.env.CLOUDFLARE_TEST_AUTH_DOMAIN
30 ? Effect.succeed(process.env.CLOUDFLARE_TEST_AUTH_DOMAIN)
31 : zeroTrust.listOrganizationsForAccount({ accountId }).pipe(
32 Effect.map((org) => {
33 expect(org.authDomain).toBeTruthy();
34 return org.authDomain!;
35 }),
36 );
37 // The organization's settings as an update body, to restore it after a test.
38 // A `serviceTokenInactivity` without an `action` is left out: Cloudflare
39 // rejects the bare `{ enabled: false }` shape it returns.
40 const restorable = (accountId: string, org: zeroTrust.ListOrganizationsResponse) => ({
41 accountId,
42 authDomain: org.authDomain ?? undefined,
43 name: org.name ?? undefined,
44 allowAuthenticateViaWarp: org.allowAuthenticateViaWarp ?? undefined,
45 autoRedirectToIdentity: org.autoRedirectToIdentity ?? undefined,
46 isUiReadOnly: org.isUiReadOnly ?? undefined,
47 sessionDuration: org.sessionDuration ?? undefined,
48 warpAuthSessionDuration: org.warpAuthSessionDuration ?? undefined,
49 userSeatExpirationInactiveTime: org.userSeatExpirationInactiveTime ?? undefined,
50 uiReadOnlyToggleReason: org.uiReadOnlyToggleReason ?? undefined,
51 denyUnmatchedRequests: org.denyUnmatchedRequests ?? undefined,
52 denyUnmatchedRequestsExemptedZoneNames: org.denyUnmatchedRequestsExemptedZoneNames
53 ? [...org.denyUnmatchedRequestsExemptedZoneNames]
54 : undefined,
55 disableEndUserAppCreation: org.disableEndUserAppCreation ?? undefined,
56 strictServiceTokenAuth: org.strictServiceTokenAuth ?? undefined,
57 mfaRequiredForAllApps: org.mfaRequiredForAllApps ?? undefined,
58 warp_auth_non_browser_401: org.warp_auth_non_browser_401 ?? undefined,
59 loginDesign: withoutNulls(org.loginDesign),
60 customPages: withoutNulls(org.customPages),
61 mfaConfig: withoutNulls(org.mfaConfig),
62 mfaPivKeyRequirements: withoutNulls(org.mfaPivKeyRequirements),
63 serviceTokenInactivity: org.serviceTokenInactivity?.action
64 ? withoutNulls(org.serviceTokenInactivity)
65 : undefined,
66 });
67
68 const withoutNulls = <T extends object>(value: T | null | undefined) =>
69 value
70 ? (Object.fromEntries(Object.entries(value).filter(([, v]) => v !== null)) as {
71 [K in keyof T]: Exclude<T[K], null>;
72 })
73 : undefined;
74
75 // Every deploy converges the whole organization, so a test that deploys it
76 // puts the account's organization back the way it found it.
77 const restoringOrganization = <A, E, R>(test: Effect.Effect<A, E, R>) =>
78 Effect.gen(function* () {
79 const { accountId } = yield* yield* CloudflareEnvironment;
80 const original = yield* zeroTrust.listOrganizationsForAccount({ accountId });
81 return yield* test.pipe(
82 Effect.ensuring(
83 zeroTrust.updateOrganizationForAccount(restorable(accountId, original)).pipe(Effect.ignore),
84 ),
85 );
86 });
87
88 // Both cases mutate the same account-wide Access organization singleton; run
89 // them serially so they don't corrupt each other under the global concurrent
90 // test config.
91 describe.sequential(
92 "Organization",
93 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
94 () => {
95 test.provider.skipIf(skip)("adopts the existing Access organization", (stack) =>
96 Effect.gen(function* () {
97 const { accountId } = yield* yield* CloudflareEnvironment;
98 const authDomain = yield* resolveAuthDomain(accountId);
99
100 const org = yield* stack.deploy(
101 Effect.gen(function* () {
102 return yield* Cloudflare.Access.Organization("Org", {
103 authDomain,
104 name: authDomain,
105 });
106 }),
107 );
108
109 expect(org.accountId).toEqual(accountId);
110 expect(org.authDomain).toEqual(authDomain);
111
112 const live = yield* zeroTrust.listOrganizationsForAccount({ accountId });
113 expect(live.authDomain).toEqual(authDomain);
114
115 // Singleton: delete is a no-op, so destroy must NOT remove the org.
116 yield* stack.destroy();
117 const stillThere = yield* zeroTrust.listOrganizationsForAccount({ accountId });
118 expect(stillThere.authDomain).toEqual(authDomain);
119 }).pipe(restoringOrganization, logLevel),
120 );
121
122 // Same gate as above: toggling allow_authenticate_via_warp mutates the
123 // account's live singleton org (restored at the end).
124 test.provider.skipIf(skip)("toggles allow_authenticate_via_warp and restores", (stack) =>
125 Effect.gen(function* () {
126 const { accountId } = yield* yield* CloudflareEnvironment;
127 const authDomain = yield* resolveAuthDomain(accountId);
128
129 const original = yield* zeroTrust.listOrganizationsForAccount({ accountId });
130 const originalWarp = original.allowAuthenticateViaWarp ?? false;
131 const originalName = original.name ?? authDomain;
132
133 // Step 1 — set to true.
134 const enabled = yield* stack.deploy(
135 Effect.gen(function* () {
136 return yield* Cloudflare.Access.Organization("Org", {
137 authDomain,
138 name: originalName,
139 allowAuthenticateViaWarp: true,
140 });
141 }),
142 );
143 expect(enabled.allowAuthenticateViaWarp).toEqual(true);
144 const liveEnabled = yield* zeroTrust.listOrganizationsForAccount({ accountId });
145 expect(liveEnabled.allowAuthenticateViaWarp).toEqual(true);
146
147 // Step 2 — flip to false.
148 const disabled = yield* stack.deploy(
149 Effect.gen(function* () {
150 return yield* Cloudflare.Access.Organization("Org", {
151 authDomain,
152 name: originalName,
153 allowAuthenticateViaWarp: false,
154 });
155 }),
156 );
157 expect(disabled.allowAuthenticateViaWarp).toEqual(false);
158 const liveDisabled = yield* zeroTrust.listOrganizationsForAccount({ accountId });
159 expect(liveDisabled.allowAuthenticateViaWarp).toEqual(false);
160
161 // Restore to original value via a final deploy so the account
162 // isn't left mutated by the test.
163 yield* stack.deploy(
164 Effect.gen(function* () {
165 return yield* Cloudflare.Access.Organization("Org", {
166 authDomain,
167 name: originalName,
168 allowAuthenticateViaWarp: originalWarp,
169 });
170 }),
171 );
172
173 yield* stack.destroy();
174 }).pipe(restoringOrganization, logLevel),
175 );
176
177 // Every setting is declarable, and a deploy converges the whole
178 // organization: a setting dropped from the props goes back to its default.
179 test.provider.skipIf(skip)("converges declared and undeclared settings", (stack) =>
180 Effect.gen(function* () {
181 const { accountId } = yield* yield* CloudflareEnvironment;
182 const authDomain = yield* resolveAuthDomain(accountId);
183 const original = yield* zeroTrust.listOrganizationsForAccount({ accountId });
184 const name = original.name ?? authDomain;
185
186 const org = yield* stack.deploy(
187 Effect.gen(function* () {
188 return yield* Cloudflare.Access.Organization("Org", {
189 authDomain,
190 name,
191 sessionDuration: "13h",
192 loginDesign: { footerText: "alchemy footer" },
193 disableEndUserAppCreation: true,
194 warpAuthNonBrowser401: true,
195 mfaConfig: { allowedAuthenticators: ["totp"], sessionDuration: "5h" },
196 mfaPivKeyRequirements: { pinPolicy: "always", touchPolicy: "always" },
197 serviceTokenInactivity: {
198 enabled: true,
199 action: "disable",
200 inactivityThresholdDays: 365,
201 },
202 });
203 }),
204 );
205 expect(org.mfaConfig?.allowedAuthenticators).toEqual(["totp"]);
206 expect(org.disableEndUserAppCreation).toEqual(true);
207
208 const live = yield* zeroTrust.listOrganizationsForAccount({ accountId });
209 expect(live.sessionDuration).toEqual("13h");
210 expect(live.loginDesign?.footerText).toEqual("alchemy footer");
211 expect(live.disableEndUserAppCreation).toEqual(true);
212 expect(live.warp_auth_non_browser_401).toEqual(true);
213 expect(live.mfaConfig?.allowedAuthenticators).toEqual(["totp"]);
214 expect(live.mfaConfig?.sessionDuration).toEqual("5h");
215 expect(live.mfaPivKeyRequirements?.pinPolicy).toEqual("always");
216 expect(live.serviceTokenInactivity?.enabled).toEqual(true);
217 expect(live.serviceTokenInactivity?.inactivityThresholdDays).toEqual(365);
218
219 // Change MFA, drop everything else.
220 yield* stack.deploy(
221 Effect.gen(function* () {
222 return yield* Cloudflare.Access.Organization("Org", {
223 authDomain,
224 name,
225 mfaConfig: { allowedAuthenticators: ["totp", "security_key"], sessionDuration: "8h" },
226 });
227 }),
228 );
229
230 const converged = yield* zeroTrust.listOrganizationsForAccount({ accountId });
231 expect(converged.mfaConfig?.allowedAuthenticators).toEqual(["totp", "security_key"]);
232 expect(converged.mfaConfig?.sessionDuration).toEqual("8h");
233 expect(converged.sessionDuration ?? undefined).not.toEqual("13h");
234 expect(converged.loginDesign?.footerText ?? undefined).toBeUndefined();
235 expect(converged.disableEndUserAppCreation ?? false).toEqual(false);
236 expect(converged.warp_auth_non_browser_401 ?? false).toEqual(false);
237 expect(converged.mfaPivKeyRequirements ?? undefined).toBeUndefined();
238 expect(converged.serviceTokenInactivity?.enabled ?? false).toEqual(false);
239
240 yield* stack.destroy();
241 }).pipe(restoringOrganization, logLevel),
242 );
243
244 // Branding lives in the repo: the logo is served by an assets-only
245 // Worker and the block page HTML is read from a file.
246 test.provider.skipIf(skip)("brands the login page from files in the repo", (stack) =>
247 Effect.gen(function* () {
248 const { accountId } = yield* yield* CloudflareEnvironment;
249 const authDomain = yield* resolveAuthDomain(accountId);
250 const original = yield* zeroTrust.listOrganizationsForAccount({ accountId });
251 const fs = yield* FileSystem.FileSystem;
252
253 const { org, logoUrl, forbiddenPageId } = yield* stack.deploy(
254 Effect.gen(function* () {
255 const branding = yield* Cloudflare.Worker("Branding", {
256 assets: brandingDir + "/public",
257 workersDev: true,
258 });
259 // Access custom pages need an entitled account.
260 const forbidden = customPagesEntitled
261 ? yield* Cloudflare.Access.CustomPage("Forbidden", {
262 type: "forbidden",
263 customHtml: yield* fs.readFileString(brandingDir + "/forbidden.html"),
264 })
265 : undefined;
266 const org = yield* Cloudflare.Access.Organization("Org", {
267 authDomain,
268 name: original.name ?? authDomain,
269 loginDesign: {
270 logoPath: Output.interpolate`${branding.url}/logo.svg`,
271 backgroundColor: "#111111",
272 textColor: "#ffffff",
273 },
274 customPages: forbidden ? { forbidden: forbidden.customPageId } : undefined,
275 });
276 return {
277 org,
278 logoUrl: Output.interpolate`${branding.url}/logo.svg`,
279 forbiddenPageId: forbidden?.customPageId,
280 };
281 }),
282 );
283
284 const live = yield* zeroTrust.listOrganizationsForAccount({ accountId });
285 expect(live.loginDesign?.logoPath).toEqual(logoUrl);
286 expect(live.loginDesign?.backgroundColor).toEqual("#111111");
287 if (forbiddenPageId) {
288 expect(live.customPages?.forbidden).toEqual(forbiddenPageId);
289 expect(org.customPages?.forbidden).toEqual(forbiddenPageId);
290 }
291 yield* expectUrlContains(logoUrl, "alchemy-access-logo");
292
293 // Unset the custom page before destroy deletes it.
294 yield* zeroTrust.updateOrganizationForAccount(restorable(accountId, original));
295 yield* stack.destroy();
296 }).pipe(restoringOrganization, logLevel),
297 );
298
299 // Canonical `list()` test (account singleton): there is no enumeration API
300 // for the Access organization, so `list()` reads the single account-wide
301 // org via the same path `read` uses and returns the one-element array (or
302 // `[]` when the account has never enabled Zero Trust). This is read-only —
303 // it does not mutate the singleton — so it runs unconditionally.
304 test.provider("list returns the account Access organization", (stack) =>
305 Effect.gen(function* () {
306 const { accountId } = yield* yield* CloudflareEnvironment;
307
308 const provider = yield* Provider.findProvider(Cloudflare.Access.Organization);
309 const all = yield* provider.list();
310
311 // Singleton: zero (Zero Trust never enabled) or exactly one.
312 expect(all.length).toBeLessThanOrEqual(1);
313 for (const org of all) {
314 expect(org.accountId).toEqual(accountId);
315 expect(typeof org.authDomain).toBe("string");
316 expect(typeof org.name).toBe("string");
317 }
318
319 // `stack` is unused (no resource is deployed), but keep the destroy
320 // bookend so the harness state stays clean.
321 yield* stack.destroy();
322 }).pipe(logLevel),
323 );
324 },
325 );