diff --git a/.changeset/admin-settings-protect-password-hash.md b/.changeset/admin-settings-protect-password-hash.md new file mode 100644 index 000000000..6c39d48d3 --- /dev/null +++ b/.changeset/admin-settings-protect-password-hash.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(admin): the settings API cannot change the admin password hash through a parent path + +`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. diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index ac624c6e7..c78394b3a 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -15,6 +15,7 @@ import { withSettingsWriteLock, } from '../../utils/settings-config' import { + changedWriteProtectedSettingsPaths, isWriteProtectedSettingsPath, redactSettingsValue, } from '../../utils/settings-redaction' @@ -59,10 +60,23 @@ export class PatchAdminSettingsController implements IController { | { ok: false; issues: Array<{ path: string; message: string }> } >(() => { const userSettings = loadUserSettings() as unknown as Record + // Taken before the changes are applied, in case applying them edits this object in place. + const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record const nextUserSettings = changes.reduce( (settings, change) => setByPath(settings, change.path, change.value), userSettings, ) + + // The paths of the request were checked above, but a change to a path that holds a protected value, such as + // replacing `admin`, writes that value too. Compare what would be saved with what is stored. + const changedProtected = changedWriteProtectedSettingsPaths(protectedBefore, nextUserSettings) + if (changedProtected.length > 0) { + return { + ok: false as const, + issues: changedProtected.map((path) => ({ path, message: 'Path is write-protected' })), + } + } + const merged = loadMergedSettings() as unknown as Record const mergedNext = changes.reduce( (settings, change) => setByPath(settings, change.path, getByPath(nextUserSettings, change.path)), diff --git a/src/utils/settings-redaction.ts b/src/utils/settings-redaction.ts index a3edf8f7d..4981f99b1 100644 --- a/src/utils/settings-redaction.ts +++ b/src/utils/settings-redaction.ts @@ -25,6 +25,44 @@ export const isWriteProtectedSettingsPath = (path: string): boolean => { return path === 'admin.passwordHash' || path.endsWith('.passwordHash') } +// Every write-protected value in a settings document, by its path. A request names the path it writes, but a path +// above a protected value (replacing `admin`, which holds `admin.passwordHash`) writes it too, so what is protected +// has to be compared in the document as it would be saved, not only in the paths of the request. +export const collectWriteProtectedSettings = (settings: unknown, path = ''): Record => { + const found: Record = {} + + if (Array.isArray(settings)) { + settings.forEach((entry, index) => { + Object.assign(found, collectWriteProtectedSettings(entry, `${path}[${index}]`)) + }) + return found + } + + if (!isPlainObject(settings)) { + return found + } + + for (const [key, value] of Object.entries(settings)) { + const childPath = path ? `${path}.${key}` : key + if (isWriteProtectedSettingsPath(childPath)) { + found[childPath] = value + } else { + Object.assign(found, collectWriteProtectedSettings(value, childPath)) + } + } + + return found +} + +/** The write-protected paths whose value differs between two settings documents, added or removed ones included. */ +export const changedWriteProtectedSettingsPaths = (before: unknown, after: unknown): string[] => { + const protectedBefore = collectWriteProtectedSettings(before) + const protectedAfter = collectWriteProtectedSettings(after) + const paths = new Set([...Object.keys(protectedBefore), ...Object.keys(protectedAfter)]) + + return [...paths].filter((path) => protectedBefore[path] !== protectedAfter[path]).sort() +} + export const redactSettingsValue = (path: string, value: unknown): unknown => { if (isSensitiveSettingsPath(path) && typeof value === 'string' && value.length > 0) { return '***' diff --git a/test/unit/routes/admin-settings.spec.ts b/test/unit/routes/admin-settings.spec.ts index 1186960d3..47e95baef 100644 --- a/test/unit/routes/admin-settings.spec.ts +++ b/test/unit/routes/admin-settings.spec.ts @@ -5,6 +5,7 @@ import fs from 'fs' import os from 'os' import path from 'path' import Sinon from 'sinon' +import yaml from 'js-yaml' import { hashAdminPassword } from '../../../src/utils/admin-password' import { CacheAdminSessionRevocations } from '../../../src/utils/admin-session-revocations' @@ -255,6 +256,104 @@ describe('admin settings API', () => { expect(settingsRaw).to.include('enabled: true') }) + describe('the admin password hash', () => { + const otherHash = () => hashAdminPassword('another-password') + + const startWithPassword = async () => { + const passwordHash = hashAdminPassword('settings-password') + const admin = { enabled: true, passwordHash, sessionTtlSeconds: 3600 } + saveSettings({ ...loadDefaults(), admin }) + const baseUrl = await startServer({ admin }) + const cookie = await login(baseUrl) + + return { baseUrl, cookie, passwordHash, admin } + } + + const patch = (baseUrl: string, cookie: string, body: unknown) => + axios.patch(`${baseUrl}/settings`, body, { + headers: { cookie, 'content-type': 'application/json' }, + validateStatus: () => true, + }) + + const storedHash = () => (yaml.load(fs.readFileSync(getSettingsFilePath(), 'utf-8')) as any).admin?.passwordHash + + it('refuses to change it by its own path', async () => { + const { baseUrl, cookie, passwordHash } = await startWithPassword() + + const response = await patch(baseUrl, cookie, { path: 'admin.passwordHash', value: otherHash() }) + + expect(response.status).to.equal(400) + expect(storedHash()).to.equal(passwordHash) + }) + + it('refuses to change it by replacing the admin object that holds it', async () => { + const { baseUrl, cookie, admin, passwordHash } = await startWithPassword() + + const response = await patch(baseUrl, cookie, { path: 'admin', value: { ...admin, passwordHash: otherHash() } }) + + expect(response.status, JSON.stringify(response.data)).to.equal(400) + expect(response.data.issues).to.deep.equal([{ path: 'admin.passwordHash', message: 'Path is write-protected' }]) + expect(storedHash()).to.equal(passwordHash) + }) + + it('refuses to remove it by replacing the admin object without it', async () => { + const { baseUrl, cookie, passwordHash } = await startWithPassword() + + const response = await patch(baseUrl, cookie, { + path: 'admin', + value: { enabled: true, sessionTtlSeconds: 3600 }, + }) + + expect(response.status).to.equal(400) + expect(storedHash()).to.equal(passwordHash) + }) + + it('refuses to write the redacted placeholder over it', async () => { + const { baseUrl, cookie, admin, passwordHash } = await startWithPassword() + + const response = await patch(baseUrl, cookie, { path: 'admin', value: { ...admin, passwordHash: '***' } }) + + expect(response.status).to.equal(400) + expect(storedHash()).to.equal(passwordHash) + }) + + it('refuses a batch in which one change replaces the admin object, and saves none of it', async () => { + const { baseUrl, cookie, admin, passwordHash } = await startWithPassword() + const settingsBefore = fs.readFileSync(getSettingsFilePath(), 'utf-8') + + const response = await patch(baseUrl, cookie, { + changes: [ + { path: 'payments.enabled', value: true }, + { path: 'admin', value: { ...admin, passwordHash: otherHash() } }, + ], + }) + + expect(response.status).to.equal(400) + expect(storedHash()).to.equal(passwordHash) + // The whole file, so a change of the batch that was saved before the refusal would show too. + expect(fs.readFileSync(getSettingsFilePath(), 'utf-8')).to.equal(settingsBefore) + expect((yaml.load(settingsBefore) as any).payments?.enabled).not.to.equal(true) + }) + + it('still lets an admin setting be changed on its own path', async () => { + const { baseUrl, cookie, passwordHash } = await startWithPassword() + + const response = await patch(baseUrl, cookie, { path: 'admin.sessionTtlSeconds', value: 7200 }) + + expect(response.status, JSON.stringify(response.data)).to.equal(200) + expect(storedHash()).to.equal(passwordHash) + }) + + it('still lets the admin object be replaced when the hash in it is the one stored', async () => { + const { baseUrl, cookie, admin, passwordHash } = await startWithPassword() + + const response = await patch(baseUrl, cookie, { path: 'admin', value: { ...admin, sessionTtlSeconds: 7200 } }) + + expect(response.status, JSON.stringify(response.data)).to.equal(200) + expect(storedHash()).to.equal(passwordHash) + }) + }) + it('atomically applies staged changes with a backup and audit entry', async () => { const passwordHash = hashAdminPassword('settings-password') saveSettings({ diff --git a/test/unit/utils/settings-redaction.spec.ts b/test/unit/utils/settings-redaction.spec.ts index cef8c78fb..21ae9e763 100644 --- a/test/unit/utils/settings-redaction.spec.ts +++ b/test/unit/utils/settings-redaction.spec.ts @@ -1,6 +1,8 @@ import { expect } from 'chai' import { + changedWriteProtectedSettingsPaths, + collectWriteProtectedSettings, isSensitiveSettingsPath, isWriteProtectedSettingsPath, redactSettingsSecrets, @@ -79,4 +81,67 @@ describe('settings-redaction', () => { expect(redactSettingsSecrets(input).admin.notifications.targets[0].url).to.equal('***') }) + + describe('collectWriteProtectedSettings', () => { + it('finds the protected values in a document, by path', () => { + const settings = { admin: { enabled: true, passwordHash: 'abc' }, payments: {} } + + expect(collectWriteProtectedSettings(settings)).to.deep.equal({ 'admin.passwordHash': 'abc' }) + }) + + it('finds a protected value nested in objects and arrays', () => { + const settings = { other: [{ passwordHash: 'x' }, { name: 'y' }], deep: { er: { passwordHash: 'z' } } } + + expect(collectWriteProtectedSettings(settings)).to.deep.equal({ + 'other[0].passwordHash': 'x', + 'deep.er.passwordHash': 'z', + }) + }) + + it('finds nothing in a document without one, or in something that is not a document', () => { + expect(collectWriteProtectedSettings({ admin: { enabled: true } })).to.deep.equal({}) + expect(collectWriteProtectedSettings(undefined)).to.deep.equal({}) + expect(collectWriteProtectedSettings('admin.passwordHash')).to.deep.equal({}) + }) + }) + + describe('changedWriteProtectedSettingsPaths', () => { + it('is empty when no protected value changed, whatever else did', () => { + const before = { admin: { passwordHash: 'abc', sessionTtlSeconds: 1 }, payments: { enabled: false } } + const after = { admin: { passwordHash: 'abc', sessionTtlSeconds: 2 }, payments: { enabled: true } } + + expect(changedWriteProtectedSettingsPaths(before, after)).to.deep.equal([]) + }) + + it('reports a protected value that was replaced', () => { + expect( + changedWriteProtectedSettingsPaths({ admin: { passwordHash: 'abc' } }, { admin: { passwordHash: 'new' } }), + ).to.deep.equal(['admin.passwordHash']) + }) + + it('reports a protected value that was removed', () => { + expect(changedWriteProtectedSettingsPaths({ admin: { passwordHash: 'abc' } }, { admin: {} })).to.deep.equal([ + 'admin.passwordHash', + ]) + expect(changedWriteProtectedSettingsPaths({ admin: { passwordHash: 'abc' } }, {})).to.deep.equal([ + 'admin.passwordHash', + ]) + }) + + it('reports a protected value that was added', () => { + expect(changedWriteProtectedSettingsPaths({ admin: {} }, { admin: { passwordHash: 'new' } })).to.deep.equal([ + 'admin.passwordHash', + ]) + }) + + it('reports each changed protected path once, in order', () => { + const before = { admin: { passwordHash: 'a' }, other: { passwordHash: 'b' } } + const after = { admin: { passwordHash: 'x' }, other: { passwordHash: 'y' } } + + expect(changedWriteProtectedSettingsPaths(before, after)).to.deep.equal([ + 'admin.passwordHash', + 'other.passwordHash', + ]) + }) + }) })