From bef8c4a13eeb1d1819002cd00da0dd489f6eccbd Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Mon, 23 Nov 2026 01:32:11 +0530 Subject: [PATCH 1/3] fix(admin): audit a logout only when the request has a valid session Signed-off-by: Priyanshubhartistm --- .../admin-logout-audit-only-with-session.md | 7 +++ src/admin/password-admin-auth-provider.ts | 7 ++- .../password-admin-auth-provider.spec.ts | 62 +++++++++++++++++++ 3 files changed, 74 insertions(+), 2 deletions(-) create mode 100644 .changeset/admin-logout-audit-only-with-session.md diff --git a/.changeset/admin-logout-audit-only-with-session.md b/.changeset/admin-logout-audit-only-with-session.md new file mode 100644 index 000000000..fcbe45c12 --- /dev/null +++ b/.changeset/admin-logout-audit-only-with-session.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(admin): record a logout in the audit history only when the request has a valid 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 when the request presents a valid session (as a cookie or a Bearer token). A request without one still gets the cookie cleared and a 200, and writes nothing. diff --git a/src/admin/password-admin-auth-provider.ts b/src/admin/password-admin-auth-provider.ts index 6a4e68dc0..8c8cfd108 100644 --- a/src/admin/password-admin-auth-provider.ts +++ b/src/admin/password-admin-auth-provider.ts @@ -79,9 +79,12 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider { .send({ error: 'Internal Server Error' }) return } - } - void this.auditHook?.('logout', request) + // Recorded only for a request that presents a valid session. The endpoint is public (it has to clear a cookie + // whoever sends the request), so an entry written for any request would let an anonymous caller fill the shared, + // size-limited audit history with logouts that never happened and push real administrator records out of it. + void this.auditHook?.('logout', request) + } response .status(200) diff --git a/test/unit/admin/password-admin-auth-provider.spec.ts b/test/unit/admin/password-admin-auth-provider.spec.ts index 9cbcb8cc7..5784c08e7 100644 --- a/test/unit/admin/password-admin-auth-provider.spec.ts +++ b/test/unit/admin/password-admin-auth-provider.spec.ts @@ -181,6 +181,68 @@ 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 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() From edb8fc5920cd1ecb3c7169551a09009dab6ac9bc Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Mon, 23 Nov 2026 17:49:55 +0530 Subject: [PATCH 2/3] fix(admin): audit a logout only when it ends the session Signed-off-by: Priyanshubhartistm --- .../admin-logout-audit-only-with-session.md | 4 +- src/@types/admin.ts | 3 +- src/admin/password-admin-auth-provider.ts | 15 ++-- src/utils/admin-session-revocations.ts | 8 ++- .../password-admin-auth-provider.spec.ts | 68 ++++++++++++++++++- test/unit/routes/admin-settings.spec.ts | 2 + test/unit/routes/admin.spec.ts | 2 + .../utils/admin-session-revocations.spec.ts | 34 +++++++--- 8 files changed, 115 insertions(+), 21 deletions(-) diff --git a/.changeset/admin-logout-audit-only-with-session.md b/.changeset/admin-logout-audit-only-with-session.md index fcbe45c12..065f8a30d 100644 --- a/.changeset/admin-logout-audit-only-with-session.md +++ b/.changeset/admin-logout-audit-only-with-session.md @@ -2,6 +2,6 @@ 'nostream': patch --- -fix(admin): record a logout in the audit history only when the request has a valid session +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 when the request presents a valid session (as a cookie or a Bearer token). A request without one still gets the cookie cleared and a 200, and writes nothing. +`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. diff --git a/src/@types/admin.ts b/src/@types/admin.ts index 9584fb83f..bdb53a2ed 100644 --- a/src/@types/admin.ts +++ b/src/@types/admin.ts @@ -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 + /** Resolves true when this call revoked the session, false when it was already revoked (the call changed nothing). */ + 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 8c8cfd108..77d15ed34 100644 --- a/src/admin/password-admin-auth-provider.ts +++ b/src/admin/password-admin-auth-provider.ts @@ -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 @@ -80,10 +81,14 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider { return } - // Recorded only for a request that presents a valid session. The endpoint is public (it has to clear a cookie - // whoever sends the request), so an entry written for any request would let an anonymous caller fill the shared, - // size-limited audit history with logouts that never happened and push real administrator records out of it. - 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 diff --git a/src/utils/admin-session-revocations.ts b/src/utils/admin-session-revocations.ts index ab333b69c..814a1c111 100644 --- a/src/utils/admin-session-revocations.ts +++ b/src/utils/admin-session-revocations.ts @@ -38,11 +38,13 @@ export class CacheAdminSessionRevocations implements IAdminSessionRevocations { private readonly timeoutMs: number = ADMIN_SESSION_REVOCATION_TIMEOUT_MS, ) {} - public async revoke(sessionId: string, ttlSeconds: number): Promise { + 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), + // 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), this.timeoutMs, 'revoking the admin session', ) diff --git a/test/unit/admin/password-admin-auth-provider.spec.ts b/test/unit/admin/password-admin-auth-provider.spec.ts index 5784c08e7..c4caf59c0 100644 --- a/test/unit/admin/password-admin-auth-provider.spec.ts +++ b/test/unit/admin/password-admin-auth-provider.spec.ts @@ -16,11 +16,16 @@ class FakeRevocations implements IAdminSessionRevocations { public failRevoke = false public failCheck = false - public async revoke(sessionId: string, ttlSeconds: number): Promise { + public async revoke(sessionId: string, ttlSeconds: number): Promise { 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 { @@ -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}` }, @@ -234,6 +241,65 @@ describe('PasswordAdminAuthProvider sessions', () => { 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) diff --git a/test/unit/routes/admin-settings.spec.ts b/test/unit/routes/admin-settings.spec.ts index 1186960d3..aeeb494c9 100644 --- a/test/unit/routes/admin-settings.spec.ts +++ b/test/unit/routes/admin-settings.spec.ts @@ -73,7 +73,9 @@ describe('admin settings API', () => { const revokedSessions = new Set() 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), diff --git a/test/unit/routes/admin.spec.ts b/test/unit/routes/admin.spec.ts index 79d1a2569..4a8ed2abc 100644 --- a/test/unit/routes/admin.spec.ts +++ b/test/unit/routes/admin.spec.ts @@ -109,7 +109,9 @@ describe('admin router', () => { const revokedSessions = new Set() 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), diff --git a/test/unit/utils/admin-session-revocations.spec.ts b/test/unit/utils/admin-session-revocations.spec.ts index 661730506..89548cfbb 100644 --- a/test/unit/utils/admin-session-revocations.spec.ts +++ b/test/unit/utils/admin-session-revocations.spec.ts @@ -14,15 +14,15 @@ 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(() => { @@ -32,15 +32,28 @@ describe('CacheAdminSessionRevocations', () => { 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) + expect(setKeyIfNotExists).to.have.been.calledOnceWithExactly(adminSessionRevocationCacheKey('abc'), '1', 3600) + }) + + 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', 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) + expect(setKeyIfNotExists.secondCall.args[2]).to.equal(1) }) it('keys each session separately', () => { @@ -55,7 +68,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( @@ -72,11 +85,14 @@ describe('CacheAdminSessionRevocations', () => { const neverSettles = () => new Promise(() => 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'), From 41d155f77cf56b7b5ae4b687ca3981e79e902f50 Mon Sep 17 00:00:00 2001 From: Priyanshubhartistm Date: Tue, 24 Nov 2026 01:22:05 +0530 Subject: [PATCH 3/3] fix(admin): keep a revoked session past the revocation write window Signed-off-by: Priyanshubhartistm --- src/utils/admin-session-revocations.ts | 5 ++++- test/unit/utils/admin-session-revocations.spec.ts | 15 ++++++++++----- 2 files changed, 14 insertions(+), 6 deletions(-) diff --git a/src/utils/admin-session-revocations.ts b/src/utils/admin-session-revocations.ts index 814a1c111..337ed1e0a 100644 --- a/src/utils/admin-session-revocations.ts +++ b/src/utils/admin-session-revocations.ts @@ -39,7 +39,10 @@ export class CacheAdminSessionRevocations implements IAdminSessionRevocations { ) {} public async revoke(sessionId: string, ttlSeconds: number): Promise { - const expirySeconds = Number.isSafeInteger(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : 1 + // 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 // 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. diff --git a/test/unit/utils/admin-session-revocations.spec.ts b/test/unit/utils/admin-session-revocations.spec.ts index 89548cfbb..07714c4a4 100644 --- a/test/unit/utils/admin-session-revocations.spec.ts +++ b/test/unit/utils/admin-session-revocations.spec.ts @@ -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' @@ -29,10 +30,14 @@ describe('CacheAdminSessionRevocations', () => { 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(setKeyIfNotExists).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('tells the call that revoked a session so, and a later call for it that it did not', async () => { @@ -48,12 +53,12 @@ describe('CacheAdminSessionRevocations', () => { expect(setKeyIfNotExists).to.have.been.calledOnce }) - it('keeps a revoked session id for at least a second', async () => { + 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(setKeyIfNotExists.firstCall.args[2]).to.equal(1) - expect(setKeyIfNotExists.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', () => {