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
5 changes: 5 additions & 0 deletions .changeset/admit-serializable-transaction.md
Original file line number Diff line number Diff line change
@@ -0,0 +1,5 @@
---
'nostream': patch
---

Admission now runs inside a serializable transaction. `admit_user()` opens with `PERFORM ASSERT_SERIALIZED()`, so calling it on the default read-committed connection raised `SN_NOT_SERIALIZABLE` and every NIP-43 join request failed. A caller that supplies its own client (the payments path) still runs inside the transaction it passes.
16 changes: 14 additions & 2 deletions src/repositories/user-repository.ts
Original file line number Diff line number Diff line change
Expand Up @@ -128,11 +128,23 @@ export class UserRepository implements IUserRepository {
return typeof result === 'number' ? result : 0
}

public async admitUser(pubkey: Pubkey, admittedAt: Date, client: DatabaseClient = this.dbClient): Promise<void> {
public async admitUser(pubkey: Pubkey, admittedAt: Date, client?: DatabaseClient): Promise<void> {
logger('admit user: %s at %s', pubkey, admittedAt)

const admit = (executor: DatabaseClient) =>
executor.raw('select admit_user(?, ?)', [toBuffer(pubkey), admittedAt.toISOString()])

try {
await client.raw('select admit_user(?, ?)', [toBuffer(pubkey), admittedAt.toISOString()])
// admit_user() opens with PERFORM ASSERT_SERIALIZED(), so it has to run
// inside a serializable transaction: on the default read-committed
// connection Postgres raises SN_NOT_SERIALIZABLE and every join request
// fails. Callers that already hold a transaction pass their own client.
if (client) {
await admit(client)
return
}

await this.dbClient.transaction((trx) => admit(trx), { isolationLevel: 'serializable' })
} catch (error) {
logger.error('Unable to admit user. Reason:', error)

Expand Down
23 changes: 23 additions & 0 deletions test/integration/features/nip-43/nip-43.feature
Original file line number Diff line number Diff line change
@@ -0,0 +1,23 @@
@nip43
@join
Feature: NIP-43 relay membership

# admit_user() is a stored function guarded by PERFORM ASSERT_SERIALIZED(),
# so it only runs inside a serializable transaction. A join that is not
# wrapped in one reaches the handler, claims its invite and then fails with
# SN_NOT_SERIALIZABLE — which no unit test could see, because every unit test
# stubs the repository or passes its own client.
Scenario: A join request with a valid invite admits the pubkey
Given Alice connects and keeps the relay's auth challenge
And an invite code "join-alice" with one use
When Alice authenticates with the relay
And Alice sends a join request claiming "join-alice"
Then the join request is accepted
And Alice is admitted

Scenario: A join request with an unknown invite code is refused
Given Bob connects and keeps the relay's auth challenge
When Bob authenticates with the relay
And Bob sends a join request claiming "no-such-invite"
Then the join request is refused with "restricted: invalid or expired invite code"
And Bob is not admitted
206 changes: 206 additions & 0 deletions test/integration/features/nip-43/nip-43.feature.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,206 @@
import { After, Before, Given, Then, When, World } from '@cucumber/cucumber'
import { expect } from 'chai'
import { assocPath } from 'ramda'
import { filter, firstValueFrom, map, Observable, ReplaySubject, throwError, timeout } from 'rxjs'
import WebSocket, { RawData } from 'ws'

import { createEvent, createIdentity, publishEvent } from '../helpers'
import { streams } from '../shared'
import { CommandResult, MessageType, OutgoingMessage } from '../../../../src/@types/messages'
import { Event } from '../../../../src/@types/event'
import { Settings } from '../../../../src/@types/settings'
import { getMasterDbClient } from '../../../../src/database/client'
import { InviteCodeRepository } from '../../../../src/repositories/invite-code-repository'
import { SettingsStatic } from '../../../../src/utils/settings'

const JOIN_REQUEST_KIND = 28934
const AUTH_EVENT_KIND = 22242
const CHALLENGE_TIMEOUT_MS = 3000
const RELAY_URL = 'ws://localhost:18808'

const world = (context: World<Record<string, any>>) => context.parameters as Record<string, any>

const dbClient = () => getMasterDbClient()

let settingsBeforeNip43: Settings | undefined

// Enabling NIP-43 makes the admission gate apply to every published event
// (event-message-handler), and no other feature admits the identities it
// creates — so a relay-wide override would refuse their writes. Turn it on for
// these scenarios only, and put the shared settings back afterwards.
Before({ tags: '@nip43' }, function () {
settingsBeforeNip43 = SettingsStatic._settings
SettingsStatic._settings = assocPath(['nip43', 'enabled'], true)(SettingsStatic._settings) as Settings
})

After({ tags: '@nip43' }, function () {
if (settingsBeforeNip43) {
SettingsStatic._settings = settingsBeforeNip43
}
})

// The relay sends `["AUTH", <challenge>]` the moment a socket opens and the
// socket's stream is a ReplaySubject, so this step usually sees the challenge
// replayed synchronously inside subscribe(). firstValueFrom owns the teardown,
// which keeps the replayed path from racing a subscription that does not exist
// yet.
const waitForChallenge = (ws: WebSocket): Promise<string> =>
firstValueFrom(
(streams.get(ws) as Observable<OutgoingMessage>).pipe(
Comment thread
chappie-daemon marked this conversation as resolved.
Resolved
filter((message) => message[0] === MessageType.AUTH),
map((message) => message[1] as string),
timeout({
first: CHALLENGE_TIMEOUT_MS,
with: () => throwError(() => new Error('relay did not send an AUTH challenge')),
}),
),
)

// The auth event travels as an AUTH message; sending it as an EVENT is refused
// with 'invalid: auth events must be sent using the AUTH message type'. The
// subscription is made before the send, so no replayed message can arrive
// before it exists.
const sendAuth = (ws: WebSocket, event: Event): Promise<CommandResult> =>
new Promise<CommandResult>((resolve, reject) => {
const observable = streams.get(ws) as Observable<OutgoingMessage>

const subscription = observable.subscribe((message: OutgoingMessage) => {
if (message[0] === MessageType.OK && message[1] === event.id) {
subscription.unsubscribe()
resolve(message as CommandResult)
} else if (message[0] === MessageType.NOTICE) {
subscription.unsubscribe()
Comment thread
coderabbitai[bot] marked this conversation as resolved.
Resolved
reject(new Error(message[1] as string))
}
})

ws.send(JSON.stringify(['AUTH', event]), (error?: Error) => {
if (error) {
subscription.unsubscribe()
reject(error)
}
})
})

const authenticate = async (context: World<Record<string, any>>, name: string): Promise<CommandResult> => {
const ws = world(context).clients[name] as WebSocket
const { pubkey, privkey } = world(context).identities[name]

const challenge = await waitForChallenge(ws)
const relayUrl = SettingsStatic._settings?.info?.relay_url as string

const event = await createEvent(
{
pubkey,
kind: AUTH_EVENT_KIND,
tags: [
['challenge', challenge],
['relay', relayUrl],
],
},
privkey,
)

return sendAuth(ws, event)
}

const sendJoinRequest = async (
context: World<Record<string, any>>,
name: string,
claimCode: string,
): Promise<CommandResult> => {
const ws = world(context).clients[name] as WebSocket
const { pubkey, privkey } = world(context).identities[name]

const event = await createEvent(
{
pubkey,
kind: JOIN_REQUEST_KIND,
tags: [['claim', claimCode]],
content: '',
},
privkey,
)

world(context).events[name].push(event)

return publishEvent(ws, event)
}

const isAdmitted = async (pubkey: string): Promise<boolean | undefined> => {
const [row] = await dbClient()('users').where('pubkey', Buffer.from(pubkey, 'hex')).select('is_admitted')

return row?.is_admitted
}

// The relay sends ["AUTH", <challenge>] as soon as the handshake completes,
// while the shared `someone called` step only subscribes to the socket after
// 'open' resolves — by then the challenge can already have been parsed and
// dropped. Listen from the first frame instead and hand that buffered stream to
// everything that follows, keeping the socket in the same world slots so the
// shared After hook still closes it.
Given(
/(\w+) connects and keeps the relay's auth challenge/,
async function (this: World<Record<string, any>>, name: string) {
const ws = new WebSocket(RELAY_URL)
const messages = new ReplaySubject<OutgoingMessage>(20, 10_000)
ws.on('message', (raw: RawData) => messages.next(JSON.parse(raw.toString()) as OutgoingMessage))

await new Promise<void>((resolve, reject) => {
ws.once('open', () => resolve())
ws.once('error', reject)
})

const parameters = world(this)
parameters.identities[name] = createIdentity(name)
parameters.clients[name] = ws
parameters.subscriptions[name] = []
parameters.events[name] = []
streams.set(ws, messages)
},
)

Given(/an invite code "([^"]+)" with one use/, async (code: string) => {
const repository = new InviteCodeRepository(dbClient())
await repository.create(code, { remainingUses: 1 })
})

// The relay answers AUTH with an OK carrying the auth event's id; a failure
// here means the challenge, relay tag or signature was rejected, and the
// message says which.
When(/(\w+) authenticates with the relay/, async function (this: World<Record<string, any>>, name: string) {
const result = await authenticate(this, name)

if (result[2] !== true) {
throw new Error(`authentication failed: ${result[3]}`)
}
})

When(
/(\w+) sends a join request claiming "([^"]+)"/,
async function (this: World<Record<string, any>>, name: string, claimCode: string) {
world(this).joinRequestResults = world(this).joinRequestResults ?? {}
world(this).joinRequestResults[name] = await sendJoinRequest(this, name, claimCode)
},
)

Then(/(\w+) is admitted/, async function (this: World<Record<string, any>>, name: string) {
const { pubkey } = world(this).identities[name]
expect(await isAdmitted(pubkey)).to.equal(true)
})

Then(/(\w+) is not admitted/, async function (this: World<Record<string, any>>, name: string) {
const { pubkey } = world(this).identities[name]
expect(await isAdmitted(pubkey)).to.not.equal(true)
})

Then(/the join request is accepted/, function (this: World<Record<string, any>>) {
const [result] = Object.values(world(this).joinRequestResults ?? {}) as CommandResult[]
expect(result?.[2], result?.[3]).to.equal(true)
})

Then(/the join request is refused with "([^"]+)"/, function (this: World<Record<string, any>>, reason: string) {
const [result] = Object.values(world(this).joinRequestResults ?? {}) as CommandResult[]
expect(result?.[2]).to.equal(false)
expect(result?.[3]).to.equal(reason)
})
33 changes: 33 additions & 0 deletions test/unit/repositories/user-repository.spec.ts
Original file line number Diff line number Diff line change
Expand Up @@ -326,6 +326,39 @@ describe('UserRepository', () => {
repository.admitUser(pubkeyHex, fixedDate, client),
).to.be.rejectedWith(dbError)
})

// admit_user() is guarded by PERFORM ASSERT_SERIALIZED(), which raises
// SN_NOT_SERIALIZABLE on the default read-committed connection. A caller
// that supplies no client therefore needs this method to open one.
it('opens a serializable transaction when no client is supplied', async () => {
const rawStub = sandbox.stub().resolves()
const transactionStub = sandbox.stub().callsFake(async (callback: (trx: unknown) => Promise<void>) =>
callback({ raw: rawStub }),
)
const client = { transaction: transactionStub } as unknown as DatabaseClient
const admittingRepository = new UserRepository(client, eventRepository)

await admittingRepository.admitUser(pubkeyHex, fixedDate)

expect(transactionStub).to.have.been.calledOnce
expect(transactionStub.firstCall.args[1]).to.deep.equal({ isolationLevel: 'serializable' })
expect(rawStub).to.have.been.calledOnce
expect(rawStub.firstCall.args[0]).to.equal('select admit_user(?, ?)')
expect(Buffer.isBuffer(rawStub.firstCall.args[1][0])).to.be.true
expect(rawStub.firstCall.args[1][1]).to.equal(fixedDate.toISOString())
})

it('does not open a transaction when the caller supplies a client', async () => {
const rawStub = sandbox.stub().resolves()
const transactionStub = sandbox.stub()
const client = { raw: rawStub, transaction: transactionStub } as unknown as DatabaseClient
const admittingRepository = new UserRepository(client, eventRepository)

await admittingRepository.admitUser(pubkeyHex, fixedDate, client)

expect(rawStub).to.have.been.calledOnce
expect(transactionStub).to.have.not.been.called
})
})

describe('.revokeAdmission', () => {
Expand Down
Loading