diff --git a/.changeset/admit-serializable-transaction.md b/.changeset/admit-serializable-transaction.md new file mode 100644 index 000000000..a379ef8d2 --- /dev/null +++ b/.changeset/admit-serializable-transaction.md @@ -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. diff --git a/src/repositories/user-repository.ts b/src/repositories/user-repository.ts index eb120b77f..00d258680 100644 --- a/src/repositories/user-repository.ts +++ b/src/repositories/user-repository.ts @@ -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 { + public async admitUser(pubkey: Pubkey, admittedAt: Date, client?: DatabaseClient): Promise { 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) diff --git a/test/integration/features/nip-43/nip-43.feature b/test/integration/features/nip-43/nip-43.feature new file mode 100644 index 000000000..5012d5e7d --- /dev/null +++ b/test/integration/features/nip-43/nip-43.feature @@ -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 diff --git a/test/integration/features/nip-43/nip-43.feature.ts b/test/integration/features/nip-43/nip-43.feature.ts new file mode 100644 index 000000000..abade645f --- /dev/null +++ b/test/integration/features/nip-43/nip-43.feature.ts @@ -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>) => context.parameters as Record + +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", ]` 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 => + firstValueFrom( + (streams.get(ws) as Observable).pipe( + 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 => + new Promise((resolve, reject) => { + const observable = streams.get(ws) as Observable + + 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() + 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>, name: string): Promise => { + 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>, + name: string, + claimCode: string, +): Promise => { + 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 => { + const [row] = await dbClient()('users').where('pubkey', Buffer.from(pubkey, 'hex')).select('is_admitted') + + return row?.is_admitted +} + +// The relay sends ["AUTH", ] 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>, name: string) { + const ws = new WebSocket(RELAY_URL) + const messages = new ReplaySubject(20, 10_000) + ws.on('message', (raw: RawData) => messages.next(JSON.parse(raw.toString()) as OutgoingMessage)) + + await new Promise((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>, 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>, 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>, name: string) { + const { pubkey } = world(this).identities[name] + expect(await isAdmitted(pubkey)).to.equal(true) +}) + +Then(/(\w+) is not admitted/, async function (this: World>, 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>) { + 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>, reason: string) { + const [result] = Object.values(world(this).joinRequestResults ?? {}) as CommandResult[] + expect(result?.[2]).to.equal(false) + expect(result?.[3]).to.equal(reason) +}) diff --git a/test/unit/repositories/user-repository.spec.ts b/test/unit/repositories/user-repository.spec.ts index 99e15c8a4..06354dba6 100644 --- a/test/unit/repositories/user-repository.spec.ts +++ b/test/unit/repositories/user-repository.spec.ts @@ -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) => + 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', () => {