diff --git a/Justfile b/Justfile index eb6c3020a3..35a97012b6 100644 --- a/Justfile +++ b/Justfile @@ -632,6 +632,7 @@ test-unit: + test(=state::tests::nip_fi_disconnect_does_not_close_different_pubkey_audio_socket) + test(=state::tests::nip_fi_disconnect_does_not_close_unproven_audio_socket) + test(=state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason) + + test(=state::tests::enforce_end_is_recorded_only_by_the_winning_terminal) + test(=state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame) + test(=state::tests::manager_disconnect_sets_reason_enqueues_frame_then_cancels) + test(/^api::nip_fi::/)' diff --git a/crates/buzz-db/src/store/moderation.rs b/crates/buzz-db/src/store/moderation.rs index 0452a51a8c..f47cc083c8 100644 --- a/crates/buzz-db/src/store/moderation.rs +++ b/crates/buzz-db/src/store/moderation.rs @@ -614,6 +614,8 @@ pub async fn untimeout_member( pub struct RestrictionState { /// Currently banned (row exists, `banned`, unexpired). pub banned: bool, + /// Banned by the key's own row, not only its agent owner's. + pub own_banned: bool, /// Active timeout expiry, if in the future. pub muted_until: Option>, } @@ -639,6 +641,8 @@ pub async fn restriction_state( SELECT COALESCE(bool_or(banned AND (ban_expires_at IS NULL OR ban_expires_at > now())), false) AS banned, + COALESCE(bool_or(pubkey = $2 AND banned AND (ban_expires_at IS NULL OR ban_expires_at > now())), false) + AS own_banned, max(CASE WHEN muted_until > now() THEN muted_until END) AS muted_until FROM community_bans WHERE community_id = $1 @@ -657,6 +661,7 @@ pub async fn restriction_state( Ok(RestrictionState { banned: row.try_get("banned")?, + own_banned: row.try_get("own_banned")?, muted_until: row.try_get("muted_until")?, }) } diff --git a/crates/buzz-relay/src/api/bridge.rs b/crates/buzz-relay/src/api/bridge.rs index 3c6320e044..e65b517f43 100644 --- a/crates/buzz-relay/src/api/bridge.rs +++ b/crates/buzz-relay/src/api/bridge.rs @@ -1013,21 +1013,23 @@ pub async fn submit_event( // NIP-FI admission: NIP-98 extraction runs inside the closure, followed by // assertion verify → pair → deny-map in fixed order. The proven pubkey is // only available through the returned NipFiAdmission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "bridge", || { verify_bridge_auth_with_options(&headers, "POST", &url, Some(&body), true, true).map(drop) }) .await; let admission = admit_nip_fi_http_on_state(&state, &headers, || { - verify_bridge_auth_with_options( - &headers, - "POST", - &url, - Some(&body), - state.config.require_auth_token || nip_fi_active, - nip_fi_enforce, - ) - .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) - .map_err(|e| e.into_response()) + proof + .record(verify_bridge_auth_with_options( + &headers, + "POST", + &url, + Some(&body), + state.config.require_auth_token || nip_fi_active, + nip_fi_enforce, + )) + .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) + .map_err(|e| e.into_response()) }) .await?; let pubkey = *admission.proven_pubkey(); @@ -1271,15 +1273,25 @@ async fn submit_event_authed( // token-less request, keeps its existing response. let result = match result { Err(IngestError::Ban { refusal, .. }) if token_owner.is_some() => { + use crate::handlers::{auth::BanSource, ingest::BanRefusal}; crate::handlers::ingest::reject_with_transport("http", "auth"); - let refusal = MembershipRefusal::NipFi(match refusal { - crate::handlers::ingest::BanRefusal::Banned => { - buzz_auth::DenialClass::AuthorizationDenied + let class = match refusal { + BanRefusal::Banned(_) => buzz_auth::DenialClass::AuthorizationDenied, + BanRefusal::Unavailable => buzz_auth::DenialClass::AuthorizationUnavailable, + }; + // An owner-decided late refusal is the request's verdict, not its + // earlier admit. The agent's own ban is not its owner's, as at + // every other seam. + match refusal { + BanRefusal::Banned(BanSource::Owner) => { + crate::nip_fi_http::owner_refused(class, "owner_banned"); } - crate::handlers::ingest::BanRefusal::Unavailable => { - buzz_auth::DenialClass::AuthorizationUnavailable + BanRefusal::Unavailable => { + crate::nip_fi_http::owner_refused(class, "owner_ban_unavailable"); } - }); + BanRefusal::Banned(BanSource::Own) => {} + } + let refusal = MembershipRefusal::NipFi(class); return SubmitOutcome::Err { status: refusal.status(), response: refusal, @@ -1390,21 +1402,23 @@ pub async fn query_events( let nip_fi_enforce = state.config.nip_fi.mode.enforces(); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "bridge", || { verify_bridge_auth_with_options(&headers, "POST", &url, Some(&body), true, true).map(drop) }) .await; let admission = admit_nip_fi_http_on_state(&state, &headers, || { - verify_bridge_auth_with_options( - &headers, - "POST", - &url, - Some(&body), - state.config.require_auth_token || nip_fi_active, - nip_fi_enforce, - ) - .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) - .map_err(|e| e.into_response()) + proof + .record(verify_bridge_auth_with_options( + &headers, + "POST", + &url, + Some(&body), + state.config.require_auth_token || nip_fi_active, + nip_fi_enforce, + )) + .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) + .map_err(|e| e.into_response()) }) .await?; let pubkey = *admission.proven_pubkey(); @@ -2088,21 +2102,23 @@ pub async fn count_events( let nip_fi_enforce = state.config.nip_fi.mode.enforces(); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "bridge", || { verify_bridge_auth_with_options(&headers, "POST", &url, Some(&body), true, true).map(drop) }) .await; let admission = admit_nip_fi_http_on_state(&state, &headers, || { - verify_bridge_auth_with_options( - &headers, - "POST", - &url, - Some(&body), - state.config.require_auth_token || nip_fi_active, - nip_fi_enforce, - ) - .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) - .map_err(|e| e.into_response()) + proof + .record(verify_bridge_auth_with_options( + &headers, + "POST", + &url, + Some(&body), + state.config.require_auth_token || nip_fi_active, + nip_fi_enforce, + )) + .map(|auth| auth.proof((auth.event_id_bytes, auth.signed_created_at))) + .map_err(|e| e.into_response()) }) .await?; let pubkey = *admission.proven_pubkey(); @@ -2952,20 +2968,22 @@ async fn authorize_moderation_read( let nip_fi_active = state.config.nip_fi.mode.restricts(); // NIP-FI admission. [FI-TRACE-AUTHORITY-UNIFORM] + let proof = crate::nip_fi_shadow::EnforcedProof::new(state, headers, "bridge"); crate::nip_fi_shadow::observe_strict_proof(state, headers, "bridge", || { verify_bridge_auth(headers, "GET", &url, None, true).map(drop) }) .await; let admission = admit_nip_fi_http_on_state(state, headers, || { - verify_bridge_auth( - headers, - "GET", - &url, - None, - state.config.require_auth_token || nip_fi_active, - ) - .map(|auth| auth.proof(auth.event_id_bytes)) - .map_err(|e| e.into_response()) + proof + .record(verify_bridge_auth( + headers, + "GET", + &url, + None, + state.config.require_auth_token || nip_fi_active, + )) + .map(|auth| auth.proof(auth.event_id_bytes)) + .map_err(|e| e.into_response()) }) .await?; let pubkey = *admission.proven_pubkey(); @@ -6744,7 +6762,13 @@ pub(crate) mod postgres_tests { format!("Nostr {}", B64.encode(event.as_json().as_bytes())) }; - for owner_banned in [true, false] { + // (case, the owner refusal reason it gives every route) + for (case, reason) in [ + ("owner_banned", Some("owner_banned")), + ("conflict", Some("not_stored_owner")), + ("clear", None), + ] { + let owner_banned = reason.is_some(); let host = format!("owner-routes-{}.local", uuid::Uuid::new_v4().simple()); let community = state .db @@ -6767,7 +6791,22 @@ pub(crate) mod postgres_tests { .map(|write| write.outcome) .expect("add member"); } - if owner_banned { + if case == "conflict" { + let other = Keys::generate().public_key(); + for key in [agent.public_key(), other] { + state + .db + .ensure_user(community, key.as_bytes()) + .await + .expect("ensure user"); + } + assert!(state + .db + .set_agent_owner(community, agent.public_key().as_bytes(), other.as_bytes()) + .await + .expect("seed another stored owner")); + } + if case == "owner_banned" { let owner_bytes = owner.public_key().to_bytes(); state .db @@ -6930,8 +6969,30 @@ pub(crate) mod postgres_tests { .parse() .expect("assertion header"), ); - let (status, headers, body) = - oneshot_request_full(state.clone(), method, &path, &host, headers, &body).await; + let ((status, headers, body), records, lines) = + crate::nip_fi_shadow::tests::enforce_records_during(oneshot_request_full( + state.clone(), + method, + &path, + &host, + headers, + &body, + )) + .await; + // One request, one enforce verdict, whatever its path and + // however many owner rechecks it runs. + let expected = if owner_banned { + "http owner/denied" + } else { + "http admit/admit" + }; + assert_eq!(records, [expected], "{case} {method} {path}: {lines:?}"); + if let Some(reason) = reason { + assert!( + lines.len() == 1 && lines[0].contains(&format!("reason=\"{reason}\"")), + "{case} {method} {path}: {lines:?}" + ); + } let denied = status == StatusCode::FORBIDDEN && headers .get(header::CONTENT_TYPE) @@ -6958,7 +7019,7 @@ pub(crate) mod postgres_tests { use crate::nip_fi_test_hooks::http_ban_recheck_hook::arm; use axum::http::{header, StatusCode}; - for case in ["banned", "unavailable"] { + for case in ["banned", "owner_banned", "unavailable"] { for route in ["buzz_v1", "git_settings"] { let fixture = nip_fi_enforce_test_state().await.expect("local Postgres"); let mut state = (*fixture).clone(); @@ -6998,6 +7059,10 @@ pub(crate) mod postgres_tests { db.ban_community_member(community, &agent_bytes, &owner_bytes, None, None) .await .expect("ban agent"); + } else if case == "owner_banned" { + db.ban_community_member(community, &owner_bytes, &owner_bytes, None, None) + .await + .expect("ban owner"); } else { db.pool().close().await; } @@ -7016,12 +7081,35 @@ pub(crate) mod postgres_tests { .parse() .expect("assertion header"), ); - let (status, headers, body) = - oneshot_request_full(state.clone(), "GET", &path, &host, headers, b"").await; + let ((status, headers, body), records, lines) = + crate::nip_fi_shadow::tests::enforce_records_during(oneshot_request_full( + state.clone(), + "GET", + &path, + &host, + headers, + b"", + )) + .await; refuse.await.expect("refusal task"); + // The reread's refusal is the request's one verdict: an + // unreadable ban state is the owner step's, as shadow records + // it; the agent's own ban is not an owner refusal. + let (expected, reason) = match case { + "banned" => ("http admit/admit", None), + "owner_banned" => ("http owner/denied", Some("owner_banned")), + _ => ("http owner/unavailable", Some("owner_ban_unavailable")), + }; + assert_eq!(records, [expected], "{case} {route}: {lines:?}"); + if let Some(reason) = reason { + assert!( + lines.len() == 1 && lines[0].contains(&format!("reason=\"{reason}\"")), + "{case} {route}: {lines:?}" + ); + } let (expected_status, expected_body) = match case { - "banned" => (StatusCode::FORBIDDEN, "authorization denied\n"), + "banned" | "owner_banned" => (StatusCode::FORBIDDEN, "authorization denied\n"), _ => ( StatusCode::SERVICE_UNAVAILABLE, "authorization unavailable\n", @@ -7066,15 +7154,17 @@ pub(crate) mod postgres_tests { // (check, kind, refusal, token): refusal is "banned", "unavailable" // or "timeout"; token-less rows publish as the member owner. let mut cases = Vec::new(); + // `who`: whose row a ban lands on, the agent's, its owner's or both. for check in ["write", "typing", "moderation", "relay_admin"] { - for refusal in ["banned", "unavailable"] { - cases.push((check, refusal, true)); + for who in ["agent", "owner", "both"] { + cases.push((check, "banned", who, true)); } - cases.push((check, "banned", false)); + cases.push((check, "unavailable", "agent", true)); + cases.push((check, "banned", "agent", false)); } - cases.push(("write", "timeout", true)); + cases.push(("write", "timeout", "agent", true)); - for (check, refusal, token) in cases { + for (check, refusal, who, token) in cases { let fixture = nip_fi_enforce_test_state().await.expect("local Postgres"); let mut state = (*fixture).clone(); let config = Arc::make_mut(&mut state.config); @@ -7135,14 +7225,23 @@ pub(crate) mod postgres_tests { let state = state.clone(); let target = author.public_key().to_bytes(); let actor = owner.public_key().to_bytes(); + // Without a token the author is the owner, so `agent` bans it. + let banned = match who { + "agent" => vec![target], + "owner" => vec![actor], + _ => vec![target, actor], + }; tokio::spawn(async move { arrived.await.expect("ban check reached"); if refusal == "banned" { - state - .db - .ban_community_member(community, &target, &actor, None, None) - .await - .expect("ban"); + for key in banned { + state + .db + .ban_community_member(community, &key, &actor, None, None) + .await + .expect("ban"); + state.invalidate_restriction_cache(community, &key); + } state.invalidate_restriction_cache(community, &target); } else { state.invalidate_restriction_cache(community, &target); @@ -7181,8 +7280,16 @@ pub(crate) mod postgres_tests { .expect("assertion header"), ); } - let (status, headers, body) = - oneshot_request_full(state.clone(), "POST", "/events", &host, headers, &body).await; + let ((status, headers, body), records, _) = + crate::nip_fi_shadow::tests::enforce_records_during(oneshot_request_full( + state.clone(), + "POST", + "/events", + &host, + headers, + &body, + )) + .await; if let Some(refuse) = refuse { tokio::time::timeout(std::time::Duration::from_secs(10), refuse) .await @@ -7194,7 +7301,19 @@ pub(crate) mod postgres_tests { let content_type = headers[header::CONTENT_TYPE].to_str().unwrap_or_default(); let body = std::str::from_utf8(&body).expect("utf-8 body"); - let case = format!("{check} {refusal} token={token}"); + let case = format!("{check} {refusal} {who} token={token}"); + // A late owner-decided token refusal is the request's one verdict, + // never an admit. The agent's own ban, alone or with its owner's, + // is not its owner's refusal, as at every other seam. + let expected = match (refusal, who, token) { + ("banned", "owner", true) => Some("http owner/denied"), + ("banned", _, true) => Some("http admit/admit"), + ("unavailable", _, true) => Some("http owner/unavailable"), + _ => None, + }; + if let Some(expected) = expected { + assert_eq!(records, [expected], "{case}"); + } match (refusal, token) { ("banned", true) => assert_eq!( (status, content_type, body), diff --git a/crates/buzz-relay/src/api/buzz_v1/auth.rs b/crates/buzz-relay/src/api/buzz_v1/auth.rs index 920221d856..9406f1150e 100644 --- a/crates/buzz-relay/src/api/buzz_v1/auth.rs +++ b/crates/buzz-relay/src/api/buzz_v1/auth.rs @@ -171,8 +171,17 @@ pub(super) async fn recheck( .db .moderation_restriction_state(principal.tenant.community(), &principal.actor.to_bytes()) .await - .map_err(|_| refuse(DenialClass::AuthorizationUnavailable, Error::unavailable()))?; + .map_err(|_| { + crate::nip_fi_http::owner_refused( + DenialClass::AuthorizationUnavailable, + "owner_ban_unavailable", + ); + refuse(DenialClass::AuthorizationUnavailable, Error::unavailable()) + })?; if restrictions.banned { + if !restrictions.own_banned { + crate::nip_fi_http::owner_refused(DenialClass::AuthorizationDenied, "owner_banned"); + } return Err(refuse( DenialClass::AuthorizationDenied, Error::new(StatusCode::FORBIDDEN, "forbidden"), diff --git a/crates/buzz-relay/src/api/git/transport.rs b/crates/buzz-relay/src/api/git/transport.rs index 0df9101bc0..6da1712d50 100644 --- a/crates/buzz-relay/src/api/git/transport.rs +++ b/crates/buzz-relay/src/api/git/transport.rs @@ -285,18 +285,26 @@ impl axum::extract::FromRequestParts> for GitAuth { match link_agent_owner(state, &tenant, &pubkey, &owner).await { OwnerLink::Linked => {} OwnerLink::Conflict => { + crate::nip_fi_http::owner_refused( + buzz_auth::DenialClass::AuthorizationDenied, + "not_stored_owner", + ); return Err(crate::nip_fi_core::http_denial( buzz_auth::DenialClass::AuthorizationDenied, - )) + )); } OwnerLink::Unavailable => { + crate::nip_fi_http::owner_refused( + buzz_auth::DenialClass::AuthorizationUnavailable, + "owner_link_unavailable", + ); return Err(unavailable( ( StatusCode::SERVICE_UNAVAILABLE, crate::handlers::auth::OWNER_LINK_ERROR, ) .into_response(), - )) + )); } } } @@ -324,7 +332,24 @@ pub(super) async fn deny_banned_git_principal( signed_auth_created_at: Option, token_owner: Option, ) -> Result<(), Response> { - let agent = git_restriction_state(db, community, pubkey).await?; + // A verified agent token's ban state is its owner step: an unreadable + // ban state or a banned token owner is that step's refusal, as shadow + // records it. + let owner_refused = |class, reason| { + if token_owner.is_some() { + crate::nip_fi_http::owner_refused(class, reason); + } + }; + let unavailable = |denial| { + owner_refused( + buzz_auth::DenialClass::AuthorizationUnavailable, + "owner_ban_unavailable", + ); + denial + }; + let agent = git_restriction_state(db, community, pubkey) + .await + .map_err(unavailable)?; // Skip the owner read when the agent is already banned: the denial is // identical either way. Mirrors the WebSocket cascade's short-circuit. @@ -340,11 +365,20 @@ pub(super) async fn deny_banned_git_principal( }) }; let owner_state = match owner { - Some(owner) => Some(git_restriction_state(db, community, &owner).await?), + Some(owner) => Some( + git_restriction_state(db, community, &owner) + .await + .map_err(unavailable)?, + ), None => None, }; enforce_git_ban_cascade(&agent, owner_state.as_ref()).map_err(|status| { + // The agent's own ban is not its owner's; a ban inherited from its + // stored owner, or its token owner's, is. + if !agent.own_banned { + owner_refused(buzz_auth::DenialClass::AuthorizationDenied, "owner_banned"); + } warn!( pubkey = %pubkey.to_hex(), owner = ?owner.map(|owner| owner.to_hex()), @@ -3379,6 +3413,7 @@ mod sec005_postgres_tests { fn durable_ban_denies_git_even_with_otherwise_valid_auth() { let restriction = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; @@ -3389,6 +3424,7 @@ mod sec005_postgres_tests { fn timeout_without_ban_does_not_revoke_git_access() { let restriction = buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(chrono::Utc::now()), }; @@ -3398,6 +3434,7 @@ mod sec005_postgres_tests { fn restriction(banned: bool) -> buzz_db::moderation::RestrictionState { buzz_db::moderation::RestrictionState { banned, + own_banned: banned, muted_until: None, } } diff --git a/crates/buzz-relay/src/api/media.rs b/crates/buzz-relay/src/api/media.rs index e86f37a497..904ea9d7a2 100644 --- a/crates/buzz-relay/src/api/media.rs +++ b/crates/buzz-relay/src/api/media.rs @@ -333,6 +333,7 @@ pub(crate) async fn upload_blob( // as the read path. [FI-TRACE-AUTHORITY-UNIFORM] let strictness = blossom_strictness_from_state(&state); let tenant_host = ctx.tenant.host().to_owned(); + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "blossom"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "blossom", || { let event = extract_blossom_auth(&headers).map_err(drop)?; let strict = BlossomStrictness::Strict; @@ -342,10 +343,17 @@ pub(crate) async fn upload_blob( .await; let headers_clone = headers.clone(); let admission = match admit_nip_fi_http_on_state(&state, &headers, move || { - let auth_event = extract_blossom_auth(&headers_clone).map_err(|e| e.into_response())?; // Pre-body check: freshness, cardinality, and server tag. The x-tag // hash binding is checked after body completion. - buzz_media::auth::verify_blossom_auth_event(&auth_event, Some(&tenant_host), strictness) + let auth_event = proof + .record(extract_blossom_auth(&headers_clone).and_then(|auth_event| { + buzz_media::auth::verify_blossom_auth_event( + &auth_event, + Some(&tenant_host), + strictness, + ) + .map(|()| auth_event) + })) .map_err(|e| e.into_response())?; let pubkey = auth_event.pubkey; Ok(Nip98Proof::new(pubkey, auth_event)) @@ -817,6 +825,7 @@ pub(crate) async fn get_blob( // In Enforce mode: extraction failure → NIP-FI denial bytes (MissingEvidence/ // EvidenceRejected). In Off mode: MediaError propagates unchanged [FI-INV-15]. use crate::nip_fi_http::admit_nip_fi_http_on_state; + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &req_headers, "blossom"); crate::nip_fi_shadow::observe_strict_proof(&state, &req_headers, "blossom", || { extract_blossom_read_proof( &req_headers, @@ -828,7 +837,13 @@ pub(crate) async fn get_blob( }) .await; let admission = match admit_nip_fi_http_on_state(&state, &req_headers, move || { - extract_blossom_read_proof(&headers_clone, &sha256, &tenant_host, strictness) + proof + .record(extract_blossom_read_proof( + &headers_clone, + &sha256, + &tenant_host, + strictness, + )) .map_err(|e| e.into_response()) }) .await @@ -1128,13 +1143,20 @@ pub(crate) async fn head_blob( let tenant_host = tenant.host().to_owned(); let headers_clone = headers.clone(); use crate::nip_fi_http::admit_nip_fi_http_on_state; + let proof = crate::nip_fi_shadow::EnforcedProof::new(&state, &headers, "blossom"); crate::nip_fi_shadow::observe_strict_proof(&state, &headers, "blossom", || { extract_blossom_read_proof(&headers, &sha256, &tenant_host, BlossomStrictness::Strict) .map(drop) }) .await; let admission = match admit_nip_fi_http_on_state(&state, &headers, move || { - extract_blossom_read_proof(&headers_clone, &sha256, &tenant_host, strictness) + proof + .record(extract_blossom_read_proof( + &headers_clone, + &sha256, + &tenant_host, + strictness, + )) .map_err(|e| e.into_response()) }) .await diff --git a/crates/buzz-relay/src/api/mod.rs b/crates/buzz-relay/src/api/mod.rs index eb37c91814..a446216afc 100644 --- a/crates/buzz-relay/src/api/mod.rs +++ b/crates/buzz-relay/src/api/mod.rs @@ -345,7 +345,7 @@ pub mod relay_members { signed_auth_created_at: Option, token_owner: Option, ) -> Result, MembershipRefusal> { - admit_member( + let result = admit_member( state, tenant, pubkey_bytes, @@ -353,16 +353,30 @@ pub mod relay_members { signed_auth_created_at, token_owner, ) - .await - .map_err(|refusal| match token_owner { + .await; + // An agent token's owner-decided refusal is its request's NIP-FI + // verdict, as shadow's verdict includes it. + if let (Some(_), Err((refusal, Some(reason)))) = (token_owner, &result) { + crate::nip_fi_http::owner_refused(refusal_class(refusal.0), reason); + } + result.map_err(|(refusal, _)| match token_owner { None => MembershipRefusal::Api(refusal), - Some(_) if refusal.0.is_server_error() => { - MembershipRefusal::NipFi(DenialClass::AuthorizationUnavailable) - } - Some(_) => MembershipRefusal::NipFi(DenialClass::AuthorizationDenied), + Some(_) => MembershipRefusal::NipFi(refusal_class(refusal.0)), }) } + fn refusal_class(status: StatusCode) -> DenialClass { + if status.is_server_error() { + DenialClass::AuthorizationUnavailable + } else { + DenialClass::AuthorizationDenied + } + } + + /// A membership refusal, with shadow's `owner` reason when the agent + /// token's owner decided it. + type Refused = ((StatusCode, Json), Option<&'static str>); + async fn admit_member( state: &AppState, tenant: &TenantContext, @@ -370,7 +384,7 @@ pub mod relay_members { auth_tag_header: Option<&str>, signed_auth_created_at: Option, token_owner: Option, - ) -> Result, (StatusCode, Json)> { + ) -> Result, Refused> { let community = tenant.community(); let owner = match check_relay_membership( state, @@ -386,16 +400,19 @@ pub mod relay_members { Ok(MembershipDecision::ViaOwner(owner)) => Some(owner), Ok(MembershipDecision::Denied) => { return Err(( - StatusCode::FORBIDDEN, - Json(serde_json::json!({ - "error": "relay_membership_required", - "message": "You must be a relay member to access this relay" - })), + ( + StatusCode::FORBIDDEN, + Json(serde_json::json!({ + "error": "relay_membership_required", + "message": "You must be a relay member to access this relay" + })), + ), + None, )) } Err(e) => { tracing::error!("relay membership check errored: {e}"); - return Err(super::internal_error(&e)); + return Err((super::internal_error(&e), None)); } }; deny_banned( @@ -409,17 +426,23 @@ pub mod relay_members { .await?; if let Some(token_owner) = token_owner { let Ok(agent) = nostr::PublicKey::from_slice(pubkey_bytes) else { - return Err(super::internal_error("invalid pubkey for owner link")); + return Err((super::internal_error("invalid pubkey for owner link"), None)); }; match link_agent_owner(state, tenant, &agent, &token_owner).await { OwnerLink::Linked => {} OwnerLink::Conflict => { - return Err(super::api_error(StatusCode::FORBIDDEN, OWNER_MISMATCH)) + return Err(( + super::api_error(StatusCode::FORBIDDEN, OWNER_MISMATCH), + Some("not_stored_owner"), + )) } OwnerLink::Unavailable => { - return Err(super::api_error( - StatusCode::SERVICE_UNAVAILABLE, - crate::handlers::auth::OWNER_LINK_ERROR, + return Err(( + super::api_error( + StatusCode::SERVICE_UNAVAILABLE, + crate::handlers::auth::OWNER_LINK_ERROR, + ), + Some("owner_link_unavailable"), )) } } @@ -439,11 +462,11 @@ pub mod relay_members { auth_tag_header: Option<&str>, signed_auth_created_at: Option, token_owner: Option, - ) -> Result<(), (StatusCode, Json)> { + ) -> Result<(), Refused> { let Ok(pubkey) = nostr::PublicKey::from_slice(pubkey_bytes) else { - return Err(super::internal_error("invalid pubkey for ban check")); + return Err((super::internal_error("invalid pubkey for ban check"), None)); }; - match crate::handlers::auth::community_ban_outcome( + let verdict = crate::handlers::auth::community_ban_verdict( state, community, pubkey, @@ -452,18 +475,19 @@ pub mod relay_members { token_owner, true, ) - .await - { - crate::handlers::auth::BanOutcome::Clear => Ok(()), - crate::handlers::auth::BanOutcome::Banned => Err(super::api_error( + .await; + let refusal = match verdict.outcome { + crate::handlers::auth::BanOutcome::Clear => return Ok(()), + crate::handlers::auth::BanOutcome::Banned => super::api_error( StatusCode::FORBIDDEN, "blocked: you are banned from this community", - )), - crate::handlers::auth::BanOutcome::DbError => Err(super::api_error( + ), + crate::handlers::auth::BanOutcome::DbError => super::api_error( StatusCode::SERVICE_UNAVAILABLE, "error: internal error checking restriction state", - )), - } + ), + }; + Err((refusal, verdict.owner_reason())) } /// Extract NIP-OA owner from an auth tag without membership enforcement. diff --git a/crates/buzz-relay/src/api/typing_postgres_tests.rs b/crates/buzz-relay/src/api/typing_postgres_tests.rs index 4f618876e4..38689ff227 100644 --- a/crates/buzz-relay/src/api/typing_postgres_tests.rs +++ b/crates/buzz-relay/src/api/typing_postgres_tests.rs @@ -167,6 +167,7 @@ async fn typing_uses_cached_restriction_row() { (f.community, f.member.public_key().to_bytes().to_vec()), buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }, ); @@ -200,6 +201,7 @@ async fn typing_ban_gate_uses_cached_restriction_row() { (f.community, member), buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: None, }, ); @@ -221,6 +223,7 @@ async fn persistent_post_ban_gate_uses_cached_restriction_row() { (f.community, f.member.public_key().to_bytes().to_vec()), buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }, ); diff --git a/crates/buzz-relay/src/audio/handler.rs b/crates/buzz-relay/src/audio/handler.rs index 809bb44dae..15077c994b 100644 --- a/crates/buzz-relay/src/audio/handler.rs +++ b/crates/buzz-relay/src/audio/handler.rs @@ -138,6 +138,12 @@ pub async fn ws_audio_handler( // The tenant lookup awaited since the community resolved; a snapshot // that went stale meanwhile accepts no socket. if let Err(class) = nip_fi_deadline.check() { + crate::nip_fi_upgrade::record_stale( + crate::nip_fi_session::NipFiWsRoute::Audio, + crate::nip_fi_shadow::enforce_label(&state, raw_host), + nip_fi_assertion.as_ref(), + class, + ); return crate::nip_fi_core::http_denial(class).into_response(); } let shadow_assertion = crate::nip_fi_upgrade::observe_deadline( @@ -266,6 +272,13 @@ pub(crate) async fn handle_audio_connection( let (pre_terminal_ctrl_tx, pre_terminal_ctrl_rx) = tokio::sync::mpsc::channel::(1); let control = CommunityConnectionControl::new(cancel); + if let Some(assertion) = &nip_fi_assertion { + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::enforce_label(&state, tenant.host()), + assertion.asserted_key(), + )); + } control.attach_nip_fi_shadow(nip_fi_shadow); // Its first verified AUTH writes it; else the read loop's end does. let shadow_line = shadow_line.map(Arc::new); @@ -606,6 +619,11 @@ async fn run_active_audio_connection( channel_id = %channel_id, "NIP-FI session deadline already expired at audio upgrade — rejecting before auth" ); + // Claim the expiry first, so this session ends as its deadline + // even when this branch beats the expiry worker. + if let Some(session) = control.nip_fi_enforce() { + session.expire(); + } deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; return; } @@ -692,7 +710,7 @@ async fn run_active_audio_connection( #[cfg(test)] crate::nip_fi_test_hooks::before_auth_verify(tenant.community()).await; // Every exit before the join commit leaves the shadow session unadmitted. - let shadow_attempt = crate::nip_fi_shadow_session::AuthAttempt(control.nip_fi_shadow()); + let shadow_attempt = crate::nip_fi_shadow_session::AuthAttempt::new(&control); let auth_ctx = tokio::select! { biased; @@ -793,6 +811,9 @@ async fn run_active_audio_connection( pubkey = %pubkey_hex, "NIP-FI session deadline already expired at pairing — rejecting audio admission" ); + if let Some(session) = control.nip_fi_enforce() { + session.expire(); + } deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; return; } @@ -819,6 +840,7 @@ async fn run_active_audio_connection( pubkey = %pubkey_hex, "NIP-FI deny-set hit at audio post-registration check — denying" ); + control.deny_nip_fi_enforce(crate::nip_fi_shadow::DENY_SET.by(Some(pubkey))); deny_audio_authorization(&mut ws_send, &control, &mut terminal_ctrl_rx).await; return; } @@ -841,7 +863,7 @@ async fn run_active_audio_connection( // below rereads bans. let early_ban = match token_owner { Some(_) => { - crate::handlers::auth::community_ban_outcome( + crate::handlers::auth::community_ban_verdict( &state, tenant.community(), pubkey, @@ -852,9 +874,14 @@ async fn run_active_audio_connection( ) .await } - None => crate::handlers::auth::BanOutcome::Clear, + None => crate::handlers::auth::BanVerdict::CLEAR, }; - if let Some(denial) = crate::handlers::auth::ban_admission_denial(early_ban) { + if let Some(denial) = crate::handlers::auth::ban_verdict_denial(early_ban) { + crate::handlers::auth::record_enforce_refusal( + &control, + Some(&denial), + nip_fi_assertion.as_ref(), + ); shadow_attempt.refused(); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, reason = denial.reason, "audio: denied at ban check"); exit_authorization_refusal( @@ -967,6 +994,7 @@ async fn run_active_audio_connection( let _owner_permit = match audio_gate.acquire_effect().await { Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { + shadow_attempt.effect_refused(&audio_gate); cancel.cancel(); if let Some(t) = _nip_fi_admission_expiry.take() { let _ = t.await; @@ -983,6 +1011,11 @@ async fn run_active_audio_connection( }; if let Some(denial) = crate::handlers::auth::owner_link_denial(link, token_owner.is_some()) { + crate::handlers::auth::record_enforce_refusal( + &control, + Some(&denial), + nip_fi_assertion.as_ref(), + ); shadow_attempt.refused(); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, owner = %owner.to_hex(), ?link, "audio: agent owner could not be linked, denying"); @@ -1028,6 +1061,11 @@ async fn run_active_audio_connection( } }; if let Some(denial) = denial { + crate::handlers::auth::record_enforce_refusal( + &control, + Some(&denial), + nip_fi_assertion.as_ref(), + ); shadow_attempt.refused(); let (class, message) = (denial.class, denial.reason); warn!(channel_id = %channel_id, pubkey = %pubkey_hex, reason = message, "audio: denied at final admission check"); @@ -1091,6 +1129,7 @@ async fn run_active_audio_connection( let _lease_permit = match audio_gate.acquire_effect().await { Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { + shadow_attempt.effect_refused(&audio_gate); cancel.cancel(); if let Some(t) = _nip_fi_admission_expiry.take() { let _ = t.await; @@ -1398,6 +1437,7 @@ async fn run_active_audio_connection( let _add_permit = match audio_gate.acquire_effect().await { Ok(p) => p, Err(crate::nip_fi_gate::SessionExpired) => { + shadow_attempt.effect_refused(&audio_gate); // Expiry fired before we could add the peer. No peer, no commit. // IMPORTANT 3 residual: await expiry task explicitly. cancel.cancel(); @@ -1657,6 +1697,7 @@ async fn run_active_audio_connection( // Same-pod joins pass None — room.roster_snapshot() is authoritative there. guard.remote_session.as_ref().map(|s| s.roster()), control.nip_fi_shadow().map(Arc::as_ref), + control.nip_fi_enforce().map(|session| (session, pubkey)), ) .await; if committed.is_err() { @@ -3264,11 +3305,15 @@ async fn commit_participant_join( // Admitted the instant the join commits, before publication awaits; // retired at each refusal below, before its rollback awaits. shadow: Option<&crate::nip_fi_shadow_session::ShadowSession>, + enforce: Option<(&crate::nip_fi_shadow::EnforceSession, nostr::PublicKey)>, ) -> Result { let retire_shadow = || { if let Some(shadow) = shadow { shadow.retire_pending(); } + if let Some((session, _)) = enforce { + session.retire(); + } }; // 1. Sign the 48101 event synchronously. // @@ -3502,6 +3547,11 @@ async fn commit_participant_join( let _permit = match gate.acquire_effect().await { Ok(permit) => permit, Err(crate::nip_fi_gate::SessionExpired) => { + // A deadline the gate saw first is claimed before the caller's + // refusal retirement; cancellation alone stays quiet. + if let Some((session, _)) = enforce.filter(|_| gate.deadline_passed()) { + session.expire(); + } // Rollback explicitly — no 48101 or membership write committed. let _ = tx.rollback().await; return Err(JoinCommitError::Expired); @@ -3515,6 +3565,9 @@ async fn commit_participant_join( if let Some(shadow) = shadow { shadow.admit(); } + if let Some((session, pubkey)) = enforce { + session.admit(pubkey); + } // Fix B (commit-before-publish): call `commit_peer` which atomically // marks the peer committed, increments the roster revision, and fires @@ -6200,6 +6253,93 @@ mod tests { let _ = server.await; } + /// The already-expired bootstrap fast path claims the deadline before + /// its terminal denial, so a pending enforced session ends as its + /// deadline even with no expiry worker to win the race. + /// Mutation: dropping that branch's `session.expire()` records + /// `audio deny_set/denied`. + #[tokio::test] + async fn already_expired_audio_bootstrap_records_the_deadline() { + use chrono::{Duration, Utc}; + use std::sync::Arc; + + let key = nostr::Keys::generate(); + let deadline = Utc::now() - Duration::milliseconds(50); + let assertion = + buzz_auth::VerifiedAssertion::for_test(Some(key.public_key()), vec![deadline]); + let state = audio_test_state().await; + let tenant = buzz_core::tenant::TenantContext::resolved( + buzz_core::tenant::CommunityId::from_uuid(uuid::Uuid::nil()), + "test.local".to_string(), + ); + let cancel = CancellationToken::new(); + let control = crate::state::CommunityConnectionControl::new(cancel.clone()); + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::BOUND.into(), + Some(key.public_key()), + )); + // No expiry worker: the fast path alone ends the session. + let gate = crate::nip_fi_gate::SessionAdmissionGate::new(deadline, cancel); + let (terminal_tx, terminal_rx) = + tokio::sync::mpsc::channel::(1); + let pre_built = Arc::new(std::sync::Mutex::new(Some(( + gate, + terminal_tx, + terminal_rx, + )))); + + let listener = TcpListener::bind("127.0.0.1:0").await.expect("bind"); + let addr = listener.local_addr().expect("local addr"); + let ((), records, lines) = crate::nip_fi_shadow::tests::enforce_records_during(async { + let server = tokio::spawn(async move { + let app = Router::new().route( + "/", + get(move |ws: WebSocketUpgrade| { + let (state, tenant, control, assertion, pre_built) = ( + Arc::clone(&state), + tenant.clone(), + control.clone(), + assertion.clone(), + Arc::clone(&pre_built), + ); + async move { + ws.on_upgrade(move |socket| async move { + let (gate, tx, rx) = + pre_built.lock().expect("slot").take().expect("one socket"); + handle_active_audio_connection( + socket, + state, + tenant, + uuid::Uuid::new_v4(), + control, + Some(assertion), + Utc::now(), + Some((gate, tx, rx, None)), + ) + .await + }) + } + }), + ); + axum::serve(listener, app).await.expect("test server"); + }); + let (mut client, _) = connect_async(format!("ws://{addr}/")) + .await + .expect("connect"); + // The denial frame, then the close. + for _ in 0..2 { + tokio::time::timeout(std::time::Duration::from_secs(2), client.next()) + .await + .expect("the expired session is denied"); + } + server.abort(); + let _ = server.await; + }) + .await; + assert_eq!(records, ["audio deadline/rejected"], "{lines:?}"); + } + /// Fix 3 (F3): bootstrap-drain through the real outer wrapper (`handle_audio_connection`). /// /// The `run_registered_community_connection` wrapper in `handle_audio_connection` @@ -7839,6 +7979,7 @@ mod tests { &Arc::new(crate::audio::room::Room::new(tenant.community(), channel)), None, None, + None, ) .await } @@ -8492,6 +8633,7 @@ mod tests { )), None, Some(&shadow), + None, ) .await }; @@ -8506,6 +8648,126 @@ mod tests { } } + /// Enforce's audio verdict is the join commit, as shadow's is: a + /// committed join counts its admit before publication, so a deadline + /// while publication is held ends the session `expired` once with no + /// pending denial; a join + /// refused for an ordinary reason (archived) retires the session + /// before its rollback, so an expiry held inside that rollback records + /// nothing; and a deadline the commit's effect gate sees first is + /// recorded once, as `session_deadline`, however often expiry follows. + /// Mutations: dropping enforce from `retire_shadow` records + /// `audio deadline/rejected` for `Archived`; dropping the commit + /// seam's `session.expire()` records nothing for `GateFirst`; + /// dropping the commit's admit, or moving it after publication, + /// records `audio deadline/rejected` for `Committed`. + #[test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + fn enforce_join_commit_is_the_audio_admission() { + #[derive(Clone, Copy, Debug, PartialEq)] + enum Case { + Committed, + Archived, + GateFirst, + } + for (case, expected) in [ + ( + Case::Committed, + &["audio admit/admit", "audio end/expired"][..], + ), + (Case::Archived, &[][..]), + (Case::GateFirst, &["audio deadline/rejected"][..]), + ] { + let (records, lines, _, ()) = + crate::nip_fi_shadow::tests::enforce_observed(async {}, |()| async move { + let state = audio_test_state_real_db() + .await + .expect("postgres-ci provides a database"); + let pool = state.db.pool().clone(); + let (tenant, channel_id, member) = seed_audio_fixture(&pool).await; + if case == Case::Archived { + sqlx::query("UPDATE channels SET archived_at = NOW() WHERE id = $1") + .bind(channel_id) + .execute(&pool) + .await + .expect("archive channel"); + } + let key = member.public_key(); + let session = crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::BOUND.into(), + Some(key), + ); + let deadline = match case { + Case::GateFirst => chrono::Utc::now() - chrono::Duration::seconds(1), + _ => chrono::Utc::now() + chrono::Duration::hours(1), + }; + let gate = crate::nip_fi_gate::SessionAdmissionGate::new( + deadline, + CancellationToken::new(), + ); + let (arrived, release) = + crate::nip_fi_test_hooks::join_refusal_rollback_hook::arm( + tenant.community(), + ); + // A committed join holds publication so the deadline + // lands before the commit returns. + let fanout = (case == Case::Committed).then(|| { + crate::nip_fi_test_hooks::audio_participant_fanout_hook::arm( + tenant.community(), + ) + }); + let held = async { + if case == Case::Archived { + arrived.await.expect("the join is refused"); + session.expire(); + release.notify_one(); + } + if let Some((published, release)) = fanout { + published.await.expect("the join is published"); + session.expire(); + release.notify_one(); + } + }; + let commit = async { + commit_participant_join( + &state, + &tenant, + channel_id, + channel_id, + &key.to_hex(), + &key.to_bytes(), + uuid::Uuid::new_v4(), + 0, + 0, + 1, + "1", + &MembershipAdmission::Existing { + parent_channel_id: channel_id, + }, + &gate, + &Arc::new(crate::audio::room::Room::new( + tenant.community(), + channel_id, + )), + None, + None, + Some((&session, key)), + ) + .await + }; + let (committed, ()) = tokio::join!(commit, held); + assert_eq!(committed.is_ok(), case == Case::Committed, "{committed:?}"); + // The caller's refusal retirement, then a later expiry. + if committed.is_err() { + session.retire(); + } + session.expire(); + }); + assert_eq!(records, expected, "{case:?}: {lines:?}"); + } + } + /// F2a: committed join into an already-archived channel is rejected on /// the `Existing` path. /// @@ -8572,6 +8834,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await; @@ -8679,6 +8942,7 @@ mod tests { &room, None, None, + None, ), ) .await @@ -8782,6 +9046,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -8989,6 +9254,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9124,6 +9390,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9262,6 +9529,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9307,6 +9575,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9415,6 +9684,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9460,6 +9730,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9695,6 +9966,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -9891,6 +10163,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -10457,6 +10730,7 @@ mod tests { )), None, // same-pod test — no owner roster None, + None, ) .await }); @@ -11287,6 +11561,7 @@ mod tests { &room, None, // same-pod test — no owner roster None, + None, ) .await; @@ -11413,6 +11688,7 @@ mod tests { &room2, None, // same-pod test — no owner roster None, + None, ) .await }); @@ -11647,6 +11923,7 @@ mod tests { &room, None, // same-pod test — no owner roster None, + None, ) .await; assert!( @@ -11820,6 +12097,7 @@ mod tests { &ingress_room, Some(&owner_snapshot), // cross-pod: use owner-pod roster for the broadcast None, + None, ) .await; assert!( @@ -12499,6 +12777,7 @@ mod tests { &room, None, None, + None, ) .await; assert!( diff --git a/crates/buzz-relay/src/connection.rs b/crates/buzz-relay/src/connection.rs index f2f49eedc0..a2c6ba7d66 100644 --- a/crates/buzz-relay/src/connection.rs +++ b/crates/buzz-relay/src/connection.rs @@ -394,6 +394,13 @@ pub(crate) async fn handle_connection( }; let (pre_terminal_ctrl_tx, pre_terminal_ctrl_rx) = mpsc::channel::(1); let control = CommunityConnectionControl::new(cancel); + if let Some(assertion) = &nip_fi_assertion { + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::enforce_label(&state, tenant.host()), + assertion.asserted_key(), + )); + } control.attach_nip_fi_shadow(nip_fi_shadow); // Its first verified AUTH writes it; else the read loop's end does. let shadow_line = shadow_line.map(Arc::new); @@ -1529,6 +1536,16 @@ pub(crate) mod tests { auth: AuthState, nip_fi_assertion: Option, community: buzz_core::tenant::CommunityId, + ) -> TestConn { + test_conn_gated(auth, nip_fi_assertion, community, None) + } + + /// [`test_conn_in`] whose effect gate has `deadline` (`None`: off mode). + pub(crate) fn test_conn_gated( + auth: AuthState, + nip_fi_assertion: Option, + community: buzz_core::tenant::CommunityId, + deadline: Option>, ) -> TestConn { let (send_tx, send_rx) = mpsc::channel(4); let (ctrl_tx, ctrl_rx) = mpsc::channel(8); @@ -1548,7 +1565,12 @@ pub(crate) mod tests { grace_limit: 3, nip_fi_assertion, session_deadline: None, - nip_fi_gate: crate::nip_fi_gate::SessionAdmissionGate::off_mode(cancel.clone()), + nip_fi_gate: match deadline { + Some(deadline) => { + crate::nip_fi_gate::SessionAdmissionGate::new(deadline, cancel.clone()) + } + None => crate::nip_fi_gate::SessionAdmissionGate::off_mode(cancel.clone()), + }, community_control: crate::state::CommunityConnectionControl::new(cancel.clone()), }; TestConn { diff --git a/crates/buzz-relay/src/handlers/auth.rs b/crates/buzz-relay/src/handlers/auth.rs index 626d114dfd..a8476042c5 100644 --- a/crates/buzz-relay/src/handlers/auth.rs +++ b/crates/buzz-relay/src/handlers/auth.rs @@ -67,7 +67,8 @@ fn classify_relay_membership( /// [`AppState::restriction_state_cached`], for per-request gates whose grant /// ends with the request (HTTP requests, ephemeral pulses). Socket admission /// reads fresh: an admitted socket outlives the cache's staleness bound. -pub(crate) async fn community_ban_outcome( +/// Returns the outcome with the row that decided it. +pub(crate) async fn community_ban_verdict( state: &AppState, community: buzz_core::CommunityId, pubkey: nostr::PublicKey, @@ -75,10 +76,18 @@ pub(crate) async fn community_ban_outcome( signed_auth_created_at: Option, token_owner: Option, cached: bool, -) -> BanOutcome { - let outcome = principal_ban_outcome(state, community, &pubkey, cached).await; - if outcome != BanOutcome::Clear { - return outcome; +) -> BanVerdict { + let verdict = principal_ban_verdict(state, community, &pubkey, cached).await; + // A failed read leaves a token owner unchecked too: the refusal is that + // owner's unavailable ban state, as shadow's owner read would record. + if verdict.outcome == BanOutcome::DbError && token_owner.is_some() { + return BanVerdict { + source: BanSource::Owner, + ..verdict + }; + } + if verdict.outcome != BanOutcome::Clear { + return verdict; } // A NIP-FI agent assertion's verified owner cascades unconditionally, // whether the agent is a member itself or admitted through that owner. @@ -90,18 +99,76 @@ pub(crate) async fn community_ban_outcome( ) }); match owner { - Some(owner) => principal_ban_outcome(state, community, &owner, cached).await, - None => BanOutcome::Clear, + Some(owner) => BanVerdict { + outcome: principal_ban_outcome(state, community, &owner, cached).await, + source: BanSource::Owner, + }, + None => verdict, } } -/// Ban verdict for one key, without any owner cascade. +/// Whose ban row decided a [`BanOutcome`]: the key's own, or an owner's +/// (its stored agent owner, or the NIP-OA or token owner checked after it). +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub enum BanSource { + /// The key's own row. + Own, + /// Its owner's row. + Owner, +} + +impl BanSource { + /// Whose row decided a banned restriction snapshot. + pub(crate) fn of(restriction: &buzz_db::moderation::RestrictionState) -> Self { + if restriction.own_banned { + Self::Own + } else { + Self::Owner + } + } +} + +/// A ban decision with the row that decided it. +#[derive(Clone, Copy, Debug, PartialEq, Eq)] +pub(crate) struct BanVerdict { + pub(crate) outcome: BanOutcome, + pub(crate) source: BanSource, +} + +impl BanVerdict { + pub(crate) const CLEAR: Self = Self { + outcome: BanOutcome::Clear, + source: BanSource::Own, + }; + + /// Shadow's `owner` reason when an owner's row decided the refusal. + pub(crate) fn owner_reason(self) -> Option<&'static str> { + match (self.source, self.outcome) { + (BanSource::Owner, BanOutcome::Banned) => Some("owner_banned"), + (BanSource::Owner, BanOutcome::DbError) => Some("owner_ban_unavailable"), + _ => None, + } + } +} + +/// Ban verdict for one key: its own row and its stored agent owner's. async fn principal_ban_outcome( state: &AppState, community: buzz_core::CommunityId, key: &nostr::PublicKey, cached: bool, ) -> BanOutcome { + principal_ban_verdict(state, community, key, cached) + .await + .outcome +} + +async fn principal_ban_verdict( + state: &AppState, + community: buzz_core::CommunityId, + key: &nostr::PublicKey, + cached: bool, +) -> BanVerdict { let restriction = if cached { state .restriction_state_cached(community, key.as_bytes()) @@ -112,14 +179,16 @@ async fn principal_ban_outcome( .moderation_restriction_state(community, key.as_bytes()) .await }; - match restriction { - Ok(restriction) if restriction.banned => BanOutcome::Banned, - Ok(_) => BanOutcome::Clear, + let (outcome, source) = match restriction { + Ok(r) if r.banned && !r.own_banned => (BanOutcome::Banned, BanSource::Owner), + Ok(r) if r.banned => (BanOutcome::Banned, BanSource::Own), + Ok(_) => (BanOutcome::Clear, BanSource::Own), Err(e) => { warn!(pubkey = %key.to_hex(), error = %e, "ban-state DB lookup failed, denying (fail-closed)"); - BanOutcome::DbError + (BanOutcome::DbError, BanSource::Own) } - } + }; + BanVerdict { outcome, source } } /// Shadow only: the refusal enforce's token-owner rules would give `agent`, @@ -151,6 +220,38 @@ pub(crate) async fn token_owner_denial( owner_link_denial(link, true).map(|denial| (denial.class, reason)) } +/// Enforce's `owner` refusal of an agent assertion's key, when `denial` was +/// decided by its owner: the owner's ban or the owner link. +pub(crate) fn owner_refusal( + denial: &AdmissionDenial, + assertion: Option<&buzz_auth::VerifiedAssertion>, +) -> Option { + let assertion = assertion.filter(|a| a.owner().is_some())?; + let deny = crate::nip_fi_shadow::WouldDeny::new( + crate::nip_fi_shadow::Stage::Owner, + denial.class, + denial.owner_reason?, + ); + Some(deny.by(assertion.asserted_key())) +} + +/// Claim enforce's verdict for a refused socket before its frames are +/// awaited: an owner-decided refusal of an agent assertion is recorded with +/// shadow's `owner` reason; any other refusal retires the session unrecorded. +pub(crate) fn record_enforce_refusal( + control: &crate::state::CommunityConnectionControl, + denial: Option<&AdmissionDenial>, + assertion: Option<&buzz_auth::VerifiedAssertion>, +) { + let Some(session) = control.nip_fi_enforce() else { + return; + }; + match denial.and_then(|d| owner_refusal(d, assertion)) { + Some(deny) => session.deny(deny), + None => session.retire(), + } +} + fn ban_denial(outcome: BanOutcome) -> Option<(&'static str, &'static str, AuthOutcome)> { match outcome { BanOutcome::Clear => None, @@ -173,6 +274,17 @@ pub(crate) struct AdmissionDenial { pub(crate) reason: &'static str, pub(crate) outcome: AuthOutcome, pub(crate) class: buzz_auth::DenialClass, + /// Shadow's `owner` reason when an agent's owner decided the refusal. + pub(crate) owner_reason: Option<&'static str>, +} + +/// [`ban_admission_denial`] carrying the deciding owner, if any. +pub(crate) fn ban_verdict_denial(verdict: BanVerdict) -> Option { + let denial = ban_admission_denial(verdict.outcome)?; + Some(AdmissionDenial { + owner_reason: verdict.owner_reason(), + ..denial + }) } /// The refusal for a ban outcome other than [`BanOutcome::Clear`]. @@ -187,6 +299,7 @@ pub(crate) fn ban_admission_denial(ban: BanOutcome) -> Option { reason, outcome, class, + owner_reason: None, }) } @@ -206,7 +319,7 @@ pub(crate) async fn final_admission_denial( signed_auth_created_at: Option, token_owner: Option, ) -> Option { - let ban = community_ban_outcome( + let ban = community_ban_verdict( state, community, pubkey, @@ -216,7 +329,7 @@ pub(crate) async fn final_admission_denial( false, ) .await; - if let Some(denial) = ban_admission_denial(ban) { + if let Some(denial) = ban_verdict_denial(ban) { return Some(denial); } match crate::api::relay_members::check_relay_membership_authoritative( @@ -234,6 +347,7 @@ pub(crate) async fn final_admission_denial( reason: "restricted: not a relay member", outcome: AuthOutcome::NotRelayMember, class: buzz_auth::DenialClass::AuthorizationDenied, + owner_reason: None, }), Ok(_) => None, Err(e) => { @@ -243,6 +357,7 @@ pub(crate) async fn final_admission_denial( reason: "error: internal error checking relay membership", outcome: AuthOutcome::RelayMembershipCheckError, class: buzz_auth::DenialClass::AuthorizationUnavailable, + owner_reason: None, }) } } @@ -280,6 +395,7 @@ pub(crate) async fn admitted_owner( reason: OWNER_LINK_ERROR, outcome: AuthOutcome::RelayMembershipCheckError, class: buzz_auth::DenialClass::AuthorizationUnavailable, + owner_reason: None, }) } } @@ -304,12 +420,14 @@ pub(crate) fn owner_link_denial( reason: crate::api::relay_members::OWNER_MISMATCH, outcome: AuthOutcome::NotRelayMember, class: buzz_auth::DenialClass::AuthorizationDenied, + owner_reason: Some("not_stored_owner"), }), OwnerLink::Conflict | OwnerLink::Unavailable => Some(AdmissionDenial { metric: "agent_owner_link_error", reason: OWNER_LINK_ERROR, outcome: AuthOutcome::RelayMembershipCheckError, class: buzz_auth::DenialClass::AuthorizationUnavailable, + owner_reason: token_owner.then_some("owner_link_unavailable"), }), } } @@ -351,6 +469,11 @@ fn deny_nip_fi_auth(conn: &ConnectionState, class: buzz_auth::DenialClass) { /// the outcome, send the denial (the canonical NOTICE under NIP-FI, else an /// OK false on the control channel so it drains before the Close), and close. fn deny_admission(conn: &ConnectionState, event_id_hex: &str, denial: AdmissionDenial) { + record_enforce_refusal( + &conn.community_control, + Some(&denial), + conn.nip_fi_assertion.as_ref(), + ); metrics::counter!("buzz_auth_failures_total", "reason" => denial.metric).increment(1); if !conn.reject_auth(denial.outcome) { return; @@ -432,8 +555,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: crate::api::bridge::nip42_expected_relay_url(&state.config.relay_url, &conn.tenant); let auth_svc = Arc::clone(&state.auth); - let _shadow_attempt = - crate::nip_fi_shadow_session::AuthAttempt(conn.community_control.nip_fi_shadow()); + let _shadow_attempt = crate::nip_fi_shadow_session::AuthAttempt::new(&conn.community_control); // Pure NIP-42 verification — crypto only, no DB lookups. match auth_svc .verify_auth_event(event, &challenge, &relay_url) @@ -492,7 +614,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: // pinning `Failed` for the connection's life on a false premise. // `Banned` claims the ban; `DbError` denies with `error: internal` // (mirrors the ingest write-path gate). - let outcome = community_ban_outcome( + let verdict = community_ban_verdict( &state, conn.tenant.community(), pubkey, @@ -502,9 +624,15 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: false, ) .await; + let outcome = verdict.outcome; if let Some((metric_reason, deny_reason, auth_outcome)) = ban_denial(outcome) { warn!(conn_id = %conn_id, pubkey = %pubkey.to_hex(), reason = deny_reason, "principal denied at ban seam"); + record_enforce_refusal( + &conn.community_control, + ban_verdict_denial(verdict).as_ref(), + conn.nip_fi_assertion.as_ref(), + ); metrics::counter!("buzz_auth_failures_total", "reason" => metric_reason) .increment(1); if !conn.reject_auth(auth_outcome) { @@ -695,7 +823,10 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: crate::nip_fi_test_hooks::before_auth_commit(conn.tenant.community()).await; let _auth_permit = match conn.nip_fi_gate.acquire_effect().await { Ok(permit) => permit, - Err(crate::nip_fi_gate::SessionExpired) => return, + Err(crate::nip_fi_gate::SessionExpired) => { + _shadow_attempt.effect_refused(&conn.nip_fi_gate); + return; + } }; // Record the NIP-OA owner link before admission: revoking the @@ -780,6 +911,7 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: reason: "blocked: access revoked", outcome: AuthOutcome::Banned, class: buzz_auth::DenialClass::AuthorizationDenied, + owner_reason: None, }), denial => denial, }; @@ -816,6 +948,8 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: "reason" => "deny_set_post_registration" ) .increment(1); + conn.community_control + .deny_nip_fi_enforce(crate::nip_fi_shadow::DENY_SET.by(Some(pubkey))); deny_nip_fi_auth(&conn, buzz_auth::DenialClass::AuthorizationDenied); return; } @@ -831,6 +965,9 @@ pub async fn handle_auth(event: nostr::Event, conn: Arc, state: return; } state.conn_manager.mark_admitted(conn_id); + if let Some(session) = conn.community_control.nip_fi_enforce() { + session.admit(pubkey); + } conn.send(RelayMessage::ok(&event_id_hex, true, "")); crate::verified_profiles::admitted( &state, @@ -1093,6 +1230,14 @@ mod tests { }); let state = auth_test_state().await; + conn.community_control + .attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::BOUND.into(), + conn.nip_fi_assertion + .as_ref() + .and_then(|a| a.asserted_key()), + )); // relay_url = ws:// where scheme prefix is from config // (default ws://), and host is "test.local". @@ -1103,8 +1248,20 @@ mod tests { .sign_with_keys(&key_b) .unwrap(); - // Drive the production handle_auth path. - handle_auth(auth_event, Arc::clone(&conn), state).await; + // Drive the production handle_auth path. Enforce records the + // refusal once, naming the proven key, and the deadline that fires + // after it records nothing more. Mutation: dropping the pairing + // seam's `deny_nip_fi_enforce` call → RED. + let ((), lines, counts) = crate::nip_fi_shadow::tests::enforce_records(async { + handle_auth(auth_event, Arc::clone(&conn), state).await; + conn.community_control.nip_fi_enforce().unwrap().expire(); + }) + .await; + assert_eq!(lines.len(), 1, "{lines:?}"); + let proven = format!("pubkey=\"{}\"", key_b.public_key().to_hex()); + assert!(lines[0].contains(&proven), "{lines:?}"); + assert_eq!(counts.len(), 1, "{counts:?}"); + assert_eq!(counts[0][..3], ["ws", "pairing", "denied"]); assert!( cancel.is_cancelled(), @@ -1718,6 +1875,28 @@ mod tests { assert_eq!(records, ["owner/unavailable"]); } + // The deciding row names the reason: an owner's ban or failed lookup is + // shadow's `owner` reason, the key's own is none. Mutation: reporting an + // own-row ban as the owner's → RED. + #[test] + fn ban_verdict_owner_reason_follows_the_deciding_row() { + use super::{BanSource, BanVerdict}; + let verdict = |outcome, source| BanVerdict { outcome, source }; + assert_eq!( + verdict(BanOutcome::Banned, BanSource::Owner).owner_reason(), + Some("owner_banned") + ); + assert_eq!( + verdict(BanOutcome::DbError, BanSource::Owner).owner_reason(), + Some("owner_ban_unavailable") + ); + assert_eq!( + verdict(BanOutcome::Banned, BanSource::Own).owner_reason(), + None + ); + assert_eq!(BanVerdict::CLEAR.owner_reason(), None); + } + const HOUR: chrono::Duration = chrono::Duration::hours(1); /// Fires the connection's shadow deadline once its AUTH has finished, @@ -1913,6 +2092,278 @@ mod tests { } } + /// An enforced root socket in `community` under `assertion`, with its + /// enforce lifecycle attached as the upgrade attaches it, and an AUTH + /// event `signer` signs for it. + fn enforce_root_conn( + community: buzz_core::tenant::CommunityId, + assertion: buzz_auth::VerifiedAssertion, + signer: &Keys, + ) -> (crate::connection::tests::TestConn, nostr::Event) { + enforce_root_conn_gated(community, assertion, signer, None) + } + + /// [`enforce_root_conn`] whose effect gate has `deadline`. + fn enforce_root_conn_gated( + community: buzz_core::tenant::CommunityId, + assertion: buzz_auth::VerifiedAssertion, + signer: &Keys, + deadline: Option>, + ) -> (crate::connection::tests::TestConn, nostr::Event) { + let challenge = "enforce-root-challenge".to_owned(); + let pending = AuthState::Pending { + challenge: challenge.clone(), + started_at: Instant::now(), + }; + let asserted = assertion.asserted_key(); + let t = crate::connection::tests::test_conn_gated( + pending, + Some(assertion), + community, + deadline, + ); + t.conn.community_control.attach_nip_fi_enforce( + crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::BOUND.into(), + asserted, + ), + ); + let event = EventBuilder::new(Kind::Authentication, "") + .tag(Tag::parse(["relay", "ws://test.local"]).unwrap()) + .tag(Tag::parse(["challenge", &challenge]).unwrap()) + .sign_with_keys(signer) + .unwrap(); + (t, event) + } + + /// Runs the production expiry worker for `t`'s socket with its + /// deadline already passed, to completion. + async fn run_expiry_worker(t: &crate::connection::tests::TestConn) { + let gate = crate::nip_fi_gate::SessionAdmissionGate::new( + chrono::Utc::now(), + t.conn.cancel.clone(), + ); + crate::nip_fi_session::spawn_nip_fi_expiry_task( + chrono::Utc::now(), + gate, + t.conn.community_control.clone(), + t.conn.terminal_ctrl_tx.clone(), + crate::nip_fi_session::NipFiWsRoute::Root, + ) + .await + .expect("expiry worker"); + } + + /// Enforce records each root owner refusal once, with shadow's + /// reason, from the single ban decision that refused it: a stored + /// owner's ban (the agent's own read cascades to it) costs exactly + /// one authorization read, so a reread cannot change the reason. An + /// admitted session counts one admit and, through the real expiry + /// worker, one `expired` end and no pending `deadline`. + /// Mutations: deleting root's `session.admit(pubkey)` leaves `Clean` + /// with no record (the attempt retires it); reverting to reread the owner + /// after the refusal raises `StoredOwnerBanned`'s reads above 1. + #[test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + fn enforce_root_auth_records_owner_refusals_from_one_decision() { + use crate::nip_fi_shadow_session::tests::owned_assertion; + #[derive(Clone, Copy, Debug)] + enum Case { + Clean, + BannedTokenOwner, + StoredOwnerBanned, + OtherStoredOwner, + BanReadFails, + } + for (case, expected, reason, reads) in [ + ( + Case::Clean, + &["ws admit/admit", "ws end/expired"][..], + None, + None, + ), + ( + Case::BannedTokenOwner, + &["ws owner/denied"][..], + Some("owner_banned"), + Some(2), + ), + ( + Case::StoredOwnerBanned, + &["ws owner/denied"][..], + Some("owner_banned"), + Some(1), + ), + ( + Case::OtherStoredOwner, + &["ws owner/denied"][..], + Some("not_stored_owner"), + None, + ), + ( + Case::BanReadFails, + &["ws owner/unavailable"][..], + Some("owner_ban_unavailable"), + None, + ), + ] { + let (records, lines, auth_reads, ok_true) = + crate::nip_fi_shadow::tests::enforce_observed( + async { + let state = auth_test_state_real_db_expect().await; + let (agent, owner) = (Keys::generate(), Keys::generate()); + let community = seeded_community(&state).await; + let link = |stored: nostr::PublicKey| { + let state = std::sync::Arc::clone(&state); + let agent = agent.public_key(); + async move { + for key in [agent, stored] { + state + .db + .ensure_user(community, key.as_bytes()) + .await + .expect("ensure user"); + } + assert!(state + .db + .set_agent_owner( + community, + agent.as_bytes(), + stored.as_bytes() + ) + .await + .expect("seed stored owner")); + } + }; + let ban = |key: nostr::PublicKey| { + let state = std::sync::Arc::clone(&state); + async move { + let bytes = key.to_bytes(); + state + .db + .ban_community_member(community, &bytes, &bytes, None, None) + .await + .expect("ban owner"); + } + }; + match case { + Case::Clean => {} + Case::BannedTokenOwner => ban(owner.public_key()).await, + Case::StoredOwnerBanned => { + link(owner.public_key()).await; + ban(owner.public_key()).await; + } + Case::OtherStoredOwner => link(Keys::generate().public_key()).await, + // The agent's own ban read fails: its token + // owner is left unchecked, so the refusal is the + // owner's unavailable ban state. + Case::BanReadFails => state.db.pool().close().await, + } + let conn = enforce_root_conn( + community, + owned_assertion(agent.public_key(), owner.public_key()), + &agent, + ); + (state, conn) + }, + |(state, (mut t, event))| async move { + handle_auth(event, std::sync::Arc::clone(&t.conn), state).await; + let mut ok_true = false; + while let Ok(WsMessage::Text(text)) = t.send_rx.try_recv() { + ok_true |= is_ok_true(text.as_str()); + } + run_expiry_worker(&t).await; + ok_true + }, + ); + assert_eq!(records, expected, "{case:?}: {lines:?}"); + assert_eq!(ok_true, reason.is_none(), "{case:?}: admission unchanged"); + let denials: Vec<_> = lines + .iter() + .filter(|l| l.contains("enforce deny")) + .collect(); + match reason { + Some(reason) => { + assert_eq!(denials.len(), 1, "{case:?}: {lines:?}"); + assert!( + denials[0].contains(&format!("reason=\"{reason}\"")), + "{case:?}: {lines:?}" + ); + assert!( + denials[0].contains("stage=\"owner\""), + "{case:?}: {lines:?}" + ); + assert!(denials[0].contains("route=\"ws\""), "{case:?}: {lines:?}"); + } + None => assert!(denials.is_empty(), "{case:?}: {lines:?}"), + } + if let Some(reads) = reads { + assert_eq!(auth_reads, reads, "{case:?}: authorization reads"); + } + } + } + + /// A deadline the AUTH commit's effect gate sees before the expiry + /// worker runs is recorded once, as the pending session's + /// `session_deadline` denial: in either order, the attempt's own + /// retirement cannot end it unrecorded, and the worker that follows + /// adds nothing. Admission is unchanged: no `OK true`. + /// Mutation: deleting root's `effect_refused` call records nothing + /// for `GateFirst`. + #[test] + #[ignore = "requires Postgres — runs in postgres-ci nextest lane"] + fn enforce_root_deadline_seen_by_the_gate_first_is_recorded_once() { + for worker_first in [false, true] { + let (records, lines, _, ok_true) = crate::nip_fi_shadow::tests::enforce_observed( + async { + let state = auth_test_state_real_db_expect().await; + let agent = Keys::generate(); + let community = seeded_community(&state).await; + state + .db + .ensure_user(community, agent.public_key().as_bytes()) + .await + .expect("ensure user"); + let conn = enforce_root_conn_gated( + community, + buzz_auth::VerifiedAssertion::for_test( + Some(agent.public_key()), + vec![chrono::Utc::now() + chrono::Duration::hours(1)], + ), + &agent, + Some(chrono::Utc::now() - chrono::Duration::seconds(1)), + ); + (state, conn) + }, + |(state, (mut t, event))| async move { + if worker_first { + run_expiry_worker(&t).await; + } + handle_auth(event, std::sync::Arc::clone(&t.conn), state).await; + run_expiry_worker(&t).await; + let mut ok_true = false; + while let Ok(WsMessage::Text(text)) = t.send_rx.try_recv() { + ok_true |= is_ok_true(text.as_str()); + } + ok_true + }, + ); + assert_eq!( + records, + ["ws deadline/rejected"], + "worker_first={worker_first}: {lines:?}" + ); + assert!( + lines + .iter() + .any(|l| l.contains("reason=\"session_deadline\"")), + "{lines:?}" + ); + assert!(!ok_true, "admission unchanged"); + } + } + /// A community whose row exists, so bans and users can reference it. async fn seeded_community( state: &crate::state::AppState, diff --git a/crates/buzz-relay/src/handlers/event.rs b/crates/buzz-relay/src/handlers/event.rs index ea696e5a85..a7f9a775bb 100644 --- a/crates/buzz-relay/src/handlers/event.rs +++ b/crates/buzz-relay/src/handlers/event.rs @@ -3865,6 +3865,7 @@ mod tests { key.clone(), buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }, ); @@ -3878,6 +3879,7 @@ mod tests { key, buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(chrono::Utc::now() - chrono::Duration::seconds(1)), }, ); @@ -3941,6 +3943,7 @@ mod tests { let key = (tenant.community(), user.public_key().to_bytes().to_vec()); let banned = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; let scopes = buzz_auth::Scope::all_non_admin(); diff --git a/crates/buzz-relay/src/handlers/ingest.rs b/crates/buzz-relay/src/handlers/ingest.rs index b2031936ab..82cc8ee657 100644 --- a/crates/buzz-relay/src/handlers/ingest.rs +++ b/crates/buzz-relay/src/handlers/ingest.rs @@ -466,12 +466,19 @@ pub enum IngestError { /// Which admission outcome an [`IngestError::Ban`] carries. #[derive(Debug, Clone, Copy, PartialEq, Eq)] pub enum BanRefusal { - /// The principal or its owner is banned. - Banned, + /// The principal is banned; the source says whose row decided it. + Banned(crate::handlers::auth::BanSource), /// The restriction lookup failed, so no ban decision could be made. Unavailable, } +impl BanRefusal { + /// The ban refusal for a banned restriction snapshot. + pub(crate) fn banned(restriction: &buzz_db::moderation::RestrictionState) -> Self { + Self::Banned(crate::handlers::auth::BanSource::of(restriction)) + } +} + impl IngestError { /// A ban refusal answered with `legacy` outside NIP-FI agent HTTP. pub(crate) fn ban(refusal: BanRefusal, legacy: IngestError) -> Self { @@ -517,8 +524,8 @@ fn map_relay_admin_error(error: super::relay_admin::RelayAdminError) -> IngestEr match error { // Same wire prefix and HTTP status (403) as every other durable // restriction refusal — see the write-path gate below and `auth.rs`. - RelayAdminError::Banned => IngestError::ban( - BanRefusal::Banned, + RelayAdminError::Banned(source) => IngestError::ban( + BanRefusal::Banned(source), IngestError::AuthFailed("blocked: you are banned from this community".to_string()), ), RelayAdminError::Rejected(reason) => IngestError::Rejected(format!("invalid: {reason}")), @@ -2351,7 +2358,7 @@ fn write_restriction_denial( ) -> Option { if restriction.banned { return Some(IngestError::ban( - BanRefusal::Banned, + BanRefusal::banned(restriction), IngestError::AuthFailed("blocked: you are banned from this community".to_string()), )); } @@ -3979,11 +3986,13 @@ mod postgres_tests { /// client retry-loop against an authorization decision. #[test] fn relay_admin_ban_maps_to_blocked_auth_failure() { - let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Banned); + let mapped = map_relay_admin_error(super::super::relay_admin::RelayAdminError::Banned( + crate::handlers::auth::BanSource::Own, + )); assert!(matches!( mapped, IngestError::Ban { - refusal: BanRefusal::Banned, + refusal: BanRefusal::Banned(crate::handlers::auth::BanSource::Own), .. } )); @@ -7518,7 +7527,7 @@ mod postgres_tests { match enforce_write_restriction(&state, &tenant, KIND_REPORT, &agent.public_key()).await { Err( err @ IngestError::Ban { - refusal: BanRefusal::Banned, + refusal: BanRefusal::Banned(crate::handlers::auth::BanSource::Owner), .. }, ) => match err.into_legacy() { diff --git a/crates/buzz-relay/src/handlers/moderation_commands.rs b/crates/buzz-relay/src/handlers/moderation_commands.rs index c51c247647..168f8bb5ea 100644 --- a/crates/buzz-relay/src/handlers/moderation_commands.rs +++ b/crates/buzz-relay/src/handlers/moderation_commands.rs @@ -115,8 +115,9 @@ pub async fn handle_moderation_command( ))), ) })?; - ensure_actor_not_banned(&restriction) - .map_err(|e| IngestError::ban(BanRefusal::Banned, IngestError::Rejected(e)))?; + ensure_actor_not_banned(&restriction).map_err(|e| { + IngestError::ban(BanRefusal::banned(&restriction), IngestError::Rejected(e)) + })?; execute_moderation_command(tenant, state, event, &actor) .await .map_err(IngestError::Rejected) @@ -633,6 +634,7 @@ mod tests { fn banned_admin_cannot_reach_an_unban_command() { let banned = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; assert_eq!( @@ -644,6 +646,7 @@ mod tests { // ban, so an authorized moderator can still lift it. let timed_out = buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(Utc::now() + Duration::minutes(5)), }; assert!(ensure_actor_not_banned(&timed_out).is_ok()); diff --git a/crates/buzz-relay/src/handlers/relay_admin.rs b/crates/buzz-relay/src/handlers/relay_admin.rs index 94d38fae30..bd5f7c56a4 100644 --- a/crates/buzz-relay/src/handlers/relay_admin.rs +++ b/crates/buzz-relay/src/handlers/relay_admin.rs @@ -134,8 +134,9 @@ fn may_set_workspace_profile( /// [`super::push_lease::AcceptError`] and its `map_push_accept_error` seam. #[derive(Debug, PartialEq, Eq)] pub(super) enum RelayAdminError { - /// Sender is under a durable community ban — `blocked:` / HTTP 403. - Banned, + /// Sender is under a durable community ban — `blocked:` / HTTP 403. The + /// source says whether its own row or its owner's decided it. + Banned(crate::handlers::auth::BanSource), /// Legacy command rejection — `invalid:` / HTTP 400. This is whatever /// [`execute_relay_admin_command`] returned as a `String`, which is mostly /// validation and authorization but also still includes that function's own @@ -162,7 +163,9 @@ fn admits_relay_admin_command( restriction: &buzz_db::moderation::RestrictionState, ) -> Result<(), RelayAdminError> { if restriction.banned { - return Err(RelayAdminError::Banned); + return Err(RelayAdminError::Banned( + crate::handlers::auth::BanSource::of(restriction), + )); } Ok(()) } @@ -537,11 +540,14 @@ mod postgres_tests { fn banned_actor_is_not_admitted_to_a_relay_admin_command() { let banned = buzz_db::moderation::RestrictionState { banned: true, + own_banned: true, muted_until: None, }; assert_eq!( admits_relay_admin_command(&banned), - Err(RelayAdminError::Banned), + Err(RelayAdminError::Banned( + crate::handlers::auth::BanSource::Own + )), "a durably banned admin must never reach a relay-admin command" ); } @@ -553,6 +559,7 @@ mod postgres_tests { fn timed_out_actor_is_still_admitted() { let timed_out = buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: Some(chrono::Utc::now() + chrono::Duration::minutes(5)), }; assert!( diff --git a/crates/buzz-relay/src/nip_fi_http.rs b/crates/buzz-relay/src/nip_fi_http.rs index 1578050ef8..177dc6ba8c 100644 --- a/crates/buzz-relay/src/nip_fi_http.rs +++ b/crates/buzz-relay/src/nip_fi_http.rs @@ -85,6 +85,79 @@ pub(crate) async fn with_resolved_community( GUARD_COMMUNITY.scope(community, next).await } +tokio::task_local! { + /// Enforce: the one verdict of the guarded request in flight. + static ENFORCE_VERDICT: RequestVerdict; +} + +/// An enforced HTTP request's single NIP-FI verdict. An agent token's +/// admission ends at its owner step, which may run in several rechecks (or +/// none, on an early exit or Git success): the first owner-decided refusal +/// is the verdict, else the request was admitted. Recorded once, when the +/// request ends. +#[derive(Default)] +struct RequestVerdict(std::sync::Mutex>); + +struct AgentVerdict { + community: metrics::SharedString, + pubkey: PublicKey, + refusal: Option<(DenialClass, &'static str)>, +} + +/// Run an enforced, guarded request inside its verdict. +pub(crate) async fn with_enforce_verdict(next: F) -> F::Output { + ENFORCE_VERDICT.scope(RequestVerdict::default(), next).await +} + +/// Defer an admitted agent token's verdict to the end of its request. +/// `false` outside a guarded request: the caller records the admit now. +fn defer_agent_verdict(community: &metrics::SharedString, pubkey: PublicKey) -> bool { + ENFORCE_VERDICT + .try_with(|verdict| { + *verdict.lock() = Some(AgentVerdict { + community: community.clone(), + pubkey, + refusal: None, + }); + }) + .is_ok() +} + +/// An owner-decided refusal of the request's agent token, with shadow's +/// `owner` reason. Only the first refusal of a request is its verdict; a +/// request with no deferred agent verdict records nothing. +pub(crate) fn owner_refused(class: DenialClass, reason: &'static str) { + let _ = ENFORCE_VERDICT.try_with(|verdict| { + if let Some(agent) = verdict.lock().as_mut() { + agent.refusal.get_or_insert((class, reason)); + } + }); +} + +impl RequestVerdict { + fn lock(&self) -> std::sync::MutexGuard<'_, Option> { + self.0 + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner) + } +} + +impl Drop for RequestVerdict { + fn drop(&mut self) { + let Some(agent) = self.lock().take() else { + return; + }; + match agent.refusal { + Some((class, reason)) => crate::nip_fi_shadow::record_denial( + "http", + agent.community, + WouldDeny::new(Stage::Owner, class, reason).by(Some(agent.pubkey)), + ), + None => crate::nip_fi_shadow::record_admit("http", &agent.community), + } + } +} + /// Enforce step 1 for one HTTP admission: the guard's resolution when the /// request passed through the guard, else one resolution (guard-exempt routes). pub(crate) async fn resolve_for_admission( @@ -376,6 +449,17 @@ where } let community = resolve_for_admission(communities, headers).await; + // Every denial names the verified NIP-98 key, as shadow's does. + let signed = std::cell::Cell::new(None); + let extract_nip98 = || { + let proof = extract_nip98(); + signed.set(proof.as_ref().ok().filter(|p| p.signed).map(|p| p.pubkey)); + proof + }; + let record = |deny: WouldDeny| { + let label = crate::nip_fi_shadow::label(&community); + crate::nip_fi_shadow::record_denial("http", label, deny.by(signed.get())); + }; let (proof, assertion) = evaluate_enforce_steps( headers, community.as_deref(), @@ -384,6 +468,7 @@ where extract_nip98, ) .map_err(|deny| { + record(deny); let reason = match deny.stage { Stage::Pairing => Some("nip_fi_http_key_mismatch"), Stage::DenySet => Some("nip_fi_http_denied_pubkey"), @@ -397,10 +482,22 @@ where // The handler may have awaited (tenant lookup) since the guard resolved // the community; a snapshot that went stale meanwhile admits nothing. if let Ok(community) = &community { - community.deadline().check().map_err(http_denial)?; + community.deadline().check().map_err(|class| { + record(WouldDeny::new( + Stage::Deadline, + class, + crate::nip_fi_shadow::STALE, + )); + http_denial(class) + })?; } - // Step 8: admit. + // Step 8: admit. An agent token's admission ends at its owner step, so + // its verdict is recorded when the request ends. + let label = crate::nip_fi_shadow::label(&community); + if assertion.owner().is_none() || !defer_agent_verdict(&label, proof.pubkey) { + crate::nip_fi_shadow::record_admit("http", &label); + } Ok(NipFiAdmission { proven_pubkey: proof.pubkey, assertion: Some(assertion), @@ -1345,6 +1442,41 @@ mod tests { } } + // HTTP admission records enforce's refusal once, naming the verified + // NIP-98 key, else `absent`. Mutations: dropping the `record` call, or + // attributing an unsigned proof → RED. + #[tokio::test(flavor = "current_thread")] + async fn enforce_http_denial_is_recorded_with_the_signed_key() { + use crate::nip_fi_core::test_support::TEST_COMMUNITY_URI; + use crate::nip_fi_shadow::tests::{enforce_count, enforce_records}; + let signer = nostr::Keys::generate().public_key(); + let verifier = ScriptedVerifier::new(Ok(Some(nostr::Keys::generate().public_key()))); + let mut headers = host_headers(); + headers.insert( + CLIENT_ATTACHED_HEADER, + HeaderValue::from_static("Bearer any.valid.looking.token"), + ); + let ((), lines, counts) = enforce_records(async { + let map = communities(); + let verifier = Some(&verifier as &dyn VerifyAssertion); + let mode = NipFiMode::Enforce; + let deny = &AlwaysAdmitStubDenyMap; + let signed = || Ok(Nip98Proof::new(signer, ())); + let unsigned = || Ok(Nip98Proof::unsigned(signer, ())); + let _ = admit_stateless(&headers, signed, &map, verifier, mode, deny).await; + let _ = admit_stateless(&headers, unsigned, &map, verifier, mode, deny).await; + }) + .await; + assert_eq!(lines.len(), 2, "{lines:?}"); + assert!( + lines[0].contains(&format!("pubkey=\"{}\"", signer.to_hex())), + "{lines:?}" + ); + assert!(lines[1].contains("pubkey=\"absent\""), "{lines:?}"); + let pairing = enforce_count(["http", "pairing", "denied", TEST_COMMUNITY_URI]); + assert_eq!(counts, [pairing.clone(), pairing]); + } + // ── R3 regression: Authorization cardinality ───────────────────────────── // // Thufir R3 / Carl F2: duplicate Authorization headers must be rejected in @@ -1367,6 +1499,59 @@ mod tests { // Off duplicate test would receive 403 instead of the legacy NIP-98 closure // result (401 from the always-failing closure below). The assert fires. + /// Enforce's strict proof is the deciding check's own result, counted + /// once where admission runs it: a pass and a rejection each record their + /// outcome and pass the result through unchanged, and a request refused + /// at cardinality, before its proof, records none. Mutation: recording + /// in `EnforcedProof::new` instead (a side check) counts the duplicate. + #[test] + fn enforce_strict_proof_records_the_deciding_check_once() { + use crate::nip_fi_shadow::EnforcedProof; + let recorder = metrics_util::debugging::DebuggingRecorder::new(); + metrics::with_local_recorder(&recorder, || { + let proof = EnforcedProof::for_test("bridge"); + assert_eq!(proof.record(Ok::<_, ()>(7)), Ok(7)); + assert_eq!(proof.record(Err::<(), _>("bad")), Err("bad")); + let mut headers = host_headers(); + for token in ["Nostr first.token", "Nostr second.token"] { + headers.append( + axum::http::header::AUTHORIZATION, + HeaderValue::from_static(token), + ); + } + let pubkey = any_pubkey(); + let outcome = admit_stateless::<_, (), _>( + &headers, + || proof.record(Ok(Nip98Proof::new(pubkey, ()))), + &communities(), + None::<&dyn VerifyAssertion>, + NipFiMode::Enforce, + &AlwaysAdmitStubDenyMap, + ) + .now_or_never() + .expect("env resolution never waits"); + assert!(outcome.is_err(), "cardinality refuses"); + }); + let mut strict: Vec = recorder + .snapshotter() + .snapshot() + .into_vec() + .into_iter() + .filter(|(key, ..)| key.key().name() == "buzz_nip_fi_enforce_strict_proof_total") + .map(|(key, _, _, value)| { + let outcome = key + .key() + .labels() + .find(|l| l.key() == "outcome") + .map(|l| l.value().to_owned()) + .unwrap_or_default(); + format!("{outcome}={value:?}") + }) + .collect(); + strict.sort(); + assert_eq!(strict, ["pass=Counter(1)", "rejected=Counter(1)"]); + } + #[test] fn enforce_duplicate_authorization_header_denied_403() { // Enforce mode + two Authorization fields → 403 EvidenceRejected before diff --git a/crates/buzz-relay/src/nip_fi_session.rs b/crates/buzz-relay/src/nip_fi_session.rs index 986efc0028..ef0e846f7b 100644 --- a/crates/buzz-relay/src/nip_fi_session.rs +++ b/crates/buzz-relay/src/nip_fi_session.rs @@ -105,6 +105,12 @@ pub(crate) async fn enforce_nip_fi_key_pairing( "reason" => "nip_fi_key_mismatch" ) .increment(1); + // The verdict is claimed before any denial frame is awaited. + let deny = crate::nip_fi_shadow::pairing_denial(assertion, proven_pubkey); + match &target { + PairingDenialTarget::Root(conn) => conn.community_control.deny_nip_fi_enforce(deny), + PairingDenialTarget::Audio { control, .. } => control.deny_nip_fi_enforce(deny), + } match target { PairingDenialTarget::Root(conn) => { @@ -197,7 +203,7 @@ pub(crate) fn spawn_nip_fi_expiry_task( std::time::Duration::ZERO }; let terminal = || { - control.deny_authorization(&terminal_ctrl_tx, route); + control.expire_authorization(&terminal_ctrl_tx, route); metrics::counter!("buzz_nip_fi_lease_expirations_total").increment(1); warn!( route = ?route, diff --git a/crates/buzz-relay/src/nip_fi_shadow.rs b/crates/buzz-relay/src/nip_fi_shadow.rs index b87e7dd4a3..fb5e120e53 100644 --- a/crates/buzz-relay/src/nip_fi_shadow.rs +++ b/crates/buzz-relay/src/nip_fi_shadow.rs @@ -25,6 +25,9 @@ //! | Series | Labels | One increment per | //! |---|---|---| //! | `buzz_nip_fi_shadow_total` | `route` (`http`, `ws`, `audio`), `stage`, `outcome`, `community` | NIP-FI decision enforce would make: one per HTTP request that reaches admission, one per WebSocket upgrade enforce would refuse, and one per observed session: at the AUTH where enforce would admit or deny it, or `deadline` when its deadline passes first. A request or upgrade whose community binding goes stale before enforce's final re-check also records `deadline`. An agent assertion enforce would refuse for its token owner, banned or not the agent's stored owner, records `owner` | +//! | `buzz_nip_fi_enforce_total` | as `buzz_nip_fi_shadow_total` | NIP-FI decision enforce made, the same unit: one per HTTP request admitted or denied (an agent token's at its owner step), one per refused upgrade, and one verdict per session: its admission, its NIP-FI refusal (pairing, deny set, `owner`, `deadline`), or none when refused for a non-NIP-FI reason. A denial's line is `nip-fi enforce deny`, written at once; an admit writes none | +//! | `buzz_nip_fi_enforce_session_end_total` | as `buzz_nip_fi_shadow_session_end_total` | admitted enforce session ended once, `expired` by its deadline or `revoked` by a disconnect (local or cross-pod, however often delivered). Its line is `nip-fi enforce session end`, with the admitted key | +//! | `buzz_nip_fi_enforce_strict_proof_total` | as `buzz_nip_fi_shadow_strict_proof_total` | strict NIP-98 proof enforce checked on a bridge or Blossom route, recorded from the deciding check; a rejection is the route's 403, or 401 when the proof is missing | //! | `buzz_nip_fi_shadow_strict_proof_total` | `route` (`bridge`, `blossom`), `outcome` (`pass`, `rejected`), `community` | strict NIP-98 side check on a route whose proof is stricter in enforce (payload tag, Blossom proof); not every request runs one | //! | `buzz_nip_fi_shadow_session_end_total` | `route` (`ws`, `audio`), `reason` (`expired`, `revoked`), `community` | admitted shadow session enforce would have ended; a session never admitted records none | //! | `buzz_nip_fi_shadow_disconnect_total` | `route` (`admin`, `cross_pod`), `outcome` | disconnect-path event that moves a real disconnect counter in enforce: an accepted admin command, a capacity rejection, a subscriber lag, or a cross-pod capacity or poison failsafe. An admin command refused for its header, body, proof, replay, or a dependency error records nothing | @@ -173,24 +176,203 @@ pub(crate) fn record_pending( ) .increment(1); // The counter is the record; only a would-deny earns a line. - let deny = verdict.err()?; - let line = PendingLine { + Some(PendingLine::new( + Mode::Shadow, route, - stage, - outcome, - reason: deny.reason, community, - written: std::sync::atomic::AtomicBool::new(false), + verdict.err()?, + )) +} + +/// Record one denial enforce actually returned on `buzz_nip_fi_enforce_total`, +/// the enforce twin of `buzz_nip_fi_shadow_total`, and write its line at once +/// with the key `deny` names, else `absent`. A refused upgrade or guarded +/// request ends before any later proof, so nothing waits for one. +pub(crate) fn record_denial(route: &'static str, community: SharedString, deny: WouldDeny) { + count_enforce( + route, + deny.stage.label(), + class_label(deny.class), + &community, + ); + PendingLine::new(Mode::Enforce, route, community, deny).finish(); +} + +/// Record one admission enforce granted, shadow's `admit` unit. No line, as +/// shadow writes none for an admit. +pub(crate) fn record_admit(route: &'static str, community: &SharedString) { + count_enforce(route, "admit", "admit", community); +} + +fn count_enforce( + route: &'static str, + stage: &'static str, + outcome: &'static str, + community: &SharedString, +) { + metrics::counter!( + "buzz_nip_fi_enforce_total", + "route" => route, + "stage" => stage, + "outcome" => outcome, + "community" => community.clone() + ) + .increment(1); +} + +/// The key-pairing refusal of `pubkey`, the NIP-42 key proven against +/// `assertion`, with shadow's reason. +pub(crate) fn pairing_denial( + assertion: &buzz_auth::VerifiedAssertion, + pubkey: PublicKey, +) -> WouldDeny { + let reason = if assertion.asserted_key().is_some() { + "key_mismatch" + } else { + "no_asserted_key" }; - if let Some(key) = deny.pubkey { - line.prove(key); + WouldDeny::new(Stage::Pairing, DenialClass::AuthorizationDenied, reason).by(Some(pubkey)) +} + +/// Where an enforced socket's single NIP-FI verdict stands. +enum EnforcePhase { + Pending, + Admitted(PublicKey), + Ended, +} + +/// An enforced socket's NIP-FI lifecycle: exactly one verdict (admit or +/// denial) and, once admitted, exactly one end. Every transition is claimed +/// under one lock before any terminal frame is awaited, so a refusal, a +/// revocation and the deadline cannot each record the same socket. +pub(crate) struct EnforceSession { + route: &'static str, + community: SharedString, + asserted: Option, + phase: std::sync::Mutex, +} + +impl EnforceSession { + pub(crate) fn new( + route: &'static str, + community: SharedString, + asserted: Option, + ) -> Self { + Self { + route, + community, + asserted, + phase: std::sync::Mutex::new(EnforcePhase::Pending), + } } - Some(line) + + fn step(&self, f: impl FnOnce(&mut EnforcePhase)) { + f(&mut self + .phase + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner)); + } + + /// The admission: counted once, if no verdict was reached first. + pub(crate) fn admit(&self, pubkey: PublicKey) { + self.step(|phase| { + if let EnforcePhase::Pending = phase { + *phase = EnforcePhase::Admitted(pubkey); + record_admit(self.route, &self.community); + } + }); + } + + /// A NIP-FI refusal of the pending session. + pub(crate) fn deny(&self, deny: WouldDeny) { + self.step(|phase| { + if let EnforcePhase::Pending = phase { + *phase = EnforcePhase::Ended; + record_denial(self.route, self.community.clone(), deny); + } + }); + } + + /// A refusal for a non-NIP-FI reason: the session ends unrecorded, as + /// shadow retires it. + pub(crate) fn retire(&self) { + self.step(|phase| { + if let EnforcePhase::Pending = phase { + *phase = EnforcePhase::Ended; + } + }); + } + + /// The deadline: a pending session records shadow's `session_deadline` + /// denial; an admitted one its `expired` end. + pub(crate) fn expire(&self) { + let deny = WouldDeny::new( + Stage::Deadline, + DenialClass::EvidenceRejected, + "session_deadline", + ); + self.deny(deny.by(self.asserted)); + self.end("expired"); + } + + /// A deny-set revocation: a pending session is refused by the deny set; + /// an admitted one records its `revoked` end. + pub(crate) fn revoke(&self) { + self.deny(DENY_SET.by(self.asserted)); + self.end("revoked"); + } + + fn end(&self, reason: &'static str) { + self.step(|phase| { + if let EnforcePhase::Admitted(pubkey) = *phase { + *phase = EnforcePhase::Ended; + metrics::counter!( + "buzz_nip_fi_enforce_session_end_total", + "route" => self.route, + "reason" => reason, + "community" => self.community.clone() + ) + .increment(1); + tracing::info!( + mode = "enforce", + route = self.route, + reason, + pubkey = pubkey.to_hex(), + community = %self.community, + "nip-fi enforce session end" + ); + } + }); + } +} + +/// The `community` label of an enforce denial after the upgrade, from the +/// connection's bound Host: as [`crate::nip_fi_core::ResolvedCommunity`] +/// labels it, the configured URI for an `env` community, else `bound`. +pub(crate) fn enforce_label(state: &crate::state::AppState, host: &str) -> SharedString { + let nip_fi = &state.config.nip_fi; + match nip_fi.source { + crate::nip_fi_config::CommunitySource::Database => SharedString::const_str(BOUND), + crate::nip_fi_config::CommunitySource::Env => nip_fi + .communities + .resolve(host) + .map_or(SharedString::const_str(UNMAPPED), |binding| { + binding.expected_aud().to_owned().into() + }), + } +} + +/// Whether a line records shadow's would-deny or enforce's denial. +#[derive(Clone, Copy)] +enum Mode { + Shadow, + Enforce, } /// A counted would-deny's info line, written exactly once: by the first key /// proven for it, else as `absent` when finished or dropped. pub(crate) struct PendingLine { + mode: Mode, route: &'static str, stage: &'static str, outcome: &'static str, @@ -200,6 +382,22 @@ pub(crate) struct PendingLine { } impl PendingLine { + fn new(mode: Mode, route: &'static str, community: SharedString, deny: WouldDeny) -> Self { + let line = Self { + mode, + route, + stage: deny.stage.label(), + outcome: class_label(deny.class), + reason: deny.reason, + community, + written: std::sync::atomic::AtomicBool::new(false), + }; + if let Some(key) = deny.pubkey { + line.prove(key); + } + line + } + /// Write the line for `pubkey`, a key the client proved, unless it is /// already written. pub(crate) fn prove(&self, pubkey: PublicKey) { @@ -215,15 +413,30 @@ impl PendingLine { if self.written.swap(true, std::sync::atomic::Ordering::AcqRel) { return; } - tracing::info!( - route = self.route, - stage = self.stage, - outcome = self.outcome, - reason = self.reason, - pubkey, - community = %self.community, - "nip-fi shadow would-deny" - ); + // Both lines stay in this module: production's log filter admits + // `buzz_relay::nip_fi_shadow` at info. + match self.mode { + Mode::Shadow => tracing::info!( + mode = "shadow", + route = self.route, + stage = self.stage, + outcome = self.outcome, + reason = self.reason, + pubkey, + community = %self.community, + "nip-fi shadow would-deny" + ), + Mode::Enforce => tracing::info!( + mode = "enforce", + route = self.route, + stage = self.stage, + outcome = self.outcome, + reason = self.reason, + pubkey, + community = %self.community, + "nip-fi enforce deny" + ), + } } } @@ -285,8 +498,9 @@ const fn class_label(class: DenialClass) -> &'static str { } } -/// In shadow mode only, record whether `strict` (a pure check) would reject, -/// on its own counter: a pass is one proof, not an admission verdict. +/// Shadow only: record whether `strict` (a pure side check) rejects, on +/// shadow's own counter. A pass is one proof, not an admission verdict. +/// Enforce records its deciding proof check instead ([`EnforcedProof`]). pub(crate) async fn observe_strict_proof( state: &crate::state::AppState, headers: &HeaderMap, @@ -307,6 +521,53 @@ pub(crate) async fn observe_strict_proof( } } +/// Enforce's strict proof on a route: records the outcome of the proof check +/// that decides admission, once, where it runs. Nothing is verified twice, +/// and a request refused before its proof (duplicate Authorization) records +/// no proof. Inert outside enforce. +pub(crate) struct EnforcedProof(Option<(&'static str, SharedString)>); + +impl EnforcedProof { + pub(crate) fn new( + state: &crate::state::AppState, + headers: &HeaderMap, + route: &'static str, + ) -> Self { + Self(state.config.nip_fi.mode.enforces().then(|| { + let host = headers + .get(axum::http::header::HOST) + .and_then(|v| v.to_str().ok()) + .unwrap_or(""); + (route, enforce_label(state, host)) + })) + } + + /// An enforcing observation of `route`, without a state. + #[cfg(test)] + pub(crate) fn for_test(route: &'static str) -> Self { + Self(Some((route, SharedString::const_str(BOUND)))) + } + + /// Passes the deciding check's `result` through, counting it. + pub(crate) fn record(&self, result: Result) -> Result { + if let Some((route, community)) = &self.0 { + let outcome = if result.is_ok() { + "pass" + } else { + class_label(DenialClass::EvidenceRejected) + }; + metrics::counter!( + "buzz_nip_fi_enforce_strict_proof_total", + "route" => *route, + "outcome" => outcome, + "community" => community.clone() + ) + .increment(1); + } + result + } +} + /// Bind the request's tenant from its Host header, as every HTTP handler's /// row zero does. `None` means the Host bound no community; the caller keeps /// its own legacy rejection, and shadow records enforce's verdict first. @@ -348,7 +609,7 @@ pub(crate) mod tests { use std::sync::Arc; use axum::http::{header::HOST, HeaderValue}; - use buzz_auth::NipFiMode; + use buzz_auth::{DenialClass, NipFiMode}; use metrics_util::debugging::{DebugValue, DebuggingRecorder}; use crate::nip_fi_core::test_support::{communities, TEST_COMMUNITY_URI, TEST_HOST}; @@ -572,14 +833,365 @@ pub(crate) mod tests { /// The would-deny lines logged so far. pub(crate) fn lines(&self) -> Vec { + self.lines_of("nip-fi shadow would-deny") + } + + /// The enforce denial lines logged so far. + pub(crate) fn enforce_lines(&self) -> Vec { + self.lines_of("nip-fi enforce deny") + } + + fn lines_of(&self, message: &str) -> Vec { let log = String::from_utf8(self.out.0.lock().unwrap().clone()).unwrap(); log.lines() - .filter(|l| l.contains("nip-fi shadow would-deny")) + .filter(|l| l.contains(message)) .map(str::to_owned) .collect() } } + /// What enforce recorded while running `body`: its denial lines and the + /// `(route, stage, outcome, community)` of every + /// `buzz_nip_fi_enforce_total` increment. Fails if `body` touched + /// the shadow counter. + pub(crate) async fn enforce_records( + body: F, + ) -> (F::Output, Vec, Vec<[String; 4]>) { + let recorder = DebuggingRecorder::new(); + let log = WouldDenyLog::capture(); + let output = { + let _guard = metrics::set_default_local_recorder(&recorder); + body.await + }; + let mut counts = Vec::new(); + for (key, _, _, value) in recorder.snapshotter().snapshot().into_vec() { + let key = key.key(); + assert_ne!( + key.name(), + "buzz_nip_fi_shadow_total", + "enforce counted as shadow" + ); + if key.name() != "buzz_nip_fi_enforce_total" { + continue; + } + assert_shadow_schema(key); + let label = |name| { + key.labels() + .find(|l| l.key() == name) + .map_or("-", |l| l.value()) + .to_owned() + }; + let DebugValue::Counter(n) = value else { + unreachable!() + }; + for _ in 0..n { + counts.push(["route", "stage", "outcome", "community"].map(label)); + } + } + counts.sort(); + (output, log.enforce_lines(), counts) + } + + /// `[route, stage, outcome, community]` as owned labels. + pub(crate) fn enforce_count(labels: [&str; 4]) -> [String; 4] { + labels.map(str::to_owned) + } + + // Mutations: counting on `buzz_nip_fi_shadow_total`, logging the shadow + // message or `mode`, skipping the immediate write, or logging below info + // → RED. + #[tokio::test(flavor = "current_thread")] + async fn enforce_denial_counts_its_own_series_and_logs_once_at_info() { + use super::{Stage, WouldDeny}; + use buzz_auth::DenialClass; + let key = nostr::Keys::generate().public_key(); + let ((), lines, counts) = enforce_records(async { + let pairing = WouldDeny::new( + Stage::Pairing, + DenialClass::AuthorizationDenied, + "key_mismatch", + ); + super::record_denial("ws", super::BOUND.into(), pairing.by(Some(key))); + let missing = WouldDeny::assertion(crate::nip_fi_core::AssertionRejection::Transport( + DenialClass::MissingEvidence, + )); + super::record_denial("http", super::BOUND.into(), missing); + }) + .await; + let log = lines.join("\n"); + assert_eq!(lines.len(), 2, "{log}"); + assert!(lines.iter().all(|l| l.contains(" INFO ") + && l.contains("mode=\"enforce\"") + && !l.contains("would-deny"))); + assert!(lines[0].contains("reason=\"key_mismatch\""), "{log}"); + assert!( + lines[0].contains(&format!("pubkey=\"{}\"", key.to_hex())), + "{log}" + ); + assert!(lines[1].contains("reason=\"missing_assertion\""), "{log}"); + assert!(lines[1].contains("pubkey=\"absent\""), "{log}"); + assert_eq!( + counts, + [ + enforce_count(["http", "assertion", "missing", "bound"]), + enforce_count(["ws", "pairing", "denied", "bound"]), + ] + ); + } + + // The pairing refusal names the proven key; its reason follows the + // assertion. Mutation: deriving the reason from the proven key → RED. + #[test] + fn pairing_denial_reason_follows_the_assertion() { + let key = nostr::Keys::generate().public_key(); + let other = + buzz_auth::VerifiedAssertion::new_for_test(nostr::Keys::generate().public_key()); + let claimless = buzz_auth::VerifiedAssertion::for_test(None, vec![chrono::Utc::now()]); + let denied = |reason| { + super::WouldDeny::new( + super::Stage::Pairing, + DenialClass::AuthorizationDenied, + reason, + ) + .by(Some(key)) + }; + assert_eq!(super::pairing_denial(&other, key), denied("key_mismatch")); + assert_eq!( + super::pairing_denial(&claimless, key), + denied("no_asserted_key") + ); + } + + /// Runs `setup`, then `body` on its output, on one current-thread + /// runtime, and returns each enforce record `body` made as + /// `route stage/outcome` or `route end/reason`, sorted, the enforce + /// lines it wrote, how many authorization pool acquisitions (ban, + /// membership and owner-link reads) it made, and its output. Setup's + /// seeding is not observed. + pub(crate) fn enforce_observed>( + setup: impl std::future::Future, + body: impl FnOnce(T) -> F, + ) -> (Vec, Vec, u64, R) { + let recorder = DebuggingRecorder::new(); + let log = WouldDenyLog::capture(); + let rt = tokio::runtime::Builder::new_current_thread() + .enable_all() + .build() + .unwrap(); + let seeded = rt.block_on(setup); + let output = metrics::with_local_recorder(&recorder, || rt.block_on(body(seeded))); + let (records, reads) = enforce_records_of(&recorder); + let mut lines = log.enforce_lines(); + lines.extend(log.lines_of("nip-fi enforce session end")); + (records, lines, reads, output) + } + + /// Each enforce record in `recorder` as `route stage/outcome` or + /// `route end/reason`, sorted, and its authorization pool acquisitions. + pub(crate) fn enforce_records_of(recorder: &DebuggingRecorder) -> (Vec, u64) { + let (mut records, mut reads) = (Vec::new(), 0); + for (key, _, _, value) in recorder.snapshotter().snapshot().into_vec() { + let key = key.key(); + let label = |name| { + key.labels() + .find(|l| l.key() == name) + .map_or(String::new(), |l| l.value().to_owned()) + }; + let DebugValue::Counter(n) = value else { + continue; + }; + let record = match key.name() { + "buzz_nip_fi_enforce_total" => { + format!("{} {}/{}", label("route"), label("stage"), label("outcome")) + } + "buzz_nip_fi_enforce_session_end_total" => { + format!("{} end/{}", label("route"), label("reason")) + } + "buzz_db_pool_acquire_attempts_total" if label("operation") == "authorization" => { + reads += n; + continue; + } + _ => continue, + }; + records.extend(std::iter::repeat_n(record, n as usize)); + } + records.sort(); + (records, reads) + } + + /// Runs `request` with a local recorder and log capture; returns its + /// output, its enforce records and its enforce denial lines. + pub(crate) async fn enforce_records_during( + request: F, + ) -> (F::Output, Vec, Vec) { + let recorder = DebuggingRecorder::new(); + let log = WouldDenyLog::capture(); + let output = { + let _local = metrics::set_default_local_recorder(&recorder); + request.await + }; + (output, enforce_records_of(&recorder).0, log.enforce_lines()) + } + + /// Every `buzz_nip_fi_enforce*` series `body` touched, as + /// `name labels=value` lines, sorted, with the enforce lines it wrote. + fn enforce_series(body: impl FnOnce()) -> (Vec, Vec) { + let recorder = DebuggingRecorder::new(); + let log = WouldDenyLog::capture(); + { + let _guard = metrics::set_default_local_recorder(&recorder); + body(); + } + let mut names = Vec::new(); + for (key, _, _, value) in recorder.snapshotter().snapshot().into_vec() { + let key = key.key(); + if !key.name().starts_with("buzz_nip_fi_enforce") { + continue; + } + let labels: Vec<_> = key + .labels() + .map(|l| format!("{}={}", l.key(), l.value())) + .collect(); + let DebugValue::Counter(n) = value else { + panic!("{} is not a counter", key.name()); + }; + names.push(format!("{} {} ={n}", key.name(), labels.join(","))); + } + names.sort(); + let mut lines = log.enforce_lines(); + lines.extend(log.lines_of("nip-fi enforce session end")); + (names, lines) + } + + // One verdict per socket, whichever comes first: a refusal claimed + // before the deadline leaves the deadline unrecorded, and a deadline + // first leaves the later refusal unrecorded. Mutation: dropping the + // `Pending` check in `deny` → RED. + #[test] + fn a_refusal_and_the_deadline_record_one_verdict_in_either_order() { + let asserted = nostr::Keys::generate().public_key(); + let pairing = super::WouldDeny::new( + super::Stage::Pairing, + DenialClass::AuthorizationDenied, + "key_mismatch", + ); + let (refusal_first, lines) = enforce_series(|| { + let session = super::EnforceSession::new("ws", "c".into(), Some(asserted)); + session.deny(pairing.by(Some(asserted))); + session.expire(); + }); + assert_eq!( + refusal_first, + ["buzz_nip_fi_enforce_total route=ws,stage=pairing,outcome=denied,community=c =1"] + ); + assert_eq!(lines.len(), 1, "{lines:?}"); + let (deadline_first, lines) = enforce_series(|| { + let session = super::EnforceSession::new("audio", "c".into(), Some(asserted)); + session.expire(); + session.deny(pairing.by(Some(asserted))); + session.admit(asserted); + }); + assert_eq!( + deadline_first, + ["buzz_nip_fi_enforce_total route=audio,stage=deadline,outcome=rejected,community=c =1"] + ); + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!( + lines[0].contains("reason=\"session_deadline\""), + "{lines:?}" + ); + } + + // A non-NIP-FI refusal retires the session: its later deadline records + // nothing, as shadow's retired session. Mutation: `retire` leaving the + // session pending → RED. + #[test] + fn a_retired_session_records_nothing_at_its_deadline() { + let (series, lines) = enforce_series(|| { + let session = super::EnforceSession::new("ws", "c".into(), None); + session.retire(); + session.expire(); + session.revoke(); + }); + assert!( + series.is_empty() && lines.is_empty(), + "{series:?} {lines:?}" + ); + } + + // An admitted session counts one admit and ends once: repeated + // revocations (local and cross-pod) and a later deadline add nothing; a + // pending revocation is the deny-set refusal. Mutation: dropping the + // `Admitted` check in `end` → RED. + #[test] + fn an_admitted_session_ends_once() { + let asserted = nostr::Keys::generate().public_key(); + let admitted = nostr::Keys::generate().public_key(); + let (series, lines) = enforce_series(|| { + let session = super::EnforceSession::new("ws", "c".into(), Some(asserted)); + session.admit(admitted); + session.admit(admitted); + session.revoke(); + session.revoke(); + session.expire(); + let pending = super::EnforceSession::new("audio", "c".into(), Some(asserted)); + pending.revoke(); + }); + assert_eq!( + series, + [ + "buzz_nip_fi_enforce_session_end_total route=ws,reason=revoked,community=c =1", + "buzz_nip_fi_enforce_total route=audio,stage=deny_set,outcome=denied,community=c =1", + "buzz_nip_fi_enforce_total route=ws,stage=admit,outcome=admit,community=c =1", + ] + ); + assert_eq!(lines.len(), 2, "{lines:?}"); + assert!(lines + .iter() + .any(|l| l.contains("reason=\"revoked\"") && l.contains(&admitted.to_hex()))); + } + + #[tokio::test(flavor = "current_thread")] + async fn enforce_session_expiry_tells_pending_from_admitted() { + let asserted = nostr::Keys::generate().public_key(); + let admitted = nostr::Keys::generate().public_key(); + let recorder = DebuggingRecorder::new(); + let log = WouldDenyLog::capture(); + { + let _guard = metrics::set_default_local_recorder(&recorder); + super::EnforceSession::new("ws", "c".into(), Some(asserted)).expire(); + let session = super::EnforceSession::new("audio", "c".into(), Some(asserted)); + session.admit(admitted); + session.expire(); + } + let denies = log.enforce_lines(); + assert_eq!(denies.len(), 1, "{denies:?}"); + assert!(denies[0].contains("reason=\"session_deadline\"")); + assert!(denies[0].contains(&format!("pubkey=\"{}\"", asserted.to_hex()))); + let ends = log.lines_of("nip-fi enforce session end"); + assert_eq!(ends.len(), 1, "{ends:?}"); + assert!(ends[0].contains(" INFO ") && ends[0].contains("community=c")); + assert!(ends[0].contains(&admitted.to_hex()), "{ends:?}"); + let mut names = Vec::new(); + for (key, _, _, _) in recorder.snapshotter().snapshot().into_vec() { + let key = key.key(); + let labels: Vec<_> = key + .labels() + .map(|l| format!("{}={}", l.key(), l.value())) + .collect(); + names.push(format!("{} {}", key.name(), labels.join(","))); + } + names.sort(); + assert_eq!( + names, + [ + "buzz_nip_fi_enforce_session_end_total route=audio,reason=expired,community=c", + "buzz_nip_fi_enforce_total route=audio,stage=admit,outcome=admit,community=c", + "buzz_nip_fi_enforce_total route=ws,stage=deadline,outcome=rejected,community=c", + ] + ); + } + /// The counted line of a `route` upgrade would-deny for a missing /// assertion, as `check_nip_fi_at_upgrade` hands it to the connection. pub(crate) fn upgrade_line(route: &'static str) -> Arc { diff --git a/crates/buzz-relay/src/nip_fi_shadow_session.rs b/crates/buzz-relay/src/nip_fi_shadow_session.rs index c8599db826..3b43f8fb88 100644 --- a/crates/buzz-relay/src/nip_fi_shadow_session.rs +++ b/crates/buzz-relay/src/nip_fi_shadow_session.rs @@ -264,16 +264,35 @@ impl ShadowSession { /// One AUTH attempt, audio's through its join commit: refused, or dropped, /// while the session is still pending, it ended unadmitted for a non-NIP-FI /// reason (NIP-42 failure, ordinary policy refusal), so the session retires -/// without a record. -pub(crate) struct AuthAttempt<'a>(pub(crate) Option<&'a Arc>); +/// without a record. Both the shadow and the enforce session retire. +pub(crate) struct AuthAttempt<'a>(&'a crate::state::CommunityConnectionControl); + +impl<'a> AuthAttempt<'a> { + pub(crate) fn new(control: &'a crate::state::CommunityConnectionControl) -> Self { + Self(control) + } -impl AuthAttempt<'_> { /// Retires a pending session where the refusal is decided, before the /// refusal's frames and cleanup are awaited. pub(crate) fn refused(&self) { - if let Some(session) = self.0 { + if let Some(session) = self.0.nip_fi_shadow() { session.retire_pending(); } + if let Some(session) = self.0.nip_fi_enforce() { + session.retire(); + } + } +} + +impl AuthAttempt<'_> { + /// An effect permit refused at `gate`: when its deadline has passed, the + /// gate saw the expiry before the expiry worker could, so the enforce + /// session claims that deadline outcome now, before this attempt's + /// retirement could end it unrecorded. Cancellation alone stays quiet. + pub(crate) fn effect_refused(&self, gate: &crate::nip_fi_gate::SessionAdmissionGate) { + if let Some(session) = self.0.nip_fi_enforce().filter(|_| gate.deadline_passed()) { + session.expire(); + } } } @@ -516,6 +535,65 @@ pub(crate) mod tests { } } + /// Audio's owner-link refusal is recorded through the same admission + /// seam root uses (`owner_link_denial` → `record_enforce_refusal`), on + /// route `audio`, with root's reasons: a conflicting stored owner is + /// `not_stored_owner`, an unwritable link `owner_link_unavailable`; a + /// NIP-OA (non-token) link failure is no owner verdict and retires. + /// Mutation: dropping `owner_reason` from `owner_link_denial` records + /// nothing for the token cases. + #[test] + fn audio_owner_link_refusal_shares_roots_seam_and_reasons() { + use crate::api::relay_members::OwnerLink; + for (link, token, expected, reason) in [ + ( + OwnerLink::Conflict, + true, + &["audio owner/denied"][..], + Some("not_stored_owner"), + ), + ( + OwnerLink::Unavailable, + true, + &["audio owner/unavailable"][..], + Some("owner_link_unavailable"), + ), + (OwnerLink::Unavailable, false, &[][..], None), + ] { + let (records, lines, _, ()) = + crate::nip_fi_shadow::tests::enforce_observed(async {}, |()| async move { + let (agent, owner) = ( + nostr::Keys::generate().public_key(), + nostr::Keys::generate().public_key(), + ); + let control = crate::state::CommunityConnectionControl::new( + tokio_util::sync::CancellationToken::new(), + ); + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "audio", + crate::nip_fi_shadow::BOUND.into(), + Some(agent), + )); + let denial = crate::handlers::auth::owner_link_denial(link, token); + assert!(denial.is_some(), "{link:?} refuses"); + crate::handlers::auth::record_enforce_refusal( + &control, + denial.as_ref(), + Some(&owned_assertion(agent, owner)), + ); + }); + assert_eq!(records, expected, "{link:?} token={token}: {lines:?}"); + if let Some(reason) = reason { + assert!( + lines.len() == 1 + && lines[0].contains(&format!("reason=\"{reason}\"")) + && lines[0].contains("route=\"audio\""), + "{lines:?}" + ); + } + } + } + /// An agent assertion for `agent` acting for `owner`, valid for an hour. pub(crate) fn owned_assertion(agent: PublicKey, owner: PublicKey) -> VerifiedAssertion { VerifiedAssertion::for_test(Some(agent), vec![Utc::now() + Duration::hours(1)]) diff --git a/crates/buzz-relay/src/nip_fi_upgrade.rs b/crates/buzz-relay/src/nip_fi_upgrade.rs index fdaa2cc693..f8b9f92fc5 100644 --- a/crates/buzz-relay/src/nip_fi_upgrade.rs +++ b/crates/buzz-relay/src/nip_fi_upgrade.rs @@ -16,8 +16,7 @@ use axum::http::{HeaderMap, Response}; use buzz_auth::{DenialClass, NipFiMode, VerifiedAssertion, VerifyAssertion}; use crate::nip_fi_core::{ - evaluate_attached_assertion, http_denial, AdmissionDeadline, AssertionRejection, Communities, - ResolvedCommunity, + evaluate_attached_assertion, http_denial, AdmissionDeadline, Communities, ResolvedCommunity, }; /// Outcome of NIP-FI assertion validation at upgrade time. @@ -75,6 +74,23 @@ pub(crate) fn observe_deadline( } } +/// Record enforce's refusal of an admitted upgrade whose community binding +/// went stale during the tenant lookup. +pub(crate) fn record_stale( + route: crate::nip_fi_session::NipFiWsRoute, + community: metrics::SharedString, + assertion: Option<&VerifiedAssertion>, + class: DenialClass, +) { + let deny = crate::nip_fi_shadow::WouldDeny::new( + crate::nip_fi_shadow::Stage::Deadline, + class, + crate::nip_fi_shadow::STALE, + ); + let key = assertion.and_then(VerifiedAssertion::asserted_key); + crate::nip_fi_shadow::record_denial(route.shadow_label(), community, deny.by(key)); +} + impl NipFiUpgradeOutcome { /// The enforced and the shadow-observed assertion, or the denial response. pub(crate) fn into_assertions(self) -> Result>> { @@ -151,19 +167,23 @@ pub(crate) async fn check_nip_fi_at_upgrade<'a>( } // Enforce mode: resolve the Host's community, then validate the assertion. - let community = match communities.resolve(headers).await { - Ok(community) => community, - Err(class) => return NipFiUpgradeOutcome::Denied(http_denial(class)), + // Every refusal is recorded as shadow records its would-deny; the + // refused upgrade never reaches AUTH, so its line is `absent`. + let community = communities.resolve(headers).await; + let label = crate::nip_fi_shadow::label(&community); + let deny = match community { + Ok(community) => match evaluate_attached_assertion(headers, &community, verifier) { + Ok(assertion) => return NipFiUpgradeOutcome::Admitted(assertion, community.deadline()), + Err(rejection) => crate::nip_fi_shadow::WouldDeny::assertion(rejection), + }, + Err(class) => crate::nip_fi_shadow::WouldDeny::new( + crate::nip_fi_shadow::Stage::Community, + class, + crate::nip_fi_shadow::UNRESOLVED, + ), }; - match evaluate_attached_assertion(headers, &community, verifier) { - Ok(assertion) => NipFiUpgradeOutcome::Admitted(assertion, community.deadline()), - Err(rejection) => { - if let AssertionRejection::Verifier(err) = rejection { - tracing::debug!(code = err.code(), "nip-fi assertion denied at upgrade"); - } - NipFiUpgradeOutcome::Denied(http_denial(rejection.denial_class())) - } - } + crate::nip_fi_shadow::record_denial(route.shadow_label(), label, deny); + NipFiUpgradeOutcome::Denied(http_denial(deny.class)) } #[cfg(test)] @@ -838,4 +858,51 @@ mod tests { ]; assert_eq!(records, expected); } + + // Each enforce refusal is counted once with its stage and written once + // as `absent`: the refused upgrade never reaches AUTH. An admit records + // nothing. Mutations: dropping either `record_denial` path, or recording + // an admit → RED. + #[tokio::test(flavor = "current_thread")] + async fn enforce_upgrade_denials_are_recorded_once_as_absent() { + use crate::nip_fi_core::test_support::TEST_COMMUNITY_URI; + use crate::nip_fi_shadow::tests::{enforce_count, enforce_records}; + let map = communities(); + let pass = ScriptedVerifier::new(Ok(None)); + let ((), lines, counts) = enforce_records(async { + let mode = buzz_auth::NipFiMode::Enforce; + let unmapped = HeaderMap::new(); + let missing = host_headers(); + let attached = headers_with("Bearer a.b.c"); + for (headers, verifier) in [ + (&unmapped, None), + (&missing, None), + (&attached, Some(&pass)), + ] { + let verifier = verifier.map(|v| v as &dyn VerifyAssertion); + let _ = check_nip_fi_at_upgrade(ROOT, headers, &map, verifier, mode).await; + } + }) + .await; + assert_eq!(lines.len(), 2, "{lines:?}"); + assert!( + lines.iter().all(|l| l.contains("pubkey=\"absent\"")), + "{lines:?}" + ); + assert!( + lines[0].contains("reason=\"community_unresolved\""), + "{lines:?}" + ); + assert!( + lines[1].contains("reason=\"missing_assertion\""), + "{lines:?}" + ); + assert_eq!( + counts, + [ + enforce_count(["ws", "assertion", "missing", TEST_COMMUNITY_URI]), + enforce_count(["ws", "community", "unavailable", "unmapped"]), + ] + ); + } } diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index 6800ca7686..64d5c46226 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -204,11 +204,15 @@ async fn nip_fi_assertion_guard( } match (verdict, community) { (Ok(()), Ok(community)) => { - crate::nip_fi_http::with_resolved_community(Ok(community), next.run(request)).await + let run = crate::nip_fi_http::with_resolved_community(Ok(community), next.run(request)); + crate::nip_fi_http::with_enforce_verdict(run).await } - (Err(crate::nip_fi_shadow::WouldDeny { class, .. }), _) | (Ok(()), Err(class)) => { - http_denial(class) + (Err(deny), community) => { + let label = crate::nip_fi_shadow::label(&community); + crate::nip_fi_shadow::record_denial("http", label, deny); + http_denial(deny.class) } + (Ok(()), Err(class)) => http_denial(class), } } @@ -717,6 +721,11 @@ async fn nip11_or_ws_handler( if let Some(assertion) = &nip_fi_assertion { if let Some(deny_map) = state.nip_fi_deny_map.as_deref() { if crate::nip_fi_core::assertion_denied(deny_map, assertion, chrono::Utc::now()) { + crate::nip_fi_shadow::record_denial( + "ws", + crate::nip_fi_shadow::enforce_label(&state, raw_host), + crate::nip_fi_shadow::DENY_SET.by(assertion.asserted_key()), + ); return http_denial(buzz_auth::DenialClass::AuthorizationDenied).into_response(); } } @@ -751,6 +760,12 @@ async fn nip11_or_ws_handler( // The tenant lookup awaited since the community resolved; a snapshot // that went stale meanwhile accepts no socket. if let Err(class) = nip_fi_deadline.check() { + crate::nip_fi_upgrade::record_stale( + crate::nip_fi_session::NipFiWsRoute::Root, + crate::nip_fi_shadow::enforce_label(&state, raw_host), + nip_fi_assertion.as_ref(), + class, + ); return http_denial(class).into_response(); } let shadow_assertion = crate::nip_fi_upgrade::observe_deadline( @@ -4435,6 +4450,26 @@ mod tests { } } + // The guard records its refusal once, as `absent`: no handler runs to + // prove a key. Mutation: dropping the guard's `record_denial` → RED. + #[tokio::test(flavor = "current_thread")] + async fn enforce_guard_denial_is_recorded_once() { + use crate::nip_fi_shadow::tests::enforce_records; + let (state, _verifier) = + guard_state_with(Err(buzz_auth::VerifierError::InvalidSignatureOrClaims)).await; + let (_resp, lines, counts) = enforce_records(nip_fi_gate_response( + state, + GUARD_PROTECTED_PATH, + Some("Nostr-Federated-Identity"), + Some("Bearer a.b.c"), + )) + .await; + assert_eq!(lines.len(), 1, "{lines:?}"); + assert!(lines[0].contains("pubkey=\"absent\""), "{lines:?}"); + assert_eq!(counts.len(), 1, "{counts:?}"); + assert_eq!(counts[0][..3], ["http", "assertion", "rejected"]); + } + // Pins ruling: in enforce, an unmapped Host is 503 at the router guard // (protected HTTP) and at the upgrade (root and audio WS) — with or // without an assertion, and before any verification. diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 70148f6f95..3131fca1f3 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -110,6 +110,8 @@ pub(crate) struct CommunityConnectionControl { nip_fi_shadow: Arc>>, /// A shadow upgrade would-deny's line, owned by the connection task. nip_fi_line: Arc>>, + /// An enforced NIP-FI session's labels for its expiry record. + nip_fi_enforce: Arc>, } impl CommunityConnectionControl { @@ -124,6 +126,7 @@ impl CommunityConnectionControl { owner: Arc::default(), nip_fi_shadow: Arc::default(), nip_fi_line: Arc::default(), + nip_fi_enforce: Arc::default(), } } @@ -139,6 +142,23 @@ impl CommunityConnectionControl { } } + /// Attaches the socket's enforced NIP-FI lifecycle. + pub(crate) fn attach_nip_fi_enforce(&self, session: crate::nip_fi_shadow::EnforceSession) { + let _ = self.nip_fi_enforce.set(session); + } + + /// The socket's enforced NIP-FI lifecycle, if it was upgraded under one. + pub(crate) fn nip_fi_enforce(&self) -> Option<&crate::nip_fi_shadow::EnforceSession> { + self.nip_fi_enforce.get() + } + + /// Records a NIP-FI refusal of the pending enforced session. + pub(crate) fn deny_nip_fi_enforce(&self, deny: crate::nip_fi_shadow::WouldDeny) { + if let Some(session) = self.nip_fi_enforce() { + session.deny(deny); + } + } + /// Lets the socket's AUTH write its shadow upgrade would-deny line, which /// the connection task owns. pub(crate) fn attach_nip_fi_line(&self, line: Option<&Arc>) { @@ -227,10 +247,14 @@ impl CommunityConnectionControl { /// registered by `set_terminal_frame_sender`. Every writer therefore /// yields the same single frame plus the reason's 1008 close. /// Does not cancel. [FI-TRACE-DENIAL-ORACLE] + /// `enforce` is the NIP-FI end this transition records on the socket's + /// enforce session, only when it is the socket's winning terminal: a + /// close another reason or a cancellation already chose records nothing. fn publish_authorization_denied( &self, route: crate::nip_fi_session::NipFiWsRoute, frame_tx: Option<&mpsc::Sender>, + enforce: fn(&crate::nip_fi_shadow::EnforceSession), ) { let slot = self .terminal_frame_tx @@ -246,6 +270,11 @@ impl CommunityConnectionControl { if !won { return; } + if !self.cancel.is_cancelled() { + if let Some(session) = self.nip_fi_enforce() { + enforce(session); + } + } if let Some(tx) = frame_tx.or(slot.as_ref()) { let _ = tx.try_send(crate::nip_fi_session::denial_frame( route, @@ -263,7 +292,21 @@ impl CommunityConnectionControl { frame_tx: &mpsc::Sender, route: crate::nip_fi_session::NipFiWsRoute, ) { - self.publish_authorization_denied(route, Some(frame_tx)); + self.publish_authorization_denied(route, Some(frame_tx), |_| {}); + } + + /// The lease deadline's denial: [`Self::deny_authorization`], recording + /// the enforce session's deadline when it is the winning terminal. + pub(crate) fn expire_authorization( + &self, + frame_tx: &mpsc::Sender, + route: crate::nip_fi_session::NipFiWsRoute, + ) { + self.publish_authorization_denied( + route, + Some(frame_tx), + crate::nip_fi_shadow::EnforceSession::expire, + ); } /// Denial transition for `ConnectionManager::disconnect_nip_fi`: the shared @@ -273,6 +316,7 @@ impl CommunityConnectionControl { self.publish_authorization_denied( crate::nip_fi_session::NipFiWsRoute::Root, Some(frame_tx), + crate::nip_fi_shadow::EnforceSession::revoke, ); self.cancel.cancel(); } @@ -281,7 +325,11 @@ impl CommunityConnectionControl { /// handler's own denials: the shared transition on the sender registered /// by `set_terminal_frame_sender`, then cancels. pub(crate) fn disconnect_nip_fi(&self) { - self.publish_authorization_denied(crate::nip_fi_session::NipFiWsRoute::Audio, None); + self.publish_authorization_denied( + crate::nip_fi_session::NipFiWsRoute::Audio, + None, + crate::nip_fi_shadow::EnforceSession::revoke, + ); self.cancel.cancel(); } @@ -300,7 +348,11 @@ impl CommunityConnectionControl { .read() .is_ok_and(|id| id.as_ref().is_some_and(|id| id.nip_fi.is_some())); if nip_fi { - self.publish_authorization_denied(crate::nip_fi_session::NipFiWsRoute::Audio, None); + self.publish_authorization_denied( + crate::nip_fi_session::NipFiWsRoute::Audio, + None, + |_| {}, + ); } else { self.reason_tx.send_if_modified(|current| { current.is_none() && { @@ -442,7 +494,8 @@ impl CommunityConnectionRegistry { .and_then(|v| v.as_ref().map(|id| id.matches(issuer, pubkey))) .unwrap_or(false); if matches { - entry.value().1.disconnect_nip_fi(); + let control = &entry.value().1; + control.disconnect_nip_fi(); closed += 1; } } @@ -3160,6 +3213,79 @@ pub(crate) mod tests { } } + /// An enforced socket's NIP-FI end is recorded only by the terminal + /// transition that wins: a revocation (either registry's scan) or the + /// deadline after a community close or a cancellation records nothing, + /// while one that wins records its end once, even when a community close + /// follows. Mutation: dropping the cancellation guard in + /// `publish_authorization_denied` records an end for `Cancel`. + #[test] + fn enforce_end_is_recorded_only_by_the_winning_terminal() { + #[derive(Clone, Copy, Debug)] + enum First { + Community, + Cancel, + NipFi, + } + for nip_fi in ["root_scan", "audio_scan", "deadline"] { + let end = if nip_fi == "deadline" { + "ws end/expired" + } else { + "ws end/revoked" + }; + for (first, expected) in [ + (First::Community, &[][..]), + (First::Cancel, &[][..]), + (First::NipFi, &[end][..]), + ] { + let (records, lines, _, ()) = + crate::nip_fi_shadow::tests::enforce_observed(async {}, |()| async move { + let (terminal_tx, _terminal_rx) = tokio::sync::mpsc::channel(1); + let cancel = CancellationToken::new(); + let control = CommunityConnectionControl::new(cancel.clone()); + control.set_terminal_frame_sender(terminal_tx.clone()); + let key = nostr::Keys::generate().public_key(); + control.attach_nip_fi_enforce(crate::nip_fi_shadow::EnforceSession::new( + "ws", + crate::nip_fi_shadow::BOUND.into(), + Some(key), + )); + control.nip_fi_enforce().expect("attached").admit(key); + let fi = || match nip_fi { + "root_scan" => control.manager_disconnect_nip_fi(&terminal_tx), + "audio_scan" => control.disconnect_nip_fi(), + _ => control.expire_authorization( + &terminal_tx, + crate::nip_fi_session::NipFiWsRoute::Root, + ), + }; + match first { + First::Community => { + control.disconnect_community( + CommunityDisconnectReason::CommunityArchived, + ); + fi(); + } + First::Cancel => { + cancel.cancel(); + fi(); + } + First::NipFi => { + fi(); + control.disconnect_community( + CommunityDisconnectReason::CommunityDeleted, + ); + } + } + }); + let admitted = records.iter().filter(|r| *r == "ws admit/admit").count(); + assert_eq!(admitted, 1, "{nip_fi} {first:?}"); + let ends: Vec<_> = records.iter().filter(|r| r.contains("end/")).collect(); + assert_eq!(ends, expected, "{nip_fi} {first:?}: {lines:?}"); + } + } + } + #[test] fn disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame() { // disconnect_community fires first → wins reason → no payload (community @@ -4760,6 +4886,7 @@ pub(crate) mod tests { let (target, bystander) = (vec![1u8; 32], vec![2u8; 32]); let unrestricted = || buzz_db::moderation::RestrictionState { banned: false, + own_banned: false, muted_until: None, }; for key in [ diff --git a/scripts/run-tests.sh b/scripts/run-tests.sh index 15a0a0fca2..163771cb5c 100755 --- a/scripts/run-tests.sh +++ b/scripts/run-tests.sh @@ -429,6 +429,7 @@ run_unit_tests() { state::tests::nip_fi_disconnect_does_not_close_different_pubkey_audio_socket state::tests::nip_fi_disconnect_does_not_close_unproven_audio_socket state::tests::community_disconnect_then_nip_fi_keeps_community_deleted_reason + state::tests::enforce_end_is_recorded_only_by_the_winning_terminal state::tests::disconnect_community_wins_reason_losing_nip_fi_does_not_enqueue_frame state::tests::manager_disconnect_sets_reason_enqueues_frame_then_cancels )