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/settings-pubkey-lists-lowercase-hex.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,7 @@
---
'nostream': patch
---

fix(admin): refuse pubkeys in the settings lists that cannot match an event

The pubkey blacklist, the pubkey whitelist and the rate-limit bypass list (`limits.event.pubkey.blacklist`, `limits.event.pubkey.whitelist` and `limits.event.whitelists.pubkeys`) are compared with the pubkey of each event as they are written, and an event's pubkey is always 64 lowercase hex characters. The settings API saved any value in them, so a blacklist entry written in uppercase hex was stored and then never matched, and the pubkey it was meant to ban could still publish. Settings validation now rejects an entry that is not a 64-character lowercase hex pubkey, and says which entry, for the settings API, the CLI, backup restore and the validate endpoint. Pubkeys added through the moderation endpoints are already normalized and are not affected. A settings file that already holds an entry written another way is not rejected at startup, but the next settings change made through those paths is refused until the entry is fixed.
23 changes: 23 additions & 0 deletions src/utils/settings-config.ts
Original file line number Diff line number Diff line change
Expand Up @@ -1279,6 +1279,24 @@ const validatePeering = (settings: Settings, issues: ValidationIssue[]): void =>
}
}

const LOWERCASE_HEX_PUBKEY = /^[0-9a-f]{64}$/

// An event's pubkey is always 64 lowercase hex characters, and the lists below are compared with it as they are.
// An entry written any other way, such as uppercase hex or an npub, is accepted by nothing but never matches, so a
// blacklist holding one would not ban anybody. Refuse it, instead of saving a list that cannot do what it says.
const validatePubkeyList = (list: unknown, path: string, issues: ValidationIssue[]): void => {
// A value that is not a list is reported by the check of the settings' shape.
if (!Array.isArray(list)) {
return
}

list.forEach((entry, index) => {
if (typeof entry !== 'string' || !LOWERCASE_HEX_PUBKEY.test(entry)) {
issues.push({ path: `${path}[${index}]`, message: 'must be a 64-character lowercase hex pubkey' })
}
})
}

export const validateSettings = (settings: Settings): ValidationIssue[] => {
const issues: ValidationIssue[] = []

Expand Down Expand Up @@ -1318,6 +1336,11 @@ export const validateSettings = (settings: Settings): ValidationIssue[] => {
issues.push({ path: 'limits.rateLimiter.strategy', message: 'strategy must be ewma or sliding_window' })
}

const eventLimits = settings.limits?.event
validatePubkeyList(eventLimits?.pubkey?.blacklist, 'limits.event.pubkey.blacklist', issues)
validatePubkeyList(eventLimits?.pubkey?.whitelist, 'limits.event.pubkey.whitelist', issues)
validatePubkeyList(eventLimits?.whitelists?.pubkeys, 'limits.event.whitelists.pubkeys', issues)

const eventStoreBackend = settings.eventStore?.backend
if (!isNil(eventStoreBackend) && !isEventStoreBackend(eventStoreBackend)) {
issues.push({
Expand Down
40 changes: 40 additions & 0 deletions test/unit/routes/admin-settings.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -356,6 +356,46 @@ describe('admin settings API', () => {
})
})

describe('the pubkey blacklist', () => {
const bannedPubkey = 'ab'.repeat(32)

const startAndPatch = async (body: unknown) => {
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 axios.patch(`${baseUrl}/settings`, body, {
headers: { cookie, 'content-type': 'application/json' },
validateStatus: () => true,
})
}

const storedBlacklist = () =>
(yaml.load(fs.readFileSync(getSettingsFilePath(), 'utf-8')) as any).limits?.event?.pubkey?.blacklist

it('does not save an uppercase pubkey, which would never match an event', async () => {
const response = await startAndPatch({
path: 'limits.event.pubkey.blacklist',
value: [bannedPubkey.toUpperCase()],
})

expect(response.status, JSON.stringify(response.data)).to.equal(400)
expect(response.data.issues).to.deep.equal([
{ path: 'limits.event.pubkey.blacklist[0]', message: 'must be a 64-character lowercase hex pubkey' },
])
expect(storedBlacklist() ?? []).to.deep.equal([])
})

it('saves a lowercase pubkey', async () => {
const response = await startAndPatch({ path: 'limits.event.pubkey.blacklist', value: [bannedPubkey] })

expect(response.status, JSON.stringify(response.data)).to.equal(200)
expect(storedBlacklist()).to.deep.equal([bannedPubkey])
})
})

it('atomically applies staged changes with a backup and audit entry', async () => {
const passwordHash = hashAdminPassword('settings-password')
saveSettings({
Expand Down
40 changes: 40 additions & 0 deletions test/unit/utils/settings-config.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -542,6 +542,46 @@ describe('settings-config', () => {
}
})

describe('pubkey lists', () => {
const hex = 'ab'.repeat(32)
const withLimits = (event: Record<string, unknown>) =>
validateSettings({
info: { relay_url: 'wss://relay.example.com', name: 'Test Relay' },
network: { maxPayloadSize: 1024 },
limits: { event },
} as any).filter((issue) => issue.path.startsWith('limits.event'))

it('accepts lists of 64-character lowercase hex pubkeys, and settings without lists', () => {
expect(
withLimits({ pubkey: { blacklist: [hex], whitelist: [hex] }, whitelists: { pubkeys: [hex] } }),
).to.deep.equal([])
expect(withLimits({})).to.deep.equal([])
expect(withLimits({ pubkey: { blacklist: [] } })).to.deep.equal([])
})

it('rejects an uppercase pubkey, which would never match an event and so would not ban anybody', () => {
const issues = withLimits({ pubkey: { blacklist: [hex, hex.toUpperCase()] } })

expect(issues).to.have.length(1)
expect(issues[0].path).to.equal('limits.event.pubkey.blacklist[1]')
expect(issues[0].message).to.include('lowercase hex')
})

it('rejects entries that are not 64 hex characters, such as an npub, a short key or a number', () => {
const issues = withLimits({
pubkey: { whitelist: ['npub1' + 'q'.repeat(58), 'ab'.repeat(31)] },
whitelists: { pubkeys: [123, ` ${hex}`] },
})

expect(issues.map((issue) => issue.path)).to.have.members([
'limits.event.pubkey.whitelist[0]',
'limits.event.pubkey.whitelist[1]',
'limits.event.whitelists.pubkeys[0]',
'limits.event.whitelists.pubkeys[1]',
])
})
})

describe('rate limit period validation', () => {
const baseSettings = () =>
({
Expand Down
Loading