Skip to content

Commit 7ca4c18

Browse files
authored
fix(admin): the settings API cannot change the admin password hash through a parent path (#1231)
## Description `PATCH /admin/settings` refuses to write `admin.passwordHash`, but `isWriteProtectedSettingsPath` is only applied to the **path of each request**. A request for the path `admin` passes (`admin` exists in the default settings schema and is not itself protected), and `setByPath` replaces the whole `admin` object, `passwordHash` included. I reproduced it on the real route: `PATCH /settings {"path": "admin", "value": {..., "passwordHash": <another hash>}}` answered 200 and stored the new hash. Removing the hash (an `admin` object without it) and a batch in which one of several changes replaces `admin` did the same. Anyone holding a valid admin session, or a copy of its token, could therefore set a password hash they chose, or delete it, without knowing the current password, and the change outlives the session. This is the same family as the session work in #1145: an admin session was meant to be revocable and should not be able to turn itself into a permanent credential. - new `collectWriteProtectedSettings` and `changedWriteProtectedSettingsPaths` in `src/utils/settings-redaction.ts` list every write-protected value in a settings document, by path, and report the ones that differ between two documents (replaced, added or removed); - the controller takes the protected values of the stored user settings before applying the changes, applies them, and refuses the whole request with `Path is write-protected` for each protected path that would differ in the document it is about to save. It runs inside the write lock, next to the existing merged validation, and before anything is saved, audited or notified, so a refused request changes nothing; - the checks on the request paths stay as they were; this one is on top, so it covers a parent path, several changes in one request and any path that ends up writing a protected value. Still allowed: changing any other admin setting, and replacing the `admin` object when the hash in it is the stored one. A client that sends back the redacted settings it read (the API shows `passwordHash` as `***`) is refused, which is right: it would have saved `***` as the hash. Not changed here: restoring a settings backup restores the hash that backup holds, as a restore is meant to. ## Related Issue Partly addresses #1022 (finding F-013). That issue groups nine findings, so this PR does not close it. F-040 (the audit entry on an anonymous logout) is next. ## Motivation and Context A credential the API says it protects should be protected whatever path the request names. ## 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 settings updates can no longer change or remove the password hash, including through direct edits, replacement or removal of the containing settings object, redacted placeholders, or batch updates. * Rejected updates leave the stored password hash unchanged and do not save other changes included in the same batch. * Other admin settings can still be updated when the existing password hash is retained, including when replacing the containing settings object. <!-- end of auto-generated comment: release notes by coderabbit.ai -->
2 parents 787b237 + 4d05603 commit 7ca4c18

5 files changed

Lines changed: 223 additions & 0 deletions

File tree

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): the settings API cannot change the admin password hash through a parent path
6+
7+
`PATCH /admin/settings` refused a change to `admin.passwordHash`, but it only looked at the path of the request. A request for the path `admin` with a new `admin` object, alone or inside a batch of changes, replaced the object and so wrote or removed `admin.passwordHash` without being refused. Anyone holding a valid admin session, or a copy of its token, could set a password hash they chose, or delete it, without knowing the current password, and the change outlived the session. The API now compares every write-protected value in the settings it is about to save with the stored ones and refuses the whole request when one differs (changed, added or removed), whichever path or batch caused it. Replacing the `admin` object with the same hash in it, and changing any other admin setting, still work.

‎src/controllers/admin/patch-settings-controller.ts‎

Lines changed: 14 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -15,6 +15,7 @@ import {
1515
withSettingsWriteLock,
1616
} from '../../utils/settings-config'
1717
import {
18+
changedWriteProtectedSettingsPaths,
1819
isWriteProtectedSettingsPath,
1920
redactSettingsValue,
2021
} from '../../utils/settings-redaction'
@@ -59,10 +60,23 @@ export class PatchAdminSettingsController implements IController {
5960
| { ok: false; issues: Array<{ path: string; message: string }> }
6061
>(() => {
6162
const userSettings = loadUserSettings() as unknown as Record<string, unknown>
63+
// Taken before the changes are applied, in case applying them edits this object in place.
64+
const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record<string, unknown>
6265
const nextUserSettings = changes.reduce(
6366
(settings, change) => setByPath(settings, change.path, change.value),
6467
userSettings,
6568
)
69+
70+
// The paths of the request were checked above, but a change to a path that holds a protected value, such as
71+
// replacing `admin`, writes that value too. Compare what would be saved with what is stored.
72+
const changedProtected = changedWriteProtectedSettingsPaths(protectedBefore, nextUserSettings)
73+
if (changedProtected.length > 0) {
74+
return {
75+
ok: false as const,
76+
issues: changedProtected.map((path) => ({ path, message: 'Path is write-protected' })),
77+
}
78+
}
79+
6680
const merged = loadMergedSettings() as unknown as Record<string, unknown>
6781
const mergedNext = changes.reduce(
6882
(settings, change) => setByPath(settings, change.path, getByPath(nextUserSettings, change.path)),

‎src/utils/settings-redaction.ts‎

Lines changed: 38 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -25,6 +25,44 @@ export const isWriteProtectedSettingsPath = (path: string): boolean => {
2525
return path === 'admin.passwordHash' || path.endsWith('.passwordHash')
2626
}
2727

28+
// Every write-protected value in a settings document, by its path. A request names the path it writes, but a path
29+
// above a protected value (replacing `admin`, which holds `admin.passwordHash`) writes it too, so what is protected
30+
// has to be compared in the document as it would be saved, not only in the paths of the request.
31+
export const collectWriteProtectedSettings = (settings: unknown, path = ''): Record<string, unknown> => {
32+
const found: Record<string, unknown> = {}
33+
34+
if (Array.isArray(settings)) {
35+
settings.forEach((entry, index) => {
36+
Object.assign(found, collectWriteProtectedSettings(entry, `${path}[${index}]`))
37+
})
38+
return found
39+
}
40+
41+
if (!isPlainObject(settings)) {
42+
return found
43+
}
44+
45+
for (const [key, value] of Object.entries(settings)) {
46+
const childPath = path ? `${path}.${key}` : key
47+
if (isWriteProtectedSettingsPath(childPath)) {
48+
found[childPath] = value
49+
} else {
50+
Object.assign(found, collectWriteProtectedSettings(value, childPath))
51+
}
52+
}
53+
54+
return found
55+
}
56+
57+
/** The write-protected paths whose value differs between two settings documents, added or removed ones included. */
58+
export const changedWriteProtectedSettingsPaths = (before: unknown, after: unknown): string[] => {
59+
const protectedBefore = collectWriteProtectedSettings(before)
60+
const protectedAfter = collectWriteProtectedSettings(after)
61+
const paths = new Set([...Object.keys(protectedBefore), ...Object.keys(protectedAfter)])
62+
63+
return [...paths].filter((path) => protectedBefore[path] !== protectedAfter[path]).sort()
64+
}
65+
2866
export const redactSettingsValue = (path: string, value: unknown): unknown => {
2967
if (isSensitiveSettingsPath(path) && typeof value === 'string' && value.length > 0) {
3068
return '***'

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

Lines changed: 99 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -5,6 +5,7 @@ import fs from 'fs'
55
import os from 'os'
66
import path from 'path'
77
import Sinon from 'sinon'
8+
import yaml from 'js-yaml'
89

910
import { hashAdminPassword } from '../../../src/utils/admin-password'
1011
import { CacheAdminSessionRevocations } from '../../../src/utils/admin-session-revocations'
@@ -255,6 +256,104 @@ describe('admin settings API', () => {
255256
expect(settingsRaw).to.include('enabled: true')
256257
})
257258

259+
describe('the admin password hash', () => {
260+
const otherHash = () => hashAdminPassword('another-password')
261+
262+
const startWithPassword = async () => {
263+
const passwordHash = hashAdminPassword('settings-password')
264+
const admin = { enabled: true, passwordHash, sessionTtlSeconds: 3600 }
265+
saveSettings({ ...loadDefaults(), admin })
266+
const baseUrl = await startServer({ admin })
267+
const cookie = await login(baseUrl)
268+
269+
return { baseUrl, cookie, passwordHash, admin }
270+
}
271+
272+
const patch = (baseUrl: string, cookie: string, body: unknown) =>
273+
axios.patch(`${baseUrl}/settings`, body, {
274+
headers: { cookie, 'content-type': 'application/json' },
275+
validateStatus: () => true,
276+
})
277+
278+
const storedHash = () => (yaml.load(fs.readFileSync(getSettingsFilePath(), 'utf-8')) as any).admin?.passwordHash
279+
280+
it('refuses to change it by its own path', async () => {
281+
const { baseUrl, cookie, passwordHash } = await startWithPassword()
282+
283+
const response = await patch(baseUrl, cookie, { path: 'admin.passwordHash', value: otherHash() })
284+
285+
expect(response.status).to.equal(400)
286+
expect(storedHash()).to.equal(passwordHash)
287+
})
288+
289+
it('refuses to change it by replacing the admin object that holds it', async () => {
290+
const { baseUrl, cookie, admin, passwordHash } = await startWithPassword()
291+
292+
const response = await patch(baseUrl, cookie, { path: 'admin', value: { ...admin, passwordHash: otherHash() } })
293+
294+
expect(response.status, JSON.stringify(response.data)).to.equal(400)
295+
expect(response.data.issues).to.deep.equal([{ path: 'admin.passwordHash', message: 'Path is write-protected' }])
296+
expect(storedHash()).to.equal(passwordHash)
297+
})
298+
299+
it('refuses to remove it by replacing the admin object without it', async () => {
300+
const { baseUrl, cookie, passwordHash } = await startWithPassword()
301+
302+
const response = await patch(baseUrl, cookie, {
303+
path: 'admin',
304+
value: { enabled: true, sessionTtlSeconds: 3600 },
305+
})
306+
307+
expect(response.status).to.equal(400)
308+
expect(storedHash()).to.equal(passwordHash)
309+
})
310+
311+
it('refuses to write the redacted placeholder over it', async () => {
312+
const { baseUrl, cookie, admin, passwordHash } = await startWithPassword()
313+
314+
const response = await patch(baseUrl, cookie, { path: 'admin', value: { ...admin, passwordHash: '***' } })
315+
316+
expect(response.status).to.equal(400)
317+
expect(storedHash()).to.equal(passwordHash)
318+
})
319+
320+
it('refuses a batch in which one change replaces the admin object, and saves none of it', async () => {
321+
const { baseUrl, cookie, admin, passwordHash } = await startWithPassword()
322+
const settingsBefore = fs.readFileSync(getSettingsFilePath(), 'utf-8')
323+
324+
const response = await patch(baseUrl, cookie, {
325+
changes: [
326+
{ path: 'payments.enabled', value: true },
327+
{ path: 'admin', value: { ...admin, passwordHash: otherHash() } },
328+
],
329+
})
330+
331+
expect(response.status).to.equal(400)
332+
expect(storedHash()).to.equal(passwordHash)
333+
// The whole file, so a change of the batch that was saved before the refusal would show too.
334+
expect(fs.readFileSync(getSettingsFilePath(), 'utf-8')).to.equal(settingsBefore)
335+
expect((yaml.load(settingsBefore) as any).payments?.enabled).not.to.equal(true)
336+
})
337+
338+
it('still lets an admin setting be changed on its own path', async () => {
339+
const { baseUrl, cookie, passwordHash } = await startWithPassword()
340+
341+
const response = await patch(baseUrl, cookie, { path: 'admin.sessionTtlSeconds', value: 7200 })
342+
343+
expect(response.status, JSON.stringify(response.data)).to.equal(200)
344+
expect(storedHash()).to.equal(passwordHash)
345+
})
346+
347+
it('still lets the admin object be replaced when the hash in it is the one stored', async () => {
348+
const { baseUrl, cookie, admin, passwordHash } = await startWithPassword()
349+
350+
const response = await patch(baseUrl, cookie, { path: 'admin', value: { ...admin, sessionTtlSeconds: 7200 } })
351+
352+
expect(response.status, JSON.stringify(response.data)).to.equal(200)
353+
expect(storedHash()).to.equal(passwordHash)
354+
})
355+
})
356+
258357
it('atomically applies staged changes with a backup and audit entry', async () => {
259358
const passwordHash = hashAdminPassword('settings-password')
260359
saveSettings({

‎test/unit/utils/settings-redaction.spec.ts‎

Lines changed: 65 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -1,6 +1,8 @@
11
import { expect } from 'chai'
22

33
import {
4+
changedWriteProtectedSettingsPaths,
5+
collectWriteProtectedSettings,
46
isSensitiveSettingsPath,
57
isWriteProtectedSettingsPath,
68
redactSettingsSecrets,
@@ -79,4 +81,67 @@ describe('settings-redaction', () => {
7981

8082
expect(redactSettingsSecrets(input).admin.notifications.targets[0].url).to.equal('***')
8183
})
84+
85+
describe('collectWriteProtectedSettings', () => {
86+
it('finds the protected values in a document, by path', () => {
87+
const settings = { admin: { enabled: true, passwordHash: 'abc' }, payments: {} }
88+
89+
expect(collectWriteProtectedSettings(settings)).to.deep.equal({ 'admin.passwordHash': 'abc' })
90+
})
91+
92+
it('finds a protected value nested in objects and arrays', () => {
93+
const settings = { other: [{ passwordHash: 'x' }, { name: 'y' }], deep: { er: { passwordHash: 'z' } } }
94+
95+
expect(collectWriteProtectedSettings(settings)).to.deep.equal({
96+
'other[0].passwordHash': 'x',
97+
'deep.er.passwordHash': 'z',
98+
})
99+
})
100+
101+
it('finds nothing in a document without one, or in something that is not a document', () => {
102+
expect(collectWriteProtectedSettings({ admin: { enabled: true } })).to.deep.equal({})
103+
expect(collectWriteProtectedSettings(undefined)).to.deep.equal({})
104+
expect(collectWriteProtectedSettings('admin.passwordHash')).to.deep.equal({})
105+
})
106+
})
107+
108+
describe('changedWriteProtectedSettingsPaths', () => {
109+
it('is empty when no protected value changed, whatever else did', () => {
110+
const before = { admin: { passwordHash: 'abc', sessionTtlSeconds: 1 }, payments: { enabled: false } }
111+
const after = { admin: { passwordHash: 'abc', sessionTtlSeconds: 2 }, payments: { enabled: true } }
112+
113+
expect(changedWriteProtectedSettingsPaths(before, after)).to.deep.equal([])
114+
})
115+
116+
it('reports a protected value that was replaced', () => {
117+
expect(
118+
changedWriteProtectedSettingsPaths({ admin: { passwordHash: 'abc' } }, { admin: { passwordHash: 'new' } }),
119+
).to.deep.equal(['admin.passwordHash'])
120+
})
121+
122+
it('reports a protected value that was removed', () => {
123+
expect(changedWriteProtectedSettingsPaths({ admin: { passwordHash: 'abc' } }, { admin: {} })).to.deep.equal([
124+
'admin.passwordHash',
125+
])
126+
expect(changedWriteProtectedSettingsPaths({ admin: { passwordHash: 'abc' } }, {})).to.deep.equal([
127+
'admin.passwordHash',
128+
])
129+
})
130+
131+
it('reports a protected value that was added', () => {
132+
expect(changedWriteProtectedSettingsPaths({ admin: {} }, { admin: { passwordHash: 'new' } })).to.deep.equal([
133+
'admin.passwordHash',
134+
])
135+
})
136+
137+
it('reports each changed protected path once, in order', () => {
138+
const before = { admin: { passwordHash: 'a' }, other: { passwordHash: 'b' } }
139+
const after = { admin: { passwordHash: 'x' }, other: { passwordHash: 'y' } }
140+
141+
expect(changedWriteProtectedSettingsPaths(before, after)).to.deep.equal([
142+
'admin.passwordHash',
143+
'other.passwordHash',
144+
])
145+
})
146+
})
82147
})

0 commit comments

Comments
 (0)