refactor: extract AuthPolicy interface from requireAuth boolean
Replace the requireAuth: Boolean parameter in NostrServer with a pluggable AuthPolicy interface. Each policy has trigger points for EVENT (acceptEvent), REQ (acceptReq with filter rewriting), COUNT (acceptCount), and live event delivery (canSendToSession). Built-in policies: OpenPolicy (allow all) and RequireAuthPolicy (require auth for all commands, matching the previous behavior). https://claude.ai/code/session_017vdjbdxdYK1oJMH66koVZE
This commit is contained in:
+169
@@ -0,0 +1,169 @@
|
||||
/*
|
||||
* Copyright (c) 2025 Vitor Pamplona
|
||||
*
|
||||
* Permission is hereby granted, free of charge, to any person obtaining a copy of
|
||||
* this software and associated documentation files (the "Software"), to deal in
|
||||
* the Software without restriction, including without limitation the rights to use,
|
||||
* copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the
|
||||
* Software, and to permit persons to whom the Software is furnished to do so,
|
||||
* subject to the following conditions:
|
||||
*
|
||||
* The above copyright notice and this permission notice shall be included in all
|
||||
* copies or substantial portions of the Software.
|
||||
*
|
||||
* THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
|
||||
* IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS
|
||||
* FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR
|
||||
* COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN
|
||||
* AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION
|
||||
* WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE.
|
||||
*/
|
||||
package com.vitorpamplona.quartz.nip01Core.relay.server
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.filters.Filter
|
||||
|
||||
/**
|
||||
* Policy that controls authentication requirements for relay commands.
|
||||
*
|
||||
* Each trigger point receives the set of pubkeys that have authenticated on the
|
||||
* current session, allowing the policy to make per-user decisions. Implementations
|
||||
* can range from fully open (no auth) to fine-grained per-kind or per-user rules.
|
||||
*/
|
||||
interface AuthPolicy {
|
||||
/**
|
||||
* Evaluates whether an incoming EVENT command should be accepted.
|
||||
*
|
||||
* @param event The event the client wants to publish.
|
||||
* @param authedPubkeys Pubkeys authenticated on this session (empty if none).
|
||||
* @return [Accepted] to store the event, or [Rejected] with a reason string.
|
||||
*/
|
||||
fun acceptEvent(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
): PolicyResult
|
||||
|
||||
/**
|
||||
* Evaluates a REQ command, optionally rewriting the filter list.
|
||||
*
|
||||
* The policy may narrow filters to match what the authenticated user is
|
||||
* allowed to see (e.g., restrict to their own DMs), or reject the
|
||||
* subscription entirely.
|
||||
*
|
||||
* @param filters The filters from the REQ command.
|
||||
* @param authedPubkeys Pubkeys authenticated on this session.
|
||||
* @return [Accepted] with an optional replacement filter list, or [Rejected].
|
||||
*/
|
||||
fun acceptReq(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
): ReqPolicyResult
|
||||
|
||||
/**
|
||||
* Evaluates a COUNT command.
|
||||
*
|
||||
* @param filters The filters from the COUNT command.
|
||||
* @param authedPubkeys Pubkeys authenticated on this session.
|
||||
* @return [Accepted] to allow counting, or [Rejected] with a reason.
|
||||
*/
|
||||
fun acceptCount(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
): PolicyResult
|
||||
|
||||
/**
|
||||
* Filters a live event before it is forwarded to a subscriber.
|
||||
*
|
||||
* Called for each event that matches a subscription's filters. Return
|
||||
* true to deliver the event, false to suppress it for this session.
|
||||
*
|
||||
* @param event The event about to be sent.
|
||||
* @param authedPubkeys Pubkeys authenticated on this session.
|
||||
*/
|
||||
fun canSendToSession(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
): Boolean = true
|
||||
}
|
||||
|
||||
sealed interface PolicyResult {
|
||||
data object Accepted : PolicyResult
|
||||
|
||||
data class Rejected(
|
||||
val reason: String,
|
||||
) : PolicyResult
|
||||
}
|
||||
|
||||
sealed interface ReqPolicyResult {
|
||||
data class Accepted(
|
||||
val filters: List<Filter>? = null,
|
||||
) : ReqPolicyResult
|
||||
|
||||
data class Rejected(
|
||||
val reason: String,
|
||||
) : ReqPolicyResult
|
||||
}
|
||||
|
||||
/**
|
||||
* Allows all commands without authentication. This is the default policy.
|
||||
*/
|
||||
class OpenPolicy : AuthPolicy {
|
||||
override fun acceptEvent(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
|
||||
override fun acceptReq(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = ReqPolicyResult.Accepted()
|
||||
|
||||
override fun acceptCount(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
|
||||
override fun canSendToSession(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = true
|
||||
}
|
||||
|
||||
/**
|
||||
* Requires authentication for all EVENT, REQ, and COUNT commands.
|
||||
* Replicates the previous `requireAuth = true` behavior.
|
||||
*/
|
||||
class RequireAuthPolicy : AuthPolicy {
|
||||
override fun acceptEvent(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = if (authedPubkeys.isNotEmpty()) {
|
||||
PolicyResult.Accepted
|
||||
} else {
|
||||
PolicyResult.Rejected("auth-required: this relay requires authentication")
|
||||
}
|
||||
|
||||
override fun acceptReq(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = if (authedPubkeys.isNotEmpty()) {
|
||||
ReqPolicyResult.Accepted()
|
||||
} else {
|
||||
ReqPolicyResult.Rejected("auth-required: this relay requires authentication")
|
||||
}
|
||||
|
||||
override fun acceptCount(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = if (authedPubkeys.isNotEmpty()) {
|
||||
PolicyResult.Accepted
|
||||
} else {
|
||||
PolicyResult.Rejected("auth-required: this relay requires authentication")
|
||||
}
|
||||
|
||||
override fun canSendToSession(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = authedPubkeys.isNotEmpty()
|
||||
}
|
||||
+3
-3
@@ -42,15 +42,15 @@ import kotlin.coroutines.CoroutineContext
|
||||
*
|
||||
* @param store The [EventStore] backing this relay.
|
||||
* @param relayUrl The URL of this relay, used for NIP-42 authentication.
|
||||
* @param requireAuth When true, clients must authenticate (NIP-42) before
|
||||
* sending EVENT, REQ, or COUNT commands.
|
||||
* @param authPolicy Controls authentication requirements for relay commands.
|
||||
* Defaults to [OpenPolicy] (no authentication required).
|
||||
* @param verify Validates incoming events. Defaults to cryptographic
|
||||
* verification (id + signature). Override for testing.
|
||||
*/
|
||||
class NostrServer(
|
||||
private val store: IEventStore,
|
||||
val relayUrl: NormalizedRelayUrl = NormalizedRelayUrl("wss://relay.example.com/"),
|
||||
val requireAuth: Boolean = false,
|
||||
val authPolicy: AuthPolicy = OpenPolicy(),
|
||||
private val parentContext: CoroutineContext = SupervisorJob(),
|
||||
private val verify: (Event) -> Boolean = { it.verify() },
|
||||
) {
|
||||
|
||||
+20
-8
@@ -200,8 +200,9 @@ class RelaySession(
|
||||
private fun handleEvent(cmd: EventCmd) {
|
||||
val event = cmd.event
|
||||
|
||||
if (server.requireAuth && !isAuthenticated()) {
|
||||
send(OkMessage(event.id, false, "auth-required: this relay requires authentication"))
|
||||
val result = server.authPolicy.acceptEvent(event, authenticatedPubkeys())
|
||||
if (result is PolicyResult.Rejected) {
|
||||
send(OkMessage(event.id, false, result.reason))
|
||||
return
|
||||
}
|
||||
|
||||
@@ -220,20 +221,30 @@ class RelaySession(
|
||||
|
||||
// -- NIP-01: REQ ----------------------------------------------------------
|
||||
private fun handleReq(cmd: ReqCmd) {
|
||||
if (server.requireAuth && !isAuthenticated()) {
|
||||
send(ClosedMessage(cmd.subId, "auth-required: this relay requires authentication"))
|
||||
val result = server.authPolicy.acceptReq(cmd.filters, authenticatedPubkeys())
|
||||
if (result is ReqPolicyResult.Rejected) {
|
||||
send(ClosedMessage(cmd.subId, result.reason))
|
||||
return
|
||||
}
|
||||
|
||||
// Policy may rewrite filters to match the user's access level.
|
||||
val filters = (result as ReqPolicyResult.Accepted).filters ?: cmd.filters
|
||||
|
||||
// Cancel any existing subscription with the same id (NIP-01 spec).
|
||||
cancelSubscription(cmd.subId)
|
||||
|
||||
val authed = authenticatedPubkeys()
|
||||
val policy = server.authPolicy
|
||||
val job =
|
||||
scope.launch {
|
||||
try {
|
||||
store.query(
|
||||
filters = cmd.filters,
|
||||
onEach = { send(EventMessage(cmd.subId, it)) },
|
||||
filters = filters,
|
||||
onEach = { event ->
|
||||
if (policy.canSendToSession(event, authed)) {
|
||||
send(EventMessage(cmd.subId, event))
|
||||
}
|
||||
},
|
||||
onEose = { send(EoseMessage(cmd.subId)) },
|
||||
)
|
||||
} catch (_: kotlinx.coroutines.CancellationException) {
|
||||
@@ -254,8 +265,9 @@ class RelaySession(
|
||||
|
||||
// -- NIP-45: COUNT --------------------------------------------------------
|
||||
private fun handleCount(cmd: CountCmd) {
|
||||
if (server.requireAuth && !isAuthenticated()) {
|
||||
send(ClosedMessage(cmd.queryId, "auth-required: this relay requires authentication"))
|
||||
val result = server.authPolicy.acceptCount(cmd.filters, authenticatedPubkeys())
|
||||
if (result is PolicyResult.Rejected) {
|
||||
send(ClosedMessage(cmd.queryId, result.reason))
|
||||
return
|
||||
}
|
||||
|
||||
|
||||
+173
-8
@@ -21,6 +21,7 @@
|
||||
package com.vitorpamplona.quartz.nip01Core.relay.server
|
||||
|
||||
import com.vitorpamplona.quartz.nip01Core.core.Event
|
||||
import com.vitorpamplona.quartz.nip01Core.core.HexKey
|
||||
import com.vitorpamplona.quartz.nip01Core.core.OptimizedJsonMapper
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.commands.toClient.EoseMessage
|
||||
import com.vitorpamplona.quartz.nip01Core.relay.commands.toClient.EventMessage
|
||||
@@ -63,12 +64,12 @@ class NostrServerTest {
|
||||
private fun createServer(
|
||||
store: IEventStore = EventStore(null),
|
||||
dispatcher: kotlinx.coroutines.CoroutineDispatcher,
|
||||
requireAuth: Boolean = false,
|
||||
authPolicy: AuthPolicy = OpenPolicy(),
|
||||
): NostrServer =
|
||||
NostrServer(
|
||||
store = store,
|
||||
relayUrl = relayUrl,
|
||||
requireAuth = requireAuth,
|
||||
authPolicy = authPolicy,
|
||||
parentContext = dispatcher,
|
||||
verify = { true },
|
||||
)
|
||||
@@ -605,7 +606,7 @@ class NostrServerTest {
|
||||
fun requireAuthRejectsEventWithoutAuth() =
|
||||
runTest {
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val server = createServer(dispatcher = dispatcher, requireAuth = true)
|
||||
val server = createServer(dispatcher = dispatcher, authPolicy = RequireAuthPolicy())
|
||||
val collector = MessageCollector()
|
||||
|
||||
val session = server.connect(collector.sendCallback)
|
||||
@@ -625,7 +626,7 @@ class NostrServerTest {
|
||||
fun requireAuthRejectsReqWithoutAuth() =
|
||||
runTest {
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val server = createServer(dispatcher = dispatcher, requireAuth = true)
|
||||
val server = createServer(dispatcher = dispatcher, authPolicy = RequireAuthPolicy())
|
||||
val collector = MessageCollector()
|
||||
|
||||
val session = server.connect(collector.sendCallback)
|
||||
@@ -642,7 +643,7 @@ class NostrServerTest {
|
||||
fun requireAuthRejectsCountWithoutAuth() =
|
||||
runTest {
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val server = createServer(dispatcher = dispatcher, requireAuth = true)
|
||||
val server = createServer(dispatcher = dispatcher, authPolicy = RequireAuthPolicy())
|
||||
val collector = MessageCollector()
|
||||
|
||||
val session = server.connect(collector.sendCallback)
|
||||
@@ -660,7 +661,7 @@ class NostrServerTest {
|
||||
runTest {
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val store = EventStore(null)
|
||||
val server = createServer(store = store, dispatcher = dispatcher, requireAuth = true)
|
||||
val server = createServer(store = store, dispatcher = dispatcher, authPolicy = RequireAuthPolicy())
|
||||
val collector = MessageCollector()
|
||||
|
||||
val session = server.connect(collector.sendCallback)
|
||||
@@ -694,12 +695,12 @@ class NostrServerTest {
|
||||
fun noAuthRequiredAllowsCommandsWithoutAuth() =
|
||||
runTest {
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val server = createServer(dispatcher = dispatcher, requireAuth = false)
|
||||
val server = createServer(dispatcher = dispatcher)
|
||||
val collector = MessageCollector()
|
||||
|
||||
val session = server.connect(collector.sendCallback)
|
||||
|
||||
// EVENT should work without auth when requireAuth is false
|
||||
// EVENT should work without auth when using OpenPolicy
|
||||
val event = testEvent()
|
||||
session.processMessage("""["EVENT",${event.toJson()}]""")
|
||||
|
||||
@@ -707,6 +708,170 @@ class NostrServerTest {
|
||||
assertEquals(1, okMessages.size)
|
||||
assertTrue(okMessages[0].contains("\"true\""))
|
||||
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
// -- Custom AuthPolicy tests -----------------------------------------------
|
||||
|
||||
@Test
|
||||
fun customPolicyRejectsSpecificEventKinds() =
|
||||
runTest {
|
||||
// Policy that blocks kind 4 (DMs) from unauthenticated users.
|
||||
val policy =
|
||||
object : AuthPolicy {
|
||||
override fun acceptEvent(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = if (event.kind == 4 && authedPubkeys.isEmpty()) {
|
||||
PolicyResult.Rejected("auth-required: kind 4 events require authentication")
|
||||
} else {
|
||||
PolicyResult.Accepted
|
||||
}
|
||||
|
||||
override fun acceptReq(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = ReqPolicyResult.Accepted()
|
||||
|
||||
override fun acceptCount(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
}
|
||||
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val server = createServer(dispatcher = dispatcher, authPolicy = policy)
|
||||
val collector = MessageCollector()
|
||||
val session = server.connect(collector.sendCallback)
|
||||
|
||||
// Kind 1 should be accepted without auth
|
||||
val note = testEvent(hexId(1), kind = 1)
|
||||
session.processMessage("""["EVENT",${note.toJson()}]""")
|
||||
assertTrue(collector.rawMessagesContaining("OK")[0].contains("\"true\""))
|
||||
|
||||
// Kind 4 should be rejected without auth
|
||||
val dm = testEvent(hexId(2), kind = 4)
|
||||
session.processMessage("""["EVENT",${dm.toJson()}]""")
|
||||
val okMessages = collector.rawMessagesContaining("OK")
|
||||
assertEquals(2, okMessages.size)
|
||||
assertTrue(okMessages[1].contains("\"false\""))
|
||||
assertTrue(okMessages[1].contains("auth-required:"))
|
||||
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun customPolicyRewritesFilters() =
|
||||
runTest {
|
||||
// Policy that restricts kind 4 queries to the authed user's own messages.
|
||||
val policy =
|
||||
object : AuthPolicy {
|
||||
override fun acceptEvent(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
|
||||
override fun acceptReq(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
): ReqPolicyResult {
|
||||
val hasDmFilter = filters.any { it.kinds?.contains(4) == true }
|
||||
if (!hasDmFilter) return ReqPolicyResult.Accepted()
|
||||
if (authedPubkeys.isEmpty()) {
|
||||
return ReqPolicyResult.Rejected("auth-required: kind 4 requires auth")
|
||||
}
|
||||
// Rewrite: restrict to authed user's pubkey as author
|
||||
val rewritten =
|
||||
filters.map { filter ->
|
||||
if (filter.kinds?.contains(4) == true) {
|
||||
filter.copy(authors = authedPubkeys.toList())
|
||||
} else {
|
||||
filter
|
||||
}
|
||||
}
|
||||
return ReqPolicyResult.Accepted(rewritten)
|
||||
}
|
||||
|
||||
override fun acceptCount(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
}
|
||||
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val store = EventStore(null)
|
||||
val server = createServer(store = store, dispatcher = dispatcher, authPolicy = policy)
|
||||
|
||||
// Insert DMs from two different authors
|
||||
store.insert(testEvent(hexId(1), kind = 4, createdAt = 100L)) // from pubkey
|
||||
store.insert(
|
||||
Event(hexId(2), pubkey2, 200L, 4, emptyArray(), "secret", sig),
|
||||
) // from pubkey2
|
||||
|
||||
val collector = MessageCollector()
|
||||
val session = server.connect(collector.sendCallback)
|
||||
|
||||
// Authenticate as pubkey
|
||||
val auth = authEvent(challenge = session.challenge, pubKey = pubkey)
|
||||
session.processMessage(authJson(auth))
|
||||
|
||||
// Query kind 4 — policy should rewrite to only return pubkey's events
|
||||
session.processMessage("""["REQ","sub1",{"kinds":[4]}]""")
|
||||
|
||||
val events = collector.parsedEventMessages().filterIsInstance<EventMessage>()
|
||||
assertEquals(1, events.size)
|
||||
assertEquals(pubkey, events[0].event.pubKey)
|
||||
|
||||
server.shutdown()
|
||||
}
|
||||
|
||||
@Test
|
||||
fun customPolicyFiltersLiveEvents() =
|
||||
runTest {
|
||||
// Policy that only delivers events to authenticated sessions
|
||||
val policy =
|
||||
object : AuthPolicy {
|
||||
override fun acceptEvent(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
|
||||
override fun acceptReq(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = ReqPolicyResult.Accepted()
|
||||
|
||||
override fun acceptCount(
|
||||
filters: List<Filter>,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = PolicyResult.Accepted
|
||||
|
||||
override fun canSendToSession(
|
||||
event: Event,
|
||||
authedPubkeys: Set<HexKey>,
|
||||
) = authedPubkeys.isNotEmpty()
|
||||
}
|
||||
|
||||
val dispatcher = UnconfinedTestDispatcher(testScheduler)
|
||||
val store = EventStore(null)
|
||||
val server = createServer(store = store, dispatcher = dispatcher, authPolicy = policy)
|
||||
|
||||
// Unauthenticated subscriber
|
||||
val unauthCollector = MessageCollector()
|
||||
val unauthSession = server.connect(unauthCollector.sendCallback)
|
||||
unauthSession.processMessage("""["REQ","sub1",{"kinds":[1]}]""")
|
||||
val countAfterEose = unauthCollector.messages.size
|
||||
|
||||
// Authenticated publisher
|
||||
val pubCollector = MessageCollector()
|
||||
val pubSession = server.connect(pubCollector.sendCallback)
|
||||
|
||||
// Publish an event
|
||||
pubSession.insert(testEvent(hexId(1), kind = 1))
|
||||
|
||||
// Unauthenticated session should NOT receive the live event
|
||||
assertEquals(countAfterEose, unauthCollector.messages.size)
|
||||
|
||||
server.shutdown()
|
||||
}
|
||||
}
|
||||
|
||||
Reference in New Issue
Block a user