test(19-03): add failing tests for localAuthMiddleware and GET /api/auth/mode
- RED: 8 tests failing (modules not yet created) - localAuthMiddleware: 4 tests for cookie→user shape, no-cookie passthrough, missing user row, devAuthBypass coexistence - authMode: 3 tests for mode response with no oidc, env oidc, app_config oidc
This commit is contained in:
@@ -0,0 +1,246 @@
|
|||||||
|
/**
|
||||||
|
* localAuthMiddleware() — unit tests (Plan 19-03, TDD RED → GREEN).
|
||||||
|
*
|
||||||
|
* Covers:
|
||||||
|
* Test 1: valid local-session cookie for an existing user → c.get('user') set; next() called
|
||||||
|
* Test 2: no cookie → pure passthrough; c.get('user') NOT set (OIDC guard fall-through intact)
|
||||||
|
* Test 3: cookie with valid JWT but userId has no users row → passthrough (no crash)
|
||||||
|
* Test 4: c.get('user') already set (devAuthBypass ran first) → not overwritten; next() called
|
||||||
|
*
|
||||||
|
* Security:
|
||||||
|
* - Test 2 is the Pitfall-1 guard: middleware must NEVER call c.set('user', undefined).
|
||||||
|
* The OIDC guard only fires when c.get('user') is falsy; setting it to undefined
|
||||||
|
* would suppress the OIDC guard for unauthenticated requests.
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
import { Hono } from 'hono';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Mock DB — avoids real DB connections in this middleware unit-test
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const mockDbSelectResult: Array<{
|
||||||
|
id: number;
|
||||||
|
oidcIss: string | null;
|
||||||
|
oidcSub: string | null;
|
||||||
|
displayName: string | null;
|
||||||
|
color: string;
|
||||||
|
}> = [];
|
||||||
|
|
||||||
|
vi.mock('../../src/db/client.js', () => ({
|
||||||
|
db: {
|
||||||
|
select: vi.fn().mockReturnValue({
|
||||||
|
from: vi.fn().mockReturnValue({
|
||||||
|
where: vi.fn().mockReturnValue({
|
||||||
|
limit: vi.fn().mockImplementation(() => Promise.resolve(mockDbSelectResult)),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Mock verifyLocalSessionCookie — controls what userId the cookie yields
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let mockVerifyResult: number | null = null;
|
||||||
|
|
||||||
|
vi.mock('../../src/auth/localSession.js', () => ({
|
||||||
|
verifyLocalSessionCookie: vi.fn().mockImplementation(() => Promise.resolve(mockVerifyResult)),
|
||||||
|
issueLocalSessionCookie: vi.fn(),
|
||||||
|
clearLocalSessionCookie: vi.fn(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Helpers
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
async function getMiddleware() {
|
||||||
|
const { localAuthMiddleware } = await import('../../src/auth/localAuthMiddleware.js');
|
||||||
|
return localAuthMiddleware;
|
||||||
|
}
|
||||||
|
|
||||||
|
function makeApp(middleware: ReturnType<typeof vi.fn>, presetUser?: unknown) {
|
||||||
|
const app = new Hono();
|
||||||
|
|
||||||
|
if (presetUser !== undefined) {
|
||||||
|
// Simulate devAuthBypass having already set c.get('user')
|
||||||
|
app.use('/api/*', async (c, next) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
c.set('user', presetUser as any);
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
}
|
||||||
|
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-unsafe-call
|
||||||
|
app.use('/api/*', middleware());
|
||||||
|
|
||||||
|
let capturedUser: unknown = 'NOT_SET_SENTINEL';
|
||||||
|
let nextCalled = false;
|
||||||
|
|
||||||
|
app.get('/api/test', (c) => {
|
||||||
|
capturedUser = c.get('user');
|
||||||
|
nextCalled = true;
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
return { app, getCapturedUser: () => capturedUser, wasNextCalled: () => nextCalled };
|
||||||
|
}
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe('localAuthMiddleware', () => {
|
||||||
|
beforeEach(() => {
|
||||||
|
mockVerifyResult = null;
|
||||||
|
mockDbSelectResult.splice(0);
|
||||||
|
vi.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
vi.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 1: valid local-session cookie for existing user → sets c.get("user") and calls next', async () => {
|
||||||
|
mockVerifyResult = 42;
|
||||||
|
mockDbSelectResult.push({
|
||||||
|
id: 42,
|
||||||
|
oidcIss: 'local',
|
||||||
|
oidcSub: '42',
|
||||||
|
displayName: 'Test User',
|
||||||
|
color: '#4A90D9',
|
||||||
|
});
|
||||||
|
|
||||||
|
const localAuthMiddleware = await getMiddleware();
|
||||||
|
const { app } = makeApp(localAuthMiddleware);
|
||||||
|
|
||||||
|
const res = await app.request('/api/test');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
|
||||||
|
// Re-import to inspect captured value via the route handler's closure
|
||||||
|
// We verify by checking response — route returns 200 only if next() was called
|
||||||
|
// The actual user value is verified via the app route handler
|
||||||
|
const body = (await res.json()) as { ok: boolean };
|
||||||
|
expect(body.ok).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 1b: user shape from DB row is correct (id, oidcIss, oidcSub, displayName, color)', async () => {
|
||||||
|
mockVerifyResult = 7;
|
||||||
|
mockDbSelectResult.push({
|
||||||
|
id: 7,
|
||||||
|
oidcIss: 'https://auth.example.com',
|
||||||
|
oidcSub: 'sub-abc',
|
||||||
|
displayName: 'Alice',
|
||||||
|
color: '#FF5733',
|
||||||
|
});
|
||||||
|
|
||||||
|
const localAuthMiddleware = await getMiddleware();
|
||||||
|
const app = new Hono();
|
||||||
|
let capturedUser: unknown;
|
||||||
|
|
||||||
|
app.use('/api/*', localAuthMiddleware());
|
||||||
|
app.get('/api/test', (c) => {
|
||||||
|
capturedUser = c.get('user');
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.request('/api/test');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(capturedUser).toBeDefined();
|
||||||
|
const u = capturedUser as { id: number; oidcIss: string; oidcSub: string; displayName: string | null; color: string };
|
||||||
|
expect(u.id).toBe(7);
|
||||||
|
expect(u.oidcIss).toBe('https://auth.example.com');
|
||||||
|
expect(u.oidcSub).toBe('sub-abc');
|
||||||
|
expect(u.displayName).toBe('Alice');
|
||||||
|
expect(u.color).toBe('#FF5733');
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 2: no cookie → pure passthrough; c.get("user") remains unset (Pitfall-1 guard)', async () => {
|
||||||
|
mockVerifyResult = null; // No cookie / invalid
|
||||||
|
|
||||||
|
const localAuthMiddleware = await getMiddleware();
|
||||||
|
const app = new Hono();
|
||||||
|
let capturedUser: unknown = 'NOT_SET_SENTINEL';
|
||||||
|
let nextCalled = false;
|
||||||
|
|
||||||
|
app.use('/api/*', localAuthMiddleware());
|
||||||
|
app.get('/api/test', (c) => {
|
||||||
|
capturedUser = c.get('user');
|
||||||
|
nextCalled = true;
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.request('/api/test');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(nextCalled).toBe(true);
|
||||||
|
// CRITICAL: user must remain UNSET (undefined), NOT set to undefined explicitly.
|
||||||
|
// The OIDC guard checks c.get('user') — if it's undefined (not set), the guard fires.
|
||||||
|
// The middleware must call next() without c.set('user') on the no-cookie path.
|
||||||
|
expect(capturedUser).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 3: valid cookie but userId has no users row → passthrough (no crash)', async () => {
|
||||||
|
mockVerifyResult = 999; // Valid JWT payload, userId=999
|
||||||
|
mockDbSelectResult.splice(0); // No DB row for userId 999
|
||||||
|
|
||||||
|
const localAuthMiddleware = await getMiddleware();
|
||||||
|
const app = new Hono();
|
||||||
|
let capturedUser: unknown = 'NOT_SET_SENTINEL';
|
||||||
|
let nextCalled = false;
|
||||||
|
|
||||||
|
app.use('/api/*', localAuthMiddleware());
|
||||||
|
app.get('/api/test', (c) => {
|
||||||
|
capturedUser = c.get('user');
|
||||||
|
nextCalled = true;
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.request('/api/test');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
expect(nextCalled).toBe(true);
|
||||||
|
// No row found — should passthrough without setting user
|
||||||
|
expect(capturedUser).toBeUndefined();
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 4: c.get("user") already set (devAuthBypass ran first) → not overwritten; next() called', async () => {
|
||||||
|
const preExistingUser = {
|
||||||
|
id: 1,
|
||||||
|
oidcIss: 'dev',
|
||||||
|
oidcSub: 'dev-user',
|
||||||
|
displayName: 'Dev User',
|
||||||
|
color: '#4A90D9',
|
||||||
|
};
|
||||||
|
|
||||||
|
// Even if verifyLocalSessionCookie would succeed, the existing user must not be overwritten
|
||||||
|
mockVerifyResult = 99; // A DIFFERENT userId
|
||||||
|
mockDbSelectResult.push({
|
||||||
|
id: 99,
|
||||||
|
oidcIss: 'local',
|
||||||
|
oidcSub: '99',
|
||||||
|
displayName: 'Another User',
|
||||||
|
color: '#FF0000',
|
||||||
|
});
|
||||||
|
|
||||||
|
const localAuthMiddleware = await getMiddleware();
|
||||||
|
const app = new Hono();
|
||||||
|
let capturedUser: unknown;
|
||||||
|
|
||||||
|
// Simulate devAuthBypass having set the user first
|
||||||
|
app.use('/api/*', async (c, next) => {
|
||||||
|
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
||||||
|
c.set('user', preExistingUser as any);
|
||||||
|
await next();
|
||||||
|
});
|
||||||
|
app.use('/api/*', localAuthMiddleware());
|
||||||
|
app.get('/api/test', (c) => {
|
||||||
|
capturedUser = c.get('user');
|
||||||
|
return c.json({ ok: true });
|
||||||
|
});
|
||||||
|
|
||||||
|
const res = await app.request('/api/test');
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
// User must remain the dev-bypass user, not overwritten
|
||||||
|
expect(capturedUser).toEqual(preExistingUser);
|
||||||
|
expect((capturedUser as typeof preExistingUser).id).toBe(1);
|
||||||
|
});
|
||||||
|
});
|
||||||
@@ -0,0 +1,123 @@
|
|||||||
|
/**
|
||||||
|
* GET /api/auth/mode — unit tests (Plan 19-03, TDD RED → GREEN).
|
||||||
|
*
|
||||||
|
* Covers:
|
||||||
|
* Test 5: returns { localEnabled:true, oidcEnabled:false } when no oidc_issuer in env or app_config
|
||||||
|
* Test 6: returns { oidcEnabled:true } when OIDC_ISSUER env var is set
|
||||||
|
* Test 6b: returns { oidcEnabled:true } when oidc_issuer is in app_config (no env var)
|
||||||
|
*
|
||||||
|
* Pre-auth surface: reachable without OIDC session (same as /api/setup/status).
|
||||||
|
*/
|
||||||
|
|
||||||
|
import { describe, it, expect, vi, beforeEach, afterEach } from 'vitest';
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// DB mock — controls app_config rows returned for oidc_issuer
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
let mockAppConfigOidcIssuer: string | null = null;
|
||||||
|
|
||||||
|
vi.mock('../../src/db/client.js', () => ({
|
||||||
|
db: {
|
||||||
|
execute: vi.fn().mockResolvedValue([[{ '1': 1 }]]),
|
||||||
|
select: vi.fn().mockImplementation(() => ({
|
||||||
|
from: vi.fn().mockReturnValue({
|
||||||
|
where: vi.fn().mockReturnValue({
|
||||||
|
limit: vi.fn().mockImplementation(() => {
|
||||||
|
if (mockAppConfigOidcIssuer) {
|
||||||
|
return Promise.resolve([{ value: mockAppConfigOidcIssuer }]);
|
||||||
|
}
|
||||||
|
return Promise.resolve([]);
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
})),
|
||||||
|
insert: vi.fn().mockReturnValue({
|
||||||
|
values: vi.fn().mockReturnValue({
|
||||||
|
onDuplicateKeyUpdate: vi.fn().mockResolvedValue(undefined),
|
||||||
|
}),
|
||||||
|
}),
|
||||||
|
},
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('@hono/oidc-auth', () => ({
|
||||||
|
oidcAuthMiddleware: () => async (_c: unknown, next: () => Promise<void>) => next(),
|
||||||
|
processOAuthCallback: () => async (c: { json: (v: unknown) => unknown }) => c.json({ ok: true }),
|
||||||
|
getAuth: vi.fn().mockResolvedValue(null),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../src/auth/devBypass.js', () => ({
|
||||||
|
devAuthBypass:
|
||||||
|
() => async (_c: unknown, next: () => Promise<void>) => next(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
vi.mock('../../src/auth/localAuthMiddleware.js', () => ({
|
||||||
|
localAuthMiddleware:
|
||||||
|
() => async (_c: unknown, next: () => Promise<void>) => next(),
|
||||||
|
}));
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Env snapshot
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
const originalOidcIssuer = process.env.OIDC_ISSUER;
|
||||||
|
|
||||||
|
beforeEach(() => {
|
||||||
|
mockAppConfigOidcIssuer = null;
|
||||||
|
delete process.env.OIDC_ISSUER;
|
||||||
|
vi.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
afterEach(() => {
|
||||||
|
if (originalOidcIssuer === undefined) {
|
||||||
|
delete process.env.OIDC_ISSUER;
|
||||||
|
} else {
|
||||||
|
process.env.OIDC_ISSUER = originalOidcIssuer;
|
||||||
|
}
|
||||||
|
vi.resetModules();
|
||||||
|
});
|
||||||
|
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
// Tests
|
||||||
|
// ---------------------------------------------------------------------------
|
||||||
|
|
||||||
|
describe('GET /api/auth/mode', () => {
|
||||||
|
it('Test 5: returns { localEnabled:true, oidcEnabled:false } when no oidc_issuer in env or app_config', async () => {
|
||||||
|
delete process.env.OIDC_ISSUER;
|
||||||
|
mockAppConfigOidcIssuer = null;
|
||||||
|
|
||||||
|
const { app } = await import('../../src/index.js');
|
||||||
|
const res = await app.request('/api/auth/mode');
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { localEnabled: boolean; oidcEnabled: boolean };
|
||||||
|
expect(body.localEnabled).toBe(true);
|
||||||
|
expect(body.oidcEnabled).toBe(false);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 6: returns { oidcEnabled:true } when OIDC_ISSUER env var is set', async () => {
|
||||||
|
process.env.OIDC_ISSUER = 'https://auth.example.com';
|
||||||
|
mockAppConfigOidcIssuer = null;
|
||||||
|
|
||||||
|
const { app } = await import('../../src/index.js');
|
||||||
|
const res = await app.request('/api/auth/mode');
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { localEnabled: boolean; oidcEnabled: boolean };
|
||||||
|
expect(body.localEnabled).toBe(true);
|
||||||
|
expect(body.oidcEnabled).toBe(true);
|
||||||
|
});
|
||||||
|
|
||||||
|
it('Test 6b: returns { oidcEnabled:true } when oidc_issuer is in app_config (no env var)', async () => {
|
||||||
|
delete process.env.OIDC_ISSUER;
|
||||||
|
mockAppConfigOidcIssuer = 'https://auth-from-config.example.com';
|
||||||
|
|
||||||
|
const { app } = await import('../../src/index.js');
|
||||||
|
const res = await app.request('/api/auth/mode');
|
||||||
|
|
||||||
|
expect(res.status).toBe(200);
|
||||||
|
const body = (await res.json()) as { localEnabled: boolean; oidcEnabled: boolean };
|
||||||
|
expect(body.localEnabled).toBe(true);
|
||||||
|
expect(body.oidcEnabled).toBe(true);
|
||||||
|
});
|
||||||
|
});
|
||||||
Reference in New Issue
Block a user