Skip to content

Commit 2e6edd6

Browse files
committed
Harden NIP-OA credential verification
Signed-off-by: Jordan Mecom <[email protected]>
1 parent 51ad528 commit 2e6edd6

7 files changed

Lines changed: 143 additions & 91 deletions

File tree

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

Lines changed: 3 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -920,7 +920,7 @@ async fn submit_event_authed(
920920
};
921921

922922
// Enforce relay membership (with NIP-OA fallback via x-auth-tag header).
923-
let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok());
923+
let auth_tag = super::relay_members::extract_auth_tag_header(headers);
924924
let nip_oa_owner = match super::relay_members::enforce_relay_membership(
925925
state,
926926
tenant.community(),
@@ -1099,7 +1099,7 @@ async fn query_events_authed(
10991099
check_nip98_replay(state, tenant, event_id_bytes).await?;
11001100
let pubkey_bytes = pubkey.to_bytes().to_vec();
11011101

1102-
let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok());
1102+
let auth_tag = super::relay_members::extract_auth_tag_header(headers);
11031103
super::relay_members::enforce_relay_membership(
11041104
state,
11051105
tenant.community(),
@@ -1640,7 +1640,7 @@ async fn count_events_authed(
16401640
check_nip98_replay(state, tenant, event_id_bytes).await?;
16411641
let pubkey_bytes = pubkey.to_bytes().to_vec();
16421642

1643-
let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok());
1643+
let auth_tag = super::relay_members::extract_auth_tag_header(headers);
16441644
super::relay_members::enforce_relay_membership(
16451645
state,
16461646
tenant.community(),

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -156,9 +156,7 @@ async fn authenticate(
156156
state,
157157
tenant.community(),
158158
&pubkey.to_bytes(),
159-
headers
160-
.get("x-auth-tag")
161-
.and_then(|value| value.to_str().ok()),
159+
relay_members::extract_auth_tag_header(headers),
162160
signed_created_at,
163161
)
164162
.await?;

‎crates/buzz-relay/src/api/git/transport.rs‎

Lines changed: 1 addition & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -207,10 +207,7 @@ impl axum::extract::FromRequestParts<Arc<AppState>> for GitAuth {
207207
// attach their NIP-OA attestation to the signed NIP-98 event, matching
208208
// the WebSocket NIP-42 flow.
209209
let event_auth_tag = crate::handlers::auth::extract_auth_tag_json(&event);
210-
let header_auth_tag = parts
211-
.headers
212-
.get("x-auth-tag")
213-
.and_then(|value| value.to_str().ok());
210+
let header_auth_tag = crate::api::relay_members::extract_auth_tag_header(&parts.headers);
214211
let auth_tag = event_auth_tag.as_deref().or(header_auth_tag);
215212
if crate::api::relay_members::enforce_relay_membership(
216213
state,

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

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -208,7 +208,7 @@ impl FromRequestParts<Arc<AppState>> for AuthenticatedUpload {
208208
// storage and of `require_auth_token` (which governs the REST API, not
209209
// media). On open relays (membership disabled) any valid Blossom signer
210210
// may upload, matching the WS door's admission policy.
211-
let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok());
211+
let auth_tag = crate::api::relay_members::extract_auth_tag_header(headers);
212212
crate::api::relay_members::enforce_relay_membership(
213213
state,
214214
tenant.community(),
@@ -535,7 +535,7 @@ async fn authenticate_media_read(
535535
let sha256 = sha256_ext.split('.').next().unwrap_or(sha256_ext);
536536
buzz_media::auth::verify_blossom_get_auth(&auth_event, sha256, Some(tenant.host()), 3600)?;
537537

538-
let auth_tag = headers.get("x-auth-tag").and_then(|v| v.to_str().ok());
538+
let auth_tag = crate::api::relay_members::extract_auth_tag_header(headers);
539539
crate::api::relay_members::enforce_relay_membership(
540540
state,
541541
tenant.community(),

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

Lines changed: 29 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -37,7 +37,10 @@ pub(crate) fn not_found(msg: &str) -> (StatusCode, Json<serde_json::Value>) {
3737
/// Moved here from the deleted `relay_members` module. Called by `media.rs`, `bridge.rs`,
3838
/// `git/transport.rs`, and `audio/handler.rs`.
3939
pub mod relay_members {
40-
use axum::{http::StatusCode, response::Json};
40+
use axum::{
41+
http::{HeaderMap, StatusCode},
42+
response::Json,
43+
};
4144
use buzz_core::{tenant::CommunityId, TenantContext};
4245
use tracing::{debug, info};
4346

@@ -56,6 +59,18 @@ pub mod relay_members {
5659
Denied,
5760
}
5861

62+
/// Return the sole NIP-OA credential header, if one was supplied.
63+
///
64+
/// Repeated security-sensitive headers are ambiguous across HTTP stacks,
65+
/// so they are treated as no credential instead of silently selecting one.
66+
pub fn extract_auth_tag_header(headers: &HeaderMap) -> Option<&str> {
67+
let mut values = headers.get_all("x-auth-tag").iter();
68+
let (Some(value), None) = (values.next(), values.next()) else {
69+
return None;
70+
};
71+
value.to_str().ok()
72+
}
73+
5974
/// Check relay membership without committing to an HTTP response shape.
6075
///
6176
/// `community` is the server-resolved tenant of the request; membership is
@@ -262,9 +277,22 @@ pub mod relay_members {
262277
#[cfg(test)]
263278
mod tests {
264279
use super::*;
280+
use axum::http::{HeaderMap, HeaderValue};
265281
use buzz_sdk::nip_oa::compute_auth_tag;
266282
use nostr::Keys;
267283

284+
#[test]
285+
fn auth_tag_header_must_be_unique() {
286+
let mut headers = HeaderMap::new();
287+
assert_eq!(extract_auth_tag_header(&headers), None);
288+
289+
headers.insert("x-auth-tag", HeaderValue::from_static("credential-one"));
290+
assert_eq!(extract_auth_tag_header(&headers), Some("credential-one"));
291+
292+
headers.append("x-auth-tag", HeaderValue::from_static("credential-two"));
293+
assert_eq!(extract_auth_tag_header(&headers), None);
294+
}
295+
268296
/// Valid NIP-OA auth tag → returns Some(owner_pubkey).
269297
#[test]
270298
fn valid_nip_oa_returns_owner() {

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

Lines changed: 1 addition & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -71,9 +71,7 @@ async fn authorize_workflow_read(
7171
bridge::check_nip98_replay(state, &tenant, event_id_bytes).await?;
7272

7373
let pubkey_bytes = pubkey.to_bytes().to_vec();
74-
let auth_tag = headers
75-
.get("x-auth-tag")
76-
.and_then(|value| value.to_str().ok());
74+
let auth_tag = super::relay_members::extract_auth_tag_header(headers);
7775
super::relay_members::enforce_relay_membership(
7876
state,
7977
tenant.community(),

‎crates/buzz-sdk/src/nip_oa.rs‎

Lines changed: 106 additions & 75 deletions
Original file line numberDiff line numberDiff line change
@@ -165,22 +165,18 @@ pub fn compute_auth_tag(
165165
Ok(tag_json.to_string())
166166
}
167167

168-
/// Verify a NIP-OA `auth` tag JSON string against the given `agent_pubkey`.
169-
///
170-
/// Reconstructs the preimage, hashes it, and verifies the Schnorr signature
171-
/// against the owner pubkey embedded in the tag.
172-
///
173-
/// Returns the owner's [`PublicKey`] on success.
174-
///
175-
/// # Errors
176-
///
177-
/// Returns [`SdkError::InvalidInput`] for malformed JSON, wrong element count,
178-
/// bad hex, self-attestation, or signature verification failure.
179-
pub fn verify_auth_tag(
180-
auth_tag_json: &str,
181-
agent_pubkey: &PublicKey,
182-
) -> Result<PublicKey, SdkError> {
183-
let arr = parse_json_array(auth_tag_json)?;
168+
struct ParsedAuthTag {
169+
owner_pubkey_hex: String,
170+
conditions: String,
171+
sig_hex: String,
172+
}
173+
174+
/// Parse and validate the canonical wire representation shared by every
175+
/// verification path. Keeping this check in one place prevents the crypto
176+
/// verifier from accepting non-canonical values that the structural parser
177+
/// rejects.
178+
fn parse_auth_tag_fields(json_str: &str) -> Result<ParsedAuthTag, SdkError> {
179+
let arr = parse_json_array(json_str)?;
184180

185181
if arr.len() != 4 {
186182
return Err(SdkError::InvalidInput(format!(
@@ -201,28 +197,51 @@ pub fn verify_auth_tag(
201197
let owner_pubkey_hex = arr[1].as_str().ok_or_else(|| {
202198
SdkError::InvalidInput("element 1 (owner pubkey) must be a string".into())
203199
})?;
200+
if owner_pubkey_hex.len() != 64 || !owner_pubkey_hex.chars().all(is_lowercase_hex) {
201+
return Err(SdkError::InvalidInput(format!(
202+
"owner pubkey must be 64 lowercase hex chars, got {:?}",
203+
owner_pubkey_hex
204+
)));
205+
}
206+
204207
let conditions = arr[2]
205208
.as_str()
206209
.ok_or_else(|| SdkError::InvalidInput("element 2 (conditions) must be a string".into()))?;
210+
validate_conditions(conditions)?;
211+
207212
let sig_hex = arr[3]
208213
.as_str()
209214
.ok_or_else(|| SdkError::InvalidInput("element 3 (signature) must be a string".into()))?;
215+
if sig_hex.len() != 128 || !sig_hex.chars().all(is_lowercase_hex) {
216+
return Err(SdkError::InvalidInput(format!(
217+
"signature must be 128 lowercase hex chars, got length {}",
218+
sig_hex.len()
219+
)));
220+
}
210221

211-
let owner_pubkey = PublicKey::from_hex(owner_pubkey_hex)
212-
.map_err(|e| SdkError::InvalidInput(format!("invalid owner pubkey: {e}")))?;
222+
Ok(ParsedAuthTag {
223+
owner_pubkey_hex: owner_pubkey_hex.to_owned(),
224+
conditions: conditions.to_owned(),
225+
sig_hex: sig_hex.to_owned(),
226+
})
227+
}
213228

214-
validate_conditions(conditions)?;
229+
fn verify_parsed_auth_tag(
230+
parsed: &ParsedAuthTag,
231+
agent_pubkey: &PublicKey,
232+
) -> Result<PublicKey, SdkError> {
233+
let owner_pubkey = PublicKey::from_hex(&parsed.owner_pubkey_hex)
234+
.map_err(|e| SdkError::InvalidInput(format!("invalid owner pubkey: {e}")))?;
215235

216236
if owner_pubkey == *agent_pubkey {
217237
return Err(SdkError::InvalidInput(
218238
"owner and agent pubkeys must differ (self-attestation rejected)".into(),
219239
));
220240
}
221241

222-
let sig = Signature::from_str(sig_hex)
242+
let sig = Signature::from_str(&parsed.sig_hex)
223243
.map_err(|e| SdkError::InvalidInput(format!("invalid signature hex: {e}")))?;
224-
225-
let preimage = build_preimage(agent_pubkey, conditions);
244+
let preimage = build_preimage(agent_pubkey, &parsed.conditions);
226245
let message = hash_preimage(&preimage);
227246

228247
let xonly = owner_pubkey.xonly().map_err(|e| {
@@ -235,6 +254,25 @@ pub fn verify_auth_tag(
235254
Ok(owner_pubkey)
236255
}
237256

257+
/// Verify a NIP-OA `auth` tag JSON string against the given `agent_pubkey`.
258+
///
259+
/// Reconstructs the preimage, hashes it, and verifies the Schnorr signature
260+
/// against the owner pubkey embedded in the tag.
261+
///
262+
/// Returns the owner's [`PublicKey`] on success.
263+
///
264+
/// # Errors
265+
///
266+
/// Returns [`SdkError::InvalidInput`] for malformed JSON, wrong element count,
267+
/// bad hex, self-attestation, or signature verification failure.
268+
pub fn verify_auth_tag(
269+
auth_tag_json: &str,
270+
agent_pubkey: &PublicKey,
271+
) -> Result<PublicKey, SdkError> {
272+
let parsed = parse_auth_tag_fields(auth_tag_json)?;
273+
verify_parsed_auth_tag(&parsed, agent_pubkey)
274+
}
275+
238276
/// Verify a NIP-OA credential for relay admission at a signed auth event.
239277
///
240278
/// This performs the normal signature and syntax checks, then evaluates every
@@ -253,13 +291,10 @@ pub fn verify_auth_tag_for_auth_event(
253291
agent_pubkey: &PublicKey,
254292
auth_event_created_at: u64,
255293
) -> Result<PublicKey, SdkError> {
256-
let owner_pubkey = verify_auth_tag(auth_tag_json, agent_pubkey)?;
257-
let arr = parse_json_array(auth_tag_json)?;
258-
let conditions = arr[2]
259-
.as_str()
260-
.ok_or_else(|| SdkError::InvalidInput("element 2 (conditions) must be a string".into()))?;
294+
let parsed = parse_auth_tag_fields(auth_tag_json)?;
295+
let owner_pubkey = verify_parsed_auth_tag(&parsed, agent_pubkey)?;
261296

262-
for clause in conditions.split('&') {
297+
for clause in parsed.conditions.split('&') {
263298
let satisfied = if let Some(value) = clause.strip_prefix("created_at<") {
264299
let bound = value
265300
.parse::<u64>()
@@ -299,52 +334,14 @@ pub fn verify_auth_tag_for_auth_event(
299334
///
300335
/// Returns [`SdkError::InvalidInput`] for any structural violation.
301336
pub fn parse_auth_tag(json_str: &str) -> Result<Tag, SdkError> {
302-
let arr = parse_json_array(json_str)?;
303-
304-
if arr.len() != 4 {
305-
return Err(SdkError::InvalidInput(format!(
306-
"auth tag must have 4 elements, got {}",
307-
arr.len()
308-
)));
309-
}
310-
311-
let label = arr[0]
312-
.as_str()
313-
.ok_or_else(|| SdkError::InvalidInput("element 0 must be a string".into()))?;
314-
if label != "auth" {
315-
return Err(SdkError::InvalidInput(format!(
316-
"first element must be \"auth\", got \"{label}\""
317-
)));
318-
}
319-
320-
let owner_pubkey_hex = arr[1].as_str().ok_or_else(|| {
321-
SdkError::InvalidInput("element 1 (owner pubkey) must be a string".into())
322-
})?;
323-
if owner_pubkey_hex.len() != 64 || !owner_pubkey_hex.chars().all(is_lowercase_hex) {
324-
return Err(SdkError::InvalidInput(format!(
325-
"owner pubkey must be 64 hex chars, got {:?}",
326-
owner_pubkey_hex
327-
)));
328-
}
329-
330-
let conditions = arr[2]
331-
.as_str()
332-
.ok_or_else(|| SdkError::InvalidInput("element 2 (conditions) must be a string".into()))?;
333-
334-
validate_conditions(conditions)?;
335-
336-
let sig_hex = arr[3]
337-
.as_str()
338-
.ok_or_else(|| SdkError::InvalidInput("element 3 (signature) must be a string".into()))?;
339-
if sig_hex.len() != 128 || !sig_hex.chars().all(is_lowercase_hex) {
340-
return Err(SdkError::InvalidInput(format!(
341-
"signature must be 128 hex chars, got length {}",
342-
sig_hex.len()
343-
)));
344-
}
345-
346-
Tag::parse(["auth", owner_pubkey_hex, conditions, sig_hex])
347-
.map_err(|e| SdkError::InvalidInput(format!("failed to construct Tag: {e}")))
337+
let parsed = parse_auth_tag_fields(json_str)?;
338+
Tag::parse([
339+
"auth",
340+
&parsed.owner_pubkey_hex,
341+
&parsed.conditions,
342+
&parsed.sig_hex,
343+
])
344+
.map_err(|e| SdkError::InvalidInput(format!("failed to construct Tag: {e}")))
348345
}
349346

350347
#[cfg(test)]
@@ -461,6 +458,32 @@ mod tests {
461458
assert!(verify_auth_tag(&wrong_sig, &agent_pubkey).is_err());
462459
}
463460

461+
#[test]
462+
fn test_verify_rejects_noncanonical_hex() {
463+
let owner_keys = Keys::generate();
464+
let agent_pubkey = Keys::generate().public_key();
465+
let tag_json = compute_auth_tag(&owner_keys, &agent_pubkey, "")
466+
.expect("compute_auth_tag must succeed");
467+
let mut tag: Value = serde_json::from_str(&tag_json).expect("auth tag is valid JSON");
468+
469+
tag[1] = Value::String(owner_keys.public_key().to_hex().to_uppercase());
470+
assert!(
471+
verify_auth_tag(&tag.to_string(), &agent_pubkey).is_err(),
472+
"uppercase owner pubkeys must not reach the permissive hex decoder"
473+
);
474+
475+
let mut tag: Value = serde_json::from_str(&tag_json).expect("auth tag is valid JSON");
476+
let uppercase_sig = tag[3]
477+
.as_str()
478+
.expect("signature is a string")
479+
.to_uppercase();
480+
tag[3] = Value::String(uppercase_sig);
481+
assert!(
482+
verify_auth_tag(&tag.to_string(), &agent_pubkey).is_err(),
483+
"uppercase signatures must not reach the permissive hex decoder"
484+
);
485+
}
486+
464487
/// parse_auth_tag with a well-formed JSON array returns a Tag.
465488
#[test]
466489
fn test_parse_auth_tag_valid() {
@@ -640,14 +663,22 @@ mod tests {
640663
let owner_keys = Keys::generate();
641664
let agent_pubkey = Keys::generate().public_key();
642665

643-
let expired = compute_auth_tag(&owner_keys, &agent_pubkey, "created_at<200")
666+
let expired = compute_auth_tag(&owner_keys, &agent_pubkey, "created_at<1")
644667
.expect("sign expired credential");
645668
assert!(verify_auth_tag_for_auth_event(&expired, &agent_pubkey, 200).is_err());
646669

647670
let not_yet_valid = compute_auth_tag(&owner_keys, &agent_pubkey, "created_at>200")
648671
.expect("sign future credential");
649672
assert!(verify_auth_tag_for_auth_event(&not_yet_valid, &agent_pubkey, 200).is_err());
650673

674+
let failed_second_clause =
675+
compute_auth_tag(&owner_keys, &agent_pubkey, "created_at<201&created_at<200")
676+
.expect("sign credential with two upper bounds");
677+
assert!(
678+
verify_auth_tag_for_auth_event(&failed_second_clause, &agent_pubkey, 200).is_err(),
679+
"every clause must pass, even when an earlier clause succeeds"
680+
);
681+
651682
let in_window = compute_auth_tag(
652683
&owner_keys,
653684
&agent_pubkey,

0 commit comments

Comments
 (0)