Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
9 changes: 9 additions & 0 deletions .changeset/admin-session-logout-revocation.md
Original file line number Diff line number Diff line change
@@ -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 `<expiresAt>.<signature>` 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.
12 changes: 10 additions & 2 deletions resources/admin/assets/dashboard.js
Original file line number Diff line number Diff line change
Expand Up @@ -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', () => {
Expand Down
13 changes: 11 additions & 2 deletions src/@types/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -2,7 +2,16 @@ import { Request, Response } from 'express'

export interface IAdminAuthProvider {
handleLogin(request: Request, response: Response): Promise<void>
handleLogout(request: Request, response: Response): void
isRequestAuthenticated(request: Request): boolean
handleLogout(request: Request, response: Response): Promise<void>
isRequestAuthenticated(request: Request): Promise<boolean>
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<void>
isRevoked(sessionId: string): Promise<boolean>
}
50 changes: 45 additions & 5 deletions src/admin/password-admin-auth-provider.ts
Original file line number Diff line number Diff line change
@@ -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 {
Expand All @@ -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<void>

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<void> {
Expand Down Expand Up @@ -54,20 +59,55 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider {
}
}

public handleLogout(request: Request, response: Response): void {
public async handleLogout(request: Request, response: Response): Promise<void> {
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' })
Comment thread
Priyanshubhartistm marked this conversation as resolved.
Resolved
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<boolean> {
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 {
Expand Down
2 changes: 1 addition & 1 deletion src/controllers/admin/post-logout-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,6 +7,6 @@ export class PostAdminLogoutController implements IController {
public constructor(private readonly authProvider: IAdminAuthProvider) {}

public async handleRequest(request: Request, response: Response): Promise<void> {
this.authProvider.handleLogout(request, response)
await this.authProvider.handleLogout(request, response)
}
}
4 changes: 2 additions & 2 deletions src/handlers/request-handlers/admin-auth-middleware.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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
}
Expand Down Expand Up @@ -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
}
Expand Down
62 changes: 62 additions & 0 deletions src/utils/admin-session-revocations.ts
Original file line number Diff line number Diff line change
@@ -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 = <T>(operation: () => Promise<T>, timeoutMs: number, name: string): Promise<T> =>
new Promise<T>((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<void> {
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<boolean> {
return withTimeout(
() => this.cache().hasKey(adminSessionRevocationCacheKey(sessionId)),
this.timeoutMs,
'checking the admin session revocation',
)
}
}

export const resetAdminSessionRevocationCacheAdapterForTests = (): void => {
cacheAdapter = undefined
}
56 changes: 34 additions & 22 deletions src/utils/admin-session.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { timingSafeEqual } from 'crypto'
import { randomBytes, timingSafeEqual } from 'crypto'
import { IncomingMessage } from 'http'

import { Settings } from '../@types/settings'
Expand Down Expand Up @@ -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 `<expiresAt>.<sessionId>.<signature>`. 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
Expand All @@ -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
Expand Down
Loading
Loading