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
11 changes: 11 additions & 0 deletions .changeset/index-tag-filter-matching.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,11 @@
---
'nostream': patch
---

fix(relay): index tag filters instead of comparing every tag with every value

Matching an event against a `#<letter>` filter compared every tag of the event with every value of the filter, and the live broadcast rebuilt each subscription's matcher for every event. One event could therefore cost tags × values comparisons per filter on the worker's event loop, with both sides chosen by clients (security issue #1256).

A REQ's filters are now compiled once for live delivery and once for its stored events, not per event. An event's single-letter tag values are indexed once and shared by every filter and client of a broadcast. Each tag name then costs set lookups on the smaller side, plus one binary search per `#g` prefix over values sorted once per event. A tag with no value is now skipped; before, it made `#g` prefix filters throw, which cut the broadcast short and stopped a REQ's stored events before `EOSE`.

A deliberate limit: this adds no per-connection allowance; `maxSubscriptions`, `maxFilters` and `maxFilterValues` still govern admission. `ids`, `authors` and NIP-50 `search` matching are unchanged.
19 changes: 12 additions & 7 deletions src/adapters/web-socket-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -19,7 +19,7 @@ import { ContextMetadataKey } from '../constants/base'
import { createLogger } from '../factories/logger-factory'
import { messageSchema } from '../schemas/message-schema'
import { recordWebsocketConnectionClosed, recordWebsocketConnectionOpened } from '../telemetry/event-metrics'
import { isEventMatchingFilter } from '../utils/event'
import { createSubscriptionMatcher, EventTagIndex } from '../utils/event'
import { isHidden } from '../utils/hidden-content-cache'
import { getRemoteAddress } from '../utils/http'
import {
Expand Down Expand Up @@ -78,7 +78,10 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
private clientAddress: SocketAddress
private alive: boolean
private pendingSend: Promise<void> | undefined
private subscriptions: Map<SubscriptionId, SubscriptionFilter[]>
private subscriptions: Map<
SubscriptionId,
{ filters: SubscriptionFilter[]; isMatch: ReturnType<typeof createSubscriptionMatcher> }
>
private readonly subscriptionExpiries = new Map<SubscriptionId, { timer: NodeJS.Timeout; token: symbol }>()
private readonly session: Nip42SessionManager
/** Configured peering peer proven by AUTH on this socket, if any. */
Expand Down Expand Up @@ -165,7 +168,7 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
logger('client %s subscribed %s to %o', this.clientId, subscriptionId, filters)
// Reusing an id starts a new subscription; the old expiry must not close it.
this.clearSubscriptionExpiry(subscriptionId)
this.subscriptions.set(subscriptionId, filters)
this.subscriptions.set(subscriptionId, { filters, isMatch: createSubscriptionMatcher(filters) })
}

public setSubscriptionExpiry(
Expand Down Expand Up @@ -262,7 +265,7 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
}
}

public onSendEvent(event: Event): void {
public onSendEvent(event: Event, tagIndex = new EventTagIndex(event.tags)): void {
// NIP-42: don't broadcast restricted-kind events to unauthorized clients.
const isReadAuthorized = createReadAuthorizationGuard(this.settings(), () => this.session.getAuthenticatedPubkeys())
if (!isReadAuthorized(event)) {
Expand All @@ -277,8 +280,8 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
return
}

this.subscriptions.forEach((filters, subscriptionId) => {
if (filters.map(isEventMatchingFilter).some((isMatch) => isMatch(event))) {
this.subscriptions.forEach(({ isMatch }, subscriptionId) => {
if (isMatch(event, tagIndex)) {
logger('sending event to client %s: %o', this.clientId, event)
this.sendMessage(createOutgoingEventMessage(subscriptionId, event))
}
Expand Down Expand Up @@ -333,7 +336,9 @@ export class WebSocketAdapter extends EventEmitter implements IWebSocketAdapter
}

public getSubscriptions(): Map<string, SubscriptionFilter[]> {
return new Map(this.subscriptions)
const subscriptions = new Map<string, SubscriptionFilter[]>()
this.subscriptions.forEach(({ filters }, subscriptionId) => subscriptions.set(subscriptionId, filters))
return subscriptions
}

public drainAndClose(reason = 'relay shutting down'): void {
Expand Down
4 changes: 3 additions & 1 deletion src/adapters/web-socket-server-adapter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -9,6 +9,7 @@ import { Settings } from '../@types/settings'
import { WebSocketAdapterEvent, WebSocketServerAdapterEvent } from '../constants/adapter'
import { createLogger } from '../factories/logger-factory'
import { isRateLimited } from '../handlers/request-handlers/rate-limiter-middleware'
import { EventTagIndex } from '../utils/event'
import { getRemoteAddress, redactHeaders } from '../utils/http'
import { getWsDrainTimeoutMs, isDraining } from '../utils/shutdown-state'
import { WebServerAdapter } from './web-server-adapter'
Expand Down Expand Up @@ -142,6 +143,7 @@ export class WebSocketServerAdapter extends WebServerAdapter implements IWebSock
}

private onBroadcast(event: Event) {
const tagIndex = new EventTagIndex(event.tags)
this.webSocketServer.clients.forEach((webSocket: WebSocket) => {
if (!propEq('readyState', OPEN)(webSocket)) {
return
Expand All @@ -150,7 +152,7 @@ export class WebSocketServerAdapter extends WebServerAdapter implements IWebSock
if (!webSocketAdapter) {
return
}
webSocketAdapter.emit(WebSocketAdapterEvent.Event, event)
webSocketAdapter.emit(WebSocketAdapterEvent.Event, event, tagIndex)
})
}

Expand Down
14 changes: 10 additions & 4 deletions src/handlers/subscribe-message-handler.ts
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
import { anyPass, equals, isNil, map, omit, propSatisfies, uniqWith } from 'ramda'
import { equals, isNil, omit, propSatisfies, uniqWith } from 'ramda'
import { pipeline } from 'stream/promises'
import { IWebSocketAdapter } from '../@types/adapters'
import { Factory, Pubkey } from '../@types/base'
Expand All @@ -13,7 +13,13 @@ import { SubscriptionFilter, SubscriptionId } from '../@types/subscription'
import { IRateLimiter } from '../@types/utils'
import { WebSocketAdapterEvent } from '../constants/adapter'
import { createLogger } from '../factories/logger-factory'
import { getPublicKey, getRelayPrivateKey, isEventMatchingFilter, isExpiredEvent, toNostrEvent } from '../utils/event'
import {
createSubscriptionMatcher,
getPublicKey,
getRelayPrivateKey,
isExpiredEvent,
toNostrEvent,
} from '../utils/event'
import { countFilterValues } from '../utils/filter'
import {
createClosedMessage,
Expand Down Expand Up @@ -99,7 +105,7 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable {

const rawFilters = uniqWith(equals, incomingFilters) as SubscriptionFilter[]

// NIP-50: strip search from filters when disabled so isEventMatchingFilter ignores it
// NIP-50: strip search from filters when disabled so the subscription matcher ignores it
const nip50Enabled = this.settings()?.nip50?.enabled ?? false
const filters = nip50Enabled ? rawFilters : (rawFilters.map(omit(['search'])) as SubscriptionFilter[])

Expand Down Expand Up @@ -399,7 +405,7 @@ export class SubscribeMessageHandler implements IMessageHandler, IAbortable {
}

private static isClientSubscribedToEvent(filters: SubscriptionFilter[]): (event: Event) => boolean {
return anyPass(map(isEventMatchingFilter)(filters))
return createSubscriptionMatcher(filters)
}

private canSubscribe(subscriptionId: SubscriptionId, filters: SubscriptionFilter[]): string | undefined {
Expand Down
150 changes: 125 additions & 25 deletions src/utils/event.ts
Original file line number Diff line number Diff line change
Expand Up @@ -7,7 +7,7 @@ import { EventKindsRange } from '../@types/settings'
import { SubscriptionFilter } from '../@types/subscription'
import { WebSocketServerAdapterEvent } from '../constants/adapter'
import { ALL_RELAYS, EventKinds, EventTags } from '../constants/base'
import { isGenericTagQuery, isGeohashPrefixCriterion, stripGeohashPrefixWildcard } from './filter'
import { isGenericTagName, isGenericTagQuery, isGeohashPrefixCriterion, stripGeohashPrefixWildcard } from './filter'
import { getLeadingZeroBits } from './proof-of-work'
import { deriveFromSecret } from './secret'
import { fromBuffer } from './transform'
Expand Down Expand Up @@ -36,24 +36,118 @@ export const isEventKindOrRangeMatch =
(item: EventKinds | EventKindsRange) =>
typeof item === 'number' ? item === kind : kind >= item[0] && kind <= item[1]

export const isEventMatchingFilter =
(filter: SubscriptionFilter) =>
(event: Event): boolean => {
const startsWith = (input: string) => (prefix: string) => input.startsWith(prefix)
const isMatchingGenericTagCriterion =
(key: string, criterion: string) =>
(tag: Tag): boolean => {
const [, tagName] = key
if (tag[0] !== tagName) {
return false
}
interface TagCriteria {
values: Set<string>
prefixes: string[]
}

interface TagValues {
values: Set<string>
sorted?: string[]
}

export const lowerBound = (sorted: string[], target: string): number => {
let low = 0
let high = sorted.length
while (low < high) {
const middle = (low + high) >>> 1
if (sorted[middle] < target) {
low = middle + 1
} else {
high = middle
}
}
return low
}

/**
* Each single-letter tag's first value, grouped by name: what NIP-01 tag filters match against.
* Built once and never refreshed: share it only while the tags cannot change, e.g. one broadcast.
*/
export class EventTagIndex {
private index: Map<string, TagValues> | undefined

public constructor(private readonly tags: Tag[]) {}

public intersects(name: string, criteria: TagCriteria): boolean {
const tagValues = this.getIndex().get(name)
if (!tagValues) {
return false
}

const [smaller, larger] =
criteria.values.size <= tagValues.values.size
? [criteria.values, tagValues.values]
: [tagValues.values, criteria.values]
for (const value of smaller) {
if (larger.has(value)) {
return true
}
}

if (!criteria.prefixes.length) {
return false
}

// Values starting with a prefix sort together, from the first value not below it.
if (!tagValues.sorted) {
tagValues.sorted = [...tagValues.values].sort()
}
const sorted = tagValues.sorted
return criteria.prefixes.some((prefix) => {
const candidate = sorted[lowerBound(sorted, prefix)]
return candidate !== undefined && candidate.startsWith(prefix)
})
}

if (isGeohashPrefixCriterion(key, criterion)) {
return tag[1].startsWith(stripGeohashPrefixWildcard(criterion))
private getIndex(): Map<string, TagValues> {
if (!this.index) {
this.index = new Map()
for (const tag of Array.isArray(this.tags) ? this.tags : []) {
if (!Array.isArray(tag)) {
continue
}
const [name, value] = tag
if (typeof name !== 'string' || typeof value !== 'string' || !isGenericTagName(name)) {
continue
}
const tagValues = this.index.get(name)
if (tagValues) {
tagValues.values.add(value)
} else {
this.index.set(name, { values: new Set([value]) })
}
}
}
return this.index
}
}

return tag[1] === criterion
const compileTagCriteria = (filter: SubscriptionFilter): Map<string, TagCriteria> => {
const tagCriteria = new Map<string, TagCriteria>()
for (const [key, criteria] of Object.entries(filter)) {
if (!isGenericTagQuery(key) || !Array.isArray(criteria)) {
continue
}

const compiled: TagCriteria = { values: new Set(), prefixes: [] }
for (const criterion of criteria as string[]) {
if (isGeohashPrefixCriterion(key, criterion)) {
compiled.prefixes.push(stripGeohashPrefixWildcard(criterion))
} else {
compiled.values.add(criterion)
}
}
tagCriteria.set(key[1], compiled)
}
return tagCriteria
}

const compileFilter = (filter: SubscriptionFilter) => {
const tagCriteria = compileTagCriteria(filter)

return (event: Event, tagIndex: EventTagIndex): boolean => {
const startsWith = (input: string) => (prefix: string) => input.startsWith(prefix)

// NIP-01: Basic protocol flow description

Expand Down Expand Up @@ -94,16 +188,10 @@ export const isEventMatchingFilter =
// NIP-01: Support #e and #p tags
// NIP-12: Support generic tag queries

if (
Object.entries(filter)
.filter(([key, criteria]) => isGenericTagQuery(key) && Array.isArray(criteria))
.some(([key, criteria]) => {
return !event.tags.some((tag) =>
criteria.some((criterion) => isMatchingGenericTagCriterion(key, criterion)(tag)),
)
})
) {
return false
for (const [name, criteria] of tagCriteria) {
if (!tagIndex.intersects(name, criteria)) {
return false
}
}

// NIP-50
Expand All @@ -117,6 +205,18 @@ export const isEventMatchingFilter =

return true
}
}

export const isEventMatchingFilter = (filter: SubscriptionFilter) => {
const matches = compileFilter(filter)
return (event: Event): boolean => matches(event, new EventTagIndex(event.tags))
}

export const createSubscriptionMatcher = (filters: SubscriptionFilter[]) => {
const matchers = filters.map(compileFilter)
return (event: Event, tagIndex = new EventTagIndex(event.tags)): boolean =>
matchers.some((matches) => matches(event, tagIndex))
}

export const getEventHash = async (event: Event | UnidentifiedEvent | UnsignedEvent): Promise<string> => {
const id = await secp256k1.utils.sha256(Buffer.from(JSON.stringify(serializeEvent(event))))
Expand Down
2 changes: 2 additions & 0 deletions src/utils/filter.ts
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,8 @@ import { SubscriptionFilter } from '../@types/subscription'

export const isGenericTagQuery = (key: string) => /^#[a-zA-Z]$/.test(key)

export const isGenericTagName = (name: string) => /^[a-zA-Z]$/.test(name)

// Values are the array-valued criteria of a filter (`ids`, `authors`, `kinds`,
// `#e`, `#p`, ...). Scalars (`since`, `until`, `limit`, `search`) are criteria
// too, but they are single values and bounded by their own settings.
Expand Down
16 changes: 16 additions & 0 deletions test/integration/features/nip-01/nip-01.feature
Original file line number Diff line number Diff line change
Expand Up @@ -59,6 +59,22 @@ Feature: NIP-01
When Bob sends a text_note event with content "Nostr FTW!" and tag t containing "NostrNovember"
Then Alice receives a text_note event from Bob with content "Nostr FTW!"

Scenario: Bob gets a live event that carries a tag without a value
Given someone called Alice
And someone called Bob
And someone called Charlie
And Alice subscribes to tag g with "u4*"
And Bob subscribes to tag t with "valueless-g"
When Charlie sends a text_note event with content "g without a value" and a tag g without a value before tag t "valueless-g"
Then Bob receives a text_note event from Charlie with content "g without a value"

Scenario: Alice gets Bob's stored event whose first g tag has no value
Given someone called Alice
And someone called Bob
When Bob sends a text_note event with content "first g has no value" and a tag g without a value before tag g "u4pruydqqvj"
And Alice subscribes to the last event from Bob with tag g "u4*"
Then Alice receives 1 stored text_note event from Bob with content "first g has no value" and EOSE

Scenario: Alice is interested to Bob's text_note events and Charlie's set_metadata events
Given someone called Alice
And someone called Bob
Expand Down
14 changes: 14 additions & 0 deletions test/integration/features/nip-01/nip-01.feature.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,6 +128,20 @@ When(
},
)

When(
/^(\w+) sends a text_note event with content "([^"]+)" and a tag (\w) without a value before tag (\w) "([^"]+)"$/,
async function (name: string, content: string, emptyTag: string, tag: string, value: string) {
const ws = this.parameters.clients[name] as WebSocket
const { pubkey, privkey } = this.parameters.identities[name]

const tags = [[emptyTag], [tag, value]] as Event['tags']
const event: Event = await createEvent({ pubkey, kind: 1, content, tags }, privkey)

await sendEvent(ws, event)
this.parameters.events[name].push(event)
},
)

When(
/^(\w+) sends a text_note event with content "([^"]+)" and tags (\w) "([^"]+)" and (\w) "([^"]+)"$/,
async function (name: string, content: string, tag1: string, value1: string, tag2: string, value2: string) {
Expand Down
Loading
Loading