Files
OmniRoute/tests/unit/oidc-callback.test.ts
Patryk Mikołajczyk 2acc8e84db feat(auth): OIDC as optional dashboard admin login gate (password fallback preserved) (#6973)
* feat(auth): optional OIDC for dashboard admin gate (password remains fallback)

- Settings: oidcEnabled + issuer/client/secret/scopes/redirect/allowedSubjects
- Public routes: /api/auth/oidc/ prefix (authorize + callback reachable)
- isAuthRequired: full OIDC config acts as auth method (gate requires login); partial does not (bootstrap preserved)
- New endpoints:
  - GET /api/auth/oidc/login — IdP redirect (absolute redirect_uri from request + discovery)
  - GET /api/auth/oidc/callback — code exchange, ID token validation (jose + JWKS), optional sub/email whitelist, mints identical 30d auth_token JWT + cookie as password login, redirects to /dashboard
- require-login endpoint now returns oidcEnabled
- Login UI: conditional OIDC button when enabled; password form untouched as fallback
- Tests:
  - public-api-routes: OIDC prefixes are public
  - api-auth: isAuthRequired true with full OIDC (no password); partial OIDC keeps bootstrap semantics

No new deps. No changes to proxy, keys, managementPassword, policies, MCP, CLI. Single-admin preserved.

* feat(auth): add integration test and fixes for OIDC dashboard login gate

- Add comprehensive integration test for /api/auth/oidc/callback
  (happy path + error paths: invalid_state, subject_not_allowed,
   not_configured, token_exchange, id_token_invalid, missing_code,
   server_misconfigured)
- Use static test seam (oidcCallbackInternals) for cookie store
- Mark setupComplete on first successful OIDC login (bootstrap parity)
- Ensure all redirects use absolute URLs (Next.js 16 compatibility)
- Verify identical auth_token JWT/cookie behavior as password path
- No new dependencies; reuses jose + fetch

Password login remains fully supported as fallback.

* fix(auth): address all Gemini Code Assist review comments for OIDC dashboard login gate

- Add module-level JWKS client cache (Record) + getJwksClient helper
- Wrap token exchange fetch + .json() in try/catch with 10s timeout
- Add 5s timeout to discovery fetch in both /login and /callback routes
- Case-insensitive email comparison in oidcAllowedSubjects whitelist
- Make oidc_state cookie 'secure' dynamic based on request protocol (matches auth_token)
- Expose clearJwksCache on test seam for isolation

All reviewer suggestions applied (adjusted for project rules on Map/Record).
Tests: 53/53 pass.

* fix(auth): wire OIDC config into updateSettingsSchema + SECURITY_IMPACTING_KEYS + encrypt/decrypt + non-empty subjects guard (address maintainer review)

* fix(auth): declare storedPasswordHash + align bootstrap contract for oidcEnabled

The security-impacting-keys re-auth gate in PATCH /api/settings assigned to
`storedPasswordHash` without ever declaring it (no `let`/`const`), so every
PATCH touching a SECURITY_IMPACTING_KEYS field (requireLogin, newPassword,
oidcEnabled, oidcClientSecret, the bypass toggles) threw a ReferenceError in
strict-mode ESM and fell through to the generic 500 handler. That masked the
expected 400/401/200 outcomes in settings-audit and settings-route-password
password-migration tests. Declare it as a block-scoped `const` where it's
first assigned.

Also updates the login-bootstrap-route contract tests: the public
/api/settings/require-login GET now legitimately includes `oidcEnabled` in
its response (the login page needs it to decide whether to render the OIDC
button) — the three closed-shape assertions are extended to expect
`oidcEnabled: false`, matching route.ts's existing behavior.

Co-authored-by: diegosouzapw <8016841+diegosouzapw@users.noreply.github.com>

---------

Co-authored-by: mikolaj92 <mikolaj92@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <8016841+diegosouzapw@users.noreply.github.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouza.pw@gmail.com>
Co-authored-by: Diego Rodrigues de Sa e Souza <diegosouzapw@users.noreply.github.com>
2026-07-19 23:21:43 -03:00

429 lines
14 KiB
TypeScript

import test from "node:test";
import assert from "node:assert/strict";
import fs from "node:fs";
import os from "node:os";
import path from "node:path";
import { generateKeyPair, exportJWK, SignJWT } from "jose";
// NOTE: Dynamic imports below are used (with comment) solely because the modules read process.env at evaluation time.
// The specifiers are literals. This is the established pattern in this repo's auth tests for env-controlled DB setup.
const TEST_DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), "omniroute-oidc-callback-"));
process.env.DATA_DIR = TEST_DATA_DIR;
process.env.JWT_SECRET = "test-jwt-secret-for-oidc-callback";
// @ts-ignore - intentional for test harness timing (see note at top)
const core = await import("../../src/lib/db/core.ts");
// @ts-ignore - intentional for test harness timing
const localDb = await import("../../src/lib/localDb.ts");
// @ts-ignore - intentional for test harness timing
const callbackRoute = await import("../../src/app/api/auth/oidc/callback/route.ts");
import type { default as CookieStore } from "next/headers"; // not really, just for shape
interface CapturedCookie {
value: string;
options?: Record<string, unknown>;
}
const originalGetCookieStore = callbackRoute.oidcCallbackInternals.getCookieStore;
let capturedCookies: Record<string, CapturedCookie> = {};
async function resetStorage() {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
fs.mkdirSync(TEST_DATA_DIR, { recursive: true });
capturedCookies = {};
}
function makeTestCookieStore() {
return {
get(name: string) {
const c = capturedCookies[name];
return c ? { value: c.value } : undefined;
},
set(name: string, value: string, options?: Record<string, unknown>) {
capturedCookies[name] = { value, options };
},
};
}
test.beforeEach(async () => {
await resetStorage();
callbackRoute.oidcCallbackInternals.clearJwksCache?.();
callbackRoute.oidcCallbackInternals.getCookieStore = async () => makeTestCookieStore();
});
test.afterEach(() => {
callbackRoute.oidcCallbackInternals.getCookieStore = originalGetCookieStore;
});
test.after(() => {
core.resetDbInstance();
fs.rmSync(TEST_DATA_DIR, { recursive: true, force: true });
delete process.env.JWT_SECRET;
});
async function setupFullOidcSettings() {
await localDb.updateSettings({
requireLogin: true,
password: "",
oidcEnabled: true,
oidcIssuer: "https://idp.test",
oidcClientId: "client-oidc-test",
oidcClientSecret: "secret-oidc-test",
oidcRedirectPath: "/api/auth/oidc/callback",
oidcAllowedSubjects: [],
});
}
async function createSignedIdToken(claims: Record<string, unknown>) {
const { privateKey, publicKey } = await generateKeyPair("RS256");
const idToken = await new SignJWT(claims)
.setProtectedHeader({ alg: "RS256" })
.setIssuedAt()
.setExpirationTime("5m")
.sign(privateKey);
const jwk = await exportJWK(publicKey);
const jwkWithKid = { ...jwk, kid: "test-key-1" };
const jwks = { keys: [jwkWithKid] };
return { idToken, jwks };
}
test("OIDC callback happy path: exchanges code, validates ID token, mints identical auth_token JWT, sets cookie, redirects to dashboard", async () => {
await setupFullOidcSettings();
const { idToken, jwks } = await createSignedIdToken({
iss: "https://idp.test",
aud: "client-oidc-test",
sub: "user-123",
email: "admin@example.com",
});
const testState = "test-oidc-state-xyz";
capturedCookies["oidc_state"] = { value: testState };
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL, init?: RequestInit) => {
const url = typeof input === "string" ? input : (input as URL).toString();
if (url.includes("/.well-known/openid-configuration")) {
return new Response(
JSON.stringify({
token_endpoint: "https://idp.test/token",
jwks_uri: "https://idp.test/jwks",
}),
{ status: 200 }
);
}
if (url.includes("/token")) {
return new Response(JSON.stringify({ id_token: idToken }), { status: 200 });
}
if (url.includes("/jwks")) {
return new Response(JSON.stringify(jwks), { status: 200 });
}
return new Response("not mocked", { status: 404 });
}) as unknown as typeof fetch;
try {
const reqUrl = `http://localhost/api/auth/oidc/callback?code=auth-code-123&state=${testState}`;
const response = await callbackRoute.GET(
new Request(reqUrl, {
headers: { "x-forwarded-proto": "http" },
})
);
assert.equal(response.status, 307);
const location = response.headers.get("location");
assert.ok(location && location.endsWith("/dashboard"));
const authCookie = capturedCookies["auth_token"];
assert.ok(authCookie, "auth_token cookie must be set");
assert.equal(typeof authCookie.value, "string");
assert.ok(authCookie.value.length > 20);
// Same attributes as password login path
assert.equal(authCookie.options?.httpOnly, true);
assert.equal(authCookie.options?.sameSite, "lax");
assert.equal(authCookie.options?.path, "/");
assert.equal(authCookie.options?.maxAge, 60 * 60 * 24 * 30);
const parts = authCookie.value.split(".");
assert.equal(parts.length, 3);
// State cookie must be cleared on success (CSRF hygiene)
const clearedState = capturedCookies["oidc_state"];
assert.ok(clearedState, "oidc_state should have been touched");
assert.equal(clearedState.value, "", "oidc_state must be cleared (empty value + maxAge 0)");
assert.equal(clearedState.options?.maxAge, 0);
// Pure OIDC bootstrap: setupComplete must be marked true so login page
// does not show "no password / onboarding" screens.
const { getSettings } = await import("../../src/lib/db/settings.ts");
const after = await getSettings();
assert.equal(after.setupComplete, true, "OIDC login must mark setupComplete");
} finally {
globalThis.fetch = originalFetch;
}
});
test("OIDC callback rejects invalid state", async () => {
await setupFullOidcSettings();
const response = await callbackRoute.GET(
new Request("http://localhost/api/auth/oidc/callback?code=some-code&state=wrong-state")
);
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("invalid_state"));
});
test("OIDC callback rejects subject not in allowed list (subject_not_allowed)", async () => {
await localDb.updateSettings({
requireLogin: true,
password: "",
oidcEnabled: true,
oidcIssuer: "https://idp.test",
oidcClientId: "client-oidc-test",
oidcClientSecret: "secret-oidc-test",
oidcRedirectPath: "/api/auth/oidc/callback",
oidcAllowedSubjects: ["user-123", "admin@example.com"],
});
// Sign a token whose sub/email is NOT in the allowlist
const { idToken, jwks } = await createSignedIdToken({
iss: "https://idp.test",
aud: "client-oidc-test",
sub: "evil-999",
email: "attacker@evil.com",
});
const testState = "state-for-whitelist-test";
capturedCookies["oidc_state"] = { value: testState };
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : (input as URL).toString();
if (url.includes("/.well-known/openid-configuration")) {
return new Response(
JSON.stringify({
token_endpoint: "https://idp.test/token",
jwks_uri: "https://idp.test/jwks",
}),
{ status: 200 }
);
}
if (url.includes("/token")) {
return new Response(JSON.stringify({ id_token: idToken }), { status: 200 });
}
if (url.includes("/jwks")) {
return new Response(JSON.stringify(jwks), { status: 200 });
}
return new Response("not mocked", { status: 404 });
}) as unknown as typeof fetch;
try {
const reqUrl = `http://localhost/api/auth/oidc/callback?code=code-whitelist&state=${testState}`;
const response = await callbackRoute.GET(
new Request(reqUrl, { headers: { "x-forwarded-proto": "http" } })
);
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("subject_not_allowed"));
} finally {
globalThis.fetch = originalFetch;
}
});
test("OIDC callback rejects partial/misconfigured OIDC settings (not_configured)", async () => {
// Partial config (enabled but missing issuer/clientId/secret) should hit the config guard.
// We must set a matching oidc_state cookie first, otherwise we hit invalid_state.
await localDb.updateSettings({
requireLogin: true,
password: "",
oidcEnabled: true,
oidcIssuer: "",
oidcClientId: "",
oidcClientSecret: "",
});
const testState = "partial-config-state-xyz";
capturedCookies["oidc_state"] = { value: testState };
const response = await callbackRoute.GET(
new Request(`http://localhost/api/auth/oidc/callback?code=foo&state=${testState}`)
);
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("not_configured"));
});
test("OIDC callback rejects token exchange failure (token_exchange)", async () => {
await setupFullOidcSettings();
const testState = "state-token-exchange";
capturedCookies["oidc_state"] = { value: testState };
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : (input as URL).toString();
if (url.includes("/.well-known/openid-configuration")) {
return new Response(
JSON.stringify({
token_endpoint: "https://idp.test/token",
jwks_uri: "https://idp.test/jwks",
}),
{ status: 200 }
);
}
if (url.includes("/token")) {
return new Response("bad request", { status: 400 });
}
return new Response("not mocked", { status: 404 });
}) as unknown as typeof fetch;
try {
const reqUrl = `http://localhost/api/auth/oidc/callback?code=bad-code&state=${testState}`;
const response = await callbackRoute.GET(
new Request(reqUrl, { headers: { "x-forwarded-proto": "http" } })
);
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("token_exchange"));
} finally {
globalThis.fetch = originalFetch;
}
});
test("OIDC callback rejects invalid ID token signature (id_token_invalid)", async () => {
await setupFullOidcSettings();
// Sign token with a completely different key so verification fails
const { privateKey: wrongKey } = await generateKeyPair("RS256");
const badIdToken = await new SignJWT({
iss: "https://idp.test",
aud: "client-oidc-test",
sub: "user-123",
})
.setProtectedHeader({ alg: "RS256" })
.setIssuedAt()
.setExpirationTime("5m")
.sign(wrongKey);
const testState = "state-bad-id-token";
capturedCookies["oidc_state"] = { value: testState };
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : (input as URL).toString();
if (url.includes("/.well-known/openid-configuration")) {
return new Response(
JSON.stringify({
token_endpoint: "https://idp.test/token",
jwks_uri: "https://idp.test/jwks",
}),
{ status: 200 }
);
}
if (url.includes("/token")) {
return new Response(JSON.stringify({ id_token: badIdToken }), { status: 200 });
}
// Return some unrelated JWKS so verification definitely fails
return new Response(JSON.stringify({ keys: [] }), { status: 200 });
}) as unknown as typeof fetch;
try {
const reqUrl = `http://localhost/api/auth/oidc/callback?code=code-bad-token&state=${testState}`;
const response = await callbackRoute.GET(
new Request(reqUrl, { headers: { "x-forwarded-proto": "http" } })
);
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("id_token_invalid"));
} finally {
globalThis.fetch = originalFetch;
}
});
test("OIDC callback rejects missing code or state (missing_code)", async () => {
await setupFullOidcSettings();
// No code and no state
const response = await callbackRoute.GET(new Request("http://localhost/api/auth/oidc/callback"));
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("missing_code"));
});
test("OIDC callback rejects missing JWT_SECRET at mint time (server_misconfigured)", async () => {
await setupFullOidcSettings();
const { idToken, jwks } = await createSignedIdToken({
iss: "https://idp.test",
aud: "client-oidc-test",
sub: "user-123",
});
const testState = "state-no-jwt-secret";
capturedCookies["oidc_state"] = { value: testState };
const originalFetch = globalThis.fetch;
globalThis.fetch = (async (input: RequestInfo | URL) => {
const url = typeof input === "string" ? input : (input as URL).toString();
if (url.includes("/.well-known/openid-configuration")) {
return new Response(
JSON.stringify({
token_endpoint: "https://idp.test/token",
jwks_uri: "https://idp.test/jwks",
}),
{ status: 200 }
);
}
if (url.includes("/token")) {
return new Response(JSON.stringify({ id_token: idToken }), { status: 200 });
}
if (url.includes("/jwks")) {
return new Response(JSON.stringify(jwks), { status: 200 });
}
return new Response("not mocked", { status: 404 });
}) as unknown as typeof fetch;
const originalJwtSecret = process.env.JWT_SECRET;
delete process.env.JWT_SECRET;
try {
const reqUrl = `http://localhost/api/auth/oidc/callback?code=code-no-secret&state=${testState}`;
const response = await callbackRoute.GET(
new Request(reqUrl, { headers: { "x-forwarded-proto": "http" } })
);
assert.equal(response.status, 307);
const loc = response.headers.get("location") || "";
assert.ok(loc.includes("login"));
assert.ok(loc.includes("server_misconfigured"));
} finally {
if (originalJwtSecret !== undefined) {
process.env.JWT_SECRET = originalJwtSecret;
}
globalThis.fetch = originalFetch;
}
});