Skip to content
File

Blob: test/auth-tessera-start.worker.test.ts

typescript63 lines
1import { applyD1Migrations } from "cloudflare:test";
2import { env, exports as workerExports } from "cloudflare:workers";
3import { afterEach, beforeAll, describe, expect, it } from "vitest";
4 
5import { __test as oidcTest } from "@/worker/auth/oidc";
6import { OIDC_TX_COOKIE_HEADER_NAME } from "@/worker/auth/cookies";
7 
8import { fakeProvider } from "./util/oidcFake";
9import { readAppD1Migrations } from "./util/d1Migrations";
10 
11beforeAll(async () => {
12 await applyD1Migrations(env.DB, readAppD1Migrations());
13});
14 
15afterEach(() => {
16 oidcTest.clearProviderCache();
17 oidcTest.setAuthorizationCodeGrantImpl(null);
18});
19 
20describe("/auth/start", () => {
21 it("returns 302 to the authorize URL with a signed transaction cookie", async () => {
22 const provider = fakeProvider({
23 authorizationEndpoint: "https://auth.example.com/oauth2/authorize",
24 tokenEndpoint: "https://auth.example.com/oauth2/token",
25 jwksUri: "https://auth.example.com/.well-known/jwks.json",
26 });
27 oidcTest.setProviderForTesting(
28 {
29 issuer: env.TESSERA_OIDC_ISSUER,
30 clientId: env.TESSERA_OIDC_CLIENT_ID,
31 clientSecret: env.TESSERA_OIDC_CLIENT_SECRET,
32 },
33 provider
34 );
35 const res = await workerExports.default.fetch("https://example.com/auth/start", {
36 redirect: "manual",
37 });
38 expect(res.status).toBe(302);
39 const location = res.headers.get("location") ?? "";
40 expect(location.startsWith("https://auth.example.com/oauth2/authorize")).toBe(true);
41 expect(location).toContain("response_type=code");
42 expect(location).toContain("code_challenge_method=S256");
43 expect(location).toContain("scope=openid");
44 const setCookie = res.headers.get("set-cookie") ?? "";
45 expect(setCookie).toContain(`${OIDC_TX_COOKIE_HEADER_NAME}=`);
46 expect(setCookie).toContain("HttpOnly");
47 expect(setCookie).toContain("Secure");
48 expect(setCookie).toContain("SameSite=Lax");
49 expect(setCookie).toContain("Path=/");
50 });
51 
52 it("redirects to /auth?error=oidc_unavailable when discovery fails", async () => {
53 // No fake provider injected and the configured issuer is not reachable
54 // from inside the test pool, so discovery will fail.
55 const res = await workerExports.default.fetch("https://example.com/auth/start", {
56 redirect: "manual",
57 });
58 expect(res.status).toBe(302);
59 const location = res.headers.get("location") ?? "";
60 expect(location).toBe("/auth?error=oidc_unavailable");
61 });
62});