diff --git a/.changeset/settings-path-default-arrays.md b/.changeset/settings-path-default-arrays.md new file mode 100644 index 000000000..d39d60be6 --- /dev/null +++ b/.changeset/settings-path-default-arrays.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(settings): keep the rest of a default array when one of its fields is set + +An array in `settings.yaml` replaces the default array as a whole. With a `settings.yaml` that has no `payments.feeSchedules.admission`, `nostream config set payments.feeSchedules.admission[0].enabled true` (also what the TUI and the admin dashboard write) saved `admission: [{ enabled: true }]`, so the admission fee lost its default `amount` and whitelists. Setting `limits.event.content[1].maxLength` saved `[null, { maxLength }]`, which no longer validated once the relay read it back, and is refused since the out-of-range index fix. `PATCH /admin/settings` and `nostream config set` now copy the effective array into `settings.yaml` before writing the field, so the other entries and fields keep their values. diff --git a/.changeset/settings-path-index-bound.md b/.changeset/settings-path-index-bound.md new file mode 100644 index 000000000..d95a46a16 --- /dev/null +++ b/.changeset/settings-path-index-bound.md @@ -0,0 +1,7 @@ +--- +'nostream': patch +--- + +fix(settings): reject an out-of-range array index instead of filling the gap + +Setting a path such as `dvm.workers[2000000000]` through `PATCH /admin/settings` or `nostream config set` grew the array one element at a time up to that index, inside the request and before the value was validated. A single request could hold the settings lock and fill the heap for as long as that took. A path may now name an array index only up to `MAX_SETTINGS_PATH_INDEX` (10,000), checked with the other path checks before the settings are read. Inside the array, a write must target an index that already exists or append one element at the end. Anything else is refused: the admin API answers with a 400 and a validation issue on the path, and the CLI prints the error. Updating an existing index and appending with `array[]` work as before. diff --git a/CLI.md b/CLI.md index d7358a6b0..48aa92187 100644 --- a/CLI.md +++ b/CLI.md @@ -102,6 +102,12 @@ nostream config set limits.event.content[0].maxLength 2048 nostream config set nip05.domainWhitelist '["example.com","relay.io"]' --type json ``` +An array index can update an element that exists or append one at the end (`[]`). An index past +the end, or above 10,000, is rejected. To replace a whole list, set the array itself with `--type json`. + +A list in `settings.yaml` replaces the default list as a whole. So when you change one element of a default +list that `settings.yaml` doesn't have yet, the whole list is copied there first, with only that field changed. + ## Development Commands ```bash diff --git a/src/cli/commands/config.ts b/src/cli/commands/config.ts index 4e3e35ce6..97057e8fd 100644 --- a/src/cli/commands/config.ts +++ b/src/cli/commands/config.ts @@ -3,6 +3,7 @@ import yaml from 'js-yaml' import { getByPath, + loadDefaults, loadMergedSettings, loadUserSettings, parseTypedValue, @@ -137,10 +138,11 @@ export const runConfigSet = async ( | { ok: false; validationIssues: Array<{ path: string; message: string }> } >(() => { const settings = loadUserSettings() as unknown as Record - const next = setByPath(settings, path, parseTypedValue(rawValue, valueType)) + const merged = loadMergedSettings() as unknown as Record + // With the defaults, writing one field of a default array keeps the rest of that array. + const next = setByPath(settings, path, parseTypedValue(rawValue, valueType), loadDefaults() as any) if (options.validate !== false) { - const merged = loadMergedSettings() as unknown as Record const mergedNext = setByPath(merged, path, getByPath(next, path)) const validationIssues = validateSettings(mergedNext as any) diff --git a/src/controllers/admin/patch-settings-controller.ts b/src/controllers/admin/patch-settings-controller.ts index c78394b3a..d01dc9c99 100644 --- a/src/controllers/admin/patch-settings-controller.ts +++ b/src/controllers/admin/patch-settings-controller.ts @@ -6,9 +6,11 @@ import { adminSettingsPatchBodySchema } from '../../schemas/admin-settings-schem import { appendSettingsAuditLog, getByPath, + loadDefaults, loadMergedSettings, loadUserSettings, saveSettings, + SettingsPathError, setByPath, validatePathAgainstDefaults, validateSettings, @@ -60,12 +62,32 @@ export class PatchAdminSettingsController implements IController { | { ok: false; issues: Array<{ path: string; message: string }> } >(() => { const userSettings = loadUserSettings() as unknown as Record + const merged = loadMergedSettings() as unknown as Record + // The seed for an indexed write. Only a key the working settings lack is seeded, so the effective + // array there is the default one: reading it from `merged` (the pre-batch settings) would bring back + // an override an earlier change in the same batch removed. + const defaults = loadDefaults() 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, - ) + let nextUserSettings: Record + // Each change's value in the state right after it was applied, not its value at the end of the batch. + // A later change can replace an array an earlier one wrote into, so reading every path from the final + // settings would replay change 3 before change 2 and fail on a batch whose final settings are valid. + const applied: unknown[] = [] + try { + // With the defaults, writing one field of a default array keeps the rest of that array. + nextUserSettings = changes.reduce((settings, change) => { + const next = setByPath(settings, change.path, change.value, defaults) + applied.push(getByPath(next, change.path)) + return next + }, userSettings) + } catch (error) { + // An index past the end of an array can only be found once the settings are read. + if (error instanceof SettingsPathError) { + return { ok: false as const, issues: [{ path: error.path, message: error.message }] } + } + throw error + } // 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. @@ -77,11 +99,22 @@ export class PatchAdminSettingsController implements IController { } } - const merged = loadMergedSettings() as unknown as Record - const mergedNext = changes.reduce( - (settings, change) => setByPath(settings, change.path, getByPath(nextUserSettings, change.path)), - merged, - ) + // The replay runs the same writes in the same order onto the merged settings, with the same seed the + // first pass used, so it can only fail where the first pass already did. + let mergedNext: Record + try { + // The seed is the same `defaults`, as in the first pass: a replay of `limits.event = {}` copies + // the default array again rather than starting it empty. + mergedNext = changes.reduce( + (settings, change, index) => setByPath(settings, change.path, applied[index], defaults), + merged, + ) + } catch (error) { + if (error instanceof SettingsPathError) { + return { ok: false as const, issues: [{ path: error.path, message: error.message }] } + } + throw error + } const validationIssues = validateSettings(mergedNext as unknown as Settings) if (validationIssues.length > 0) { diff --git a/src/utils/settings-config.ts b/src/utils/settings-config.ts index 805963cc2..263ee38f0 100644 --- a/src/utils/settings-config.ts +++ b/src/utils/settings-config.ts @@ -289,6 +289,23 @@ type PathToken = index: number } +/** + * The highest array index a settings path may name. Settings arrays are short lists, so a path such as + * `dvm.workers[2000000000]` is refused before the settings are read. + */ +export const MAX_SETTINGS_PATH_INDEX = 10_000 + +/** Thrown by `setByPath` when a path names an array index past the end of the array. */ +export class SettingsPathError extends Error { + public constructor( + public readonly path: string, + message: string, + ) { + super(message) + this.name = 'SettingsPathError' + } +} + export const toCategoryLabel = (key: string): string => { return key .split(/[_\-.]/) @@ -733,13 +750,35 @@ export const getByPath = (settings: unknown, path: string): unknown => { return current } -const ensureArrayLength = (target: unknown[], minimumLength: number): void => { - while (target.length <= minimumLength) { - target.push(undefined) +/** + * An array may be written at an index it already has, or at its length to append one element. A larger index + * would leave a gap, and filling that gap one element at a time takes as long as the caller-chosen index is big. + */ +const assertWritableIndex = (target: unknown[], index: number, path: string): void => { + if (index > target.length) { + throw new SettingsPathError( + path, + `Array index ${index} is past the end of an array of length ${target.length}. ` + + `Update an existing index or append at index ${target.length}.`, + ) } } -export const setByPath = (settings: Record, path: string, value: unknown): Record => { +/** + * Returns a copy of `settings` with `value` written at `path`. + * + * An array in settings.yaml replaces the default array as a whole. When `defaults` is given, an indexed write into + * an array that `settings` does not hold yet starts from a copy of the default array there. So + * `limits.event.content[1].maxLength` changes that one field and keeps the other entries and fields, instead of + * saving an array that holds only the field that was written. Pass the defaults, not the merged settings: a batch + * can remove an override before writing into the array, and the merged settings still carry it. + */ +export const setByPath = ( + settings: Record, + path: string, + value: unknown, + defaults?: Record, +): Record => { const tokens = parsePath(path) const clone: Record = structuredClone(settings) @@ -748,6 +787,7 @@ export const setByPath = (settings: Record, path: string, value } let current: unknown = clone + let currentDefaults: unknown = defaults for (let i = 0; i < tokens.length - 1; i++) { const token = tokens[i] @@ -759,8 +799,17 @@ export const setByPath = (settings: Record, path: string, value } const existing = current[token.key] + // A key the settings hold replaces the default value whole, so nothing below it is copied from the + // defaults: the operator's array carries its own entries, and filling a nested array from the default + // would apply the operator's rule to event kinds they never listed. + const defaultChild = + isPlainObject(currentDefaults) && hasOwn(currentDefaults, token.key) ? currentDefaults[token.key] : undefined if (existing === undefined) { - current[token.key] = nextToken.type === 'index' ? [] : {} + if (nextToken.type === 'index') { + current[token.key] = Array.isArray(defaultChild) ? structuredClone(defaultChild) : [] + } else { + current[token.key] = {} + } } else if (nextToken.type === 'index' && !Array.isArray(existing)) { current[token.key] = [] } else if (nextToken.type === 'key' && !isPlainObject(existing)) { @@ -768,6 +817,9 @@ export const setByPath = (settings: Record, path: string, value } current = current[token.key] + // An object the settings hold is merged with the default object key by key, so the defaults below it still + // apply; an array the settings hold replaces the default array whole, so nothing below it may be copied. + currentDefaults = Array.isArray(existing) ? undefined : defaultChild continue } @@ -775,7 +827,7 @@ export const setByPath = (settings: Record, path: string, value throw new Error(`Cannot index non-array path at [${token.index}]`) } - ensureArrayLength(current, token.index) + assertWritableIndex(current, token.index, path) const existing = current[token.index] if (existing === undefined) { @@ -787,6 +839,9 @@ export const setByPath = (settings: Record, path: string, value } current = current[token.index] + // Same rule one level down: an entry the settings hold is the operator's, and its missing fields are not + // filled from the default entry at that index. + currentDefaults = existing === undefined && Array.isArray(currentDefaults) ? currentDefaults[token.index] : undefined } const last = tokens[tokens.length - 1] @@ -804,16 +859,28 @@ export const setByPath = (settings: Record, path: string, value throw new Error(`Cannot index non-array path at [${last.index}]`) } - ensureArrayLength(current, last.index) + assertWritableIndex(current, last.index, path) current[last.index] = value return clone } export const validatePathAgainstDefaults = (path: string): ValidationIssue[] => { - const defaults = loadDefaults() as unknown const tokens = parsePath(path) + const outOfRange = tokens.find( + (token) => token.type === 'index' && (!Number.isSafeInteger(token.index) || token.index > MAX_SETTINGS_PATH_INDEX), + ) + if (outOfRange) { + return [ + { + path, + message: `Array index must be a whole number from 0 to ${MAX_SETTINGS_PATH_INDEX}`, + }, + ] + } + + const defaults = loadDefaults() as unknown if (pathExistsInSchema(defaults, tokens)) { return [] } diff --git a/test/unit/controllers/admin/patch-settings-controller.spec.ts b/test/unit/controllers/admin/patch-settings-controller.spec.ts index 70dad7f3f..b87f1f28d 100644 --- a/test/unit/controllers/admin/patch-settings-controller.spec.ts +++ b/test/unit/controllers/admin/patch-settings-controller.spec.ts @@ -36,6 +36,7 @@ describe('PatchAdminSettingsController settings write lock', () => { sandbox.stub(settingsConfig, 'withSettingsWriteLock').callsFake(async (operation: () => unknown) => operation()) sandbox.stub(settingsConfig, 'loadUserSettings').returns(baseSettings as any) sandbox.stub(settingsConfig, 'loadMergedSettings').returns(baseSettings as any) + sandbox.stub(settingsConfig, 'loadDefaults').returns(baseSettings as any) sandbox.stub(settingsConfig, 'saveSettings') sandbox.stub(settingsConfig, 'appendSettingsAuditLog') sandbox.stub(settingsConfig, 'validatePathAgainstDefaults').returns([]) @@ -147,4 +148,115 @@ describe('PatchAdminSettingsController settings write lock', () => { expect(settingsConfig.appendSettingsAuditLog).not.to.have.been.called expect(outboxRepository.enqueue).not.to.have.been.called }) + + it('reports an array index past the end of the stored array as a validation issue', async () => { + request.body = { path: 'limits.event.content[3].maxLength', value: 500 } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(400) + const body = response.send.firstCall.args[0] + expect(body.error).to.equal('Validation failed') + expect(body.issues).to.have.length(1) + expect(body.issues[0].path).to.equal('limits.event.content[3].maxLength') + expect(body.issues[0].message).to.include('append at index 0') + expect(settingsConfig.saveSettings).not.to.have.been.called + expect(outboxRepository.enqueue).not.to.have.been.called + }) + + it('saves the whole default array when one field of an entry the stored settings do not hold is changed', async () => { + const content = [ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ] + ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + ;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + request.body = { path: 'limits.event.content[1].maxLength', value: 500 } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }]) + expect(content[1].maxLength).to.equal(200) + }) + + it('saves a batch whose later change empties an array an earlier change wrote into', async () => { + // The replay passed each path's final value, so `pubkey` arrived as `{ blacklist: [] }` and the + // `blacklist[1]` write had no array left to append to: a valid batch answered 500. + request.body = { + changes: [ + { path: 'limits.event.pubkey', value: { blacklist: ['a.example'] } }, + { path: 'limits.event.pubkey.blacklist[1]', value: 'b.example' }, + { path: 'limits.event.pubkey.blacklist', value: [] }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.pubkey.blacklist).to.deep.equal([]) + }) + + it('keeps copying the default array when an earlier change replaced its parent', async () => { + const content = [ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ] + ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + ;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { content } } }) + request.body = { + changes: [ + { path: 'limits.event', value: {} }, + { path: 'limits.event.content[1].maxLength', value: 500 }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.content).to.deep.equal([content[0], { ...content[1], maxLength: 500 }]) + }) + + it('does not bring back a stored override an earlier change in the batch removed', async () => { + const stored = { blacklist: ['a.example', 'b.example'] } + ;(settingsConfig.loadUserSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: stored } } }) + ;(settingsConfig.loadMergedSettings as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: stored } } }) + ;(settingsConfig.loadDefaults as Sinon.SinonStub).returns({ ...baseSettings, limits: { event: { pubkey: { blacklist: [] } } } }) + request.body = { + changes: [ + { path: 'limits.event.pubkey', value: {} }, + { path: 'limits.event.pubkey.blacklist[0]', value: 'c.example' }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(200) + const saved = (settingsConfig.saveSettings as Sinon.SinonStub).firstCall.args[0] + expect(saved.limits.event.pubkey.blacklist).to.deep.equal(['c.example']) + }) + + it('reports an unappliable batch as a path issue instead of a 500', async () => { + request.body = { + changes: [ + { path: 'limits.event.pubkey.blacklist', value: [] }, + { path: 'limits.event.pubkey.blacklist[1]', value: 'b.example' }, + ], + } + + const controller = new PatchAdminSettingsController(outboxRepository as any) + await controller.handleRequest(request as any, response as any) + + expect(response.status).to.have.been.calledOnceWithExactly(400) + expect(response.send.firstCall.args[0].issues[0].path).to.equal('limits.event.pubkey.blacklist[1]') + expect(settingsConfig.saveSettings).not.to.have.been.called + }) }) diff --git a/test/unit/utils/settings-config.spec.ts b/test/unit/utils/settings-config.spec.ts index 495579737..39634a2b0 100644 --- a/test/unit/utils/settings-config.spec.ts +++ b/test/unit/utils/settings-config.spec.ts @@ -2,6 +2,7 @@ import { expect } from 'chai' import fs from 'fs' import os from 'os' import path from 'path' +import { mergeDeepRight } from 'ramda' import Sinon from 'sinon' import yaml from 'js-yaml' @@ -15,8 +16,10 @@ import { getByPath, getTopLevelSettingCategories, loadDefaults, + MAX_SETTINGS_PATH_INDEX, parseTypedValue, parseValue, + SettingsPathError, setByPath, validatePathAgainstDefaults, validateSettings, @@ -100,6 +103,124 @@ describe('settings-config', () => { expect(issues[0].message).to.include('does not exist') }) + it('updates an existing array index and appends at the end of an array', () => { + const input = { limits: { event: { content: [{ maxLength: 100 }] } } } + + const updated = setByPath(input as any, 'limits.event.content[0].maxLength', 500) + const appended = setByPath(updated, 'limits.event.content[1].maxLength', 200) + const created = setByPath({} as any, 'dvm.workers[0].enabled', true) + + expect(getByPath(appended, 'limits.event.content')).to.deep.equal([{ maxLength: 500 }, { maxLength: 200 }]) + expect(getByPath(created, 'dvm.workers')).to.deep.equal([{ enabled: true }]) + }) + + it('refuses an array index past the end of an array without growing it', () => { + const input = { limits: { event: { content: [{ maxLength: 100 }] } } } + + for (const path of ['limits.event.content[2].maxLength', 'limits.event.content[2000000000]']) { + let error: unknown + try { + setByPath(input as any, path, 1) + } catch (caught) { + error = caught + } + + expect(error).to.be.instanceOf(SettingsPathError) + expect((error as SettingsPathError).path).to.equal(path) + expect((error as SettingsPathError).message).to.include('append at index 1') + } + + expect(() => setByPath({} as any, 'dvm.workers[2000000000].enabled', true)).to.throw(SettingsPathError) + expect(input.limits.event.content).to.deep.equal([{ maxLength: 100 }]) + }) + + it('starts an indexed write from the effective array when the settings do not hold that array', () => { + const effective = { + limits: { + event: { + content: [ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ], + }, + }, + } + + const second = setByPath({} as any, 'limits.event.content[1].maxLength', 500, effective) + const first = setByPath({ limits: { event: {} } } as any, 'limits.event.content[0].maxLength', 50, effective) + + expect(getByPath(second, 'limits.event.content')).to.deep.equal([ + { description: 'kinds 0-10', maxLength: 100, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 500, kinds: [[11, 39]] }, + ]) + expect(getByPath(first, 'limits.event.content')).to.deep.equal([ + { description: 'kinds 0-10', maxLength: 50, kinds: [[0, 10]] }, + { description: 'kinds 11-39', maxLength: 200, kinds: [[11, 39]] }, + ]) + expect(effective.limits.event.content[1].maxLength).to.equal(200) + }) + + it('writes into an array the settings already hold, and refuses an index past the end of the effective array', () => { + const effective = { limits: { event: { content: [{ maxLength: 100 }, { maxLength: 200 }] } } } + + const updated = setByPath( + { limits: { event: { content: [{ maxLength: 300 }] } } } as any, + 'limits.event.content[0].maxLength', + 400, + effective, + ) + + expect(getByPath(updated, 'limits.event.content')).to.deep.equal([{ maxLength: 400 }]) + expect(() => setByPath({} as any, 'limits.event.content[3].maxLength', 1, effective)) + .to.throw(SettingsPathError) + .with.property('message') + .that.includes('append at index 2') + }) + + it('keeps the rest of a default array when a guided field writes one of its fields', () => { + const defaults = loadDefaults() as any + + for (const [path, value] of [ + ['limits.event.content[1].maxLength', 50000], + ['payments.feeSchedules.admission[0].enabled', true], + ] as const) { + const saved = setByPath({} as any, path, value, defaults) + const reloaded = mergeDeepRight(defaults, saved) as any + const arrayPath = path.slice(0, path.lastIndexOf('[')) + const expected = setByPath(defaults, path, value) + + expect(getByPath(reloaded, arrayPath)).to.deep.equal(getByPath(expected, arrayPath)) + expect(getByPath(reloaded, path)).to.equal(value) + expect(validateSettings(reloaded).filter((issue) => issue.path.startsWith(arrayPath))).to.deep.equal([]) + } + }) + + it('does not copy a default into a nested array of a rule the settings hold', () => { + const defaults = { + limits: { event: { rateLimits: [{ period: 60000, rate: 720, kinds: [[3, 40, 41]] }] } }, + } as any + const settings = { limits: { event: { rateLimits: [{ period: 1000, rate: 5 }] } } } as any + + const next = setByPath(settings, 'limits.event.rateLimits[0].kinds[0]', 1, defaults) as any + + expect(next.limits.event.rateLimits[0]).to.deep.equal({ period: 1000, rate: 5, kinds: [1] }) + }) + + it('rejects an out-of-range array index as a path validation issue', () => { + expect(validatePathAgainstDefaults(`limits.event.content[${MAX_SETTINGS_PATH_INDEX}].maxLength`)).to.deep.equal([]) + + for (const path of [ + `limits.event.content[${MAX_SETTINGS_PATH_INDEX + 1}].maxLength`, + 'limits.event.content[2000000000].maxLength', + 'limits.event.content[99999999999999999999].maxLength', + ]) { + const issues = validatePathAgainstDefaults(path) + expect(issues).to.have.length(1) + expect(issues[0].path).to.equal(path) + expect(issues[0].message).to.include(`from 0 to ${MAX_SETTINGS_PATH_INDEX}`) + } + }) + it('validates basic required fields', () => { const issues = validateSettings({} as any)