diff --git a/.changeset/admin-session-logout-revocation.md b/.changeset/admin-session-logout-revocation.md new file mode 100644 index 000000000..956210c24 --- /dev/null +++ b/.changeset/admin-session-logout-revocation.md @@ -0,0 +1,9 @@ +--- +'nostream': patch +--- + +fix(admin): revoke the session token at logout, not only its cookie + +`POST /admin/logout` deleted the browser cookie but the session token itself stayed valid until it expired (24 hours by default), because the token was only `.` and nothing on the server recorded a logout. A copy of the token kept elsewhere (a `Bearer` client, a log, a proxy) could restore administrator access after sign-out. The token now carries a random session id under the same signature, logout records that id in Redis until the token would have expired, and every admin request checks it, so a logout on one worker ends the session on all of them and ends only that session. If Redis cannot be read the token is refused, and a logout that cannot record the id answers 500 (and still clears the cookie). + +Tokens issued before this change have no session id and are refused, so every administrator signs in once more after the upgrade. diff --git a/resources/admin/assets/dashboard.js b/resources/admin/assets/dashboard.js index 9f5b88abf..ace91f4a2 100644 --- a/resources/admin/assets/dashboard.js +++ b/resources/admin/assets/dashboard.js @@ -1786,16 +1786,24 @@ }) logoutButton.addEventListener('click', async () => { + let sessionEnded = false + try { - await fetch(`${adminBase}/logout`, { + const response = await fetch(`${adminBase}/logout`, { method: 'POST', credentials: 'include', }) + sessionEnded = response.ok } catch { - // Still return to the login screen if the network request fails. + // The request did not reach the server, so nothing was revoked and the cookie was not cleared. } showLogin() + + if (!sessionEnded) { + // Neither a retry nor a new sign-in revokes the original token, so do not suggest one. + showLoginError('Sign-out could not be confirmed. The session may stay active until it expires.') + } }) copySnapshotButton?.addEventListener('click', () => { diff --git a/src/@types/admin.ts b/src/@types/admin.ts index 0a742db13..9584fb83f 100644 --- a/src/@types/admin.ts +++ b/src/@types/admin.ts @@ -2,7 +2,16 @@ import { Request, Response } from 'express' export interface IAdminAuthProvider { handleLogin(request: Request, response: Response): Promise - handleLogout(request: Request, response: Response): void - isRequestAuthenticated(request: Request): boolean + handleLogout(request: Request, response: Response): Promise + isRequestAuthenticated(request: Request): Promise getSessionExpiresAt(request: Request): number | undefined } + +/** + * Admin session tokens are signed, so the server cannot take one back by itself. Logout records the + * token's session id here, until the token would have expired anyway, and every request checks it. + */ +export interface IAdminSessionRevocations { + revoke(sessionId: string, ttlSeconds: number): Promise + isRevoked(sessionId: string): Promise +} diff --git a/src/admin/password-admin-auth-provider.ts b/src/admin/password-admin-auth-provider.ts index 9ac041546..6a4e68dc0 100644 --- a/src/admin/password-admin-auth-provider.ts +++ b/src/admin/password-admin-auth-provider.ts @@ -1,7 +1,8 @@ import { Request, Response } from 'express' -import { IAdminAuthProvider } from '../@types/admin' +import { IAdminAuthProvider, IAdminSessionRevocations } from '../@types/admin' import { Settings } from '../@types/settings' +import { createLogger } from '../factories/logger-factory' import { adminLoginBodySchema } from '../schemas/admin-login-schema' import { verifyAdminPasswordHash, verifyPlaintextPassword } from '../utils/admin-password' import { @@ -13,14 +14,18 @@ import { parseAdminSessionToken, resolveAdminSessionTtlSeconds, } from '../utils/admin-session' +import { CacheAdminSessionRevocations } from '../utils/admin-session-revocations' import { validateSchema } from '../utils/validation' +const logger = createLogger('password-admin-auth-provider') + export type AdminAuthAuditHook = (event: 'login' | 'logout', request: Request) => void | Promise export class PasswordAdminAuthProvider implements IAdminAuthProvider { public constructor( private readonly settings: () => Settings, private readonly auditHook?: AdminAuthAuditHook, + private readonly sessionRevocations: IAdminSessionRevocations = new CacheAdminSessionRevocations(), ) {} public async handleLogin(request: Request, response: Response): Promise { @@ -54,20 +59,55 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider { } } - public handleLogout(request: Request, response: Response): void { + public async handleLogout(request: Request, response: Response): Promise { const currentSettings = this.settings() + const clearCookie = buildAdminSessionClearCookieHeader(request, currentSettings) + const token = this.getToken(request) + const session = token && isValidAdminSessionToken(token) ? parseAdminSessionToken(token) : undefined + + if (session) { + // The token is signed, so only a record of its session id can end it before it expires. + try { + const remainingSeconds = session.expiresAt - Math.floor(Date.now() / 1000) + await this.sessionRevocations.revoke(session.sessionId, remainingSeconds + 1) + } catch (error) { + logger.error('unable to revoke the admin session at logout: %o', error) + response + .status(500) + .setHeader('content-type', 'application/json') + .setHeader('Set-Cookie', clearCookie) + .send({ error: 'Internal Server Error' }) + return + } + } + void this.auditHook?.('logout', request) response .status(200) .setHeader('content-type', 'application/json') - .setHeader('Set-Cookie', buildAdminSessionClearCookieHeader(request, currentSettings)) + .setHeader('Set-Cookie', clearCookie) .send({ authenticated: false }) } - public isRequestAuthenticated(request: Request): boolean { + public async isRequestAuthenticated(request: Request): Promise { const token = this.getToken(request) - return token ? isValidAdminSessionToken(token) : false + if (!token || !isValidAdminSessionToken(token)) { + return false + } + + const session = parseAdminSessionToken(token) + if (!session) { + return false + } + + try { + return !(await this.sessionRevocations.isRevoked(session.sessionId)) + } catch (error) { + // Without the revocation list a logged-out token cannot be told from a live one. + logger.error('unable to check whether the admin session was revoked: %o', error) + return false + } } public getSessionExpiresAt(request: Request): number | undefined { diff --git a/src/controllers/admin/post-logout-controller.ts b/src/controllers/admin/post-logout-controller.ts index 50fc7829d..271f78d7d 100644 --- a/src/controllers/admin/post-logout-controller.ts +++ b/src/controllers/admin/post-logout-controller.ts @@ -7,6 +7,6 @@ export class PostAdminLogoutController implements IController { public constructor(private readonly authProvider: IAdminAuthProvider) {} public async handleRequest(request: Request, response: Response): Promise { - this.authProvider.handleLogout(request, response) + await this.authProvider.handleLogout(request, response) } } diff --git a/src/handlers/request-handlers/admin-auth-middleware.ts b/src/handlers/request-handlers/admin-auth-middleware.ts index e13d8c4f1..f1992da21 100644 --- a/src/handlers/request-handlers/admin-auth-middleware.ts +++ b/src/handlers/request-handlers/admin-auth-middleware.ts @@ -38,7 +38,7 @@ const sendUnauthorized = (response: Response): void => { export const adminAuthGateMiddleware = async (request: AdminRequest, response: Response, next: NextFunction) => { try { - if (adminAuthProvider.isRequestAuthenticated(request)) { + if (await adminAuthProvider.isRequestAuthenticated(request)) { next() return } @@ -93,7 +93,7 @@ export const adminAuthGateMiddleware = async (request: AdminRequest, response: R export const adminAuthMiddleware = async (request: AdminRequest, response: Response, next: NextFunction) => { try { - if (adminAuthProvider.isRequestAuthenticated(request)) { + if (await adminAuthProvider.isRequestAuthenticated(request)) { next() return } diff --git a/src/utils/admin-session-revocations.ts b/src/utils/admin-session-revocations.ts new file mode 100644 index 000000000..ab333b69c --- /dev/null +++ b/src/utils/admin-session-revocations.ts @@ -0,0 +1,62 @@ +import { ICacheAdapter } from '../@types/adapters' +import { IAdminSessionRevocations } from '../@types/admin' +import { RedisAdapter } from '../adapters/redis-adapter' +import { getCacheClient } from '../cache/client' + +let cacheAdapter: ICacheAdapter | undefined + +const getCache = (): ICacheAdapter => { + if (!cacheAdapter) { + cacheAdapter = new RedisAdapter(getCacheClient()) + } + + return cacheAdapter +} + +/** A stalled Redis connection must not leave an admin request waiting, so each cache call gets a deadline. */ +export const ADMIN_SESSION_REVOCATION_TIMEOUT_MS = 2000 + +const withTimeout = (operation: () => Promise, timeoutMs: number, name: string): Promise => + new Promise((resolve, reject) => { + const timer = setTimeout(() => reject(new Error(`${name} timed out after ${timeoutMs} ms`)), timeoutMs) + + Promise.resolve() + .then(operation) + .then(resolve, reject) + .finally(() => clearTimeout(timer)) + }) + +export const adminSessionRevocationCacheKey = (sessionId: string): string => `admin:session:revoked:${sessionId}` + +/** + * Revoked session ids live in the shared cache, so a logout handled by one worker ends the session on all of + * them. An entry only has to outlast the token, which is rejected on its own once it has expired. + */ +export class CacheAdminSessionRevocations implements IAdminSessionRevocations { + public constructor( + private readonly cache: () => ICacheAdapter = getCache, + private readonly timeoutMs: number = ADMIN_SESSION_REVOCATION_TIMEOUT_MS, + ) {} + + public async revoke(sessionId: string, ttlSeconds: number): Promise { + const expirySeconds = Number.isSafeInteger(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : 1 + + await withTimeout( + () => this.cache().setKey(adminSessionRevocationCacheKey(sessionId), '1', expirySeconds), + this.timeoutMs, + 'revoking the admin session', + ) + } + + public async isRevoked(sessionId: string): Promise { + return withTimeout( + () => this.cache().hasKey(adminSessionRevocationCacheKey(sessionId)), + this.timeoutMs, + 'checking the admin session revocation', + ) + } +} + +export const resetAdminSessionRevocationCacheAdapterForTests = (): void => { + cacheAdapter = undefined +} diff --git a/src/utils/admin-session.ts b/src/utils/admin-session.ts index e83ed25c5..ffa2c06c0 100644 --- a/src/utils/admin-session.ts +++ b/src/utils/admin-session.ts @@ -1,4 +1,4 @@ -import { timingSafeEqual } from 'crypto' +import { randomBytes, timingSafeEqual } from 'crypto' import { IncomingMessage } from 'http' import { Settings } from '../@types/settings' @@ -37,41 +37,50 @@ export const buildAdminSessionClearCookieHeader = (request: IncomingMessage, set return `admin_session=; Path=${cookiePath}; HttpOnly; SameSite=Strict; Max-Age=0${secure}` } +const SESSION_ID_PATTERN = /^[0-9a-f]{32}$/ + +const signAdminSession = (expiresAt: number, sessionId: string): string => + hmacSha256(deriveFromSecret('admin-session'), `${expiresAt}.${sessionId}`).toString('hex') + +/** + * A token is `..`. The session id is random and signed with the expiry, so + * two logins never share a token and one session can be revoked without ending the others. + */ export const createAdminSessionToken = (expiresAt: number): string => { - const signature = hmacSha256(deriveFromSecret('admin-session'), `${expiresAt}`).toString('hex') - return `${expiresAt}.${signature}` + const sessionId = randomBytes(16).toString('hex') + return `${expiresAt}.${sessionId}.${signAdminSession(expiresAt, sessionId)}` } -export const parseAdminSessionToken = (token: string): { expiresAt: number } | undefined => { - const separatorIndex = token.indexOf('.') - if (separatorIndex <= 0) { +const splitAdminSessionToken = ( + token: string, +): { expiresAt: number; sessionId: string; signature: string } | undefined => { + const parts = token.split('.') + if (parts.length !== 3) { return undefined } - const expiresAt = Number(token.slice(0, separatorIndex)) - if (!Number.isFinite(expiresAt)) { + const [expiresAtText, sessionId, signature] = parts + const expiresAt = Number(expiresAtText) + if (!expiresAtText || !Number.isFinite(expiresAt) || !SESSION_ID_PATTERN.test(sessionId)) { return undefined } - return { expiresAt } + return { expiresAt, sessionId, signature } } -export const isValidAdminSessionToken = (token: string, nowSeconds = Math.floor(Date.now() / 1000)): boolean => { - const separatorIndex = token.indexOf('.') - if (separatorIndex <= 0) { - return false - } - - const expiresAt = Number(token.slice(0, separatorIndex)) - const signature = token.slice(separatorIndex + 1) +export const parseAdminSessionToken = (token: string): { expiresAt: number; sessionId: string } | undefined => { + const parsed = splitAdminSessionToken(token) + return parsed ? { expiresAt: parsed.expiresAt, sessionId: parsed.sessionId } : undefined +} - if (!Number.isFinite(expiresAt) || expiresAt <= nowSeconds || !/^[0-9a-f]+$/.test(signature)) { +export const isValidAdminSessionToken = (token: string, nowSeconds = Math.floor(Date.now() / 1000)): boolean => { + const parsed = splitAdminSessionToken(token) + if (!parsed || parsed.expiresAt <= nowSeconds || !/^[0-9a-f]+$/.test(parsed.signature)) { return false } - const expected = hmacSha256(deriveFromSecret('admin-session'), `${expiresAt}`).toString('hex') - const expectedBuf = Buffer.from(expected, 'utf8') - const actualBuf = Buffer.from(signature, 'utf8') + const expectedBuf = Buffer.from(signAdminSession(parsed.expiresAt, parsed.sessionId), 'utf8') + const actualBuf = Buffer.from(parsed.signature, 'utf8') if (expectedBuf.length !== actualBuf.length) { return false @@ -80,7 +89,10 @@ export const isValidAdminSessionToken = (token: string, nowSeconds = Math.floor( return timingSafeEqual(expectedBuf, actualBuf) } -export const getAdminSessionTokenFromRequest = (authorizationHeader?: string, cookieHeader?: string): string | undefined => { +export const getAdminSessionTokenFromRequest = ( + authorizationHeader?: string, + cookieHeader?: string, +): string | undefined => { if (authorizationHeader?.startsWith('Bearer ')) { const token = authorizationHeader.slice('Bearer '.length).trim() return token.length > 0 ? token : undefined diff --git a/test/unit/admin/password-admin-auth-provider.spec.ts b/test/unit/admin/password-admin-auth-provider.spec.ts new file mode 100644 index 000000000..9cbcb8cc7 --- /dev/null +++ b/test/unit/admin/password-admin-auth-provider.spec.ts @@ -0,0 +1,217 @@ +import chai from 'chai' +import { Request, Response } from 'express' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import { IAdminSessionRevocations } from '../../../src/@types/admin' +import { PasswordAdminAuthProvider } from '../../../src/admin/password-admin-auth-provider' +import { createAdminSessionToken } from '../../../src/utils/admin-session' + +chai.use(sinonChai) + +const { expect } = chai + +class FakeRevocations implements IAdminSessionRevocations { + public readonly revoked = new Map() + public failRevoke = false + public failCheck = false + + public async revoke(sessionId: string, ttlSeconds: number): Promise { + if (this.failRevoke) { + throw new Error('redis is down') + } + this.revoked.set(sessionId, ttlSeconds) + } + + public async isRevoked(sessionId: string): Promise { + if (this.failCheck) { + throw new Error('redis is down') + } + return this.revoked.has(sessionId) + } +} + +describe('PasswordAdminAuthProvider sessions', () => { + const originalSecret = process.env.SECRET + const originalPassword = process.env.ADMIN_PASSWORD + const settings = () => ({ info: { relay_url: 'wss://relay.example.com' }, network: {}, admin: {} }) as any + + let sandbox: Sinon.SinonSandbox + let revocations: FakeRevocations + let audit: Sinon.SinonStub + let provider: PasswordAdminAuthProvider + + before(() => { + process.env.SECRET = 'test-admin-secret-value' + process.env.ADMIN_PASSWORD = 'correct horse' + }) + + after(() => { + if (originalSecret === undefined) { + delete process.env.SECRET + } else { + process.env.SECRET = originalSecret + } + if (originalPassword === undefined) { + delete process.env.ADMIN_PASSWORD + } else { + process.env.ADMIN_PASSWORD = originalPassword + } + }) + + beforeEach(() => { + sandbox = Sinon.createSandbox() + revocations = new FakeRevocations() + audit = sandbox.stub() + provider = new PasswordAdminAuthProvider(settings, audit, revocations) + }) + + afterEach(() => { + sandbox.restore() + }) + + const mockResponse = () => { + const headers: Record = {} + const response = { + statusCode: 0, + body: undefined as unknown, + headers, + status(code: number) { + response.statusCode = code + return response + }, + setHeader(name: string, value: string) { + headers[name] = value + return response + }, + send(body: unknown) { + response.body = body + return response + }, + } + return response + } + + const requestWithToken = (token: string, via: 'cookie' | 'bearer' = 'cookie'): Request => + ({ + headers: via === 'cookie' ? { cookie: `admin_session=${token}` } : { authorization: `Bearer ${token}` }, + socket: { remoteAddress: '203.0.113.9' }, + }) as unknown as Request + + const login = async (): Promise => { + const response = mockResponse() + await provider.handleLogin({ body: { password: 'correct horse' }, headers: {}, socket: {} } as any, response as any) + + expect(response.statusCode).to.equal(200) + return /admin_session=([^;]+)/.exec(response.headers['Set-Cookie'])?.[1] as string + } + + const logout = async (token: string, via: 'cookie' | 'bearer' = 'cookie') => { + const response = mockResponse() + await provider.handleLogout(requestWithToken(token, via), response as unknown as Response) + return response + } + + it('authenticates a token it has just issued', async () => { + const token = await login() + + expect(await provider.isRequestAuthenticated(requestWithToken(token))).to.equal(true) + expect(await provider.isRequestAuthenticated(requestWithToken(token, 'bearer'))).to.equal(true) + }) + + it('refuses a retained copy of the token once its owner has logged out', async () => { + const token = await login() + + const response = await logout(token) + + expect(response.statusCode).to.equal(200) + expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/) + expect(await provider.isRequestAuthenticated(requestWithToken(token))).to.equal(false) + expect(await provider.isRequestAuthenticated(requestWithToken(token, 'bearer'))).to.equal(false) + }) + + it('keeps the revocation for as long as the token would have lasted', async () => { + const token = await login() + + await logout(token) + + const [ttl] = [...revocations.revoked.values()] + expect(ttl).to.be.within(86400, 86402) + }) + + it('ends only the session that logged out', async () => { + const first = await login() + const second = await login() + + await logout(first) + + expect(await provider.isRequestAuthenticated(requestWithToken(first))).to.equal(false) + expect(await provider.isRequestAuthenticated(requestWithToken(second))).to.equal(true) + }) + + it('ends a session that logged in in the same second as another', async () => { + const expiresAt = Math.floor(Date.now() / 1000) + 600 + const first = createAdminSessionToken(expiresAt) + const second = createAdminSessionToken(expiresAt) + + await logout(first) + + expect(await provider.isRequestAuthenticated(requestWithToken(first))).to.equal(false) + expect(await provider.isRequestAuthenticated(requestWithToken(second))).to.equal(true) + }) + + it('answers a second logout of the same token the same way', async () => { + const token = await login() + + await logout(token) + const again = await logout(token) + + expect(again.statusCode).to.equal(200) + expect(await provider.isRequestAuthenticated(requestWithToken(token))).to.equal(false) + }) + + it('clears the cookie without revoking anything when there is no valid token', async () => { + const forged = await logout(`${Math.floor(Date.now() / 1000) + 600}.${'0'.repeat(32)}.${'0'.repeat(64)}`) + const none = mockResponse() + await provider.handleLogout({ headers: {}, socket: {} } as any, none as any) + + expect(forged.statusCode).to.equal(200) + expect(none.statusCode).to.equal(200) + expect(none.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/) + expect(revocations.revoked.size).to.equal(0) + }) + + it('reports the logout to the audit hook only once the session is revoked', async () => { + const token = await login() + + await logout(token) + + expect(audit).to.have.been.calledWith('logout') + }) + + it('answers 500 and clears the cookie when the session cannot be revoked', async () => { + const token = await login() + revocations.failRevoke = true + + const response = await logout(token) + + expect(response.statusCode).to.equal(500) + expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/) + expect(audit).not.to.have.been.calledWith('logout') + }) + + it('refuses every token while the revocation list cannot be read', async () => { + const token = await login() + revocations.failCheck = true + + expect(await provider.isRequestAuthenticated(requestWithToken(token))).to.equal(false) + }) + + it('refuses a token that is invalid without asking the revocation list', async () => { + const isRevoked = sandbox.spy(revocations, 'isRevoked') + + expect(await provider.isRequestAuthenticated({ headers: {} } as any)).to.equal(false) + expect(await provider.isRequestAuthenticated(requestWithToken('abc.def'))).to.equal(false) + expect(isRevoked).not.to.have.been.called + }) +}) diff --git a/test/unit/handlers/request-handlers/admin-auth-middleware.spec.ts b/test/unit/handlers/request-handlers/admin-auth-middleware.spec.ts index f4f463651..24ccc9870 100644 --- a/test/unit/handlers/request-handlers/admin-auth-middleware.spec.ts +++ b/test/unit/handlers/request-handlers/admin-auth-middleware.spec.ts @@ -38,7 +38,7 @@ describe('adminAuthMiddleware', () => { beforeEach(() => { sandbox = Sinon.createSandbox() - isRequestAuthenticated = sandbox.stub(PasswordAdminAuthProvider.prototype, 'isRequestAuthenticated').returns(false) + isRequestAuthenticated = sandbox.stub(PasswordAdminAuthProvider.prototype, 'isRequestAuthenticated').resolves(false) claimNip98AuthEventId = sandbox.stub(nip98Replay, 'claimNip98AuthEventId').resolves('claimed') next = sandbox.stub() response = { @@ -119,7 +119,7 @@ describe('adminAuthMiddleware', () => { describe('adminAuthGateMiddleware', () => { it('continues for session-authenticated requests', async () => { - isRequestAuthenticated.returns(true) + isRequestAuthenticated.resolves(true) const request = mockRequest() await adminAuthGateMiddleware(request, response as any, next) @@ -188,7 +188,7 @@ describe('adminAuthMiddleware', () => { }) it('allows cookie/session authenticated requests without NIP-98', async () => { - isRequestAuthenticated.returns(true) + isRequestAuthenticated.resolves(true) const request = mockRequest() await adminAuthMiddleware(request, response as any, next) diff --git a/test/unit/routes/admin-settings.spec.ts b/test/unit/routes/admin-settings.spec.ts index fdf483cd1..1186960d3 100644 --- a/test/unit/routes/admin-settings.spec.ts +++ b/test/unit/routes/admin-settings.spec.ts @@ -7,6 +7,7 @@ import path from 'path' import Sinon from 'sinon' import { hashAdminPassword } from '../../../src/utils/admin-password' +import { CacheAdminSessionRevocations } from '../../../src/utils/admin-session-revocations' import * as adminRateLimitMiddleware from '../../../src/handlers/request-handlers/admin-rate-limit-middleware' import * as rateLimiterMiddleware from '../../../src/handlers/request-handlers/rate-limiter-middleware' import { PatchAdminSettingsController } from '../../../src/controllers/admin/patch-settings-controller' @@ -30,6 +31,7 @@ describe('admin settings API', () => { let adminLoginRateLimitMiddlewareStub: Sinon.SinonStub let createPatchAdminSettingsControllerStub: Sinon.SinonStub let server: any + let revocationStubs: Sinon.SinonStub[] = [] const loadAdminRouter = () => { // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -67,6 +69,16 @@ describe('admin settings API', () => { enqueue: Sinon.stub().resolves(), } as any), ) + // Logout records the session in Redis, which these tests do not run, so an in-memory list stands in for it. + const revokedSessions = new Set() + revocationStubs = [ + Sinon.stub(CacheAdminSessionRevocations.prototype, 'revoke').callsFake(async (sessionId: string) => { + revokedSessions.add(sessionId) + }), + Sinon.stub(CacheAdminSessionRevocations.prototype, 'isRevoked').callsFake(async (sessionId: string) => + revokedSessions.has(sessionId), + ), + ] const router = loadAdminRouter() const app = express() app.use('/admin', router) @@ -79,6 +91,8 @@ describe('admin settings API', () => { } const stopServer = async () => { + revocationStubs.forEach((stub) => stub.restore()) + revocationStubs = [] createSettingsStub?.restore() rateLimiterMiddlewareStub?.restore() adminRateLimitMiddlewareStub?.restore() @@ -183,7 +197,9 @@ describe('admin settings API', () => { sessionTtlSeconds: 3600, notifications: { ...loadDefaults().admin?.notifications, - targets: [{ id: 'ops-telegram', type: 'telegram', enabled: true, botToken: 'telegram-bot-token', chatId: '1' }], + targets: [ + { id: 'ops-telegram', type: 'telegram', enabled: true, botToken: 'telegram-bot-token', chatId: '1' }, + ], }, }, }) diff --git a/test/unit/routes/admin.spec.ts b/test/unit/routes/admin.spec.ts index 82ba4f77b..79d1a2569 100644 --- a/test/unit/routes/admin.spec.ts +++ b/test/unit/routes/admin.spec.ts @@ -13,6 +13,7 @@ import * as adminRateLimitMiddleware from '../../../src/handlers/request-handler import * as rateLimiterMiddleware from '../../../src/handlers/request-handlers/rate-limiter-middleware' import * as settingsFactory from '../../../src/factories/settings-factory' import { hashAdminPassword } from '../../../src/utils/admin-password' +import { CacheAdminSessionRevocations } from '../../../src/utils/admin-session-revocations' import { getPublicKey, identifyEvent, signEvent } from '../../../src/utils/event' import * as nip98Replay from '../../../src/utils/nip98-replay' @@ -29,6 +30,7 @@ describe('admin router', () => { let adminLoginRateLimitMiddlewareStub: Sinon.SinonStub let claimNip98AuthEventIdStub: Sinon.SinonStub | undefined let server: any + let revocationStubs: Sinon.SinonStub[] = [] const loadAdminRouter = () => { // eslint-disable-next-line @typescript-eslint/no-var-requires @@ -76,10 +78,7 @@ describe('admin router', () => { 'createGetAdminNetworkHealthController', ).returns({ handleRequest: async (_request: any, response: any) => { - response - .status(200) - .setHeader('content-type', 'application/json') - .send({ snapshot: null }) + response.status(200).setHeader('content-type', 'application/json').send({ snapshot: null }) }, } as any) createGetAdminNotificationsControllerStub = Sinon.stub( @@ -90,7 +89,9 @@ describe('admin router', () => { response .status(200) .setHeader('content-type', 'application/json') - .send({ notifications: { enabled: false, targets: [], events: {}, retry: { maxAttempts: 5, baseDelayMs: 1000 } } }) + .send({ + notifications: { enabled: false, targets: [], events: {}, retry: { maxAttempts: 5, baseDelayMs: 1000 } }, + }) }, } as any) createSettingsStub = Sinon.stub(settingsFactory, 'createSettings').returns(settings as any) @@ -104,6 +105,16 @@ describe('admin router', () => { adminLoginRateLimitMiddlewareStub = Sinon.stub(adminRateLimitMiddleware, 'adminLoginRateLimitMiddleware').callsFake( passthrough, ) + // Logout records the session in Redis, which these tests do not run, so an in-memory list stands in for it. + const revokedSessions = new Set() + revocationStubs = [ + Sinon.stub(CacheAdminSessionRevocations.prototype, 'revoke').callsFake(async (sessionId: string) => { + revokedSessions.add(sessionId) + }), + Sinon.stub(CacheAdminSessionRevocations.prototype, 'isRevoked').callsFake(async (sessionId: string) => + revokedSessions.has(sessionId), + ), + ] const router = loadAdminRouter() const app = express() app.use((request, response, next) => { @@ -120,6 +131,8 @@ describe('admin router', () => { } const stopServer = async () => { + revocationStubs.forEach((stub) => stub.restore()) + revocationStubs = [] createGetAdminHealthControllerStub?.restore() createGetAdminMetricsControllerStub?.restore() createGetAdminNetworkHealthControllerStub?.restore() @@ -306,7 +319,7 @@ describe('admin router', () => { const baseUrl = await startServer({ admin: { enabled: true } }) const response = await axios.get(`${baseUrl}/session`, { - headers: { cookie: 'admin_session=9999999999.deadbeef' }, + headers: { cookie: `admin_session=9999999999.${'0'.repeat(32)}.deadbeef` }, validateStatus: () => true, }) @@ -366,6 +379,44 @@ describe('admin router', () => { expect(adminRateLimitMiddlewareStub.callCount).to.equal(3) }) + it('refuses the session token again once it has been logged out, for the token and not for other sessions', async () => { + process.env.ADMIN_PASSWORD = 'correct-password' + const baseUrl = await startServer({ admin: { enabled: true, sessionTtlSeconds: 3600 } }) + const login = async () => { + const response = await axios.post( + `${baseUrl}/login`, + { password: 'correct-password' }, + { headers: { 'content-type': 'application/json' }, validateStatus: () => true }, + ) + return response.headers['set-cookie']?.[0]?.split(';')[0] as string + } + const sessionStatus = async (cookie: string) => + (await axios.get(`${baseUrl}/session`, { headers: { cookie }, validateStatus: () => true })).status + + const loggedOut = await login() + const other = await login() + expect(await sessionStatus(loggedOut)).to.equal(200) + + const logoutResponse = await axios.post( + `${baseUrl}/logout`, + {}, + { headers: { cookie: loggedOut, 'content-type': 'application/json' }, validateStatus: () => true }, + ) + + expect(logoutResponse.status).to.equal(200) + expect(logoutResponse.headers['set-cookie']?.[0]).to.include('Max-Age=0') + // The same token, as a retained copy would present it, is no longer accepted by the cookie or by Bearer. + expect(await sessionStatus(loggedOut)).to.equal(401) + const bearerStatus = ( + await axios.get(`${baseUrl}/session`, { + headers: { authorization: `Bearer ${loggedOut.replace('admin_session=', '')}` }, + validateStatus: () => true, + }) + ).status + expect(bearerStatus).to.equal(401) + expect(await sessionStatus(other)).to.equal(200) + }) + it('authenticates with passwordHash from settings', async () => { const passwordHash = hashAdminPassword('settings-password') const baseUrl = await startServer({ diff --git a/test/unit/utils/admin-session-revocations.spec.ts b/test/unit/utils/admin-session-revocations.spec.ts new file mode 100644 index 000000000..661730506 --- /dev/null +++ b/test/unit/utils/admin-session-revocations.spec.ts @@ -0,0 +1,107 @@ +import chai from 'chai' +import Sinon from 'sinon' +import sinonChai from 'sinon-chai' + +import { ICacheAdapter } from '../../../src/@types/adapters' +import { + adminSessionRevocationCacheKey, + CacheAdminSessionRevocations, +} from '../../../src/utils/admin-session-revocations' + +chai.use(sinonChai) + +const { expect } = chai + +describe('CacheAdminSessionRevocations', () => { + let sandbox: Sinon.SinonSandbox + let setKey: Sinon.SinonStub + let hasKey: Sinon.SinonStub + let revocations: CacheAdminSessionRevocations + + beforeEach(() => { + sandbox = Sinon.createSandbox() + setKey = sandbox.stub().resolves(true) + hasKey = sandbox.stub().resolves(false) + revocations = new CacheAdminSessionRevocations(() => ({ setKey, hasKey }) as unknown as ICacheAdapter) + }) + + afterEach(() => { + sandbox.restore() + }) + + it('keeps a revoked session id until the token would have expired', async () => { + await revocations.revoke('abc', 3600) + + expect(setKey).to.have.been.calledOnceWithExactly(adminSessionRevocationCacheKey('abc'), '1', 3600) + }) + + it('keeps a revoked session id for at least a second', async () => { + await revocations.revoke('abc', 0) + await revocations.revoke('def', Number.NaN) + + expect(setKey.firstCall.args[2]).to.equal(1) + expect(setKey.secondCall.args[2]).to.equal(1) + }) + + it('keys each session separately', () => { + expect(adminSessionRevocationCacheKey('abc')).to.not.equal(adminSessionRevocationCacheKey('def')) + }) + + it('reports whether a session id was revoked', async () => { + hasKey.withArgs(adminSessionRevocationCacheKey('revoked')).resolves(true) + + expect(await revocations.isRevoked('revoked')).to.equal(true) + expect(await revocations.isRevoked('live')).to.equal(false) + }) + + it('does not hide a cache failure', async () => { + setKey.rejects(new Error('redis is down')) + hasKey.rejects(new Error('redis is down')) + + await revocations.revoke('abc', 60).then( + () => expect.fail('revoke should reject'), + (error: Error) => expect(error.message).to.equal('redis is down'), + ) + await revocations.isRevoked('abc').then( + () => expect.fail('isRevoked should reject'), + (error: Error) => expect(error.message).to.equal('redis is down'), + ) + }) + + describe('when the cache never answers', () => { + const neverSettles = () => new Promise(() => undefined) + + beforeEach(() => { + revocations = new CacheAdminSessionRevocations(() => ({ setKey, hasKey }) as unknown as ICacheAdapter, 10) + }) + + it('stops waiting for a revocation that is never stored', async () => { + setKey.callsFake(neverSettles) + + await revocations.revoke('abc', 60).then( + () => expect.fail('revoke should reject'), + (error: Error) => expect(error.message).to.match(/timed out after 10 ms/), + ) + }) + + it('stops waiting for a revocation check that is never answered', async () => { + hasKey.callsFake(neverSettles) + + await revocations.isRevoked('abc').then( + () => expect.fail('isRevoked should reject'), + (error: Error) => expect(error.message).to.match(/timed out after 10 ms/), + ) + }) + + it('rejects when the cache cannot even be created', async () => { + revocations = new CacheAdminSessionRevocations(() => { + throw new Error('no redis client') + }, 10) + + await revocations.isRevoked('abc').then( + () => expect.fail('isRevoked should reject'), + (error: Error) => expect(error.message).to.equal('no redis client'), + ) + }) + }) +}) diff --git a/test/unit/utils/admin-session.spec.ts b/test/unit/utils/admin-session.spec.ts index 3c5edee6f..29f456d68 100644 --- a/test/unit/utils/admin-session.spec.ts +++ b/test/unit/utils/admin-session.spec.ts @@ -5,6 +5,7 @@ import { createAdminSessionToken, getAdminSessionTokenFromRequest, isValidAdminSessionToken, + parseAdminSessionToken, resolveAdminSessionTtlSeconds, } from '../../../src/utils/admin-session' @@ -31,6 +32,65 @@ describe('admin-session', () => { expect(isValidAdminSessionToken(`${expiresAt}.deadbeef`)).to.equal(false) }) + describe('the session id in a token', () => { + const expiresAt = () => Math.floor(Date.now() / 1000) + 3600 + + it('differs between two tokens made for the same expiry', () => { + const at = expiresAt() + const first = createAdminSessionToken(at) + const second = createAdminSessionToken(at) + + expect(first).to.not.equal(second) + expect(parseAdminSessionToken(first)?.sessionId).to.not.equal(parseAdminSessionToken(second)?.sessionId) + expect(isValidAdminSessionToken(first)).to.equal(true) + expect(isValidAdminSessionToken(second)).to.equal(true) + }) + + it('is read back with the expiry', () => { + const at = expiresAt() + const token = createAdminSessionToken(at) + + expect(parseAdminSessionToken(token)).to.deep.equal({ expiresAt: at, sessionId: token.split('.')[1] }) + }) + + it('is signed, so another id under the same signature is refused', () => { + const at = expiresAt() + const [, , signature] = createAdminSessionToken(at).split('.') + + expect(isValidAdminSessionToken(`${at}.${'0'.repeat(32)}.${signature}`)).to.equal(false) + }) + + it('is signed with the expiry, so a later expiry under the same id is refused', () => { + const at = expiresAt() + const [, sessionId, signature] = createAdminSessionToken(at).split('.') + + expect(isValidAdminSessionToken(`${at + 3600}.${sessionId}.${signature}`)).to.equal(false) + }) + + it('refuses the old token without a session id, which cannot be revoked', () => { + const at = expiresAt() + const [, , signature] = createAdminSessionToken(at).split('.') + + expect(isValidAdminSessionToken(`${at}.${signature}`)).to.equal(false) + expect(parseAdminSessionToken(`${at}.${signature}`)).to.equal(undefined) + }) + + it('refuses an id that is not 32 hex characters, and extra parts', () => { + const at = expiresAt() + const [, sessionId, signature] = createAdminSessionToken(at).split('.') + + expect(parseAdminSessionToken(`${at}.${sessionId.slice(1)}.${signature}`)).to.equal(undefined) + expect(parseAdminSessionToken(`${at}.${sessionId.toUpperCase()}.${signature}`)).to.equal(undefined) + expect(parseAdminSessionToken(`${at}.${sessionId}.${signature}.extra`)).to.equal(undefined) + }) + + it('refuses an expired token', () => { + const past = Math.floor(Date.now() / 1000) - 1 + + expect(isValidAdminSessionToken(createAdminSessionToken(past))).to.equal(false) + }) + }) + it('reads bearer and cookie session tokens from request headers', () => { expect(getAdminSessionTokenFromRequest('Bearer abc.def', undefined)).to.equal('abc.def') expect(getAdminSessionTokenFromRequest(undefined, 'admin_session=abc.def; other=value')).to.equal('abc.def')