@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 817 lines 32.3 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 zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
6 import * as AdoptPolicy from "alchemy/AdoptPolicy";
7 import * as Provider from "alchemy/Provider";
8 import * as State from "alchemy/State/State";
9 import * as Effect from "effect/Effect";
10 import { MinimumLogLevel } from "effect/References";
11 import * as Schedule from "effect/Schedule";
12 import * as Stream from "effect/Stream";
13 import { testName } from "../../names.ts";
14
15 const { test } = Test.make({ providers: Cloudflare.providers() });
16
17 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
18
19 // Self-hosted Access Applications require a domain that belongs to an
20 // *active* zone in the account (pending zones are rejected with "domain does
21 // not belong to zone"). Tests can't activate a fresh zone (that requires
22 // nameserver delegation), so we adopt the shared pre-existing active zone.
23 // It must stay on the default `retain` removal policy: it's registered via
24 // Cloudflare Registrar, and the API refuses to delete registrar zones.
25 const zoneName = process.env.CLOUDFLARE_TEST_ACCESS_ZONE_NAME ?? "alchemy-test-2.us";
26
27 // Hostname-safe per-stage suffix, so concurrent runs by different users
28 // never fight over one application domain.
29 const stageLabel = (stage: string) => stage.toLowerCase().replace(/[^a-z0-9-]/g, "-");
30
31 test.provider(
32 "create and delete a self_hosted application gated by a reusable policy",
33 (stack) =>
34 Effect.gen(function* () {
35 const { accountId } = yield* yield* CloudflareEnvironment;
36
37 yield* stack.destroy();
38
39 const domain = `${testName("alchemy-test-app")}.${zoneName}`;
40 const { app, policy } = yield* stack.deploy(
41 Effect.gen(function* () {
42 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
43 const policy = yield* Cloudflare.Access.Policy("AllowExampleDomain", {
44 name: testName("Allow example.com"),
45 decision: "allow",
46 include: [{ emailDomain: { domain: "example.com" } }],
47 });
48 const app = yield* Cloudflare.Access.Application("SelfHostedApp", {
49 type: "self_hosted",
50 domain,
51 sessionDuration: "24h",
52 oauthConfiguration: {
53 enabled: true,
54 grant: { sessionDuration: "24h", accessTokenLifetime: "15m" },
55 dynamicClientRegistration: {
56 enabled: true,
57 allowedUris: [],
58 allowAnyOnLocalhost: true,
59 allowAnyOnLoopback: true,
60 },
61 },
62 policies: [policy.policyId],
63 });
64 return { app, policy };
65 }),
66 );
67
68 expect(app.applicationId).toBeDefined();
69 expect(app.type).toEqual("self_hosted");
70 expect(app.domain).toEqual(domain);
71 expect(app.aud.length).toBeGreaterThan(0);
72 expect(app.oauthConfiguration?.enabled).toBe(true);
73 expect(app.oauthConfiguration?.grant?.sessionDuration).toBe("24h");
74 expect(app.oauthConfiguration?.grant?.accessTokenLifetime).toBe("15m");
75 expect(app.oauthConfiguration?.dynamicClientRegistration?.enabled).toBe(true);
76 expect(app.oauthConfiguration?.dynamicClientRegistration?.allowedUris ?? []).toEqual([]);
77 expect(policy.policyId.length).toBeGreaterThan(0);
78
79 const live = yield* zeroTrust.getAccessApplicationForAccount({
80 accountId,
81 appId: app.applicationId,
82 });
83 const liveRecord = live as unknown as {
84 id?: string | null;
85 type?: string | null;
86 policies?: ReadonlyArray<{ id?: string | null }> | null;
87 oauthConfiguration?: {
88 enabled?: boolean | null;
89 grant?: { sessionDuration?: string | null; accessTokenLifetime?: string | null } | null;
90 dynamicClientRegistration?: {
91 enabled?: boolean | null;
92 allowedUris?: ReadonlyArray<string | null> | null;
93 allowAnyOnLocalhost?: boolean | null;
94 allowAnyOnLoopback?: boolean | null;
95 } | null;
96 } | null;
97 };
98 expect(liveRecord.id).toEqual(app.applicationId);
99 expect(liveRecord.type).toEqual("self_hosted");
100 expect(liveRecord.policies?.length ?? 0).toBeGreaterThanOrEqual(1);
101 const liveIds = (liveRecord.policies ?? []).map((p) => p.id);
102 expect(liveIds).toContain(policy.policyId);
103 expect(liveRecord.oauthConfiguration?.enabled).toBe(true);
104 expect(liveRecord.oauthConfiguration?.grant?.sessionDuration).toBe("24h");
105 expect(liveRecord.oauthConfiguration?.grant?.accessTokenLifetime).toBe("15m");
106 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.enabled).toBe(true);
107 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.allowedUris ?? []).toEqual(
108 [],
109 );
110 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.allowAnyOnLocalhost).toBe(
111 true,
112 );
113 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.allowAnyOnLoopback).toBe(
114 true,
115 );
116
117 yield* stack.destroy();
118 }).pipe(logLevel),
119 {
120 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
121 },
122 );
123
124 test.provider(
125 "create and delete a warp device-enrollment application",
126 (stack) =>
127 Effect.gen(function* () {
128 const idp = process.env.CLOUDFLARE_TEST_GOOGLE_IDP_ID;
129 if (!idp) {
130 // Skip when no Google IdP is configured in the test account.
131 return;
132 }
133
134 yield* stack.destroy();
135
136 const app = yield* stack.deploy(
137 Effect.gen(function* () {
138 // Warp apps derive their domain from the auth domain — no zone needed.
139 const policy = yield* Cloudflare.Access.Policy("WarpAllowDomain", {
140 name: testName("Allow example.com"),
141 decision: "allow",
142 include: [{ emailDomain: { domain: "example.com" } }],
143 });
144 return yield* Cloudflare.Access.Application("WarpEnroll", {
145 type: "warp",
146 sessionDuration: "720h",
147 allowedIdps: [idp],
148 autoRedirectToIdentity: true,
149 policies: [policy.policyId],
150 });
151 }),
152 );
153
154 expect(app.type).toEqual("warp");
155 // Cloudflare derives the warp domain as `${authDomain}/warp`.
156 expect(app.domain.endsWith("/warp")).toBe(true);
157
158 yield* stack.destroy();
159 }).pipe(logLevel),
160 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
161 );
162
163 test.provider(
164 "list enumerates the deployed access application",
165 (stack) =>
166 Effect.gen(function* () {
167 yield* stack.destroy();
168
169 const domain = `${testName("alchemy-test-list-app")}.${zoneName}`;
170 const app = yield* stack.deploy(
171 Effect.gen(function* () {
172 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
173 const policy = yield* Cloudflare.Access.Policy("ListAllowDomain", {
174 name: testName("Allow example.com"),
175 decision: "allow",
176 include: [{ emailDomain: { domain: "example.com" } }],
177 });
178 return yield* Cloudflare.Access.Application("ListApp", {
179 type: "self_hosted",
180 domain,
181 sessionDuration: "24h",
182 policies: [policy.policyId],
183 });
184 }),
185 );
186
187 const provider = yield* Provider.findProvider(Cloudflare.Access.Application);
188
189 // `list()` enumerates every Access application in the account. The
190 // provider already rides out the transient enumeration failures internally
191 // (the typed `AccessReferenceNotFound` from a sibling app mid-teardown
192 // still referencing a deleted policy, plus throttling 403s), so here we
193 // only poll until our own freshly created app becomes visible.
194 const all = yield* provider.list().pipe(
195 Effect.flatMap((rows) =>
196 rows.some((a) => a.applicationId === app.applicationId)
197 ? Effect.succeed(rows)
198 : Effect.fail({ _tag: "AppNotListed" as const }),
199 ),
200 Effect.retry({
201 while: (e) => e._tag === "AppNotListed",
202 schedule: Schedule.spaced("2 seconds"),
203 times: 15,
204 }),
205 );
206
207 const match = all.find((a) => a.applicationId === app.applicationId);
208 expect(match).toBeDefined();
209 expect(match?.type).toEqual("self_hosted");
210 expect(match?.aud.length).toBeGreaterThan(0);
211
212 yield* stack.destroy();
213 }).pipe(logLevel),
214 {
215 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
216 },
217 );
218
219 test.provider(
220 "update policies in place keeps the applicationId stable",
221 (stack) =>
222 Effect.gen(function* () {
223 const { accountId } = yield* yield* CloudflareEnvironment;
224
225 yield* stack.destroy();
226
227 const domain = `${testName("alchemy-test-update-policies")}.${zoneName}`;
228
229 const initial = yield* stack.deploy(
230 Effect.gen(function* () {
231 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
232 const allow = yield* Cloudflare.Access.Policy("UpdateAllow", {
233 name: testName("Allow example.com"),
234 decision: "allow",
235 include: [{ emailDomain: { domain: "example.com" } }],
236 });
237 return yield* Cloudflare.Access.Application("UpdatePolicies", {
238 type: "self_hosted",
239 domain,
240 oauthConfiguration: {
241 enabled: true,
242 grant: { sessionDuration: "24h", accessTokenLifetime: "15m" },
243 dynamicClientRegistration: {
244 enabled: true,
245 allowedUris: ["https://client.example.com/callback"],
246 allowAnyOnLocalhost: true,
247 },
248 },
249 policies: [allow.policyId],
250 });
251 }),
252 );
253
254 const updated = yield* stack.deploy(
255 Effect.gen(function* () {
256 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
257 const allow = yield* Cloudflare.Access.Policy("UpdateAllow", {
258 name: testName("Allow example.com"),
259 decision: "allow",
260 include: [{ emailDomain: { domain: "example.com" } }],
261 });
262 const deny = yield* Cloudflare.Access.Policy("UpdateDeny", {
263 decision: "deny",
264 include: [{ everyone: {} }],
265 });
266 return yield* Cloudflare.Access.Application("UpdatePolicies", {
267 type: "self_hosted",
268 domain,
269 // Update one managed OAuth leaf while preserving omitted fields.
270 oauthConfiguration: { dynamicClientRegistration: { allowAnyOnLoopback: true } },
271 policies: [allow.policyId, deny.policyId],
272 });
273 }),
274 );
275
276 expect(updated.applicationId).toEqual(initial.applicationId);
277
278 const live = yield* zeroTrust.getAccessApplicationForAccount({
279 accountId,
280 appId: updated.applicationId,
281 });
282 const liveRecord = live as unknown as {
283 policies?: ReadonlyArray<unknown> | null;
284 oauthConfiguration?: {
285 enabled?: boolean | null;
286 grant?: { sessionDuration?: string | null; accessTokenLifetime?: string | null } | null;
287 dynamicClientRegistration?: {
288 enabled?: boolean | null;
289 allowedUris?: ReadonlyArray<string | null> | null;
290 allowAnyOnLocalhost?: boolean | null;
291 allowAnyOnLoopback?: boolean | null;
292 } | null;
293 } | null;
294 };
295 expect(liveRecord.policies?.length ?? 0).toEqual(2);
296 // The partial desired body must merge over the live managed OAuth
297 // configuration before the PUT-style application update.
298 expect(liveRecord.oauthConfiguration?.enabled).toBe(true);
299 expect(liveRecord.oauthConfiguration?.grant?.sessionDuration).toBe("24h");
300 expect(liveRecord.oauthConfiguration?.grant?.accessTokenLifetime).toBe("15m");
301 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.enabled).toBe(true);
302 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.allowedUris).toEqual([
303 "https://client.example.com/callback",
304 ]);
305 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.allowAnyOnLocalhost).toBe(
306 true,
307 );
308 expect(liveRecord.oauthConfiguration?.dynamicClientRegistration?.allowAnyOnLoopback).toBe(
309 true,
310 );
311
312 yield* stack.destroy();
313 }).pipe(logLevel),
314 {
315 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
316 },
317 );
318
319 // Regression test for the cold-recovery `read` fallback: after state loss
320 // (or a stage migration rebuilding state via the adoption probe) there is
321 // no persisted `applicationId`. Without the domain-match fallback the
322 // engine plans a blind `create` and Cloudflare accepts a DUPLICATE
323 // application on the same domain with a fresh `aud`. With it, the app is
324 // found by domain, surfaces as `Unowned`, and adopts cleanly under
325 // `adopt(true)` — same applicationId/aud, no duplicate.
326 test.provider(
327 "cold-recovery: read matches an existing app by domain after state loss",
328 (stack) =>
329 Effect.gen(function* () {
330 const { accountId } = yield* yield* CloudflareEnvironment;
331
332 yield* stack.destroy();
333
334 const domain = `${testName("alchemy-test-cold-read")}.${zoneName}`;
335 const program = Effect.gen(function* () {
336 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
337 const policy = yield* Cloudflare.Access.Policy("ColdReadAllow", {
338 decision: "allow",
339 include: [{ emailDomain: { domain: "example.com" } }],
340 });
341 return yield* Cloudflare.Access.Application("ColdReadApp", {
342 type: "self_hosted",
343 domain,
344 sessionDuration: "24h",
345 policies: [policy.policyId],
346 });
347 });
348
349 const first = yield* stack.deploy(program);
350 expect(first.applicationId).toBeDefined();
351 expect(first.aud.length).toBeGreaterThan(0);
352
353 // Simulate state loss for the application only: the app still
354 // exists in Cloudflare, but the engine has no applicationId.
355 const state = yield* yield* State.State;
356 yield* state.delete({ stack: stack.name, stage: stack.stage, fqn: "ColdReadApp" });
357
358 // Without adopt, the domain-matched app is Unowned — the engine
359 // must refuse the takeover rather than create a duplicate.
360 const refused = yield* stack.deploy(program).pipe(Effect.flip);
361 expect(refused).toBeInstanceOf(AdoptPolicy.OwnedBySomeoneElse);
362
363 // With adopt, the SAME app is adopted: identity is preserved and
364 // no duplicate application appears on the domain.
365 const readopted = yield* stack.deploy(program.pipe(AdoptPolicy.adopt(true)));
366 expect(readopted.applicationId).toEqual(first.applicationId);
367 expect(readopted.aud).toEqual(first.aud);
368
369 const all = yield* zeroTrust.listAccessApplicationsForAccount
370 .items({ accountId })
371 .pipe(Stream.runCollect);
372 const onDomain = Array.from(all).filter(
373 (a) => (a as { domain?: string | null }).domain === domain,
374 );
375 expect(onDomain).toHaveLength(1);
376
377 yield* stack.destroy();
378 }).pipe(logLevel),
379 {
380 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
381 },
382 );
383
384 /** Structural view of live application policies for inline-policy asserts. */
385 interface LiveInlineApp {
386 policies?: ReadonlyArray<{
387 id?: string | null;
388 decision?: string | null;
389 name?: string | null;
390 reusable?: boolean | null;
391 sessionDuration?: string | null;
392 include?: ReadonlyArray<unknown> | null;
393 exclude?: ReadonlyArray<unknown> | null;
394 require?: ReadonlyArray<unknown> | null;
395 }> | null;
396 }
397
398 test.provider(
399 "inline policies: scalar shorthand, update in place, switch to reusable, no mixing",
400 (stack) =>
401 Effect.gen(function* () {
402 const { accountId } = yield* yield* CloudflareEnvironment;
403
404 yield* stack.destroy();
405
406 const domain = `${testName("alchemy-test-inline-policies")}.${zoneName}`;
407 const makeApp = (policies: Cloudflare.Access.ApplicationProps["policies"]) =>
408 Effect.gen(function* () {
409 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
410 return yield* Cloudflare.Access.Application("InlinePolicyApp", {
411 type: "self_hosted",
412 domain,
413 policies,
414 });
415 });
416
417 // v1 — one inline policy via scalar shorthand.
418 const first = yield* stack.deploy(
419 makeApp([
420 { decision: "allow", name: "primary", include: [{ emailDomain: "example.com" }] },
421 ]),
422 );
423 const live1 = (yield* zeroTrust.getAccessApplicationForAccount({
424 accountId,
425 appId: first.applicationId,
426 })) as unknown as LiveInlineApp;
427 expect(live1.policies?.length).toBe(1);
428 expect(live1.policies![0].reusable).toBe(false);
429 // Shorthand expanded to the wire shape on the way out.
430 expect(live1.policies![0].include).toEqual([{ emailDomain: { domain: "example.com" } }]);
431 const inlineId = live1.policies![0].id;
432 expect(inlineId).toBeDefined();
433
434 // v2 — mutate the same inline policy: more shorthand kinds, exclude,
435 // require, session duration. The policy must update IN PLACE (same
436 // id) — an id-less inline item in the update PUT would mint a fresh
437 // policy.
438 yield* stack.deploy(
439 makeApp([
440 {
441 decision: "allow",
442 name: "primary",
443 include: [{ emailDomain: "example.com" }, "everyone"],
444 exclude: [{ email: "intern@example.com" }],
445 require: [{ geo: "US" }],
446 sessionDuration: "12h",
447 },
448 ]),
449 );
450 const live2 = (yield* zeroTrust.getAccessApplicationForAccount({
451 accountId,
452 appId: first.applicationId,
453 })) as unknown as LiveInlineApp;
454 expect(live2.policies?.length).toBe(1);
455 expect(live2.policies![0].id).toBe(inlineId);
456 expect(live2.policies![0].include).toEqual([
457 { emailDomain: { domain: "example.com" } },
458 { everyone: {} },
459 ]);
460 expect(live2.policies![0].exclude).toEqual([{ email: { email: "intern@example.com" } }]);
461 expect(live2.policies![0].require).toEqual([{ geo: { countryCode: "US" } }]);
462 expect(live2.policies![0].sessionDuration).toBe("12h");
463
464 // v3 — switch the application from inline to a reusable Policy
465 // resource (passed directly).
466 const reusableProgram = Effect.gen(function* () {
467 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
468 const reusable = yield* Cloudflare.Access.Policy("InlineSwapPolicy", {
469 decision: "allow",
470 include: [{ emailDomain: "example.com" }],
471 });
472 const app = yield* Cloudflare.Access.Application("InlinePolicyApp", {
473 type: "self_hosted",
474 domain,
475 policies: [reusable],
476 });
477 return { app, reusable };
478 });
479 const { reusable } = yield* stack.deploy(reusableProgram);
480 const live3 = (yield* zeroTrust.getAccessApplicationForAccount({
481 accountId,
482 appId: first.applicationId,
483 })) as unknown as LiveInlineApp;
484 expect(live3.policies?.length).toBe(1);
485 expect(live3.policies![0].id).toBe(reusable.policyId);
486 expect(live3.policies![0].reusable).toBe(true);
487
488 // Mixing inline and reusable forms on one application fails fast.
489 const mixed = yield* stack
490 .deploy(
491 makeApp([
492 reusable.policyId,
493 { decision: "allow", include: [{ emailDomain: "example.com" }] },
494 ]),
495 )
496 .pipe(Effect.flip);
497 expect(String(mixed)).toMatch(/mix/i);
498
499 yield* stack.destroy();
500 }).pipe(logLevel),
501 {
502 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
503 timeout: 300_000,
504 },
505 );
506
507 test.provider(
508 "adopts an existing application by id and keeps its unmanaged settings",
509 (stack) =>
510 Effect.gen(function* () {
511 const { accountId } = yield* yield* CloudflareEnvironment;
512
513 yield* stack.destroy();
514
515 const name = `alchemy-test-adopt-by-id-${stageLabel(stack.stage)}`;
516 const domain = `${name}.${zoneName}`;
517 const existing = yield* zeroTrust.createAccessApplicationForAccount({
518 accountId,
519 type: "self_hosted",
520 name,
521 domain,
522 sessionDuration: "24h",
523 corsHeaders: {
524 allowedOrigins: ["https://app.example.com"],
525 allowedMethods: ["GET", "POST"],
526 allowCredentials: true,
527 },
528 sameSiteCookieAttribute: "lax",
529 httpOnlyCookieAttribute: true,
530 pathCookieAttribute: true,
531 skipInterstitial: true,
532 });
533
534 const program = (applicationId: string, sessionDuration: string) =>
535 Effect.gen(function* () {
536 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
537 return yield* Cloudflare.Access.Application("AdoptById", {
538 applicationId,
539 type: "self_hosted",
540 name,
541 domain,
542 sessionDuration,
543 });
544 });
545
546 // A declared id that does not exist fails rather than creating an
547 // application with a new id and `aud`.
548 const missingId = "00000000-0000-4000-8000-000000000000";
549 const refused = yield* stack.deploy(program(missingId, "12h")).pipe(Effect.flip);
550 expect(refused._tag).toEqual("DeclaredApplicationNotFound");
551 const named = yield* zeroTrust.listAccessApplicationsForAccount.items({ accountId }).pipe(
552 Stream.filter((app) => app.name === name),
553 Stream.runCollect,
554 );
555 expect(Array.from(named, (app) => app.id)).toEqual([existing.id]);
556
557 // No `--adopt` needed: naming the id is the adoption.
558 const adopted = yield* stack.deploy(program(existing.id!, "12h"));
559 expect(adopted.applicationId).toEqual(existing.id);
560 expect(adopted.aud).toEqual(existing.aud);
561
562 const live = (yield* zeroTrust.getAccessApplicationForAccount({
563 accountId,
564 appId: existing.id!,
565 })) as unknown as Record<string, any>;
566 expect(live.sessionDuration).toEqual("12h");
567 expect(live.corsHeaders?.allowedOrigins).toEqual(["https://app.example.com"]);
568 expect(live.corsHeaders?.allowCredentials).toBe(true);
569 expect(live.sameSiteCookieAttribute).toEqual("lax");
570 expect(live.httpOnlyCookieAttribute).toBe(true);
571 expect(live.pathCookieAttribute).toBe(true);
572 expect(live.skipInterstitial).toBe(true);
573
574 yield* stack.destroy();
575
576 const gone = yield* zeroTrust
577 .getAccessApplicationForAccount({ accountId, appId: existing.id! })
578 .pipe(
579 Effect.map(() => false),
580 Effect.catchTag("AccessApplicationNotFound", () => Effect.succeed(true)),
581 );
582 expect(gone).toBe(true);
583 }).pipe(logLevel),
584 {
585 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
586 },
587 );
588
589 test.provider(
590 "adopted application keeps live policy links and hostnames it does not declare",
591 (stack) =>
592 Effect.gen(function* () {
593 const { accountId } = yield* yield* CloudflareEnvironment;
594
595 yield* stack.destroy();
596
597 const name = `alchemy-test-adopt-keeps-links-${stageLabel(stack.stage)}`;
598 const domain = `${name}.${zoneName}`;
599 const extraDomain = `${name}-2.${zoneName}`;
600 const policy = yield* zeroTrust.createAccessPolicy({
601 accountId,
602 name,
603 decision: "allow",
604 include: [{ emailDomain: { domain: "example.com" } }],
605 });
606 // The policy is outside the stack: delete it even when the test fails,
607 // after the application releases it.
608 const cleanup = stack
609 .destroy()
610 .pipe(
611 Effect.andThen(
612 zeroTrust
613 .deleteAccessPolicy({ accountId, policyId: policy.id! })
614 .pipe(Effect.retry({ schedule: Schedule.spaced("2 seconds"), times: 5 })),
615 ),
616 Effect.orDie,
617 );
618
619 yield* Effect.gen(function* () {
620 const existing = yield* zeroTrust.createAccessApplicationForAccount({
621 accountId,
622 type: "self_hosted",
623 name,
624 domain,
625 destinations: [
626 { type: "public", uri: domain },
627 { type: "public", uri: extraDomain },
628 ],
629 sessionDuration: "24h",
630 policies: [policy.id!],
631 });
632
633 // The changed `sessionDuration` forces a PUT, which must keep the
634 // undeclared policy link and hostnames.
635 const adopted = yield* stack.deploy(
636 Effect.gen(function* () {
637 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(
638 AdoptPolicy.adopt(true),
639 );
640 return yield* Cloudflare.Access.Application("AdoptKeepsLinks", {
641 applicationId: existing.id!,
642 type: "self_hosted",
643 name,
644 domain,
645 sessionDuration: "12h",
646 });
647 }),
648 );
649 expect(adopted.updatedAt).toBeDefined();
650
651 const live = (yield* zeroTrust.getAccessApplicationForAccount({
652 accountId,
653 appId: existing.id!,
654 })) as unknown as {
655 sessionDuration?: string;
656 policies?: ReadonlyArray<{ id?: string }>;
657 destinations?: ReadonlyArray<{ uri?: string }>;
658 };
659 expect(live.sessionDuration).toEqual("12h");
660 expect(live.policies?.map((p) => p.id)).toEqual([policy.id]);
661 expect(live.destinations?.map((d) => d.uri)).toEqual([domain, extraDomain]);
662 }).pipe(Effect.ensuring(cleanup));
663 }).pipe(logLevel),
664 {
665 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
666 },
667 );
668
669 test.provider(
670 "manages CORS, cookie and preflight settings",
671 (stack) =>
672 Effect.gen(function* () {
673 const { accountId } = yield* yield* CloudflareEnvironment;
674
675 yield* stack.destroy();
676
677 const program = (props: Partial<Cloudflare.Access.ApplicationProps>) =>
678 Effect.gen(function* () {
679 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(AdoptPolicy.adopt(true));
680 const cors = yield* Cloudflare.Access.Application("CorsApp", {
681 type: "self_hosted",
682 domain: `alchemy-test-cors-${stageLabel(stack.stage)}.${zoneName}`,
683 ...props,
684 });
685 const preflight = yield* Cloudflare.Access.Application("PreflightApp", {
686 type: "self_hosted",
687 domain: `alchemy-test-preflight-${stageLabel(stack.stage)}.${zoneName}`,
688 optionsPreflightBypass: true,
689 });
690 return { cors, preflight };
691 });
692 const getLive = (appId: string) =>
693 zeroTrust
694 .getAccessApplicationForAccount({ accountId, appId })
695 .pipe(Effect.map((app) => app as unknown as Record<string, any>));
696
697 const { cors, preflight } = yield* stack.deploy(
698 program({
699 corsHeaders: {
700 allowedOrigins: ["https://app.example.com"],
701 allowedMethods: ["GET"],
702 },
703 sameSiteCookieAttribute: "strict",
704 httpOnlyCookieAttribute: true,
705 enableBindingCookie: true,
706 eagerRedirectCookieSetting: false,
707 }),
708 );
709 const live1 = yield* getLive(cors.applicationId);
710 expect(live1.corsHeaders?.allowedOrigins).toEqual(["https://app.example.com"]);
711 expect(live1.corsHeaders?.allowedMethods).toEqual(["GET"]);
712 expect(live1.sameSiteCookieAttribute).toEqual("strict");
713 expect(live1.httpOnlyCookieAttribute).toBe(true);
714 expect(live1.enableBindingCookie).toBe(true);
715 expect(live1.eagerRedirectCookieSetting).toBe(false);
716 expect((yield* getLive(preflight.applicationId)).optionsPreflightBypass).toBe(true);
717
718 // Settings dropped from the props are left as they are live.
719 yield* stack.deploy(
720 program({
721 corsHeaders: { allowedMethods: ["GET", "POST"] },
722 sameSiteCookieAttribute: "lax",
723 }),
724 );
725 const live2 = yield* getLive(cors.applicationId);
726 expect(live2.corsHeaders?.allowedOrigins).toEqual(["https://app.example.com"]);
727 expect(live2.corsHeaders?.allowedMethods?.toSorted()).toEqual(["GET", "POST"]);
728 expect(live2.sameSiteCookieAttribute).toEqual("lax");
729 expect(live2.httpOnlyCookieAttribute).toBe(true);
730 expect(live2.enableBindingCookie).toBe(true);
731 expect(live2.eagerRedirectCookieSetting).toBe(false);
732
733 const { cors: eager } = yield* stack.deploy(program({ eagerRedirectCookieSetting: true }));
734 expect(eager.applicationId).toEqual(cors.applicationId);
735 expect(eager.aud).toEqual(cors.aud);
736 const live3 = yield* getLive(eager.applicationId);
737 expect(live3.eagerRedirectCookieSetting).toBe(true);
738 expect(live3.corsHeaders?.allowedOrigins).toEqual(["https://app.example.com"]);
739 expect(live3.corsHeaders?.allowedMethods?.toSorted()).toEqual(["GET", "POST"]);
740 expect(live3.sameSiteCookieAttribute).toEqual("lax");
741 expect(live3.httpOnlyCookieAttribute).toBe(true);
742 expect(live3.enableBindingCookie).toBe(true);
743
744 // A neighboring setting update keeps the now-enabled Eager Redirect value.
745 const { cors: final } = yield* stack.deploy(program({ sameSiteCookieAttribute: "strict" }));
746 expect(final.applicationId).toEqual(cors.applicationId);
747 expect(final.aud).toEqual(cors.aud);
748 const live4 = yield* getLive(final.applicationId);
749 expect(live4.eagerRedirectCookieSetting).toBe(true);
750 expect(live4.corsHeaders?.allowedOrigins).toEqual(["https://app.example.com"]);
751 expect(live4.corsHeaders?.allowedMethods?.toSorted()).toEqual(["GET", "POST"]);
752 expect(live4.sameSiteCookieAttribute).toEqual("strict");
753 expect(live4.httpOnlyCookieAttribute).toBe(true);
754 expect(live4.enableBindingCookie).toBe(true);
755
756 yield* stack.destroy();
757 }).pipe(logLevel),
758 {
759 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
760 },
761 );
762
763 test.provider(
764 "SAML and OIDC SaaS applications",
765 (stack) =>
766 Effect.gen(function* () {
767 const { accountId } = yield* yield* CloudflareEnvironment;
768
769 yield* stack.destroy();
770
771 const program = (redirectUri: string) =>
772 Effect.gen(function* () {
773 const saml = yield* Cloudflare.Access.Application("SamlApp", {
774 type: "saas",
775 saasApp: {
776 authType: "saml",
777 spEntityId: "https://saml.example.com",
778 consumerServiceUrl: "https://saml.example.com/acs",
779 nameIdFormat: "email",
780 },
781 });
782 const oidc = yield* Cloudflare.Access.Application("OidcApp", {
783 type: "saas",
784 saasApp: {
785 authType: "oidc",
786 redirectUris: [redirectUri],
787 grantTypes: ["authorization_code"],
788 scopes: ["openid", "email", "profile"],
789 },
790 });
791 return { saml, oidc };
792 });
793
794 const first = yield* stack.deploy(program("https://oidc.example.com/cb"));
795 const samlApp = first.saml.saasApp as Record<string, any>;
796 expect(first.saml.type).toEqual("saas");
797 expect(samlApp.spEntityId).toEqual("https://saml.example.com");
798 expect(samlApp.ssoEndpoint).toBeDefined();
799 expect(samlApp.publicKey).toBeDefined();
800 const oidcApp = first.oidc.saasApp as Record<string, any>;
801 expect(oidcApp.clientId).toBeDefined();
802 expect(oidcApp.clientSecret).toBeUndefined();
803
804 const second = yield* stack.deploy(program("https://oidc.example.com/callback"));
805 expect(second.oidc.applicationId).toEqual(first.oidc.applicationId);
806 const live = (yield* zeroTrust.getAccessApplicationForAccount({
807 accountId,
808 appId: second.oidc.applicationId,
809 })) as unknown as { saasApp?: Record<string, any> };
810 expect(live.saasApp?.redirectUris).toEqual(["https://oidc.example.com/callback"]);
811 // The client id survives the update — clients stay configured.
812 expect(live.saasApp?.clientId).toEqual(oidcApp.clientId);
813
814 yield* stack.destroy();
815 }).pipe(logLevel),
816 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
817 );