mirror of
https://github.com/mauriceboe/TREK.git
synced 2026-11-22 21:11:14 +00:00
fix(server): tidy oidc quirks after the DI fold
This commit is contained in:
+49
-4
@@ -31,10 +31,11 @@ oidc.e2e swapped its 12-fn whole-module mock for
|
||||
`vi.spyOn(app.get(OidcService), …)` instance spies, and the integration suite
|
||||
now spies the four HTTP methods on the container instance while driving the
|
||||
real `createState`/`createAuthCode` state on that same instance — the maps
|
||||
live where the routes look. No trailing quirk commit yet — the carried
|
||||
defects (un-timeboxed `fetch`es, the 10-min state cookie vs the 5-min
|
||||
STATE_TTL, the hand-built no-re-select new-user object, the single-slot
|
||||
discovery cache) await their own `fix(server)` pass. Before that, the
|
||||
live where the routes look. The trailing `fix(server)` commit then cleared
|
||||
the carried defects (un-timeboxed `fetch`es, the 10-min state cookie vs the
|
||||
5-min STATE_TTL, the hand-built no-re-select new-user object, the single-slot
|
||||
discovery cache, the `no_email` assert, the `any`-typed invite row and the
|
||||
lazy requires) — see "Quirks fixed after the oidc fold" below. Before that, the
|
||||
authService fold — the Wave-5 chain opener, cashed in the moment the atlas
|
||||
fold unblocked it: the 1497-line auth core — the biggest single fold of the
|
||||
migration — split places-style. The pure crypto half (backup-code hash/match/generate with
|
||||
@@ -720,6 +721,50 @@ Wave-2 `permissions` + `auditLog` pair were the first frontier picks — all don
|
||||
instance now that the state maps are per-instance, or the routes look in a different
|
||||
map than the test wrote to.
|
||||
|
||||
## Quirks fixed after the oidc fold (the trailing `fix(server)` commit)
|
||||
|
||||
The relocation itself was byte-identical; these were then fixed on top, each with a
|
||||
regression test (`OIDC-SVC-049…054` + a controller cookie case), so the parity diff and
|
||||
the behaviour change stayed in separate commits:
|
||||
|
||||
1. **All four outbound `fetch`es ran unbounded and `as`-cast their responses.**
|
||||
Discovery, token exchange, userinfo and JWKS now carry
|
||||
`AbortSignal.timeout(10s)` + a content-length cap (transit/exchange-rates
|
||||
pattern), and responses are boundary-validated instead of cast: the discovery
|
||||
doc must carry its three endpoints (OIDC-SVC-049/050), the token response is
|
||||
narrowed to its three typed fields, userinfo must be an object with a string
|
||||
`sub`, and JWKS keys are filtered to records.
|
||||
2. **`getUserInfo` never checked `res.ok`** — a provider error body parsed as
|
||||
userinfo and surfaced as a misleading `no_email` redirect. Non-ok now throws
|
||||
(→ `server_error`) (OIDC-SVC-052).
|
||||
3. **The discovery cache was a single slot** keyed by `_issuer === url` — a second
|
||||
configured issuer thrashed it every login. Now a Map keyed by discovery URL,
|
||||
same 1 h TTL (OIDC-SVC-051).
|
||||
4. **The state cookie outlived its state**: cookie maxAge was 10 min against the
|
||||
server's 5-min `STATE_TTL` — the extra five minutes could only ever produce
|
||||
`invalid_state`. Both now share the exported `OIDC_STATE_TTL_MS` (controller
|
||||
cookie case).
|
||||
5. **`findOrCreateUser` non-null-asserted `userInfo.email!`** — safe only via the
|
||||
controller's `no_email` guard; a direct call threw a TypeError. Now an explicit
|
||||
`{ error: 'no_email' }` guard, flowing through the controller's existing
|
||||
error pass-through to the same redirect code (OIDC-SVC-053).
|
||||
6. **The new-user return was a hand-built partial** (`{ id, username, email, role,
|
||||
avatar }`) with no post-insert re-select — missing `password_version`/
|
||||
`is_guest`/`created_at` vs the real row the existing-user branch returns. Now
|
||||
re-selected (OIDC-SVC-054).
|
||||
7. **`validInvite` was `any`** → a typed `InviteTokenRow`; and the `uuid`/`bcryptjs`
|
||||
lazy `require()`s became top-level imports (both already load at boot
|
||||
elsewhere), taking the relocated file's lint warnings to zero.
|
||||
|
||||
**Quirks deliberately preserved** (parity, not oversights): `frontendUrl`'s
|
||||
case-sensitive `nodeEnv === 'production'` compare (commented "on purpose") with the
|
||||
hardcoded dev origin; `consumeAuthCode` burning an expired code before the expiry
|
||||
check (single-use beats replay); the `invite_exhausted` sentinel compared by
|
||||
reference across the transaction; the `${username}_${Date.now() % 10000}` collision
|
||||
fallback; the last-admin demotion guard (#1274), guest exclusion (#1362), avatar
|
||||
sync rules (#1399) and trip-bound invites (#1402); the documented missing-nonce gap
|
||||
in `verifyIdToken`; and the duplicated OIDC-SVC-025/025b test IDs.
|
||||
|
||||
## Quirks fixed after the auth fold (the trailing `fix(server)` commit)
|
||||
|
||||
The relocation itself was byte-identical; these were then fixed on top, each with a
|
||||
|
||||
@@ -1,7 +1,7 @@
|
||||
import { Controller, Get, Query, Req, Res } from '@nestjs/common';
|
||||
import type { Request, Response } from 'express';
|
||||
import { readEnv } from '../../app-config';
|
||||
import { OidcService } from './oidc.service';
|
||||
import { OidcService, OIDC_STATE_TTL_MS } from './oidc.service';
|
||||
import { cookieOptions } from '../../services/cookie';
|
||||
|
||||
const OIDC_STATE_COOKIE = 'trek_oidc_state';
|
||||
@@ -48,7 +48,9 @@ export class OidcController {
|
||||
// so an attacker-initiated login (whose callback URL carries a valid state
|
||||
// from the shared server map) cannot be replayed in a victim's browser to
|
||||
// log them into the attacker's account (OIDC login CSRF / session fixation).
|
||||
res.cookie(OIDC_STATE_COOKIE, state, { ...cookieOptions(false, req), maxAge: 10 * 60 * 1000 });
|
||||
// maxAge matches the server-side pending-state TTL — a cookie that
|
||||
// outlives its state entry could only ever produce invalid_state.
|
||||
res.cookie(OIDC_STATE_COOKIE, state, { ...cookieOptions(false, req), maxAge: OIDC_STATE_TTL_MS });
|
||||
const params = new URLSearchParams({
|
||||
response_type: 'code',
|
||||
client_id: config.clientId,
|
||||
|
||||
@@ -1,6 +1,9 @@
|
||||
import { Injectable, OnModuleDestroy } from '@nestjs/common';
|
||||
import crypto from 'crypto';
|
||||
import type { webcrypto } from 'crypto';
|
||||
import jwt from 'jsonwebtoken';
|
||||
import { v4 as uuidv4 } from 'uuid';
|
||||
import bcrypt from 'bcryptjs';
|
||||
import type { Request, Response } from 'express';
|
||||
import { readEnv, getAppUrl } from '../../app-config';
|
||||
import { JWT_SECRET, SESSION_DURATION_SECONDS } from '../../config';
|
||||
@@ -58,10 +61,17 @@ export interface OidcConfig {
|
||||
|
||||
const AUTH_CODE_TTL = 60000; // 1 minute
|
||||
const AUTH_CODE_CLEANUP = 30000; // 30 seconds
|
||||
const STATE_TTL = 5 * 60 * 1000; // 5 minutes
|
||||
/** 5 minutes — the server-side pending-state TTL AND the controller's state-cookie maxAge. */
|
||||
export const OIDC_STATE_TTL_MS = 5 * 60 * 1000;
|
||||
const STATE_TTL = OIDC_STATE_TTL_MS;
|
||||
const STATE_CLEANUP = 60 * 1000; // 1 minute
|
||||
const DISCOVERY_TTL = 60 * 60 * 1000; // 1 hour
|
||||
|
||||
const FETCH_TIMEOUT_MS = 10_000;
|
||||
// Discovery docs, token responses, userinfo payloads and JWKS sets are all a
|
||||
// few KB; anything near this cap is not the endpoint we think it is.
|
||||
const MAX_RESPONSE_BYTES = 1024 * 1024;
|
||||
|
||||
// 5 minute JWKS cache — short enough to pick up key rotation within a
|
||||
// reasonable window, long enough that normal login flow doesn't fetch
|
||||
// JWKS on every callback.
|
||||
@@ -76,6 +86,38 @@ function base64url(buf: Buffer): string {
|
||||
return buf.toString('base64').replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, '');
|
||||
}
|
||||
|
||||
const isRecord = (v: unknown): v is Record<string, unknown> =>
|
||||
typeof v === 'object' && v !== null && !Array.isArray(v);
|
||||
|
||||
const str = (v: unknown): string | undefined => (typeof v === 'string' ? v : undefined);
|
||||
|
||||
function isDiscoveryDoc(v: unknown): v is OidcDiscoveryDoc {
|
||||
if (!isRecord(v)) return false;
|
||||
if (typeof v.authorization_endpoint !== 'string' || typeof v.token_endpoint !== 'string' || typeof v.userinfo_endpoint !== 'string') return false;
|
||||
if (v.issuer !== undefined && typeof v.issuer !== 'string') return false;
|
||||
if (v.jwks_uri !== undefined && typeof v.jwks_uri !== 'string') return false;
|
||||
return true;
|
||||
}
|
||||
|
||||
// Same content-length pattern as transit.service.ts — structural param (the
|
||||
// express Response import shadows the fetch Response type here) and the
|
||||
// optional chain keeps header-less test stubs flowing through.
|
||||
function assertResponseSize(res: { headers?: { get(name: string): string | null } }): void {
|
||||
const length = Number(res.headers?.get('content-length') ?? 0);
|
||||
if (length > MAX_RESPONSE_BYTES) throw new Error('OIDC response too large');
|
||||
}
|
||||
|
||||
/** The invite_tokens row shape findOrCreateUser consumes. */
|
||||
interface InviteTokenRow {
|
||||
id: number;
|
||||
token: string;
|
||||
max_uses: number;
|
||||
used_count: number;
|
||||
expires_at: string | null;
|
||||
created_by: number | null;
|
||||
trip_id: number | null;
|
||||
}
|
||||
|
||||
function base64UrlDecode(input: string): Buffer {
|
||||
const padded = input.replace(/-/g, '+').replace(/_/g, '/') + '='.repeat((4 - (input.length % 4)) % 4);
|
||||
return Buffer.from(padded, 'base64');
|
||||
@@ -104,6 +146,16 @@ function safeOidcPicture(picture: unknown): string | null {
|
||||
* nothing outside the container consumes this domain, so no bridge needs to
|
||||
* share it. The sweepers start in the constructor (legacy started them at
|
||||
* import) and are cleared in onModuleDestroy.
|
||||
*
|
||||
* Post-migration fixes on top of the relocated legacy behavior (exchange-rates
|
||||
* precedent): every outbound fetch carries an AbortSignal timeout and a
|
||||
* content-length cap, responses are boundary-validated instead of `as`-cast
|
||||
* (getUserInfo now also refuses non-ok responses), the discovery cache is
|
||||
* keyed by URL instead of a single slot, findOrCreateUser guards the email
|
||||
* claim and re-selects the inserted user row, and the uuid/bcryptjs lazy
|
||||
* requires became top-level imports. Kept on purpose: frontendUrl's
|
||||
* case-sensitive nodeEnv compare, consumeAuthCode burning expired codes
|
||||
* before the expiry check, and the invite_exhausted reference sentinel.
|
||||
*/
|
||||
@Injectable()
|
||||
export class OidcService implements OnModuleDestroy {
|
||||
@@ -119,9 +171,9 @@ export class OidcService implements OnModuleDestroy {
|
||||
|
||||
private readonly authCodes = new Map<string, { token: string; created: number }>();
|
||||
|
||||
// Discovery document cache (1 h TTL)
|
||||
private discoveryCache: OidcDiscoveryDoc | null = null;
|
||||
private discoveryCacheTime = 0;
|
||||
// Discovery document cache (1 h TTL), keyed by discovery URL so two
|
||||
// configured issuers no longer thrash a single slot.
|
||||
private readonly discoveryCache = new Map<string, { doc: OidcDiscoveryDoc; fetchedAt: number }>();
|
||||
|
||||
private readonly jwksCache = new Map<string, JwksEntry>();
|
||||
|
||||
@@ -176,7 +228,6 @@ export class OidcService implements OnModuleDestroy {
|
||||
}
|
||||
|
||||
createAuthCode(token: string): string {
|
||||
const { v4: uuidv4 } = require('uuid');
|
||||
const authCode: string = uuidv4();
|
||||
this.authCodes.set(authCode, { token, created: Date.now() });
|
||||
return authCode;
|
||||
@@ -215,12 +266,16 @@ export class OidcService implements OnModuleDestroy {
|
||||
|
||||
async discover(issuer: string, discoveryUrl?: string | null): Promise<OidcDiscoveryDoc> {
|
||||
const url = discoveryUrl || `${issuer}/.well-known/openid-configuration`;
|
||||
if (this.discoveryCache && Date.now() - this.discoveryCacheTime < DISCOVERY_TTL && this.discoveryCache._issuer === url) {
|
||||
return this.discoveryCache;
|
||||
const cached = this.discoveryCache.get(url);
|
||||
if (cached && Date.now() - cached.fetchedAt < DISCOVERY_TTL) {
|
||||
return cached.doc;
|
||||
}
|
||||
const res = await fetch(url);
|
||||
const res = await fetch(url, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error('Failed to fetch OIDC discovery document');
|
||||
const doc = (await res.json()) as OidcDiscoveryDoc;
|
||||
assertResponseSize(res);
|
||||
const parsed: unknown = await res.json();
|
||||
if (!isDiscoveryDoc(parsed)) throw new Error('Invalid OIDC discovery document');
|
||||
const doc = parsed;
|
||||
// Validate that the discovery doc's issuer matches the operator-configured one.
|
||||
// When no custom discoveryUrl is set, a mismatch signals a MITM or misconfiguration
|
||||
// and we reject. When the operator explicitly overrides the discovery URL (e.g.
|
||||
@@ -238,8 +293,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
}
|
||||
}
|
||||
doc._issuer = url;
|
||||
this.discoveryCache = doc;
|
||||
this.discoveryCacheTime = Date.now();
|
||||
this.discoveryCache.set(url, { doc, fetchedAt: Date.now() });
|
||||
return doc;
|
||||
}
|
||||
|
||||
@@ -304,8 +358,14 @@ export class OidcService implements OnModuleDestroy {
|
||||
method: 'POST',
|
||||
headers: { 'Content-Type': 'application/x-www-form-urlencoded' },
|
||||
body,
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
const tokenData = (await tokenRes.json()) as OidcTokenResponse;
|
||||
assertResponseSize(tokenRes);
|
||||
// Error responses are still parsed on purpose — callers branch on _ok/_status.
|
||||
const parsed: unknown = await tokenRes.json();
|
||||
const tokenData: OidcTokenResponse = isRecord(parsed)
|
||||
? { access_token: str(parsed.access_token), id_token: str(parsed.id_token), token_type: str(parsed.token_type) }
|
||||
: {};
|
||||
return { ...tokenData, _ok: tokenRes.ok, _status: tokenRes.status };
|
||||
}
|
||||
|
||||
@@ -316,8 +376,13 @@ export class OidcService implements OnModuleDestroy {
|
||||
async getUserInfo(userinfoEndpoint: string, accessToken: string): Promise<OidcUserInfo> {
|
||||
const res = await fetch(userinfoEndpoint, {
|
||||
headers: { Authorization: `Bearer ${accessToken}` },
|
||||
signal: AbortSignal.timeout(FETCH_TIMEOUT_MS),
|
||||
});
|
||||
return (await res.json()) as OidcUserInfo;
|
||||
if (!res.ok) throw new Error(`Userinfo fetch failed: HTTP ${res.status}`);
|
||||
assertResponseSize(res);
|
||||
const parsed: unknown = await res.json();
|
||||
if (!isRecord(parsed) || typeof parsed.sub !== 'string') throw new Error('Invalid userinfo response');
|
||||
return parsed as OidcUserInfo;
|
||||
}
|
||||
|
||||
// -------------------------------------------------------------------------
|
||||
@@ -327,10 +392,11 @@ export class OidcService implements OnModuleDestroy {
|
||||
private async fetchJwks(jwksUri: string): Promise<Array<Record<string, unknown>>> {
|
||||
const cached = this.jwksCache.get(jwksUri);
|
||||
if (cached && Date.now() - cached.fetchedAt < JWKS_TTL_MS) return cached.keys;
|
||||
const res = await fetch(jwksUri);
|
||||
const res = await fetch(jwksUri, { signal: AbortSignal.timeout(FETCH_TIMEOUT_MS) });
|
||||
if (!res.ok) throw new Error(`JWKS fetch failed: HTTP ${res.status}`);
|
||||
const json = (await res.json()) as { keys?: Array<Record<string, unknown>> };
|
||||
const keys = json.keys ?? [];
|
||||
assertResponseSize(res);
|
||||
const json: unknown = await res.json();
|
||||
const keys = isRecord(json) && Array.isArray(json.keys) ? json.keys.filter(isRecord) : [];
|
||||
this.jwksCache.set(jwksUri, { keys, fetchedAt: Date.now() });
|
||||
return keys;
|
||||
}
|
||||
@@ -367,7 +433,7 @@ export class OidcService implements OnModuleDestroy {
|
||||
|
||||
let keys: Array<Record<string, unknown>>;
|
||||
try { keys = await this.fetchJwks(doc.jwks_uri); }
|
||||
catch (e) { return { ok: false, error: 'jwks_fetch_failed' }; }
|
||||
catch { return { ok: false, error: 'jwks_fetch_failed' }; }
|
||||
|
||||
// When the token carries a `kid`, refuse to fall back to any other
|
||||
// key in the JWKS — a mismatch means the token was signed with a key
|
||||
@@ -380,10 +446,10 @@ export class OidcService implements OnModuleDestroy {
|
||||
|
||||
let publicKey;
|
||||
try {
|
||||
// Node 16+ understands JWK directly; no PEM conversion library needed.
|
||||
// Node's crypto accepts a JWK object directly as `{ key, format: 'jwk' }`.
|
||||
// The type signature isn't strict on our TS config so we cast through any.
|
||||
publicKey = crypto.createPublicKey({ key: jwk as any, format: 'jwk' });
|
||||
// Node 16+ understands JWK directly; no PEM conversion library needed —
|
||||
// JsonWebKey carries an unknown-valued index signature, so the record
|
||||
// narrows without an any-cast.
|
||||
publicKey = crypto.createPublicKey({ key: jwk as webcrypto.JsonWebKey, format: 'jwk' });
|
||||
} catch {
|
||||
return { ok: false, error: 'key_import_failed' };
|
||||
}
|
||||
@@ -419,7 +485,11 @@ export class OidcService implements OnModuleDestroy {
|
||||
config: OidcConfig,
|
||||
inviteToken?: string,
|
||||
): { user: User } | { error: string } {
|
||||
const email = userInfo.email!.trim().toLowerCase();
|
||||
// Defense-in-depth for direct callers — the controller redirects on a
|
||||
// missing email before it ever calls this; the same code flows through its
|
||||
// `oidc_error=' + result.error` pass-through if reached here.
|
||||
if (!userInfo.email) return { error: 'no_email' };
|
||||
const email = userInfo.email.trim().toLowerCase();
|
||||
const name = userInfo.name || userInfo.preferred_username || email.split('@')[0];
|
||||
const sub = userInfo.sub;
|
||||
const picture = safeOidcPicture(userInfo.picture);
|
||||
@@ -477,9 +547,9 @@ export class OidcService implements OnModuleDestroy {
|
||||
const userCount = (this.db.prepare('SELECT COUNT(*) as count FROM users WHERE COALESCE(is_guest, 0) = 0').get() as { count: number }).count;
|
||||
const isFirstUser = userCount === 0;
|
||||
|
||||
let validInvite: any = null;
|
||||
let validInvite: InviteTokenRow | null = null;
|
||||
if (inviteToken) {
|
||||
validInvite = this.db.prepare('SELECT * FROM invite_tokens WHERE token = ?').get(inviteToken);
|
||||
validInvite = (this.db.prepare('SELECT * FROM invite_tokens WHERE token = ?').get(inviteToken) as InviteTokenRow | undefined) ?? null;
|
||||
if (validInvite) {
|
||||
if (validInvite.max_uses > 0 && validInvite.used_count >= validInvite.max_uses) validInvite = null;
|
||||
if (validInvite?.expires_at && new Date(validInvite.expires_at) < new Date()) validInvite = null;
|
||||
@@ -495,7 +565,6 @@ export class OidcService implements OnModuleDestroy {
|
||||
|
||||
const role = this.resolveOidcRole(userInfo, isFirstUser);
|
||||
const randomPass = crypto.randomBytes(32).toString('hex');
|
||||
const bcrypt = require('bcryptjs');
|
||||
const hash = bcrypt.hashSync(randomPass, 10);
|
||||
|
||||
// Username: sanitize and avoid collisions. Keep dots — they are valid in
|
||||
@@ -529,7 +598,10 @@ export class OidcService implements OnModuleDestroy {
|
||||
}
|
||||
return ins;
|
||||
}) as { lastInsertRowid: number | bigint };
|
||||
user = { id: Number(result.lastInsertRowid), username, email, role, avatar: picture } as User;
|
||||
// Re-select so the returned User carries the real row (password_version,
|
||||
// is_guest, created_at, …) instead of a hand-built partial — same shape
|
||||
// the existing-user branch returns.
|
||||
user = this.db.prepare('SELECT * FROM users WHERE id = ?').get(Number(result.lastInsertRowid)) as User;
|
||||
return { user };
|
||||
} catch (err) {
|
||||
if (err === inviteRaceError) {
|
||||
|
||||
@@ -2,6 +2,7 @@ import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||
import type { Request, Response } from 'express';
|
||||
|
||||
import { OidcController } from '../../../src/nest/oidc/oidc.controller';
|
||||
import { OIDC_STATE_TTL_MS } from '../../../src/nest/oidc/oidc.service';
|
||||
import type { OidcService } from '../../../src/nest/oidc/oidc.service';
|
||||
|
||||
function svc(o: Partial<OidcService> = {}): OidcService {
|
||||
@@ -72,6 +73,12 @@ describe('OidcController /login', () => {
|
||||
expect(res.redirectedTo).toContain('code_challenge_method=S256');
|
||||
});
|
||||
|
||||
it('binds the state cookie with a maxAge matching the server-side state TTL', async () => {
|
||||
const res = makeRes();
|
||||
await new OidcController(svc()).login(req, res);
|
||||
expect(res.cookie).toHaveBeenCalledWith('trek_oidc_state', 'st', expect.objectContaining({ maxAge: OIDC_STATE_TTL_MS }));
|
||||
});
|
||||
|
||||
it('400 when a non-HTTPS issuer is used in production', async () => {
|
||||
process.env.NODE_ENV = 'production';
|
||||
const res = makeRes();
|
||||
|
||||
@@ -1,11 +1,13 @@
|
||||
/**
|
||||
* Unit tests for the DI-native OidcService — OIDC-SVC-001 through OIDC-SVC-048
|
||||
* Unit tests for the DI-native OidcService — OIDC-SVC-001 through OIDC-SVC-054
|
||||
* (moved 1:1 from the legacy tests/unit/services/oidcService.test.ts with case
|
||||
* IDs preserved; 046–048 carry over the wrapper cases from the superseded
|
||||
* delegation-shim suite). Covers state management, auth codes, role
|
||||
* resolution, findOrCreateUser, discover caching, and the ReDoS-sensitive
|
||||
* issuer trailing-slash regex. Constructed directly (no TestingModule, repo
|
||||
* convention) over a real in-memory SQLite database.
|
||||
* delegation-shim suite; 049–054 pin the post-fold `fix(server)` quirk fixes —
|
||||
* fetch timeout/validation, per-URL discovery cache, userinfo ok-check, the
|
||||
* no_email guard and the post-insert re-select). Covers state management,
|
||||
* auth codes, role resolution, findOrCreateUser, discover caching, and the
|
||||
* ReDoS-sensitive issuer trailing-slash regex. Constructed directly (no
|
||||
* TestingModule, repo convention) over a real in-memory SQLite database.
|
||||
*/
|
||||
import { describe, it, expect, vi, beforeAll, beforeEach, afterAll, afterEach } from 'vitest';
|
||||
import { generateKeyPairSync } from 'crypto';
|
||||
@@ -302,6 +304,51 @@ describe('discover', () => {
|
||||
);
|
||||
});
|
||||
|
||||
it('OIDC-SVC-049: passes an abort-signal timeout to the discovery fetch', async () => {
|
||||
const doc = {
|
||||
authorization_endpoint: 'https://unique-t.example.com/auth',
|
||||
token_endpoint: 'https://unique-t.example.com/token',
|
||||
userinfo_endpoint: 'https://unique-t.example.com/userinfo',
|
||||
};
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => doc }));
|
||||
|
||||
await svc.discover('https://unique-t.example.com');
|
||||
|
||||
const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(fetchCall[1].signal).toBeInstanceOf(AbortSignal);
|
||||
});
|
||||
|
||||
it('OIDC-SVC-050: rejects a discovery document missing the required endpoints', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({ ok: true, json: async () => ({ foo: 'bar' }) }));
|
||||
await expect(svc.discover('https://unique-bad.example.com')).rejects.toThrow(
|
||||
'Invalid OIDC discovery document',
|
||||
);
|
||||
});
|
||||
|
||||
it('OIDC-SVC-051: caches per discovery URL — two issuers do not thrash each other', async () => {
|
||||
const docFor = (base: string) => ({
|
||||
authorization_endpoint: `${base}/auth`,
|
||||
token_endpoint: `${base}/token`,
|
||||
userinfo_endpoint: `${base}/userinfo`,
|
||||
issuer: base,
|
||||
});
|
||||
const fetchMock = vi.fn((url: string) => {
|
||||
const base = url.replace('/.well-known/openid-configuration', '');
|
||||
return Promise.resolve({ ok: true, json: async () => docFor(base) });
|
||||
});
|
||||
vi.stubGlobal('fetch', fetchMock);
|
||||
|
||||
await svc.discover('https://unique-3.example.com');
|
||||
await svc.discover('https://unique-4.example.com');
|
||||
const again3 = await svc.discover('https://unique-3.example.com');
|
||||
const again4 = await svc.discover('https://unique-4.example.com');
|
||||
|
||||
// One network round-trip per URL — the second pair served from cache.
|
||||
expect(fetchMock).toHaveBeenCalledTimes(2);
|
||||
expect(again3.issuer).toBe('https://unique-3.example.com');
|
||||
expect(again4.issuer).toBe('https://unique-4.example.com');
|
||||
});
|
||||
|
||||
it('OIDC-SVC-039: trailing-slash-only mismatch with explicit discoveryUrl does not warn', async () => {
|
||||
const doc = {
|
||||
issuer: 'https://auth.example.com/',
|
||||
@@ -567,6 +614,26 @@ describe('findOrCreateUser', () => {
|
||||
expect(row.avatar).toBe('https://idp.example.com/u/new.png');
|
||||
});
|
||||
|
||||
it('OIDC-SVC-053: returns no_email when the email claim is missing (no throw)', () => {
|
||||
const result = svc.findOrCreateUser({ sub: 'sub-no-email', name: 'No Email' }, MOCK_CONFIG);
|
||||
expect('error' in result).toBe(true);
|
||||
expect((result as { error: string }).error).toBe('no_email');
|
||||
});
|
||||
|
||||
it('OIDC-SVC-054: a new user is returned as the re-selected DB row, not a hand-built partial', () => {
|
||||
const result = svc.findOrCreateUser(
|
||||
{ sub: 'sub-full-row', email: 'fullrow@example.com', name: 'Full Row' },
|
||||
MOCK_CONFIG
|
||||
);
|
||||
expect('user' in result).toBe(true);
|
||||
const user = (result as { user: any }).user;
|
||||
// Columns the legacy hand-built object silently lacked.
|
||||
expect(user.password_version).toBeDefined();
|
||||
expect(user.is_guest).toBeDefined();
|
||||
expect(user.created_at).toBeDefined();
|
||||
expect(user.email).toBe('fullrow@example.com');
|
||||
});
|
||||
|
||||
it('OIDC-SVC-045: a trip-bound invite auto-adds the new SSO user as a trip member (#1402)', () => {
|
||||
const { user: admin } = createUser(testDb, { role: 'admin' });
|
||||
const trip = createTrip(testDb, admin.id);
|
||||
@@ -638,6 +705,7 @@ describe('getUserInfo', () => {
|
||||
it('OIDC-SVC-032: fetches userinfo with Bearer token and returns parsed JSON', async () => {
|
||||
const userInfoData = { sub: 'user-sub', email: 'user@example.com', name: 'User Name' };
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: true,
|
||||
json: async () => userInfoData,
|
||||
}));
|
||||
|
||||
@@ -649,6 +717,18 @@ describe('getUserInfo', () => {
|
||||
const fetchCall = (fetch as ReturnType<typeof vi.fn>).mock.calls[0];
|
||||
expect(fetchCall[1].headers.Authorization).toBe('Bearer access-token-123');
|
||||
});
|
||||
|
||||
it('OIDC-SVC-052: throws on a non-ok userinfo response instead of parsing the error body', async () => {
|
||||
vi.stubGlobal('fetch', vi.fn().mockResolvedValue({
|
||||
ok: false,
|
||||
status: 401,
|
||||
json: async () => ({ error: 'invalid_token' }),
|
||||
}));
|
||||
|
||||
await expect(svc.getUserInfo('https://oidc.example.com/userinfo', 'expired-token')).rejects.toThrow(
|
||||
'Userinfo fetch failed: HTTP 401',
|
||||
);
|
||||
});
|
||||
});
|
||||
|
||||
// ── verifyIdToken ─────────────────────────────────────────────────────────────
|
||||
|
||||
Reference in New Issue
Block a user