Skip to content

Commit 2dd9ba2

Browse files
fix(admin): record a logout in the audit history only when the request has a valid session (#1234)
## Description `POST /admin/logout` is public by design: it has to clear the session cookie whoever sends the request. `handleLogout` called the audit hook (`void this.auditHook?.('logout', request)`) for every request, whether or not the request carried a valid session, so each anonymous `POST /admin/logout` wrote an `admin.logout` record, with the caller's address, to the shared audit history in Redis. That history is retention-limited, so someone who can reach the admin routes could post to this endpoint in a loop, fill it with logouts that never happened, and push the real administrator records (settings changes, logins) out of it. - the audit record is now written only when the request presents a valid session, as a cookie or a Bearer token, and only after that session has been revoked, which is where the code already was for a valid session; - a request with no token, a token that was not signed by the relay, a malformed one or an expired one still gets the cookie cleared and a 200 (the response stays idempotent, as it was), and writes nothing; - a failed revocation still answers 500 and writes nothing, as before. I did not add a separate record for the anonymous requests. The issue mentions that as optional, and a record per anonymous request is the very thing that filled the history. ## Related Issue Partly addresses #1022 (finding F-040). That issue groups nine findings, so this PR does not close it. F-013 is in #1231. ## Motivation and Context The audit history is the record an operator reads after an incident. A caller with no session should not be able to write to it. ## How Has This Been Tested? ## Screenshots (if appropriate): ## Types of changes - [ ] Non-functional change (docs, style, minor refactor) - [x] Bug fix (non-breaking change which fixes an issue) - [ ] New feature (non-breaking change which adds functionality) - [ ] Breaking change (fix or feature that would cause existing functionality to change) ## Checklist: - [x] My code follows the code style of this project. - [ ] My change requires a change to the documentation. - [ ] I have updated the documentation accordingly. - [x] I have read the **CONTRIBUTING** document. - [x] I have added tests to cover my code changes. - [x] I added a changeset, or this is docs-only and I added an empty changeset. - [x] All new and existing tests passed. <!-- This is an auto-generated comment: release notes by coderabbit.ai --> <!-- coderabbit-ai-generated:v1 --> ## Summary by CodeRabbit * **Bug Fixes** * Admin logout audit records are created only when that request revokes a valid session, whether authenticated by cookie or Bearer token. * Repeated or concurrent logout requests for an already-revoked session do not create duplicate audit records. Requests without a valid session still clear the cookie and return a successful response. * If session revocation fails, logout returns an internal server error and does not create an audit record. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents 5d829a2 + 41d155f commit 2dd9ba2

8 files changed

Lines changed: 194 additions & 20 deletions
Lines changed: 7 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,7 @@
1+
---
2+
'nostream': patch
3+
---
4+
5+
fix(admin): record a logout in the audit history only when it ends a session
6+
7+
`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.

‎src/@types/admin.ts‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -12,6 +12,7 @@ export interface IAdminAuthProvider {
1212
* token's session id here, until the token would have expired anyway, and every request checks it.
1313
*/
1414
export interface IAdminSessionRevocations {
15-
revoke(sessionId: string, ttlSeconds: number): Promise<void>
15+
/** Resolves true when this call revoked the session, false when it was already revoked (the call changed nothing). */
16+
revoke(sessionId: string, ttlSeconds: number): Promise<boolean>
1617
isRevoked(sessionId: string): Promise<boolean>
1718
}

‎src/admin/password-admin-auth-provider.ts‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -67,9 +67,10 @@ export class PasswordAdminAuthProvider implements IAdminAuthProvider {
6767

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

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

8694
response
8795
.status(200)

‎src/utils/admin-session-revocations.ts‎

Lines changed: 9 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -38,11 +38,16 @@ export class CacheAdminSessionRevocations implements IAdminSessionRevocations {
3838
private readonly timeoutMs: number = ADMIN_SESSION_REVOCATION_TIMEOUT_MS,
3939
) {}
4040

41-
public async revoke(sessionId: string, ttlSeconds: number): Promise<void> {
42-
const expirySeconds = Number.isSafeInteger(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : 1
41+
public async revoke(sessionId: string, ttlSeconds: number): Promise<boolean> {
42+
// A replay that was valid when it started can still have its write land up to the timeout later, so the entry
43+
// has to outlast the token by that long. Otherwise the entry could expire first and the replay would win.
44+
const writeWindowSeconds = Math.ceil(this.timeoutMs / 1000)
45+
const expirySeconds = (Number.isSafeInteger(ttlSeconds) && ttlSeconds > 0 ? ttlSeconds : 1) + writeWindowSeconds
4346

44-
await withTimeout(
45-
() => this.cache().setKey(adminSessionRevocationCacheKey(sessionId), '1', expirySeconds),
47+
// Set only if absent, in one step, so that of several logouts of the same session at once exactly one is told
48+
// that it revoked it. The entry keeps the expiry of the first revocation, which is when the token ends anyway.
49+
return withTimeout(
50+
() => this.cache().setKeyIfNotExists(adminSessionRevocationCacheKey(sessionId), '1', expirySeconds),
4651
this.timeoutMs,
4752
'revoking the admin session',
4853
)

‎test/unit/admin/password-admin-auth-provider.spec.ts‎

Lines changed: 129 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -16,11 +16,16 @@ class FakeRevocations implements IAdminSessionRevocations {
1616
public failRevoke = false
1717
public failCheck = false
1818

19-
public async revoke(sessionId: string, ttlSeconds: number): Promise<void> {
19+
public async revoke(sessionId: string, ttlSeconds: number): Promise<boolean> {
2020
if (this.failRevoke) {
2121
throw new Error('redis is down')
2222
}
23+
// Check and set in one step, like the cache does with SET NX.
24+
if (this.revoked.has(sessionId)) {
25+
return false
26+
}
2327
this.revoked.set(sessionId, ttlSeconds)
28+
return true
2429
}
2530

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

100+
const sessionIdOf = (token: string): string => token.split('.')[1]
101+
95102
const requestWithToken = (token: string, via: 'cookie' | 'bearer' = 'cookie'): Request =>
96103
({
97104
headers: via === 'cookie' ? { cookie: `admin_session=${token}` } : { authorization: `Bearer ${token}` },
@@ -181,6 +188,127 @@ describe('PasswordAdminAuthProvider sessions', () => {
181188
expect(revocations.revoked.size).to.equal(0)
182189
})
183190

191+
describe('the audit record of a logout', () => {
192+
it('is written for a request that presents a valid session, with that request', async () => {
193+
const token = await login()
194+
audit.resetHistory()
195+
const request = requestWithToken(token)
196+
197+
await provider.handleLogout(request, mockResponse() as unknown as Response)
198+
199+
expect(audit).to.have.been.calledOnceWithExactly('logout', request)
200+
})
201+
202+
it('is also written when the session is presented as a Bearer token', async () => {
203+
const token = await login()
204+
audit.resetHistory()
205+
206+
await logout(token, 'bearer')
207+
208+
expect(audit).to.have.been.calledOnceWith('logout')
209+
})
210+
211+
it('is not written for a request without a token', async () => {
212+
const response = mockResponse()
213+
214+
await provider.handleLogout({ headers: {}, socket: {} } as any, response as any)
215+
216+
expect(response.statusCode).to.equal(200)
217+
expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
218+
expect(audit).not.to.have.been.calledWith('logout')
219+
})
220+
221+
it('is not written for a token that was not signed by the relay', async () => {
222+
const response = await logout(`${Math.floor(Date.now() / 1000) + 600}.${'0'.repeat(32)}.${'0'.repeat(64)}`)
223+
224+
expect(response.statusCode).to.equal(200)
225+
expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
226+
expect(audit).not.to.have.been.calledWith('logout')
227+
})
228+
229+
it('is not written for a malformed token', async () => {
230+
const response = await logout('abc.def')
231+
232+
expect(response.statusCode).to.equal(200)
233+
expect(audit).not.to.have.been.calledWith('logout')
234+
})
235+
236+
it('is not written for a token that has expired', async () => {
237+
const response = await logout(createAdminSessionToken(Math.floor(Date.now() / 1000) - 10))
238+
239+
expect(response.statusCode).to.equal(200)
240+
expect(response.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
241+
expect(audit).not.to.have.been.calledWith('logout')
242+
})
243+
244+
it('is written once for the logout that ended the session, not again when the token is sent again', async () => {
245+
const token = await login()
246+
audit.resetHistory()
247+
248+
const first = await logout(token)
249+
const replay = await logout(token)
250+
const another = await logout(token, 'bearer')
251+
252+
expect(first.statusCode).to.equal(200)
253+
expect(replay.statusCode).to.equal(200)
254+
expect(replay.headers['Set-Cookie']).to.match(/admin_session=;.*Max-Age=0/)
255+
expect(another.statusCode).to.equal(200)
256+
expect(audit).to.have.been.calledOnceWith('logout')
257+
})
258+
259+
it('is not written for a replay however many times it is sent', async () => {
260+
const token = await login()
261+
await logout(token)
262+
audit.resetHistory()
263+
264+
for (let i = 0; i < 20; i++) {
265+
await logout(token)
266+
}
267+
268+
expect(audit).not.to.have.been.called
269+
})
270+
271+
it('is written once when the same session is logged out by several requests at the same time', async () => {
272+
const token = await login()
273+
audit.resetHistory()
274+
275+
const responses = await Promise.all([logout(token), logout(token), logout(token), logout(token)])
276+
277+
expect(responses.map((response) => response.statusCode)).to.deep.equal([200, 200, 200, 200])
278+
expect(audit).to.have.been.calledOnceWith('logout')
279+
})
280+
281+
it('is not written for a session that was revoked elsewhere, for example by another worker', async () => {
282+
const token = await login()
283+
revocations.revoked.set(sessionIdOf(token), 3600)
284+
audit.resetHistory()
285+
286+
const response = await logout(token)
287+
288+
expect(response.statusCode).to.equal(200)
289+
expect(audit).not.to.have.been.called
290+
})
291+
292+
it('is written again for a new session of the same administrator', async () => {
293+
const first = await login()
294+
await logout(first)
295+
const second = await login()
296+
audit.resetHistory()
297+
298+
await logout(second)
299+
300+
expect(audit).to.have.been.calledOnceWith('logout')
301+
})
302+
303+
it('is not written once for every anonymous request, however many there are', async () => {
304+
for (let i = 0; i < 20; i++) {
305+
await provider.handleLogout({ headers: {}, socket: {} } as any, mockResponse() as any)
306+
}
307+
308+
expect(audit).not.to.have.been.calledWith('logout')
309+
})
310+
})
311+
184312
it('reports the logout to the audit hook only once the session is revoked', async () => {
185313
const token = await login()
186314

‎test/unit/routes/admin-settings.spec.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -74,7 +74,9 @@ describe('admin settings API', () => {
7474
const revokedSessions = new Set<string>()
7575
revocationStubs = [
7676
Sinon.stub(CacheAdminSessionRevocations.prototype, 'revoke').callsFake(async (sessionId: string) => {
77+
const alreadyRevoked = revokedSessions.has(sessionId)
7778
revokedSessions.add(sessionId)
79+
return !alreadyRevoked
7880
}),
7981
Sinon.stub(CacheAdminSessionRevocations.prototype, 'isRevoked').callsFake(async (sessionId: string) =>
8082
revokedSessions.has(sessionId),

‎test/unit/routes/admin.spec.ts‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -109,7 +109,9 @@ describe('admin router', () => {
109109
const revokedSessions = new Set<string>()
110110
revocationStubs = [
111111
Sinon.stub(CacheAdminSessionRevocations.prototype, 'revoke').callsFake(async (sessionId: string) => {
112+
const alreadyRevoked = revokedSessions.has(sessionId)
112113
revokedSessions.add(sessionId)
114+
return !alreadyRevoked
113115
}),
114116
Sinon.stub(CacheAdminSessionRevocations.prototype, 'isRevoked').callsFake(async (sessionId: string) =>
115117
revokedSessions.has(sessionId),

‎test/unit/utils/admin-session-revocations.spec.ts‎

Lines changed: 32 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -4,6 +4,7 @@ import sinonChai from 'sinon-chai'
44

55
import { ICacheAdapter } from '../../../src/@types/adapters'
66
import {
7+
ADMIN_SESSION_REVOCATION_TIMEOUT_MS,
78
adminSessionRevocationCacheKey,
89
CacheAdminSessionRevocations,
910
} from '../../../src/utils/admin-session-revocations'
@@ -14,33 +15,50 @@ const { expect } = chai
1415

1516
describe('CacheAdminSessionRevocations', () => {
1617
let sandbox: Sinon.SinonSandbox
17-
let setKey: Sinon.SinonStub
18+
let setKeyIfNotExists: Sinon.SinonStub
1819
let hasKey: Sinon.SinonStub
1920
let revocations: CacheAdminSessionRevocations
2021

2122
beforeEach(() => {
2223
sandbox = Sinon.createSandbox()
23-
setKey = sandbox.stub().resolves(true)
24+
setKeyIfNotExists = sandbox.stub().resolves(true)
2425
hasKey = sandbox.stub().resolves(false)
25-
revocations = new CacheAdminSessionRevocations(() => ({ setKey, hasKey }) as unknown as ICacheAdapter)
26+
revocations = new CacheAdminSessionRevocations(() => ({ setKeyIfNotExists, hasKey }) as unknown as ICacheAdapter)
2627
})
2728

2829
afterEach(() => {
2930
sandbox.restore()
3031
})
3132

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

35-
expect(setKey).to.have.been.calledOnceWithExactly(adminSessionRevocationCacheKey('abc'), '1', 3600)
36+
expect(setKeyIfNotExists).to.have.been.calledOnceWithExactly(
37+
adminSessionRevocationCacheKey('abc'),
38+
'1',
39+
3600 + ADMIN_SESSION_REVOCATION_TIMEOUT_MS / 1000,
40+
)
3641
})
3742

38-
it('keeps a revoked session id for at least a second', async () => {
43+
it('tells the call that revoked a session so, and a later call for it that it did not', async () => {
44+
setKeyIfNotExists.onFirstCall().resolves(true).onSecondCall().resolves(false)
45+
46+
expect(await revocations.revoke('abc', 3600)).to.equal(true)
47+
expect(await revocations.revoke('abc', 3600)).to.equal(false)
48+
})
49+
50+
it('revokes with a set-if-absent, so that simultaneous revocations of one session cannot both win', async () => {
51+
await revocations.revoke('abc', 3600)
52+
53+
expect(setKeyIfNotExists).to.have.been.calledOnce
54+
})
55+
56+
it('keeps a revoked session id for at least a second, plus the time a write may take', async () => {
3957
await revocations.revoke('abc', 0)
4058
await revocations.revoke('def', Number.NaN)
4159

42-
expect(setKey.firstCall.args[2]).to.equal(1)
43-
expect(setKey.secondCall.args[2]).to.equal(1)
60+
expect(setKeyIfNotExists.firstCall.args[2]).to.equal(1 + ADMIN_SESSION_REVOCATION_TIMEOUT_MS / 1000)
61+
expect(setKeyIfNotExists.secondCall.args[2]).to.equal(1 + ADMIN_SESSION_REVOCATION_TIMEOUT_MS / 1000)
4462
})
4563

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

5775
it('does not hide a cache failure', async () => {
58-
setKey.rejects(new Error('redis is down'))
76+
setKeyIfNotExists.rejects(new Error('redis is down'))
5977
hasKey.rejects(new Error('redis is down'))
6078

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

7492
beforeEach(() => {
75-
revocations = new CacheAdminSessionRevocations(() => ({ setKey, hasKey }) as unknown as ICacheAdapter, 10)
93+
revocations = new CacheAdminSessionRevocations(
94+
() => ({ setKeyIfNotExists, hasKey }) as unknown as ICacheAdapter,
95+
10,
96+
)
7697
})
7798

7899
it('stops waiting for a revocation that is never stored', async () => {
79-
setKey.callsFake(neverSettles)
100+
setKeyIfNotExists.callsFake(neverSettles)
80101

81102
await revocations.revoke('abc', 60).then(
82103
() => expect.fail('revoke should reject'),

0 commit comments

Comments
 (0)