Skip to content
Merged
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-settings-protect-password-hash.md
Original file line number Diff line number Diff line change
@@ -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.
14 changes: 14 additions & 0 deletions src/controllers/admin/patch-settings-controller.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@ import {
withSettingsWriteLock,
} from '../../utils/settings-config'
import {
changedWriteProtectedSettingsPaths,
isWriteProtectedSettingsPath,
redactSettingsValue,
} from '../../utils/settings-redaction'
Expand Down Expand Up @@ -59,10 +60,23 @@ export class PatchAdminSettingsController implements IController {
| { ok: false; issues: Array<{ path: string; message: string }> }
>(() => {
const userSettings = loadUserSettings() as unknown as Record<string, unknown>
// Taken before the changes are applied, in case applying them edits this object in place.
const protectedBefore = JSON.parse(JSON.stringify(userSettings)) as Record<string, unknown>
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<string, unknown>
const mergedNext = changes.reduce(
(settings, change) => setByPath(settings, change.path, getByPath(nextUserSettings, change.path)),
Expand Down
38 changes: 38 additions & 0 deletions src/utils/settings-redaction.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<string, unknown> => {
const found: Record<string, unknown> = {}

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 '***'
Expand Down
99 changes: 99 additions & 0 deletions test/unit/routes/admin-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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'
Expand Down Expand Up @@ -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({
Expand Down
65 changes: 65 additions & 0 deletions test/unit/utils/settings-redaction.spec.ts
Original file line number Diff line number Diff line change
@@ -1,6 +1,8 @@
import { expect } from 'chai'

import {
changedWriteProtectedSettingsPaths,
collectWriteProtectedSettings,
isSensitiveSettingsPath,
isWriteProtectedSettingsPath,
redactSettingsSecrets,
Expand Down Expand Up @@ -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',
])
})
})
})
Loading