Repository navigation
fix(nip-43): admit users inside a serializable transaction #1075
New issue
Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.
By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.
Already on GitHub? Sign in to your account
Merged
+281
−2
Merged
Changes from all commits
Commits
Show all changes
4 commits
Select commit
Hold shift + click to select a range
4b4b247
fix(nip-43): admit users inside a serializable transaction
chappie-daemon ea47a9d
test(nip-43): cover the join path against a real Postgres
chappie-daemon a3ab362
test(nip-43): send AUTH properly and scope the setting to the feature
chappie-daemon 99deb22
test(nip-43): capture the AUTH challenge from the socket's first frame
chappie-daemon File filter
Filter by extension
Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
There are no files selected for viewing
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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. |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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 |
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| 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( | ||
| 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() | ||
|
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) | ||
| }) | ||
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
Oops, something went wrong.
Add this suggestion to a batch that can be applied as a single commit.
This suggestion is invalid because no changes were made to the code.
Suggestions cannot be applied while the pull request is closed.
Suggestions cannot be applied while viewing a subset of changes.
Only one suggestion per line can be applied in a batch.
Add this suggestion to a batch that can be applied as a single commit.
Applying suggestions on deleted lines is not supported.
You must change the existing code in this line in order to create a valid suggestion.
Outdated suggestions cannot be applied.
This suggestion has been applied or marked resolved.
Suggestions cannot be applied from pending reviews.
Suggestions cannot be applied on multi-line comments.
Suggestions cannot be applied while the pull request is queued to merge.
Suggestion cannot be applied right now. Please check back later.
Uh oh!
There was an error while loading. Please reload this page.