Skip to content
Open
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
7 changes: 7 additions & 0 deletions .changeset/admin-logout-audit-only-with-session.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': patch
---

fix(admin): record a logout in the audit history only when it ends a session

`POST /admin/logout` is public, because it has to clear the session cookie whoever sends the request, and it wrote an `admin.logout` record to the audit history for every request, with or without a session. Anyone who could reach the admin routes could post to it repeatedly and fill the shared, size-limited audit history in Redis with logouts that never happened, pushing real administrator records out of it. The record is now written only by the logout that ends a session: a request with a valid session (as a cookie or a Bearer token) whose session had not been revoked yet. Revoking a session now tells the caller whether it was this call that did it, in one atomic step, so a copy of a token that was already logged out, or several logouts of the same session at once, write nothing more. Every such request still gets the cookie cleared and a 200.
3 changes: 2 additions & 1 deletion src/@types/admin.ts
Original file line number Diff line number Diff line change
Expand Up @@ -12,6 +12,7 @@ export interface IAdminAuthProvider {
* 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>
/** Resolves true when this call revoked the session, false when it was already revoked (the call changed nothing). */
revoke(sessionId: string, ttlSeconds: number): Promise<boolean>
isRevoked(sessionId: string): Promise<boolean>
}
14 changes: 11 additions & 3 deletions src/admin/password-admin-auth-provider.ts
Original file line number Diff line number Diff line change
Expand Up @@ -67,9 +67,10 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider {

if (session) {
// The token is signed, so only a record of its session id can end it before it expires.
let revokedNow: boolean
try {
const remainingSeconds = session.expiresAt - Math.floor(Date.now() / 1000)
await this.sessionRevocations.revoke(session.sessionId, remainingSeconds + 1)
revokedNow = await this.sessionRevocations.revoke(session.sessionId, remainingSeconds + 1)
} catch (error) {
logger.error('unable to revoke the admin session at logout: %o', error)
response
Expand All @@ -79,9 +80,16 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider {
.send({ error: 'Internal Server Error' })
return
}
}

void this.auditHook?.('logout', request)
// Recorded only by the call that ended the session. The endpoint is public (it has to clear a cookie whoever
// sends the request), and a signed token stays well-formed after its session is revoked, so a copy of a token
// that was logged out could otherwise be sent again and again, each time adding a record for a logout that did
// not happen, until the shared, size-limited audit history held nothing else. A request with no valid token
// never gets here, and a replay of a revoked one gets the same 200 and writes nothing.
if (revokedNow) {
void this.auditHook?.('logout', request)
}
}

response
.status(200)
Expand Down
13 changes: 9 additions & 4 deletions src/utils/admin-session-revocations.ts
Original file line number Diff line number Diff line change
Expand Up @@ -38,11 +38,16 @@ export class CacheAdminSessionRevocations implements IAdminSessionRevocations {
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
public async revoke(sessionId: string, ttlSeconds: number): Promise<boolean> {
// A replay that was valid when it started can still have its write land up to the timeout later, so the entry
// has to outlast the token by that long. Otherwise the entry could expire first and the replay would win.
const writeWindowSeconds = Math.ceil(this.timeoutMs / 1000)
const expirySeconds = (Number.isSafeInteger(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : 1) + writeWindowSeconds

await withTimeout(
() => this.cache().setKey(adminSessionRevocationCacheKey(sessionId), '1', expirySeconds),
// Set only if absent, in one step, so that of several logouts of the same session at once exactly one is told
// that it revoked it. The entry keeps the expiry of the first revocation, which is when the token ends anyway.
return withTimeout(
() => this.cache().setKeyIfNotExists(adminSessionRevocationCacheKey(sessionId), '1', expirySeconds),
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
this.timeoutMs,
'revoking the admin session',
)
Expand Down
130 changes: 129 additions & 1 deletion test/unit/admin/password-admin-auth-provider.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -16,11 +16,16 @@ class FakeRevocations implements IAdminSessionRevocations {
public failRevoke = false
public failCheck = false

public async revoke(sessionId: string, ttlSeconds: number): Promise<void> {
public async revoke(sessionId: string, ttlSeconds: number): Promise<boolean> {
if (this.failRevoke) {
throw new Error('redis is down')
}
// Check and set in one step, like the cache does with SET NX.
if (this.revoked.has(sessionId)) {
return false
}
this.revoked.set(sessionId, ttlSeconds)
return true
}

public async isRevoked(sessionId: string): Promise<boolean> {
Expand Down Expand Up @@ -92,6 +97,8 @@ describe('PasswordAdminAuthProvider sessions', () => {
return response
}

const sessionIdOf = (token: string): string => token.split('.')[1]

const requestWithToken = (token: string, via: 'cookie' | 'bearer' = 'cookie'): Request =>
({
headers: via === 'cookie' ? { cookie: `admin_session=${token}` } : { authorization: `Bearer ${token}` },
Expand Down Expand Up @@ -181,6 +188,127 @@ describe('PasswordAdminAuthProvider sessions', () => {
expect(revocations.revoked.size).to.equal(0)
})

describe('the audit record of a logout', () => {
it('is written for a request that presents a valid session, with that request', async () => {
const token = await login()
audit.resetHistory()
const request = requestWithToken(token)

await provider.handleLogout(request, mockResponse() as unknown as Response)

expect(audit).to.have.been.calledOnceWithExactly('logout', request)
})

it('is also written when the session is presented as a Bearer token', async () => {
const token = await login()
audit.resetHistory()

await logout(token, 'bearer')

expect(audit).to.have.been.calledOnceWith('logout')
})

it('is not written for a request without a token', async () => {
const response = mockResponse()

await provider.handleLogout({ headers: {}, socket: {} } as any, response as any)

expect(response.statusCode).to.equal(200)
expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
expect(audit).not.to.have.been.calledWith('logout')
})

it('is not written for a token that was not signed by the relay', async () => {
const response = await logout(`${Math.floor(Date.now() / 1000) + 600}.${'0'.repeat(32)}.${'0'.repeat(64)}`)

expect(response.statusCode).to.equal(200)
expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
expect(audit).not.to.have.been.calledWith('logout')
})

it('is not written for a malformed token', async () => {
const response = await logout('abc.def')

expect(response.statusCode).to.equal(200)
expect(audit).not.to.have.been.calledWith('logout')
})

it('is not written for a token that has expired', async () => {
const response = await logout(createAdminSessionToken(Math.floor(Date.now() / 1000) - 10))

expect(response.statusCode).to.equal(200)
expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
expect(audit).not.to.have.been.calledWith('logout')
})

it('is written once for the logout that ended the session, not again when the token is sent again', async () => {
const token = await login()
audit.resetHistory()

const first = await logout(token)
const replay = await logout(token)
const another = await logout(token, 'bearer')

expect(first.statusCode).to.equal(200)
expect(replay.statusCode).to.equal(200)
expect(replay.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
expect(another.statusCode).to.equal(200)
expect(audit).to.have.been.calledOnceWith('logout')
})

it('is not written for a replay however many times it is sent', async () => {
const token = await login()
await logout(token)
audit.resetHistory()

for (let i = 0; i < 20; i++) {
await logout(token)
}

expect(audit).not.to.have.been.called
})

it('is written once when the same session is logged out by several requests at the same time', async () => {
const token = await login()
audit.resetHistory()

const responses = await Promise.all([logout(token), logout(token), logout(token), logout(token)])

expect(responses.map((response) => response.statusCode)).to.deep.equal([200, 200, 200, 200])
expect(audit).to.have.been.calledOnceWith('logout')
})

it('is not written for a session that was revoked elsewhere, for example by another worker', async () => {
const token = await login()
revocations.revoked.set(sessionIdOf(token), 3600)
audit.resetHistory()

const response = await logout(token)

expect(response.statusCode).to.equal(200)
expect(audit).not.to.have.been.called
})

it('is written again for a new session of the same administrator', async () => {
const first = await login()
await logout(first)
const second = await login()
audit.resetHistory()

await logout(second)

expect(audit).to.have.been.calledOnceWith('logout')
})

it('is not written once for every anonymous request, however many there are', async () => {
for (let i = 0; i < 20; i++) {
await provider.handleLogout({ headers: {}, socket: {} } as any, mockResponse() as any)
}

expect(audit).not.to.have.been.calledWith('logout')
})
})

it('reports the logout to the audit hook only once the session is revoked', async () => {
const token = await login()

Expand Down
2 changes: 2 additions & 0 deletions test/unit/routes/admin-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -73,7 +73,9 @@ describe('admin settings API', () => {
const revokedSessions = new Set<string>()
revocationStubs = [
Sinon.stub(CacheAdminSessionRevocations.prototype, 'revoke').callsFake(async (sessionId: string) => {
const alreadyRevoked = revokedSessions.has(sessionId)
revokedSessions.add(sessionId)
return !alreadyRevoked
}),
Sinon.stub(CacheAdminSessionRevocations.prototype, 'isRevoked').callsFake(async (sessionId: string) =>
revokedSessions.has(sessionId),
Expand Down
2 changes: 2 additions & 0 deletions test/unit/routes/admin.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -109,7 +109,9 @@ describe('admin router', () => {
const revokedSessions = new Set<string>()
revocationStubs = [
Sinon.stub(CacheAdminSessionRevocations.prototype, 'revoke').callsFake(async (sessionId: string) => {
const alreadyRevoked = revokedSessions.has(sessionId)
revokedSessions.add(sessionId)
return !alreadyRevoked
}),
Sinon.stub(CacheAdminSessionRevocations.prototype, 'isRevoked').callsFake(async (sessionId: string) =>
revokedSessions.has(sessionId),
Expand Down
43 changes: 32 additions & 11 deletions test/unit/utils/admin-session-revocations.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import sinonChai from 'sinon-chai'

import { ICacheAdapter } from '../../../src/@types/adapters'
import {
ADMIN_SESSION_REVOCATION_TIMEOUT_MS,
adminSessionRevocationCacheKey,
CacheAdminSessionRevocations,
} from '../../../src/utils/admin-session-revocations'
Expand All @@ -14,33 +15,50 @@ const { expect } = chai

describe('CacheAdminSessionRevocations', () => {
let sandbox: Sinon.SinonSandbox
let setKey: Sinon.SinonStub
let setKeyIfNotExists: Sinon.SinonStub
let hasKey: Sinon.SinonStub
let revocations: CacheAdminSessionRevocations

beforeEach(() => {
sandbox = Sinon.createSandbox()
setKey = sandbox.stub().resolves(true)
setKeyIfNotExists = sandbox.stub().resolves(true)
hasKey = sandbox.stub().resolves(false)
revocations = new CacheAdminSessionRevocations(() => ({ setKey, hasKey }) as unknown as ICacheAdapter)
revocations = new CacheAdminSessionRevocations(() => ({ setKeyIfNotExists, hasKey }) as unknown as ICacheAdapter)
})

afterEach(() => {
sandbox.restore()
})

it('keeps a revoked session id until the token would have expired', async () => {
it('keeps a revoked session id until the token would have expired, plus the time a write may take', async () => {
await revocations.revoke('abc', 3600)

expect(setKey).to.have.been.calledOnceWithExactly(adminSessionRevocationCacheKey('abc'), '1', 3600)
expect(setKeyIfNotExists).to.have.been.calledOnceWithExactly(
adminSessionRevocationCacheKey('abc'),
'1',
3600 + ADMIN_SESSION_REVOCATION_TIMEOUT_MS / 1000,
)
})

it('keeps a revoked session id for at least a second', async () => {
it('tells the call that revoked a session so, and a later call for it that it did not', async () => {
setKeyIfNotExists.onFirstCall().resolves(true).onSecondCall().resolves(false)

expect(await revocations.revoke('abc', 3600)).to.equal(true)
expect(await revocations.revoke('abc', 3600)).to.equal(false)
})

it('revokes with a set-if-absent, so that simultaneous revocations of one session cannot both win', async () => {
await revocations.revoke('abc', 3600)

expect(setKeyIfNotExists).to.have.been.calledOnce
})

it('keeps a revoked session id for at least a second, plus the time a write may take', 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)
expect(setKeyIfNotExists.firstCall.args[2]).to.equal(1 + ADMIN_SESSION_REVOCATION_TIMEOUT_MS / 1000)
expect(setKeyIfNotExists.secondCall.args[2]).to.equal(1 + ADMIN_SESSION_REVOCATION_TIMEOUT_MS / 1000)
})

it('keys each session separately', () => {
Expand All @@ -55,7 +73,7 @@ describe('CacheAdminSessionRevocations', () => {
})

it('does not hide a cache failure', async () => {
setKey.rejects(new Error('redis is down'))
setKeyIfNotExists.rejects(new Error('redis is down'))
hasKey.rejects(new Error('redis is down'))

await revocations.revoke('abc', 60).then(
Expand All @@ -72,11 +90,14 @@ describe('CacheAdminSessionRevocations', () => {
const neverSettles = () => new Promise<never>(() => undefined)

beforeEach(() => {
revocations = new CacheAdminSessionRevocations(() => ({ setKey, hasKey }) as unknown as ICacheAdapter, 10)
revocations = new CacheAdminSessionRevocations(
() => ({ setKeyIfNotExists, hasKey }) as unknown as ICacheAdapter,
10,
)
})

it('stops waiting for a revocation that is never stored', async () => {
setKey.callsFake(neverSettles)
setKeyIfNotExists.callsFake(neverSettles)

await revocations.revoke('abc', 60).then(
() => expect.fail('revoke should reject'),
Expand Down
Loading