@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 704 lines 26.2 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 { expect } from "@alchemy.run/test";
5 import * as Test from "@alchemy.run/test/Alchemy";
6 import * as zeroTrust from "@distilled.cloud/cloudflare/zero-trust";
7 import { adopt, OwnedBySomeoneElse } from "alchemy/AdoptPolicy";
8 import * as Provider from "alchemy/Provider";
9 import { State } from "alchemy/State";
10 import * as Cause from "effect/Cause";
11 import * as Data from "effect/Data";
12 import * as Effect from "effect/Effect";
13 import * as HttpClient from "effect/http/HttpClient";
14 import * as Option from "effect/Option";
15 import * as Redacted from "effect/Redacted";
16 import { MinimumLogLevel } from "effect/References";
17 import * as Schedule from "effect/Schedule";
18 import * as Stream from "effect/Stream";
19 import { testName } from "../../names.ts";
20 import IdpLookupWorker from "./fixtures/idp-lookup-worker.ts";
21
22 const { test } = Test.make({ providers: Cloudflare.providers() });
23
24 const logLevel = Effect.provideService(MinimumLogLevel, process.env.DEBUG ? "Debug" : "Info");
25
26 const zoneName = process.env.CLOUDFLARE_TEST_DNS_ZONE_NAME ?? "alchemy-test-2.us";
27
28 const resolveZoneId = Effect.gen(function* () {
29 const { accountId } = yield* yield* CloudflareEnvironment;
30 const zone = yield* findZoneByName({ accountId, name: zoneName });
31 if (!zone) {
32 return yield* Effect.die(new Error(`zone "${zoneName}" not found in account`));
33 }
34 return zone.id;
35 });
36
37 // Ride out 403 blips (`Forbidden`) while the harness-minted token
38 // propagates across Cloudflare's edge. Zone-level when `zoneId` is set,
39 // account-level otherwise — mirroring the provider's own scoping.
40 const getIdp = (zoneId: string | undefined, accountId: string, identityProviderId: string) =>
41 (zoneId !== undefined
42 ? zeroTrust.getIdentityProviderForZone({ zoneId, identityProviderId })
43 : zeroTrust.getIdentityProviderForAccount({ accountId, identityProviderId })
44 ).pipe(
45 Effect.retry({
46 while: (e) => e._tag === "Forbidden",
47 schedule: Schedule.exponential("500 millis"),
48 times: 8,
49 }),
50 );
51
52 // A deleted IdP surfaces as `AccessIdentityProviderNotFound` (Cloudflare
53 // code 12135, `access.api.error.not_found`).
54 const expectGone = (zoneId: string | undefined, accountId: string, identityProviderId: string) =>
55 getIdp(zoneId, accountId, identityProviderId).pipe(
56 Effect.flatMap(() => Effect.fail({ _tag: "IdpNotDeleted" } as const)),
57 Effect.catchTag("AccessIdentityProviderNotFound", () => Effect.void),
58 Effect.retry({
59 while: (e) => e._tag === "IdpNotDeleted",
60 schedule: Schedule.max([Schedule.exponential("500 millis"), Schedule.recurs(10)]),
61 }),
62 );
63
64 // Generic OIDC config with documentation-only placeholder endpoints —
65 // Cloudflare validates the shape, not the reachability.
66 const oidcConfig = {
67 clientId: "alchemy-test-client",
68 clientSecret: "alchemy-test-secret",
69 authUrl: "https://idp.alchemy-test.example/authorize",
70 tokenUrl: "https://idp.alchemy-test.example/token",
71 certsUrl: "https://idp.alchemy-test.example/keys",
72 scopes: ["openid", "email", "profile"],
73 };
74
75 test.provider(
76 "create, verify, and destroy an OIDC IdP",
77 (stack) =>
78 Effect.gen(function* () {
79 const { accountId } = yield* yield* CloudflareEnvironment;
80
81 yield* stack.destroy();
82
83 const idp = yield* stack.deploy(
84 Cloudflare.Access.IdentityProvider("BasicOidc", {
85 name: testName("alchemy-zt-idp-basic"),
86 type: "oidc",
87 config: oidcConfig,
88 }),
89 );
90
91 expect(idp.identityProviderId).toBeTruthy();
92 expect(idp.accountId).toEqual(accountId);
93 expect(idp.name).toEqual(testName("alchemy-zt-idp-basic"));
94 expect(idp.type).toEqual("oidc");
95
96 const live = yield* getIdp(undefined, accountId, idp.identityProviderId);
97 expect(live.name).toEqual(testName("alchemy-zt-idp-basic"));
98 expect(live.type).toEqual("oidc");
99 // Cloudflare masks the client secret on read.
100 expect((live.config as { clientSecret?: string | null }).clientSecret ?? null).toBeNull();
101
102 yield* stack.destroy();
103 yield* expectGone(undefined, accountId, idp.identityProviderId);
104 }).pipe(logLevel),
105 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
106 );
107
108 test.provider(
109 "update name and config in place (same id)",
110 (stack) =>
111 Effect.gen(function* () {
112 const { accountId } = yield* yield* CloudflareEnvironment;
113
114 yield* stack.destroy();
115
116 const initial = yield* stack.deploy(
117 Cloudflare.Access.IdentityProvider("UpdateOidc", {
118 name: testName("alchemy-zt-idp-update"),
119 type: "oidc",
120 config: oidcConfig,
121 }),
122 );
123
124 // Note: assert the config change through `claims` — distilled decodes
125 // the GET response through a discriminated union whose matched variant
126 // does not carry the oidc-only fields (authUrl/tokenUrl/…), so those
127 // are stripped from the decoded value even though Cloudflare returns
128 // them on the wire.
129 const updated = yield* stack.deploy(
130 Cloudflare.Access.IdentityProvider("UpdateOidc", {
131 name: testName("alchemy-zt-idp-update-v2"),
132 type: "oidc",
133 config: { ...oidcConfig, claims: ["email", "groups"] },
134 }),
135 );
136
137 // Same IdP mutated in place — not a replacement.
138 expect(updated.identityProviderId).toEqual(initial.identityProviderId);
139 expect(updated.name).toEqual(testName("alchemy-zt-idp-update-v2"));
140
141 const live = yield* getIdp(undefined, accountId, updated.identityProviderId);
142 expect(live.name).toEqual(testName("alchemy-zt-idp-update-v2"));
143 expect([...((live.config as { claims?: string[] | null }).claims ?? [])].sort()).toEqual([
144 "email",
145 "groups",
146 ]);
147
148 // Redeploying identical props is a no-op (still the same IdP).
149 const noop = yield* stack.deploy(
150 Cloudflare.Access.IdentityProvider("UpdateOidc", {
151 name: testName("alchemy-zt-idp-update-v2"),
152 type: "oidc",
153 config: { ...oidcConfig, claims: ["email", "groups"] },
154 }),
155 );
156 expect(noop.identityProviderId).toEqual(initial.identityProviderId);
157
158 yield* stack.destroy();
159 yield* expectGone(undefined, accountId, initial.identityProviderId);
160 }).pipe(logLevel),
161 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
162 );
163
164 test.provider(
165 "a Redacted client secret stays out of state and a rotation updates in place",
166 (stack) =>
167 Effect.gen(function* () {
168 const { accountId } = yield* yield* CloudflareEnvironment;
169
170 yield* stack.destroy();
171
172 const githubIdp = (clientSecret: Redacted.Redacted<string>) =>
173 Cloudflare.Access.IdentityProvider("RedactedSecret", {
174 type: "github",
175 config: { clientId: "alchemy-test-client", clientSecret },
176 });
177
178 const initial = yield* stack.deploy(githubIdp(Redacted.make("alchemy-redacted-secret-v1")));
179 const live = yield* getIdp(undefined, accountId, initial.identityProviderId);
180 expect(live.type).toEqual("github");
181
182 // Rotating the secret is a change even though both values are Redacted.
183 const rotated = githubIdp(Redacted.make("alchemy-redacted-secret-v2"));
184 const plan = yield* stack.plan(rotated);
185 expect(plan.resources.RedactedSecret?.action).toBe("update");
186 const updated = yield* stack.deploy(rotated);
187 expect(updated.identityProviderId).toEqual(initial.identityProviderId);
188
189 // Neither secret was persisted in plain text.
190 const state = yield* yield* State;
191 const fqns = yield* state.list({ stack: stack.name, stage: stack.stage });
192 const rows = yield* Effect.forEach(fqns, (fqn) =>
193 state.get({ stack: stack.name, stage: stack.stage, fqn }),
194 );
195 const persisted = yield* Effect.sync(() => JSON.stringify(rows));
196 expect(persisted).not.toContain("alchemy-redacted-secret-v1");
197 expect(persisted).not.toContain("alchemy-redacted-secret-v2");
198
199 yield* stack.destroy();
200 yield* expectGone(undefined, accountId, initial.identityProviderId);
201 }).pipe(logLevel),
202 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
203 );
204
205 test.provider(
206 "list enumerates the deployed IdP",
207 (stack) =>
208 Effect.gen(function* () {
209 yield* stack.destroy();
210
211 const deployed = yield* stack.deploy(
212 Cloudflare.Access.IdentityProvider("ListOidc", {
213 type: "oidc",
214 config: oidcConfig,
215 }),
216 );
217
218 const provider = yield* Provider.findProvider(Cloudflare.Access.IdentityProvider);
219 const all = yield* provider.list();
220
221 expect(all.some((x) => x.identityProviderId === deployed.identityProviderId)).toBe(true);
222
223 yield* stack.destroy();
224 yield* expectGone(undefined, deployed.accountId, deployed.identityProviderId);
225 }).pipe(logLevel),
226 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
227 );
228
229 test.provider(
230 "changing the type replaces the IdP",
231 (stack) =>
232 Effect.gen(function* () {
233 const { accountId } = yield* yield* CloudflareEnvironment;
234
235 yield* stack.destroy();
236
237 const oidc = yield* stack.deploy(
238 Cloudflare.Access.IdentityProvider("ReplaceIdp", {
239 name: testName("alchemy-zt-idp-replace"),
240 type: "oidc",
241 config: oidcConfig,
242 }),
243 );
244
245 // The name is the resource's cold-read identity, so a replacement
246 // (type change) pairs with a rename — keeping the old name would make
247 // the engine find the doomed sibling and refuse to adopt it.
248 const github = yield* stack.deploy(
249 Cloudflare.Access.IdentityProvider("ReplaceIdp", {
250 name: testName("alchemy-zt-idp-replace-github"),
251 type: "github",
252 config: { clientId: "alchemy-test-client", clientSecret: "alchemy-test-secret" },
253 }),
254 );
255
256 // Type is immutable in our model — the engine must have replaced it.
257 expect(github.identityProviderId).not.toEqual(oidc.identityProviderId);
258 expect(github.type).toEqual("github");
259
260 const live = yield* getIdp(undefined, accountId, github.identityProviderId);
261 expect(live.type).toEqual("github");
262 // The old IdP was deleted by the replacement.
263 yield* expectGone(undefined, accountId, oidc.identityProviderId);
264
265 yield* stack.destroy();
266 yield* expectGone(undefined, accountId, github.identityProviderId);
267 }).pipe(logLevel),
268 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
269 );
270
271 test.provider(
272 "zone-scoped IdP lifecycle (create, rename, destroy)",
273 (stack) =>
274 Effect.gen(function* () {
275 const { accountId } = yield* yield* CloudflareEnvironment;
276 const zoneId = yield* resolveZoneId;
277
278 yield* stack.destroy();
279
280 const idp = yield* stack.deploy(
281 Cloudflare.Access.IdentityProvider("ZoneOidc", {
282 zoneId,
283 name: testName("alchemy-zt-idp-zone"),
284 type: "oidc",
285 config: oidcConfig,
286 }),
287 );
288
289 expect(idp.identityProviderId).toBeTruthy();
290 expect(idp.zoneId).toEqual(zoneId);
291
292 // Out-of-band via the zone-scoped route.
293 const live = yield* getIdp(zoneId, accountId, idp.identityProviderId);
294 expect(live.name).toEqual(testName("alchemy-zt-idp-zone"));
295 expect(live.type).toEqual("oidc");
296
297 // Rename converges in place — same IdP, same scope.
298 const renamed = yield* stack.deploy(
299 Cloudflare.Access.IdentityProvider("ZoneOidc", {
300 zoneId,
301 name: testName("alchemy-zt-idp-zone-v2"),
302 type: "oidc",
303 config: oidcConfig,
304 }),
305 );
306 expect(renamed.identityProviderId).toEqual(idp.identityProviderId);
307 expect(renamed.name).toEqual(testName("alchemy-zt-idp-zone-v2"));
308
309 yield* stack.destroy();
310 yield* expectGone(zoneId, accountId, idp.identityProviderId);
311 }).pipe(logLevel),
312 {
313 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
314 },
315 );
316
317 test.provider(
318 "moving an IdP between scopes replaces it",
319 (stack) =>
320 Effect.gen(function* () {
321 const { accountId } = yield* yield* CloudflareEnvironment;
322 const zoneId = yield* resolveZoneId;
323
324 yield* stack.destroy();
325
326 const accountScoped = yield* stack.deploy(
327 Cloudflare.Access.IdentityProvider("ScopeMove", {
328 name: testName("alchemy-zt-idp-scope-move"),
329 type: "oidc",
330 config: oidcConfig,
331 }),
332 );
333 expect(accountScoped.zoneId).toBeUndefined();
334
335 // Adding zoneId is a scope change — a replacement, paired with a
336 // rename so the doomed sibling isn't found by the cold-read scan.
337 const zoneScoped = yield* stack.deploy(
338 Cloudflare.Access.IdentityProvider("ScopeMove", {
339 zoneId,
340 name: testName("alchemy-zt-idp-scope-move-zone"),
341 type: "oidc",
342 config: oidcConfig,
343 }),
344 );
345 expect(zoneScoped.identityProviderId).not.toEqual(accountScoped.identityProviderId);
346 expect(zoneScoped.zoneId).toEqual(zoneId);
347
348 // The old account-scoped IdP was deleted by the replacement.
349 yield* expectGone(undefined, accountId, accountScoped.identityProviderId);
350
351 yield* stack.destroy();
352 yield* expectGone(zoneId, accountId, zoneScoped.identityProviderId);
353 }).pipe(logLevel),
354 {
355 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
356 },
357 );
358
359 // Adoption + data-source coverage below. Live IdPs carry no ownership
360 // markers, so the provider locates them by name (or by type for the
361 // singleton `cloudflare` / `onetimepin` types) and the engine gates
362 // takeover behind `adopt(true)`.
363
364 const forbiddenRetryPolicy = { schedule: Schedule.exponential("500 millis"), times: 8 } as const;
365
366 const retryForbidden = <A, E extends { _tag: string }, R>(effect: Effect.Effect<A, E, R>) =>
367 effect.pipe(
368 Effect.retry({ while: (e): boolean => e._tag === "Forbidden", ...forbiddenRetryPolicy }),
369 );
370
371 interface LiveIdp {
372 readonly id?: string | null;
373 readonly name?: string | null;
374 readonly type?: string | null;
375 }
376
377 const findLiveIdp = (
378 accountId: string,
379 predicate: (idp: { name: string; type: string }) => boolean,
380 ) =>
381 retryForbidden(
382 zeroTrust.listIdentityProvidersForAccount.items({ accountId }).pipe(
383 Stream.filter(predicate),
384 Stream.runHead,
385 Effect.map(Option.getOrUndefined),
386 Effect.map((idp): LiveIdp | undefined => idp as LiveIdp | undefined),
387 ),
388 );
389
390 /**
391 * Pull the {@link OwnedBySomeoneElse} value out of a Cause regardless of
392 * whether the engine raised it as a typed failure or a defect.
393 */
394 const findOwnedError = (cause: Cause.Cause<unknown>): OwnedBySomeoneElse | undefined =>
395 cause.reasons
396 .map((reason) =>
397 Cause.isFailReason(reason)
398 ? reason.error
399 : Cause.isDieReason(reason)
400 ? reason.defect
401 : undefined,
402 )
403 .find((value): value is OwnedBySomeoneElse => value instanceof OwnedBySomeoneElse);
404
405 test.provider(
406 "adoption — existing IdP errors without adopt, takes over with adopt(true)",
407 (stack) =>
408 Effect.gen(function* () {
409 const { accountId } = yield* yield* CloudflareEnvironment;
410
411 yield* stack.destroy();
412
413 // Create the IdP out-of-band so the stack has no state of its own for
414 // it — exactly the "already configured in the dashboard" scenario. A
415 // leftover from an interrupted run is fine: it is the same fixture.
416 const NAME = testName("alchemy-zt-idp-adopt");
417 const pre =
418 (yield* findLiveIdp(accountId, (idp) => idp.name === NAME)) ??
419 (yield* retryForbidden(
420 zeroTrust.createIdentityProviderForAccount({
421 accountId,
422 name: NAME,
423 type: "oidc",
424 config: oidcConfig,
425 }),
426 ).pipe(Effect.map((created): LiveIdp => created as LiveIdp)));
427 expect(pre.id).toBeTruthy();
428
429 // Without `adopt`: Access IdPs carry no ownership markers, so the
430 // engine cannot prove we created it and refuses to take it over.
431 const error = yield* stack
432 .deploy(
433 Cloudflare.Access.IdentityProvider("AdoptOidc", {
434 name: NAME,
435 type: "oidc",
436 config: oidcConfig,
437 }),
438 )
439 .pipe(
440 Effect.as(undefined),
441 Effect.catchCause((cause) => Effect.succeed(findOwnedError(cause))),
442 );
443 expect(error).toBeInstanceOf(OwnedBySomeoneElse);
444
445 // With `adopt(true)`: the engine takes over the pre-existing IdP
446 // (same physical id) — no duplicate create.
447 const adopted = yield* stack.deploy(
448 Cloudflare.Access.IdentityProvider("AdoptOidc", {
449 name: NAME,
450 type: "oidc",
451 config: oidcConfig,
452 }).pipe(adopt(true)),
453 );
454 expect(adopted.identityProviderId).toEqual(pre.id);
455
456 // Adopted means owned — destroy deletes the live IdP.
457 yield* stack.destroy();
458 yield* expectGone(undefined, accountId, adopted.identityProviderId);
459 }).pipe(logLevel),
460 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
461 );
462
463 // The `cloudflare` (WARP) IdP is an account singleton whose display name is
464 // `""` when provisioned from the Zero Trust dashboard. Both rounds run in
465 // ONE sequential case because the singleton is account-global and
466 // `test.provider` cases within a file run concurrently.
467 test.provider(
468 "adoption — cloudflare-type IdP by empty name, then by type alone",
469 (stack) =>
470 Effect.gen(function* () {
471 const { accountId } = yield* yield* CloudflareEnvironment;
472
473 yield* stack.destroy();
474
475 const findWarp = findLiveIdp(accountId, (idp) => idp.type === "cloudflare");
476
477 // Round 1 — the user-reported regression: an explicit `name: ""` must
478 // match the live IdP (a truthiness check used to swallow `""` and
479 // probe for a generated physical name instead, so the provider tried
480 // to create a second singleton and failed).
481 const pre1 =
482 (yield* findWarp) ??
483 (yield* retryForbidden(
484 zeroTrust.createIdentityProviderForAccount({
485 accountId,
486 name: "",
487 type: "cloudflare",
488 config: { restrictToAccountMembers: true },
489 }),
490 ).pipe(Effect.map((created): LiveIdp => created as LiveIdp)));
491 expect(pre1.id).toBeTruthy();
492
493 const adopted1 = yield* stack.deploy(
494 Cloudflare.Access.IdentityProvider("CloudflareIDP", {
495 name: "",
496 type: "cloudflare",
497 config: { restrictToAccountMembers: true },
498 }).pipe(adopt(true)),
499 );
500 expect(adopted1.identityProviderId).toEqual(pre1.id);
501 expect(adopted1.name).toEqual("");
502
503 yield* stack.destroy();
504 yield* expectGone(undefined, accountId, adopted1.identityProviderId);
505
506 // Round 2 — omitted name: singletons are located by type and keep
507 // their observed display name (no rename to a generated physical
508 // name).
509 const pre2 = yield* retryForbidden(
510 zeroTrust.createIdentityProviderForAccount({
511 accountId,
512 name: "",
513 type: "cloudflare",
514 config: { restrictToAccountMembers: true },
515 }),
516 ).pipe(Effect.map((created): LiveIdp => created as LiveIdp));
517 expect(pre2.id).toBeTruthy();
518
519 const adopted2 = yield* stack.deploy(
520 Cloudflare.Access.IdentityProvider("CloudflareIDP", {
521 type: "cloudflare",
522 config: { restrictToAccountMembers: true },
523 }).pipe(adopt(true)),
524 );
525 expect(adopted2.identityProviderId).toEqual(pre2.id);
526 expect(adopted2.name).toEqual("");
527
528 yield* stack.destroy();
529 yield* expectGone(undefined, accountId, adopted2.identityProviderId);
530 }).pipe(logLevel),
531 { tags: ["provider:cloudflare", "provider:cloudflare:access", "live"] },
532 );
533
534 test.provider(
535 "getIdentityProvider data source feeds another resource's props",
536 (stack) =>
537 Effect.gen(function* () {
538 const { accountId } = yield* yield* CloudflareEnvironment;
539
540 yield* stack.destroy();
541
542 const NAME = testName("alchemy-zt-idp-lookup");
543
544 // First deploy creates the IdP alone so the live IdP exists before
545 // the next plan's data-source Output resolves.
546 const idp = yield* stack.deploy(
547 Cloudflare.Access.IdentityProvider("LookupOidc", {
548 name: NAME,
549 type: "oidc",
550 config: oidcConfig,
551 }),
552 );
553
554 // Second deploy consumes the lookup Output IN PLACE OF a resource
555 // reference: `allowedIdps` receives the looked-up id — the "gate an
556 // application on an IdP managed outside the stack" use case.
557 const result = yield* stack.deploy(
558 Effect.gen(function* () {
559 const same = yield* Cloudflare.Access.IdentityProvider("LookupOidc", {
560 name: NAME,
561 type: "oidc",
562 config: oidcConfig,
563 });
564 yield* Cloudflare.Zone.Zone("TestZone", { name: zoneName }).pipe(adopt(true));
565 const app = yield* Cloudflare.Access.Application("LookupGatedApp", {
566 type: "self_hosted",
567 domain: `${testName("alchemy-test-idp-lookup")}.${zoneName}`,
568 sessionDuration: "24h",
569 allowedIdps: [
570 Cloudflare.Access.getIdentityProvider({ name: NAME }).identityProviderId.as<string>(),
571 ],
572 });
573 return {
574 deployedId: same.identityProviderId,
575 app,
576 missing: Cloudflare.Access.getIdentityProvider({
577 name: "alchemy-zt-idp-lookup-nonexistent",
578 }),
579 };
580 }),
581 );
582
583 expect(result.deployedId).toEqual(idp.identityProviderId);
584 expect(result.missing).toBeUndefined();
585 expect(result.app.applicationId).toBeTruthy();
586
587 // The application's allowed-IdP list must carry the looked-up id —
588 // verified out-of-band against the live application.
589 const liveApp = yield* zeroTrust
590 .getAccessApplicationForAccount({ accountId, appId: result.app.applicationId })
591 .pipe(
592 Effect.retry({ while: (e): boolean => e._tag === "Forbidden", ...forbiddenRetryPolicy }),
593 );
594 const allowed =
595 (liveApp as { allowedIdps?: ReadonlyArray<string | null> | null }).allowedIdps ?? [];
596 expect(allowed).toContain(idp.identityProviderId);
597
598 yield* stack.destroy();
599 yield* expectGone(undefined, idp.accountId, idp.identityProviderId);
600 }).pipe(logLevel),
601 {
602 tags: ["provider:cloudflare", "provider:cloudflare:access", "provider:cloudflare:zone", "live"],
603 },
604 );
605
606 // The lookup Worker finds its IdP by display name, which it reads from
607 // `IDP_LOOKUP_NAME` at deploy time (see fixtures/idp-lookup-worker.ts).
608 const IDP_LOOKUP_NAME = (process.env.IDP_LOOKUP_NAME = testName("alchemy-zt-idp-worker-lookup"));
609
610 class LookupNotServing extends Data.TaggedError("LookupNotServing")<{ message: string }> {}
611
612 test.provider(
613 "GetIdentityProvider binding resolves the IdP at runtime inside a Worker",
614 (stack) =>
615 Effect.gen(function* () {
616 yield* stack.destroy();
617
618 const deployed = yield* stack.deploy(
619 Effect.gen(function* () {
620 const idp = yield* Cloudflare.Access.IdentityProvider("WorkerLookupOidc", {
621 name: IDP_LOOKUP_NAME,
622 type: "oidc",
623 config: oidcConfig,
624 });
625 const worker = yield* IdpLookupWorker;
626 return { idp, worker };
627 }),
628 );
629
630 // Anchor on the expected marker, never a bare 200 — fresh workers.dev
631 // hostnames serve a placeholder with 200 while propagating, and the
632 // freshly-minted scoped token can 403 (→ worker 500) for ~30s.
633 const client = yield* HttpClient.HttpClient;
634 const body = yield* client.get(`${deployed.worker.url}/`).pipe(
635 Effect.flatMap((res) =>
636 Effect.gen(function* () {
637 const text = yield* res.text;
638 if (res.status !== 200 || !text.includes("identityProviderId")) {
639 return yield* new LookupNotServing({
640 message: `status=${res.status} body=${text.slice(0, 300)}`,
641 });
642 }
643 return JSON.parse(text) as { identityProviderId: string | null; type: string | null };
644 }),
645 ),
646 Effect.retry({
647 while: (e): boolean => e._tag === "LookupNotServing",
648 schedule: Schedule.max([
649 Schedule.min([Schedule.exponential("1 second"), Schedule.spaced("5 seconds")]),
650 Schedule.recurs(15),
651 ]),
652 }),
653 );
654
655 expect(body.identityProviderId).toEqual(deployed.idp.identityProviderId);
656 expect(body.type).toEqual("oidc");
657
658 yield* stack.destroy();
659 yield* expectGone(undefined, deployed.idp.accountId, deployed.idp.identityProviderId);
660 }).pipe(logLevel),
661 {
662 tags: [
663 "provider:cloudflare",
664 "provider:cloudflare:access",
665 "provider:cloudflare:worker",
666 "live",
667 ],
668 timeout: 180_000,
669 },
670 );
671
672 // Compile-time contract of the per-type configs — never executed. The
673 // discriminated Props union must reject a config from the wrong provider
674 // type and enforce each type's required fields. Type-level assertions
675 // (not @ts-expect-error) so the checks don't depend on where tsc anchors
676 // a multi-line object-literal diagnostic.
677 type IdpProps = Cloudflare.Access.IdentityProviderProps;
678 type Extends<A, B> = [A] extends [B] ? true : false;
679 type Not<T extends boolean> = T extends true ? false : true;
680 type Assert<T extends true> = T;
681
682 // Valid shapes are accepted.
683 type _OkOidc = Assert<Extends<{ type: "oidc"; config: typeof oidcConfig }, IdpProps>>;
684 type _OkPin = Assert<Extends<{ type: "onetimepin" }, IdpProps>>;
685 type _OkSaml = Assert<
686 Extends<
687 {
688 type: "saml";
689 config: { issuerUrl: string; ssoTargetUrl: string; idpPublicCerts: string[] };
690 samlCertificateSetId: string;
691 },
692 IdpProps
693 >
694 >;
695 // An OAuth-only config is rejected on an oidc IdP (missing endpoints).
696 type _BadOidc = Assert<
697 Not<Extends<{ type: "oidc"; config: { clientId: string; clientSecret: string } }, IdpProps>>
698 >;
699 // azureAD requires directoryId.
700 type _BadAzure = Assert<
701 Not<Extends<{ type: "azureAD"; config: { clientId: string; clientSecret: string } }, IdpProps>>
702 >;
703 // saml requires issuerUrl/ssoTargetUrl/idpPublicCerts.
704 type _BadSaml = Assert<Not<Extends<{ type: "saml"; config: { issuerUrl: string } }, IdpProps>>>;