Skip to content

Commit 3a3806e

Browse files
rmichelenaclaude
andcommitted
fix(relay): trust and time-bound the NIP-OA owner before recording it
Review of the previous commit found two ways it granted authority from an attestation that had not earned it, plus a test gap that hid both. **The claimed owner must be trusted, not merely attested.** On a closed relay the only prior path to an owner was `ViaOwner`, which requires the owner to be a relay member. `resolve_nip_oa_owner` bypassed that for direct members: any member could mint a throwaway keypair, attest itself, and have that key recorded. The resolved owner is not inert — `materialize_nip_oa_owner` creates a user row for it, and `connection.rs:632` derives `is_agent` from `agent_owner_pubkey.is_some()` alone, switching the message limit from 60/min to 120/min. So a member could double its own quota. Worse, `set_agent_owner` is first-write-wins: one authentication with a wrong or stale tag pins that mapping permanently and the legitimate owner is refused afterwards, which is durable corruption rather than a transient privilege bump. The claimed owner must now be a relay member on closed relays, exactly as `ViaOwner` demands. Open relays are unchanged — with no membership boundary there is nothing to check against. `allow_nip_oa_auth` stays out of it: its own doc comment scopes it to granting *membership*, which this never does. **A signature that verifies is not a credential that is valid.** `validate_conditions` is purely syntactic — it checks `created_at<N` is a canonical decimal and never compares N to anything — so an expired tag was indistinguishable from a live one. `evaluate_time_bounds` and `verify_auth_tag_at` add that evaluation, judged against the `created_at` of the signed authentication event that carried the tag (the NIP-42 AUTH event, or the NIP-98 request event) rather than wall clock, because the bound is a property of what the owner authorized. The semantics are not invented here: `enforce_request_auth_time_bounds` already enforced these clauses for NIP-IA archive requests with both bounds strict, and now delegates to the shared evaluator so the two cannot drift. The bounds are enforced even when the membership gate already resolved an owner, since that gate does not evaluate them — an expired tag can still produce a `ViaOwner` decision. Leaving that pre-existing membership grant alone is deliberate and out of scope here; what changes is that it can no longer be *materialized* into an ownership record. Time bounds gate granting, never denying. `extract_nip_oa_owner` keeps its signature-only behaviour for the ban cascades in `handlers::auth` and `api::git::transport`: widening who gets denied is safe, and an expired attestation must not become an escape hatch from an owner ban. `verify_bridge_auth` now reports the NIP-98 request event's `created_at`. It is `None` under X-Pubkey dev auth, where nothing was signed and there is no timestamp to judge bounds against; no ownership is recorded in that case rather than treating the tag as unbounded. The four unit tests this replaces did not protect the regression — reverting both production call sites left them green, because they exercised the helper rather than its callers. They are replaced with coverage of what is genuinely pure (time bounds, signature binding, and the grant/deny split). The Postgres-backed tests through the real HTTP and NIP-42 paths are still owed, along with the CI filter that selects them: no job currently runs `api::relay_members::tests` at all. Also corrects three doc comments the previous commit falsified, including `AuthContext::agent_owner_pubkey`, which still claimed `None` for direct relay members. Refs block#4223, block#4937, block#4260. Co-Authored-By: Claude Opus 5 (1M context) <[email protected]> Signed-off-by: Roberto Michelena <[email protected]>
1 parent 9bb913f commit 3a3806e

8 files changed

Lines changed: 453 additions & 101 deletions

File tree

‎crates/buzz-auth/src/lib.rs‎

Lines changed: 11 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -72,10 +72,18 @@ pub struct AuthContext {
7272
pub channel_ids: Option<Vec<uuid::Uuid>>,
7373
/// How the connection was authenticated.
7474
pub auth_method: AuthMethod,
75-
/// NIP-OA verified owner pubkey (if authenticated via owner attestation).
75+
/// NIP-OA verified owner pubkey.
7676
///
77-
/// `None` for direct relay members or non-NIP-OA auth paths.
78-
/// Set by the relay membership gate when NIP-OA fallback succeeds.
77+
/// Set for any caller whose presented attestation resolved to a trusted
78+
/// owner — including a direct relay member, which is why membership alone
79+
/// no longer implies `None`. On a closed relay the claimed owner must also
80+
/// be a relay member; an expired or not-yet-valid attestation resolves to
81+
/// `None`.
82+
///
83+
/// `None` for non-NIP-OA auth paths, and whenever the attestation could not
84+
/// be trusted. Note this field selects the agent rate class in
85+
/// `connection.rs`, so it must never be populated from an unverified or
86+
/// untrusted owner.
7987
pub agent_owner_pubkey: Option<nostr::PublicKey>,
8088
}
8189

‎crates/buzz-relay/src/api/bridge.rs‎

Lines changed: 78 additions & 19 deletions
Original file line numberDiff line numberDiff line change
@@ -55,17 +55,28 @@ async fn enforce_http_admission(
5555
}
5656
}
5757

58+
/// Outcome of bridge authentication.
59+
#[derive(Debug)]
60+
pub(crate) struct BridgeAuth {
61+
/// The authenticated public key.
62+
pub pubkey: nostr::PublicKey,
63+
/// Event ID used for replay detection. Zero hash in X-Pubkey dev mode,
64+
/// where there is no signed event and so no replay concern.
65+
pub event_id_bytes: [u8; 32],
66+
/// `created_at` of the NIP-98 request event, when one authenticated this
67+
/// request. `None` in X-Pubkey dev mode: nothing was signed, so there is no
68+
/// timestamp a NIP-OA attestation's bounds could be judged against.
69+
pub created_at: Option<u64>,
70+
}
71+
5872
/// Verify bridge auth: NIP-98 (production) or X-Pubkey (dev mode).
59-
///
60-
/// Returns the authenticated public key and an event ID for replay detection.
61-
/// For X-Pubkey dev mode, the event ID is a zero hash (no replay concern).
6273
pub(crate) fn verify_bridge_auth(
6374
headers: &HeaderMap,
6475
method: &str,
6576
url: &str,
6677
body: Option<&[u8]>,
6778
require_auth_token: bool,
68-
) -> Result<(nostr::PublicKey, [u8; 32]), (StatusCode, Json<Value>)> {
79+
) -> Result<BridgeAuth, (StatusCode, Json<Value>)> {
6980
verify_bridge_auth_with_options(headers, method, url, body, require_auth_token, false)
7081
}
7182

@@ -76,7 +87,7 @@ pub(crate) fn verify_bridge_auth_with_options(
7687
body: Option<&[u8]>,
7788
require_auth_token: bool,
7889
require_payload: bool,
79-
) -> Result<(nostr::PublicKey, [u8; 32]), (StatusCode, Json<Value>)> {
90+
) -> Result<BridgeAuth, (StatusCode, Json<Value>)> {
8091
// Try NIP-98 first (Authorization: Nostr <base64>)
8192
if let Some(auth_str) = headers
8293
.get("authorization")
@@ -111,7 +122,11 @@ pub(crate) fn verify_bridge_auth_with_options(
111122
let pubkey = buzz_auth::verify_nip98_event(&event_json, url, method, body)
112123
.map_err(|e| api_error(StatusCode::UNAUTHORIZED, &format!("NIP-98: {e}")))?;
113124

114-
return Ok((pubkey, event_id_bytes));
125+
return Ok(BridgeAuth {
126+
pubkey,
127+
event_id_bytes,
128+
created_at: Some(event.created_at.as_secs()),
129+
});
115130
}
116131

117132
// Dev-mode fallback: X-Pubkey header (only when require_auth_token is false)
@@ -120,7 +135,11 @@ pub(crate) fn verify_bridge_auth_with_options(
120135
let pubkey = nostr::PublicKey::from_hex(hex_val)
121136
.map_err(|_| api_error(StatusCode::UNAUTHORIZED, "invalid X-Pubkey hex"))?;
122137
// Zero event ID — no replay detection needed for dev mode
123-
return Ok((pubkey, [0u8; 32]));
138+
return Ok(BridgeAuth {
139+
pubkey,
140+
event_id_bytes: [0u8; 32],
141+
created_at: None,
142+
});
124143
}
125144
}
126145

@@ -637,7 +656,11 @@ pub async fn submit_event(
637656
})?;
638657

639658
let url = nip98_expected_url(&state.config.relay_url, &tenant, "/events");
640-
let (pubkey, event_id_bytes) = verify_bridge_auth(
659+
let BridgeAuth {
660+
pubkey,
661+
event_id_bytes,
662+
created_at: auth_event_created_at,
663+
} = verify_bridge_auth(
641664
&headers,
642665
"POST",
643666
&url,
@@ -650,8 +673,16 @@ pub async fn submit_event(
650673
// runs inside the helper. The thin wrapper here owns the single terminal
651674
// attribution line so it fires for every outcome, including admission/
652675
// replay/membership failures that previously returned before any log fired.
653-
let outcome =
654-
submit_event_authed(&state, &tenant, &headers, &body, pubkey, event_id_bytes).await;
676+
let outcome = submit_event_authed(
677+
&state,
678+
&tenant,
679+
&headers,
680+
&body,
681+
pubkey,
682+
event_id_bytes,
683+
auth_event_created_at,
684+
)
685+
.await;
655686

656687
match &outcome {
657688
SubmitOutcome::Ok { accepted, .. } => {
@@ -758,6 +789,7 @@ async fn submit_event_authed(
758789
body: &[u8],
759790
pubkey: nostr::PublicKey,
760791
event_id_bytes: [u8; 32],
792+
auth_event_created_at: Option<u64>,
761793
) -> SubmitOutcome {
762794
// Admission and replay checks fire before body parse — a 429 or replay
763795
// reject on a malformed body must still be attributed.
@@ -809,7 +841,23 @@ async fn submit_event_authed(
809841
)
810842
.await
811843
{
812-
Ok(owner) => super::relay_members::resolve_nip_oa_owner(owner, &pubkey_bytes, auth_tag),
844+
// Without a NIP-98 request event there is no signed timestamp to judge
845+
// the attestation's time bounds against (X-Pubkey dev auth), so no
846+
// ownership is recorded rather than treating the tag as unbounded.
847+
Ok(owner) => match auth_event_created_at {
848+
Some(created_at) => {
849+
super::relay_members::resolve_nip_oa_owner(
850+
state,
851+
tenant.community(),
852+
owner,
853+
&pubkey_bytes,
854+
auth_tag,
855+
created_at,
856+
)
857+
.await
858+
}
859+
None => None,
860+
},
813861
Err(e) => {
814862
return SubmitOutcome::Err {
815863
status: e.0,
@@ -899,7 +947,11 @@ pub async fn query_events(
899947
})?;
900948

901949
let url = nip98_expected_url(&state.config.relay_url, &tenant, "/query");
902-
let (pubkey, event_id_bytes) = verify_bridge_auth(
950+
let BridgeAuth {
951+
pubkey,
952+
event_id_bytes,
953+
..
954+
} = verify_bridge_auth(
903955
&headers,
904956
"POST",
905957
&url,
@@ -1342,7 +1394,11 @@ pub async fn count_events(
13421394
})?;
13431395

13441396
let url = nip98_expected_url(&state.config.relay_url, &tenant, "/count");
1345-
let (pubkey, event_id_bytes) = verify_bridge_auth(
1397+
let BridgeAuth {
1398+
pubkey,
1399+
event_id_bytes,
1400+
..
1401+
} = verify_bridge_auth(
13461402
&headers,
13471403
"POST",
13481404
&url,
@@ -2081,8 +2137,11 @@ async fn authorize_moderation_read(
20812137
_ => path.to_string(),
20822138
};
20832139
let url = nip98_expected_url(&state.config.relay_url, &tenant, &path_with_query);
2084-
let (pubkey, event_id_bytes) =
2085-
verify_bridge_auth(headers, "GET", &url, None, state.config.require_auth_token)?;
2140+
let BridgeAuth {
2141+
pubkey,
2142+
event_id_bytes,
2143+
..
2144+
} = verify_bridge_auth(headers, "GET", &url, None, state.config.require_auth_token)?;
20862145
check_nip98_replay(state, &tenant, event_id_bytes).await?;
20872146
let pubkey_bytes = pubkey.to_bytes().to_vec();
20882147

@@ -2544,7 +2603,7 @@ mod tests {
25442603
let tenant_a = fresh_tenant("host-a.example");
25452604
let expected_url = nip98_expected_url(config_relay_url, &tenant_a, "/events");
25462605

2547-
let (pubkey, _event_id_bytes) =
2606+
let BridgeAuth { pubkey, .. } =
25482607
verify_bridge_auth(&headers, "POST", &expected_url, Some(b""), true)
25492608
.expect("matching-host NIP-98 event must verify");
25502609
assert_eq!(
@@ -2593,7 +2652,7 @@ mod tests {
25932652
Some("limit=20&status=open"),
25942653
);
25952654

2596-
let (pubkey, _event_id_bytes) =
2655+
let BridgeAuth { pubkey, .. } =
25972656
verify_bridge_auth(&headers, "GET", &expected_url, None, true)
25982657
.expect("query-bearing moderation read must verify against the same query");
25992658
assert_eq!(pubkey, keys.public_key());
@@ -2650,7 +2709,7 @@ mod tests {
26502709
Some("limit=20"),
26512710
);
26522711

2653-
let (pubkey, _event_id_bytes) =
2712+
let BridgeAuth { pubkey, .. } =
26542713
verify_bridge_auth(&headers, "GET", &expected_url, None, true)
26552714
.expect("audit query-bearing read must verify");
26562715
assert_eq!(pubkey, keys.public_key());
@@ -2675,7 +2734,7 @@ mod tests {
26752734
);
26762735
assert_eq!(expected_url, "https://host-a.example/moderation/restricted");
26772736

2678-
let (pubkey, _event_id_bytes) =
2737+
let BridgeAuth { pubkey, .. } =
26792738
verify_bridge_auth(&headers, "GET", &expected_url, None, true)
26802739
.expect("query-less restricted read must verify against the bare path");
26812740
assert_eq!(pubkey, keys.public_key());

‎crates/buzz-relay/src/api/invites.rs‎

Lines changed: 5 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -247,7 +247,11 @@ async fn authenticate(
247247
})?;
248248

249249
let url = bridge::nip98_expected_url(&state.config.relay_url, &tenant, path);
250-
let (pubkey, event_id_bytes) = bridge::verify_bridge_auth_with_options(
250+
let bridge::BridgeAuth {
251+
pubkey,
252+
event_id_bytes,
253+
..
254+
} = bridge::verify_bridge_auth_with_options(
251255
headers,
252256
"POST",
253257
&url,

0 commit comments

Comments
 (0)