Skip to content

Commit 0820dea

Browse files
rmichelenaclaude
authored 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 491ddd1 commit 0820dea

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 @@ pub(crate) 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, kind, .. } => {
@@ -760,6 +791,7 @@ async fn submit_event_authed(
760791
body: &[u8],
761792
pubkey: nostr::PublicKey,
762793
event_id_bytes: [u8; 32],
794+
auth_event_created_at: Option<u64>,
763795
) -> SubmitOutcome {
764796
// Admission and replay checks fire before body parse — a 429 or replay
765797
// reject on a malformed body must still be attributed.
@@ -811,7 +843,23 @@ async fn submit_event_authed(
811843
)
812844
.await
813845
{
814-
Ok(owner) => super::relay_members::resolve_nip_oa_owner(owner, &pubkey_bytes, auth_tag),
846+
// Without a NIP-98 request event there is no signed timestamp to judge
847+
// the attestation's time bounds against (X-Pubkey dev auth), so no
848+
// ownership is recorded rather than treating the tag as unbounded.
849+
Ok(owner) => match auth_event_created_at {
850+
Some(created_at) => {
851+
super::relay_members::resolve_nip_oa_owner(
852+
state,
853+
tenant.community(),
854+
owner,
855+
&pubkey_bytes,
856+
auth_tag,
857+
created_at,
858+
)
859+
.await
860+
}
861+
None => None,
862+
},
815863
Err(e) => {
816864
return SubmitOutcome::Err {
817865
status: e.0,
@@ -902,7 +950,11 @@ pub async fn query_events(
902950
})?;
903951

904952
let url = nip98_expected_url(&state.config.relay_url, &tenant, "/query");
905-
let (pubkey, event_id_bytes) = verify_bridge_auth(
953+
let BridgeAuth {
954+
pubkey,
955+
event_id_bytes,
956+
..
957+
} = verify_bridge_auth(
906958
&headers,
907959
"POST",
908960
&url,
@@ -1389,7 +1441,11 @@ pub async fn count_events(
13891441
})?;
13901442

13911443
let url = nip98_expected_url(&state.config.relay_url, &tenant, "/count");
1392-
let (pubkey, event_id_bytes) = verify_bridge_auth(
1444+
let BridgeAuth {
1445+
pubkey,
1446+
event_id_bytes,
1447+
..
1448+
} = verify_bridge_auth(
13931449
&headers,
13941450
"POST",
13951451
&url,
@@ -2157,8 +2213,11 @@ async fn authorize_moderation_read(
21572213
_ => path.to_string(),
21582214
};
21592215
let url = nip98_expected_url(&state.config.relay_url, &tenant, &path_with_query);
2160-
let (pubkey, event_id_bytes) =
2161-
verify_bridge_auth(headers, "GET", &url, None, state.config.require_auth_token)?;
2216+
let BridgeAuth {
2217+
pubkey,
2218+
event_id_bytes,
2219+
..
2220+
} = verify_bridge_auth(headers, "GET", &url, None, state.config.require_auth_token)?;
21622221
check_nip98_replay(state, &tenant, event_id_bytes).await?;
21632222
let pubkey_bytes = pubkey.to_bytes().to_vec();
21642223

@@ -2620,7 +2679,7 @@ mod tests {
26202679
let tenant_a = fresh_tenant("host-a.example");
26212680
let expected_url = nip98_expected_url(config_relay_url, &tenant_a, "/events");
26222681

2623-
let (pubkey, _event_id_bytes) =
2682+
let BridgeAuth { pubkey, .. } =
26242683
verify_bridge_auth(&headers, "POST", &expected_url, Some(b""), true)
26252684
.expect("matching-host NIP-98 event must verify");
26262685
assert_eq!(
@@ -2669,7 +2728,7 @@ mod tests {
26692728
Some("limit=20&status=open"),
26702729
);
26712730

2672-
let (pubkey, _event_id_bytes) =
2731+
let BridgeAuth { pubkey, .. } =
26732732
verify_bridge_auth(&headers, "GET", &expected_url, None, true)
26742733
.expect("query-bearing moderation read must verify against the same query");
26752734
assert_eq!(pubkey, keys.public_key());
@@ -2726,7 +2785,7 @@ mod tests {
27262785
Some("limit=20"),
27272786
);
27282787

2729-
let (pubkey, _event_id_bytes) =
2788+
let BridgeAuth { pubkey, .. } =
27302789
verify_bridge_auth(&headers, "GET", &expected_url, None, true)
27312790
.expect("audit query-bearing read must verify");
27322791
assert_eq!(pubkey, keys.public_key());
@@ -2751,7 +2810,7 @@ mod tests {
27512810
);
27522811
assert_eq!(expected_url, "https://host-a.example/moderation/restricted");
27532812

2754-
let (pubkey, _event_id_bytes) =
2813+
let BridgeAuth { pubkey, .. } =
27552814
verify_bridge_auth(&headers, "GET", &expected_url, None, true)
27562815
.expect("query-less restricted read must verify against the bare path");
27572816
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)