diff --git a/ARCHITECTURE.md b/ARCHITECTURE.md index 6a25d266bb..aaedf89f0a 100644 --- a/ARCHITECTURE.md +++ b/ARCHITECTURE.md @@ -743,7 +743,7 @@ pub struct ConnectionState { pub enum AuthState { Pending { challenge: String }, Authenticated(AuthContext), Failed } ``` -**Community FI admission:** Protected HTTP and root/audio WebSocket requests read the normalized Host's active authentication policy from the primary database. Stored `requires_nip_fi` OR global enforce requires FI; repair mode denies first. HTTP middleware shares one request-local policy read with handlers. Root NIP-11 and `/info` publish a no-store host-specific requirement and compatible capability fields. Policy lookup failure is unavailable, never optional. See [community auth upgrades](docs/community-auth-upgrades.md); completed activation additionally requires existing-session drain evidence. +**Community FI admission:** Protected HTTP and root/audio WebSocket requests read the normalized Host's active authentication policy from the primary database. Stored `requires_nip_fi` OR global enforce requires FI, as does membership in the shadow-mode `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort; repair mode denies first. HTTP middleware shares one request-local policy read with handlers. Root NIP-11 and `/info` publish a no-store host-specific requirement and compatible capability fields. Policy lookup failure is unavailable, never optional. See [community auth upgrades](docs/community-auth-upgrades.md); completed activation additionally requires existing-session drain evidence. **HTTP endpoints:** diff --git a/crates/buzz-relay/src/api/nip_fi.rs b/crates/buzz-relay/src/api/nip_fi.rs index 2809c215a4..7d9fdbeaab 100644 --- a/crates/buzz-relay/src/api/nip_fi.rs +++ b/crates/buzz-relay/src/api/nip_fi.rs @@ -2237,6 +2237,7 @@ mod route_integration_tests { }, )]; config.nip_fi = NipFiRelayConfig { + enforce_percent: 0, profile_policies: Vec::new(), accept_shadow_disconnects: false, source: Default::default(), @@ -5120,6 +5121,7 @@ mod route_integration_tests { }, )]; config.nip_fi = NipFiRelayConfig { + enforce_percent: 0, profile_policies: Vec::new(), accept_shadow_disconnects: false, source: Default::default(), diff --git a/crates/buzz-relay/src/api/operator/community_policy.rs b/crates/buzz-relay/src/api/operator/community_policy.rs index ed9d660b93..5661a868f3 100644 --- a/crates/buzz-relay/src/api/operator/community_policy.rs +++ b/crates/buzz-relay/src/api/operator/community_policy.rs @@ -48,12 +48,13 @@ fn unavailable(error: buzz_db::DbError) -> Error { ) } -fn mode_fields(state: &AppState, required: Option) -> Value { +fn mode_fields(state: &AppState, id: uuid::Uuid, required: Option) -> Value { let mode = state.config.nip_fi.mode; let name = crate::nip_fi_config::mode_name(mode); serde_json::json!({ "mode": name, - "effective_required": required.map(|r| mode.with_requirement(r).restricts()), + "effective_required": required + .map(|r| state.config.nip_fi.effective_mode(id, r).restricts()), }) } @@ -69,7 +70,11 @@ fn response(state: &AppState, mut record: PolicyRecord) -> Json { { record.acceptance.state = "unavailable".into(); } - let fields = mode_fields(state, record.current_requires_nip_fi); + let fields = mode_fields( + state, + record.acceptance.community_id, + record.current_requires_nip_fi, + ); Json(serde_json::json!({ "receipt": record, "mode": fields["mode"], @@ -196,7 +201,7 @@ pub async fn community_nip_fi_policy_status( "community not found", ) })?; - let fields = mode_fields(&state, Some(policy.requires_nip_fi)); + let fields = mode_fields(&state, id, Some(policy.requires_nip_fi)); Ok(Json(serde_json::json!({ "community_id": id, "expected_host": host, "expected_policy_generation": policy.policy_generation, diff --git a/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs b/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs index db0bbddbed..88d6782a0e 100644 --- a/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs +++ b/crates/buzz-relay/src/api/operator/postgres_tests/policy_tests.rs @@ -331,6 +331,20 @@ mod postgres_tests { assert_eq!(response["receipt"]["state"], "applied"); assert_eq!(response["receipt"]["current_requires_nip_fi"], false); assert_eq!(response["effective_required"], true); + // Shadow reports the rollout cohort while the stored flag stays false. + for (percent, expected) in [(0, false), (100, true)] { + let config = Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config); + config.nip_fi.mode = buzz_auth::NipFiMode::Shadow; + config.nip_fi.enforce_percent = percent; + let current = read_json( + fresh_upgrade_request(state.clone(), &operator, "GET", ¤t_path, None).await, + ) + .await; + assert_eq!(current["effective_required"], expected, "{percent}"); + } + Arc::make_mut(&mut Arc::get_mut(&mut state).unwrap().config) + .nip_fi + .mode = buzz_auth::NipFiMode::Enforce; let invalid = fresh_upgrade_request( state.clone(), &operator, diff --git a/crates/buzz-relay/src/main.rs b/crates/buzz-relay/src/main.rs index 12f56c6f1d..3f7a23fe16 100644 --- a/crates/buzz-relay/src/main.rs +++ b/crates/buzz-relay/src/main.rs @@ -311,6 +311,11 @@ async fn run_relay_main(boot: BootTracker) -> anyhow::Result<()> { push_enabled = config.push_enabled, "Config loaded" ); + info!( + mode = buzz_relay::nip_fi_config::mode_name(config.nip_fi.mode), + enforce_percent = config.nip_fi.enforce_percent, + "NIP-FI config loaded" + ); let usage_interval_secs = usage_metrics_interval_secs(); let metrics_refresh_interval_secs = diff --git a/crates/buzz-relay/src/nip11.rs b/crates/buzz-relay/src/nip11.rs index 7feb2e4c5d..cfd75bab89 100644 --- a/crates/buzz-relay/src/nip11.rs +++ b/crates/buzz-relay/src/nip11.rs @@ -146,7 +146,8 @@ pub struct RelayLimitation { pub restricted_writes: bool, /// Whether the relay supports NIP-FI federated identity assertions. /// Advertised `true` in `Enforce` and `Shadow` mode, so clients attach - /// evidence; in `Shadow` the relay evaluates it without requiring it. + /// evidence; in `Shadow` the relay evaluates it, requiring it only for + /// communities stored Required or inside the enforce-percent cohort. #[serde(skip_serializing_if = "std::ops::Not::not")] pub federated_identity: bool, /// NIP-ER: how the relay delivers due reminders ("push" or "lazy"). @@ -438,13 +439,13 @@ pub(crate) async fn nip11_document( community_id: *tenant.community().as_uuid(), mode: state.config.nip_fi.mode, required: false, - stored_required: false, + policy_required: false, mapped: true, } } else { crate::nip_fi_policy::resolve(state, &headers).await? }; - if !state.config.nip_fi.mode.is_off() && policy.stored_required { + if !state.config.nip_fi.mode.is_off() && policy.policy_required { // Required implies a usable binding and verifier, not merely a bit. state .nip_fi_communities() diff --git a/crates/buzz-relay/src/nip_fi_config.rs b/crates/buzz-relay/src/nip_fi_config.rs index fb359a9463..7190ae6734 100644 --- a/crates/buzz-relay/src/nip_fi_config.rs +++ b/crates/buzz-relay/src/nip_fi_config.rs @@ -13,6 +13,7 @@ //! | `BUZZ_NIP_FI_ISSUERS` | If enforce | JSON array of issuer configs (see [`IssuerEnvConfig`]). | //! | `BUZZ_NIP_FI_COMMUNITIES` | If enforce | JSON array mapping each community's canonical URI to its authorized issuers (see [`CommunityEnvConfig`]). | //! | `BUZZ_NIP_FI_MAX_CONNECTION_LIFETIME_SECS` | If enforce | Per-partition limit on session lifetime. | +//! | `BUZZ_NIP_FI_ENFORCE_PERCENT` | No | Integer 0-100 (default 0), validated in every mode. In `shadow`, communities whose stable [`rollout_bucket`] is below it are required as if stored Required. | //! | `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` | No | `true` lets an enforce pod honor disconnects accepted by shadow pods, for the deploy that switches shadow → enforce. Default `false`; rejected unless the mode is `enforce`. | //! | `BUZZ_NIP_FI_PROVISION_BINDING` | No | JSON `{"host_suffix", "authorized_issuers"}` binding communities created one label under the suffix; read in every mode (see [`buzz_auth::ProvisionBindingPolicy`]). | //! @@ -296,6 +297,8 @@ pub struct NipFiRelayConfig { pub command_configs: Vec<(String, crate::api::nip_fi::CommandIssuerEnvConfig)>, /// Output-only publication policies; independent of authorization capabilities. pub profile_policies: Vec, + /// `BUZZ_NIP_FI_ENFORCE_PERCENT`: share of communities required in shadow. + pub enforce_percent: u8, /// `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS`: an enforce pod also receives /// and restores disconnects accepted by shadow pods. Enforce mode only. pub accept_shadow_disconnects: bool, @@ -308,6 +311,7 @@ impl NipFiRelayConfig { /// missing or invalid (fail-closed: no token is accepted until this passes). pub fn from_env() -> Result { let mode = parse_mode()?; + let enforce_percent = parse_enforce_percent()?; let accept_shadow_disconnects = crate::config::parse_bool("BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS", false)?; if accept_shadow_disconnects && mode != NipFiMode::Enforce { @@ -343,6 +347,7 @@ impl NipFiRelayConfig { max_connection_lifetime_secs: 0, command_configs: Vec::new(), profile_policies: Vec::new(), + enforce_percent, accept_shadow_disconnects, }); } @@ -561,6 +566,7 @@ impl NipFiRelayConfig { max_connection_lifetime_secs, command_configs, profile_policies, + enforce_percent, accept_shadow_disconnects, }) } @@ -634,8 +640,56 @@ fn parse_mode() -> Result { } } +fn parse_enforce_percent() -> Result { + let raw = match std::env::var("BUZZ_NIP_FI_ENFORCE_PERCENT") { + Ok(raw) => raw, + Err(std::env::VarError::NotPresent) => String::new(), + Err(std::env::VarError::NotUnicode(_)) => { + return Err(ConfigError::InvalidValue( + "BUZZ_NIP_FI_ENFORCE_PERCENT must be an integer from 0 to 100; got non-UTF-8" + .to_string(), + )) + } + }; + match raw.trim() { + "" => Ok(0), + value => value.parse().ok().filter(|p| *p <= 100).ok_or_else(|| { + ConfigError::InvalidValue(format!( + "BUZZ_NIP_FI_ENFORCE_PERCENT must be an integer from 0 to 100; got {value:?}" + )) + }), + } +} + +/// Stable rollout bucket in `0..100`: SHA-256 of the UUID's RFC 4122 bytes, +/// first 8 bytes as a big-endian `u64`, mod 100. Raising the percentage only +/// adds communities. +pub(crate) fn rollout_bucket(community_id: uuid::Uuid) -> u8 { + use sha2::Digest; + let digest = sha2::Sha256::digest(community_id.as_bytes()); + let mut prefix = [0u8; 8]; + prefix.copy_from_slice(&digest[..8]); + let head = u64::from_be_bytes(prefix); + (head % 100) as u8 +} + +impl NipFiRelayConfig { + /// A community's requirement: stored Required, or, in shadow only, inside + /// the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort. Stored policy stays raw. + pub(crate) fn policy_required(&self, community_id: uuid::Uuid, stored: bool) -> bool { + stored || (self.mode.observes_only() && rollout_bucket(community_id) < self.enforce_percent) + } + + /// The mode a community runs under: the relay mode narrowed by + /// [`Self::policy_required`]. + pub(crate) fn effective_mode(&self, community_id: uuid::Uuid, stored: bool) -> NipFiMode { + self.mode + .with_requirement(self.policy_required(community_id, stored)) + } +} + /// Stable configured mode name for operator diagnostics and status. -pub(crate) fn mode_name(mode: NipFiMode) -> &'static str { +pub fn mode_name(mode: NipFiMode) -> &'static str { match mode { NipFiMode::Enforce => "enforce", NipFiMode::Shadow => "shadow", @@ -937,6 +991,119 @@ mod tests { assert!(matches!(mode, NipFiMode::Off)); } + fn rollout_config(mode: NipFiMode, enforce_percent: u8) -> NipFiRelayConfig { + NipFiRelayConfig { + mode, + source: Default::default(), + registry: IssuerRegistry::new(), + communities: NipFiCommunities::default(), + jwks_configs: Vec::new(), + max_connection_lifetime_secs: 0, + command_configs: Vec::new(), + profile_policies: Vec::new(), + enforce_percent, + accept_shadow_disconnects: false, + } + } + + // Frozen: changing the hash reshuffles every rollout cohort. + #[test] + fn rollout_bucket_golden_vectors() { + for (id, bucket) in [ + ("00000000-0000-0000-0000-000000000000", 69), + ("ffffffff-ffff-ffff-ffff-ffffffffffff", 77), + ("6ba7b810-9dad-11d1-80b4-00c04fd430c8", 11), + ("123e4567-e89b-12d3-a456-426614174000", 22), + ] { + assert_eq!(rollout_bucket(id.parse().unwrap()), bucket, "{id}"); + } + } + + #[test] + fn rollout_cohorts_are_bounded_and_nested() { + let ids: Vec = (0..1000).map(|_| uuid::Uuid::new_v4()).collect(); + let mut config = rollout_config(NipFiMode::Shadow, 0); + let mut previous = Vec::new(); + for percent in 0..=100 { + config.enforce_percent = percent; + let cohort: Vec<_> = ids + .iter() + .filter(|id| config.policy_required(**id, false)) + .collect(); + assert!(previous.iter().all(|id| cohort.contains(id)), "{percent}"); + previous = cohort; + } + assert_eq!(previous.len(), ids.len(), "100 includes every community"); + config.enforce_percent = 0; + assert!(ids.iter().all(|id| !config.policy_required(*id, false))); + assert!(ids.iter().all(|id| config.policy_required(*id, true))); + } + + // Only shadow widens the requirement; every other mode keeps stored policy. + #[test] + fn rollout_only_widens_shadow() { + let id = uuid::Uuid::nil(); + for mode in [ + NipFiMode::Off, + NipFiMode::Shadow, + NipFiMode::Enforce, + NipFiMode::DenyProtected, + ] { + for stored in [false, true] { + for percent in [69, 70] { + let config = rollout_config(mode, percent); + let cohort = percent == 70; + assert_eq!( + config.policy_required(id, stored), + stored || (mode == NipFiMode::Shadow && cohort), + "{mode:?} stored={stored} cohort={cohort}" + ); + } + } + } + } + + #[test] + fn malformed_enforce_percent_refuses_startup_in_every_mode() { + let _guard = super::NIP_FI_ENV_LOCK + .lock() + .unwrap_or_else(std::sync::PoisonError::into_inner); + let _env = EnvGuard::new(&["BUZZ_NIP_FI_MODE", "BUZZ_NIP_FI_ENFORCE_PERCENT"]); + for mode in ["off", "deny_protected", "shadow", "enforce"] { + std::env::set_var("BUZZ_NIP_FI_MODE", mode); + for value in ["101", "-1", "abc", "1.5"] { + std::env::set_var("BUZZ_NIP_FI_ENFORCE_PERCENT", value); + let err = NipFiRelayConfig::from_env().expect_err(value); + assert!( + err.to_string().contains("BUZZ_NIP_FI_ENFORCE_PERCENT"), + "{mode} {value}: {err}" + ); + } + } + #[cfg(unix)] + for mode in ["off", "deny_protected", "shadow", "enforce"] { + use std::os::unix::ffi::OsStrExt; + std::env::set_var("BUZZ_NIP_FI_MODE", mode); + std::env::set_var( + "BUZZ_NIP_FI_ENFORCE_PERCENT", + std::ffi::OsStr::from_bytes(b"5\xff"), + ); + let err = NipFiRelayConfig::from_env().expect_err(mode); + assert!( + err.to_string().contains("BUZZ_NIP_FI_ENFORCE_PERCENT"), + "{mode}: {err}" + ); + } + std::env::set_var("BUZZ_NIP_FI_MODE", "off"); + for (value, percent) in [("", 0), (" 100 ", 100), ("0", 0)] { + std::env::set_var("BUZZ_NIP_FI_ENFORCE_PERCENT", value); + assert_eq!( + NipFiRelayConfig::from_env().unwrap().enforce_percent, + percent + ); + } + } + #[test] fn accept_shadow_disconnects_requires_enforce() { let _guard = super::NIP_FI_ENV_LOCK diff --git a/crates/buzz-relay/src/nip_fi_http.rs b/crates/buzz-relay/src/nip_fi_http.rs index 5d312a4c98..f35bd67872 100644 --- a/crates/buzz-relay/src/nip_fi_http.rs +++ b/crates/buzz-relay/src/nip_fi_http.rs @@ -1686,14 +1686,14 @@ mod tests { use crate::nip_fi_shadow::EnforcedProof; let mut state = (*crate::state::tests::test_state().await).clone(); for global in [NipFiMode::Off, NipFiMode::Shadow, NipFiMode::Enforce] { - for stored_required in [false, true] { + for policy_required in [false, true] { std::sync::Arc::make_mut(&mut state.config).nip_fi.mode = global; - let mode = global.with_requirement(stored_required); + let mode = global.with_requirement(policy_required); let policy = crate::nip_fi_policy::Policy { community_id: uuid::Uuid::new_v4(), mode, required: mode.enforces(), - stored_required, + policy_required, mapped: true, }; let recorder = metrics_util::debugging::DebuggingRecorder::new(); @@ -1750,7 +1750,7 @@ mod tests { } else { assert!( strict.is_empty(), - "{global:?} stored={stored_required}: {strict:?}" + "{global:?} stored={policy_required}: {strict:?}" ); } } diff --git a/crates/buzz-relay/src/nip_fi_policy.rs b/crates/buzz-relay/src/nip_fi_policy.rs index ff448294b2..b321165277 100644 --- a/crates/buzz-relay/src/nip_fi_policy.rs +++ b/crates/buzz-relay/src/nip_fi_policy.rs @@ -39,7 +39,8 @@ pub(crate) struct Policy { pub community_id: uuid::Uuid, pub mode: NipFiMode, pub required: bool, - pub stored_required: bool, + /// Stored Required, or inside the shadow rollout cohort. + pub policy_required: bool, // False only for the guard's legacy rejection scope after an authoritative // host miss. Such a scope must never yield an admission proof. @@ -80,11 +81,6 @@ pub(crate) async fn with_policy(policy: Policy, next: F) REQUEST_POLICY.scope(policy, next).await } -/// Repair mode precedes all policy and evidence failures. -pub(crate) fn effective(global: NipFiMode, required: bool) -> NipFiMode { - global.with_requirement(required) -} - /// One bounded policy fill. Its serving row also supplies ordinary routing. /// Misses, errors, expired reads and invalidated in-flight results are not cached. pub(crate) async fn cached_lookup( @@ -158,12 +154,18 @@ pub(crate) async fn resolve( generation = policy.policy_generation, "resolved community auth policy" ); + let policy_required = state + .config + .nip_fi + .policy_required(policy.community_id, policy.requires_nip_fi); Ok(Policy { community_id: policy.community_id, - mode: effective(global, policy.requires_nip_fi), - required: !global.is_off() && (policy.requires_nip_fi || global.enforces()), - - stored_required: policy.requires_nip_fi, + mode: state + .config + .nip_fi + .effective_mode(policy.community_id, policy.requires_nip_fi), + required: !global.is_off() && (policy_required || global.enforces()), + policy_required, mapped: true, }) } @@ -212,13 +214,19 @@ pub(crate) async fn bind_for_upgrade( // failed lookup. Neither outcome can yield a tenant or an upgrade. _ => return Err(not_found()), }; + let policy_required = state + .config + .nip_fi + .policy_required(policy.community_id, policy.requires_nip_fi); let policy = Policy { community_id: policy.community_id, - mode: effective(state.config.nip_fi.mode, policy.requires_nip_fi), + mode: state + .config + .nip_fi + .effective_mode(policy.community_id, policy.requires_nip_fi), required: !state.config.nip_fi.mode.is_off() - && (policy.requires_nip_fi || state.config.nip_fi.mode.enforces()), - - stored_required: policy.requires_nip_fi, + && (policy_required || state.config.nip_fi.mode.enforces()), + policy_required, mapped: true, }; Ok(( @@ -259,7 +267,7 @@ pub(crate) fn required_dependencies_ready(state: &crate::state::AppState) -> boo fn configured_mode(state: &crate::state::AppState, policy: Policy) -> NipFiMode { if !state.config.nip_fi.mode.is_off() - && policy.stored_required + && policy.policy_required && !required_dependencies_ready(state) { NipFiMode::unavailable() diff --git a/crates/buzz-relay/src/nip_fi_policy/postgres_tests.rs b/crates/buzz-relay/src/nip_fi_policy/postgres_tests.rs index a26063b4a5..c0b455e345 100644 --- a/crates/buzz-relay/src/nip_fi_policy/postgres_tests.rs +++ b/crates/buzz-relay/src/nip_fi_policy/postgres_tests.rs @@ -158,7 +158,7 @@ async fn optional_leases_on_another_pod_expire_before_acceptance_with_or_without .unwrap(); let mut h = HeaderMap::new(); h.insert(header::HOST, host.to_uppercase().parse().unwrap()); - assert!(!resolve(&pod_b, &h).await.unwrap().stored_required); + assert!(!resolve(&pod_b, &h).await.unwrap().policy_required); let primed_at = pod_b .tenant_host_cache .policy_read_started_at(&host) @@ -263,7 +263,7 @@ async fn optional_leases_on_another_pod_expire_before_acceptance_with_or_without headers.insert(header::HOST, candidate.parse().unwrap()); let serving = candidate == if double_remap { &host } else { &remapped }; if serving { - assert!(resolve(&pod_b, &headers).await.unwrap().stored_required); + assert!(resolve(&pod_b, &headers).await.unwrap().policy_required); assert_eq!( crate::nip_fi_http::admit_nip_fi_http_on_state( &pod_b, @@ -355,80 +355,89 @@ async fn bound_row_policy_wins_when_required_host_becomes_serving_after_initial_ .unwrap(); let key = Keys::generate(); let token = sign_assertion("nip-fi+jwt", &key.public_key().to_hex(), None); - for global in [NipFiMode::Shadow, NipFiMode::Enforce] { - for path in ["/", "/huddle/00000000-0000-4000-8000-000000000001/audio"] { - for assertion in [false, true] { - sqlx::query("UPDATE communities SET archived_at = now() WHERE id = $1") + // A stored-Optional community inside the shadow rollout cohort must be + // enforced by the bound row alone; outside the cohort it stays free. + let bucket = crate::nip_fi_config::rollout_bucket(*community.id.as_uuid()); + for (stored, cohort) in [(true, false), (false, true), (false, false)] { + for global in [NipFiMode::Shadow, NipFiMode::Enforce] { + let required = stored || cohort || global.enforces(); + for path in ["/", "/huddle/00000000-0000-4000-8000-000000000001/audio"] { + for assertion in [false, true] { + sqlx::query("UPDATE communities SET archived_at = now(), requires_nip_fi = $2 WHERE id = $1") .bind(community.id.as_uuid()) + .bind(stored) .execute(base.db.pool()) .await .unwrap(); - let pause = Arc::new(PausedPolicyRead { - db: base.db.clone(), - read: Default::default(), - resume: Default::default(), - }); - let mut state = (*base).clone(); - let config = Arc::make_mut(&mut state.config); - config.nip_fi.mode = global; - config.nip_fi.max_connection_lifetime_secs = 3600; - config.nip_fi.communities = - crate::nip_fi_core::test_support::any_host(TEST_COMMUNITY_URI); - state.nip_fi_policy = pause.clone(); - state.nip_fi_verifier = Some(Arc::new(assertion_verifier( - buzz_auth::TokenClass::DedicatedNipFi, - ))); - state.nip_fi_deny_map = Some(Arc::new(buzz_auth::NipFiDenyMap::new(100, vec![]))); - let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); - let address = listener.local_addr().unwrap(); - let app = crate::router::build_router(Arc::new(state)) - .into_make_service_with_connect_info::(); - let server = tokio::spawn(async move { axum::serve(listener, app).await }); - let mut request = format!("ws://{address}{path}") - .into_client_request() - .unwrap(); - request.headers_mut().insert("host", host.parse().unwrap()); - if assertion { - request.headers_mut().insert( - "nostr-federated-identity", - format!("Bearer {token}").parse().unwrap(), - ); - } - let connect = tokio::spawn(async move { connect_async(request).await }); - tokio::time::timeout(std::time::Duration::from_secs(5), pause.read.notified()) - .await - .unwrap(); - // The initial primary query already observed no serving row. - // Make that SAME required row serving before its result reaches - // mode selection and the authoritative row-zero binding. - sqlx::query("UPDATE communities SET archived_at = NULL WHERE id = $1") - .bind(community.id.as_uuid()) - .execute(base.db.pool()) - .await - .unwrap(); - pause.resume.notify_one(); - let result = tokio::time::timeout(std::time::Duration::from_secs(5), connect) - .await - .unwrap() - .unwrap(); - if assertion { - let (mut socket, response) = result.expect("valid bound-row evidence upgrades"); - assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS); - let _ = socket.close(None).await; - } else { - match result { - Err(Error::Http(response)) => assert_eq!( - response.status(), - StatusCode::UNAUTHORIZED, - "{global:?} {path}" - ), - other => panic!( - "bound required row must not become free: {global:?} {path} {other:?}" - ), + base.tenant_host_cache.invalidate(&host); + let pause = Arc::new(PausedPolicyRead { + db: base.db.clone(), + read: Default::default(), + resume: Default::default(), + }); + let mut state = (*base).clone(); + let config = Arc::make_mut(&mut state.config); + config.nip_fi.mode = global; + config.nip_fi.enforce_percent = bucket + u8::from(cohort); + config.nip_fi.max_connection_lifetime_secs = 3600; + config.nip_fi.communities = + crate::nip_fi_core::test_support::any_host(TEST_COMMUNITY_URI); + state.nip_fi_policy = pause.clone(); + state.nip_fi_verifier = Some(Arc::new(assertion_verifier( + buzz_auth::TokenClass::DedicatedNipFi, + ))); + state.nip_fi_deny_map = + Some(Arc::new(buzz_auth::NipFiDenyMap::new(100, vec![]))); + let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap(); + let address = listener.local_addr().unwrap(); + let app = crate::router::build_router(Arc::new(state)) + .into_make_service_with_connect_info::(); + let server = tokio::spawn(async move { axum::serve(listener, app).await }); + let mut request = format!("ws://{address}{path}") + .into_client_request() + .unwrap(); + request.headers_mut().insert("host", host.parse().unwrap()); + if assertion { + request.headers_mut().insert( + "nostr-federated-identity", + format!("Bearer {token}").parse().unwrap(), + ); } + let connect = tokio::spawn(async move { connect_async(request).await }); + tokio::time::timeout(std::time::Duration::from_secs(5), pause.read.notified()) + .await + .unwrap(); + // The initial primary query already observed no serving row. + // Make that same row serving before its result reaches + // mode selection and the authoritative row-zero binding. + sqlx::query("UPDATE communities SET archived_at = NULL WHERE id = $1") + .bind(community.id.as_uuid()) + .execute(base.db.pool()) + .await + .unwrap(); + pause.resume.notify_one(); + let result = tokio::time::timeout(std::time::Duration::from_secs(5), connect) + .await + .unwrap() + .unwrap(); + let case = format!("{global:?} stored={stored} cohort={cohort} {path}"); + if assertion || !required { + let (mut socket, response) = result.expect(&case); + assert_eq!(response.status(), StatusCode::SWITCHING_PROTOCOLS, "{case}"); + let _ = socket.close(None).await; + } else { + match result { + Err(Error::Http(response)) => { + assert_eq!(response.status(), StatusCode::UNAUTHORIZED, "{case}") + } + other => { + panic!("bound required row must not become free: {case} {other:?}") + } + } + } + server.abort(); + let _ = server.await; } - server.abort(); - let _ = server.await; } } } diff --git a/crates/buzz-relay/src/nip_fi_policy/tests.rs b/crates/buzz-relay/src/nip_fi_policy/tests.rs index 30102051ab..d05e411907 100644 --- a/crates/buzz-relay/src/nip_fi_policy/tests.rs +++ b/crates/buzz-relay/src/nip_fi_policy/tests.rs @@ -108,7 +108,7 @@ fn effective_mode_truth_table() { (NipFiMode::Shadow, true) => NipFiMode::Enforce, _ => global, }; - assert_eq!(effective(global, required), expected); + assert_eq!(global.with_requirement(required), expected); } } } @@ -161,6 +161,76 @@ async fn mode_stored_requirement_and_proof_matrix() { } } +// The fixture's community (nil UUID) has bucket 69: in the cohort at 70, out at 69. +#[tokio::test] +async fn rollout_cohort_matrix_matches_stored_required() { + for global in [ + NipFiMode::Off, + NipFiMode::Shadow, + NipFiMode::Enforce, + NipFiMode::DenyProtected, + ] { + for stored in [false, true] { + for percent in [69, 70] { + let (base, source, _, _) = fixture(global).await; + source.required.store(stored, Ordering::SeqCst); + let mut state = (*base).clone(); + Arc::make_mut(&mut state.config).nip_fi.enforce_percent = percent; + let cohort = percent == 70; + let widened = stored || (global == NipFiMode::Shadow && cohort); + let policy = resolve(&state, &headers("required.example", false)) + .await + .unwrap(); + let case = format!("{global:?} stored={stored} cohort={cohort}"); + assert_eq!(policy.policy_required, widened, "{case}"); + assert_eq!(policy.mode, global.with_requirement(widened), "{case}"); + assert_eq!( + policy.required, + !global.is_off() && (widened || global.enforces()), + "{case}" + ); + } + } + } +} + +#[tokio::test] +async fn rollout_community_in_shadow_is_enforced_and_required_in_nip11() { + let (base, source, key, _) = fixture(NipFiMode::Shadow).await; + source.required.store(false, Ordering::SeqCst); + let mut state = (*base).clone(); + Arc::make_mut(&mut state.config).nip_fi.enforce_percent = 70; + let result = admit_nip_fi_http_on_state( + &state, + &headers("required.example", false), + &crate::access::AccessSlot::default(), + || Ok(Nip98Proof::new(key, ())), + ) + .await; + assert_eq!(result.err().unwrap().status(), StatusCode::UNAUTHORIZED); + let document = crate::nip11::nip11_document(&state, "required.example") + .await + .unwrap(); + assert!(document.requires_nip_fi); + + Arc::make_mut(&mut state.config).nip_fi.communities = Default::default(); + assert!( + crate::nip11::nip11_document(&state, "required.example") + .await + .is_err(), + "a rollout community without a binding cannot advertise Required" + ); + + Arc::make_mut(&mut state.config).nip_fi.enforce_percent = 69; + let document = crate::nip11::nip11_document(&state, "required.example") + .await + .unwrap(); + assert!( + !document.requires_nip_fi, + "outside the cohort stays Optional" + ); +} + #[tokio::test] async fn required_retains_verifier_and_key_pairing_denials() { for global in [NipFiMode::Shadow, NipFiMode::Enforce] { @@ -617,8 +687,7 @@ async fn unmapped_legacy_rejection_scope_never_yields_an_admission_proof() { community_id: uuid::Uuid::nil(), mode: NipFiMode::Off, required: false, - stored_required: false, - + policy_required: false, mapped: false, }; with_policy(policy, async { diff --git a/crates/buzz-relay/src/nip_fi_shadow.rs b/crates/buzz-relay/src/nip_fi_shadow.rs index a3f087cd5e..d7e122bd0c 100644 --- a/crates/buzz-relay/src/nip_fi_shadow.rs +++ b/crates/buzz-relay/src/nip_fi_shadow.rs @@ -25,8 +25,8 @@ //! | 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_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` on target `buzz_relay::nip_fi_enforce`, 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` on target `buzz_relay::nip_fi_enforce`, 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 | @@ -341,6 +341,7 @@ impl EnforceSession { ) .increment(1); tracing::info!( + target: "buzz_relay::nip_fi_enforce", mode = "enforce", route = self.route, reason, @@ -420,8 +421,9 @@ impl PendingLine { if self.written.swap(true, std::sync::atomic::Ordering::AcqRel) { return; } - // Both lines stay in this module: production's log filter admits - // `buzz_relay::nip_fi_shadow` at info. + // The shadow line stays on this module's target; the enforce line has + // its own, `buzz_relay::nip_fi_enforce`, so a filter can keep real + // denials while suppressing would-deny volume. match self.mode { Mode::Shadow => tracing::info!( mode = "shadow", @@ -434,6 +436,7 @@ impl PendingLine { "nip-fi shadow would-deny" ), Mode::Enforce => tracing::info!( + target: "buzz_relay::nip_fi_enforce", mode = "enforce", route = self.route, stage = self.stage, @@ -818,11 +821,16 @@ pub(crate) mod tests { impl WouldDenyLog { pub(crate) fn capture() -> Self { + Self::capture_filtered("info") + } + + /// As [`Self::capture`], with an `EnvFilter` of `directives`. + pub(crate) fn capture_filtered(directives: &str) -> Self { let _tracing = crate::test_support::tracing_dispatch_lock(); let out = Captured::default(); let writer = out.clone(); let subscriber = tracing_subscriber::fmt() - .with_max_level(tracing::Level::INFO) + .with_env_filter(tracing_subscriber::EnvFilter::new(directives)) .with_writer(move || writer.clone()) .with_ansi(false) .finish(); @@ -845,9 +853,13 @@ pub(crate) mod tests { self.lines_of("nip-fi shadow would-deny") } - /// The enforce denial lines logged so far. + /// The enforce denial lines logged so far, each on its own target. pub(crate) fn enforce_lines(&self) -> Vec { - self.lines_of("nip-fi enforce deny") + let lines = self.lines_of("nip-fi enforce deny"); + for line in &lines { + assert!(line.contains(" buzz_relay::nip_fi_enforce: "), "{line}"); + } + lines } fn lines_of(&self, message: &str) -> Vec { @@ -1160,6 +1172,20 @@ pub(crate) mod tests { .any(|l| l.contains("reason=\"revoked\"") && l.contains(&admitted.to_hex()))); } + #[tokio::test(flavor = "current_thread")] + async fn enforce_session_end_survives_silenced_shadow_target() { + let log = WouldDenyLog::capture_filtered("info,buzz_relay::nip_fi_shadow=off"); + let session = super::EnforceSession::new("ws", "c".into(), None); + session.admit(nostr::Keys::generate().public_key()); + session.expire(); + let ends = log.lines_of("nip-fi enforce session end"); + assert_eq!(ends.len(), 1, "{ends:?}"); + assert!( + ends[0].contains(" buzz_relay::nip_fi_enforce: "), + "{ends:?}" + ); + } + #[tokio::test(flavor = "current_thread")] async fn enforce_session_expiry_tells_pending_from_admitted() { let asserted = nostr::Keys::generate().public_key(); diff --git a/crates/buzz-relay/src/router.rs b/crates/buzz-relay/src/router.rs index fecdea1109..583a25c14f 100644 --- a/crates/buzz-relay/src/router.rs +++ b/crates/buzz-relay/src/router.rs @@ -72,8 +72,9 @@ use crate::state::AppState; // // ## Relationship to Off and Shadow // -// Off skips FI policy reads and enforcement. Shadow preserves optional-community -// admission and enforces stored requirements. Enforce requires FI everywhere. +// Off skips FI policy reads and enforcement. Shadow preserves admission for +// communities whose effective policy is optional and enforces those stored +// Required or inside the enforce-percent cohort. Enforce requires FI everywhere. // // ## What this guard checks (and does NOT check) // @@ -207,7 +208,7 @@ async fn nip_fi_assertion_guard( community_id: uuid::Uuid::nil(), mode, required: mode.enforces(), - stored_required: false, + policy_required: false, mapped: false, }; @@ -238,7 +239,7 @@ async fn nip_fi_assertion_guard( return response; } }; - if policy.stored_required && state.nip_fi_deny_map.is_none() { + if policy.policy_required && state.nip_fi_deny_map.is_none() { return nip_fi_unavailable(&slot); } crate::nip_fi_policy::with_policy( @@ -2670,6 +2671,7 @@ mod tests { // Enforce that is the startup-race condition that must return 503 for // a token-carrying request. config.nip_fi = NipFiRelayConfig { + enforce_percent: 0, profile_policies: Vec::new(), accept_shadow_disconnects: false, source: Default::default(), @@ -4535,6 +4537,7 @@ mod tests { }; config.nip_fi = NipFiRelayConfig { + enforce_percent: 0, profile_policies: Vec::new(), accept_shadow_disconnects: false, source: Default::default(), diff --git a/crates/buzz-relay/src/router/tests/policy_sweep_postgres_tests.rs b/crates/buzz-relay/src/router/tests/policy_sweep_postgres_tests.rs index 32121467c7..81ffb9029e 100644 --- a/crates/buzz-relay/src/router/tests/policy_sweep_postgres_tests.rs +++ b/crates/buzz-relay/src/router/tests/policy_sweep_postgres_tests.rs @@ -158,11 +158,15 @@ mod postgres_tests { panic!("target") }; let free_host = format!("dark-free-{}.example", uuid::Uuid::new_v4()); - let _ = state + let buzz_db::CreateCommunityWithOwnerResult::Created(free_row) = state .db .create_community_with_owner(&free_host, &owner, &key) .await - .unwrap(); + .unwrap() + .outcome + else { + panic!("free") + }; state .db .ensure_user(row.id, &key.public_key().to_bytes()) @@ -309,6 +313,20 @@ mod postgres_tests { for client in [&mut compliant, &mut compliant_audio, &mut free] { ping_round_trip(client).await; } + // A shadow rollout closes a stored-Optional cohort member's socket; + // the same community outside the cohort keeps it. + let free_bucket = crate::nip_fi_config::rollout_bucket(*free_row.id.as_uuid()); + for (percent, closed) in [(free_bucket, 0), (free_bucket + 1, 1)] { + let mut rollout = (*state).clone(); + Arc::make_mut(&mut rollout.config).nip_fi.enforce_percent = percent; + assert_eq!( + rollout.revalidate_live_communities().await, + closed, + "{percent}" + ); + } + policy_close(&mut free).await; + let mut free = authenticated_socket(addr, &free_host, "/", &key, None, false).await; // Global Enforce also closes an optional community's legacy socket. let mut enforce = (*state).clone(); Arc::make_mut(&mut enforce.config).nip_fi.mode = buzz_auth::NipFiMode::Enforce; diff --git a/crates/buzz-relay/src/state.rs b/crates/buzz-relay/src/state.rs index 80e78af9f3..31b184bde5 100644 --- a/crates/buzz-relay/src/state.rs +++ b/crates/buzz-relay/src/state.rs @@ -2715,7 +2715,10 @@ impl AppState { } }; let required = policy.as_ref().is_some_and(|policy| { - crate::nip_fi_policy::effective(mode, policy.requires_nip_fi).enforces() + self.config + .nip_fi + .effective_mode(policy.community_id, policy.requires_nip_fi) + .enforces() }); let outcome = if required { "required" diff --git a/docs/community-auth-upgrades.md b/docs/community-auth-upgrades.md index 3a98b2af2d..538e4781c1 100644 --- a/docs/community-auth-upgrades.md +++ b/docs/community-auth-upgrades.md @@ -110,7 +110,8 @@ policy operation. This removal does not erase receipts or rewrite schema. ## Request enforcement and discovery -`off` ignores stored requirements; `shadow` enforces stored true; `enforce` is a +`off` ignores stored requirements; `shadow` enforces stored true and communities inside the +`BUZZ_NIP_FI_ENFORCE_PERCENT` cohort; `enforce` is a global requirement floor; `deny_protected` denies protected traffic. Report `effective_required` alongside stored state so disable under enforce and enable under off cannot be mistaken for effective changes. Evaluating policy lookups @@ -125,9 +126,12 @@ lease after disable. It cannot renew that stale lease. `/info` advertises effect ### Existing connections The periodic revalidator reads stored policy without row-locking transactions. -After disable it stops requesting required-policy closes; a concurrent sweep may -request one last non-FI close from its earlier snapshot. That client reconnects -under optional policy. FI-admitted sockets retain their finite lifetime and then +When disable makes the effective policy optional, it stops requesting +required-policy closes; a concurrent sweep may request one last non-FI close from +its earlier snapshot. That client reconnects under optional policy. A community +inside the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort, or any community under global +`enforce`, stays required: its non-FI sockets keep closing on revalidation, and +reconnects still need FI. FI-admitted sockets retain their finite lifetime and then reconnect under current policy. Disable does not reopen or force-logout sessions. Re-enable repeats the optional-lease drain; non-FI root/audio sockets close through existing revalidation. Valid FI-admitted sockets retain existing rules. diff --git a/docs/multi-tenant-conformance.md b/docs/multi-tenant-conformance.md index 0eca3ff8d0..2efe190408 100644 --- a/docs/multi-tenant-conformance.md +++ b/docs/multi-tenant-conformance.md @@ -40,7 +40,7 @@ Conformance obligations: | Surface | Today's observable behavior | Tenant source | Community-global vs operator-global | Required DB/index/RLS scope | Auth/fan-out/search effects | Single-community compatibility check | Open decision/test | |---|---|---|---|---|---|---|---| | Row zero: host binding | A user connects to one relay URL and all state they can observe belongs to that relay. | `resolve_host(connection.host)` before handler entry. | Community-global selector; operator only manages the host map. | `communities(host, id, signing_key, …)`; every scoped table references immutable `community_id`. | All auth, event, REST, media, git, search, pub/sub, and workflow paths consume `TenantContext`; host/token mismatch rejects generically. | One host maps to the default community; no client-visible protocol field changes. | Add model/prose gate that `ctx.community` is derived from host, not supplied by the client. | -| NIP-11 relay info and relay `self` | `GET /`/`/info` returns one relay info document; `RelayInfo::build` advertises static NIPs, a stable relay signing pubkey when configured, the community's workspace icon (NIP-WP), host-specific `requires_nip_fi` and compatible FI capability fields, and the config-derived `buzz-gif` descriptor when GIF search is configured. | Host-derived community for community-specific facts; host policy is read from the primary by normalized Host (unknown/non-serving host → generic 404, unavailable policy → 503); optional workspace `icon` is pre-fetched as a scalar via `bind_community`; GIF provider availability is passed as a credential-free config scalar; no other DB lookup from unauthenticated global state unless explicitly through `TenantContext`. | NIP-11 is community-global. Operator-global software/version and GIF provider configuration may be shared; relay `self` for group/system/audit signing is per-community; `icon` is per-community intentionally-public presentation. | `communities.signing_key` or equivalent per-community signing material; no platform-global `self` for tenant-observable system events. | Unauthenticated reads must not become enumeration oracles for other communities: host-specific fields reveal only the requesting host's public icon, requirement and capabilities, never a neighboring community's facts. Discovery is no-store. The GIF descriptor reveals provider availability but never its credential; NIP-43 advertisement reflects membership enforcement for that community only. | One community retains existing capability/descriptor semantics; the additive requirement boolean reflects stored policy OR global enforce. | Signature/static-input lint remains: `RelayInfo::build` must not grow unscoped DB/search/audit inputs — host-scoped or config-derived scalars (like `icon`, pairing URL, and GIF provider) are passed in pre-derived. | +| NIP-11 relay info and relay `self` | `GET /`/`/info` returns one relay info document; `RelayInfo::build` advertises static NIPs, a stable relay signing pubkey when configured, the community's workspace icon (NIP-WP), host-specific `requires_nip_fi` and compatible FI capability fields, and the config-derived `buzz-gif` descriptor when GIF search is configured. | Host-derived community for community-specific facts; host policy is read from the primary by normalized Host (unknown/non-serving host → generic 404, unavailable policy → 503); optional workspace `icon` is pre-fetched as a scalar via `bind_community`; GIF provider availability is passed as a credential-free config scalar; no other DB lookup from unauthenticated global state unless explicitly through `TenantContext`. | NIP-11 is community-global. Operator-global software/version and GIF provider configuration may be shared; relay `self` for group/system/audit signing is per-community; `icon` is per-community intentionally-public presentation. | `communities.signing_key` or equivalent per-community signing material; no platform-global `self` for tenant-observable system events. | Unauthenticated reads must not become enumeration oracles for other communities: host-specific fields reveal only the requesting host's public icon, requirement and capabilities, never a neighboring community's facts. Discovery is no-store. The GIF descriptor reveals provider availability but never its credential; NIP-43 advertisement reflects membership enforcement for that community only. | One community retains existing capability/descriptor semantics; the additive requirement boolean reflects stored policy OR global enforce OR, in `shadow`, membership in the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort. | Signature/static-input lint remains: `RelayInfo::build` must not grow unscoped DB/search/audit inputs — host-scoped or config-derived scalars (like `icon`, pairing URL, and GIF provider) are passed in pre-derived. | | API tokens and NIP-98 replay | API/NIP-98 clients authenticate REST/media/git; API tokens may carry scopes and channel IDs; NIP-98 replay uses an in-process seen-set today. | Host-derived community plus token's stamped community; stamps must agree. | Community-global token namespace; operator-global only for deployment health/secrets. | `api_tokens` gains `community_id`; token hash uniqueness and lookup are `(community_id, token_hash)` or the token cryptographically embeds community and lookup verifies both. Channel claims must reference channels in the same community. | Replay seen-set key is `(community_id, event_id)` in shared HA storage or equivalent sticky routing; NIP-98 `u` URL host must match `req.community`. | Existing single-community tokens continue to authorize the same scopes/channels after backfill to default community. | HA gate: Redis/shared seen-set with atomic insert-if-absent and TTL ≥ replay window, or documented single-replica/sticky alternative. | | Relay membership, pubkey allowlist, archived identities | `relay_members`, `pubkey_allowlist`, and `archived_identities` are relay-global gates over pubkeys. | Host-derived community for tenant access; operator context only for platform administration. | Community-global membership/allowlist/archive by default. Operator-global only for explicit platform ops tables that are never tenant-observable. | Add `community_id` to these tables; primary/unique keys become `(community_id, pubkey)` and indexes include `community_id`. | Membership errors remain generic. NIP-OA owner checks test owner membership in the same community. Identity archive requests cannot hide/archive a key in another community. | One default community preserves today's closed/open relay behavior and admin CLI semantics after commands target the default community. | Decide any future operator-global super-admin surface separately; do not reuse tenant membership tables for it. | | Users, profiles, NIP-05, and user search | Kind:0 updates sync a `users` row; NIP-05 handles are unique; `/api/users/search` searches display name/NIP-05/pubkey. | Channel-less events use `req.community`; NIP-05 domain is the connected community host. | Community-global. Same pubkey can have one profile per community; users repost kind:0 in each community they join. | `users` gains `community_id`; keys/uniques are `(community_id, pubkey)`, `(community_id, lower(nip05_handle))`, and `(community_id, okta_user_id)` where applicable. Profile event replacement is scoped by `(community_id, pubkey)`. | Search and batch profile reads include `community_id`; NIP-05 lookup only resolves handles for the requested host/community. No cross-community profile inheritance. | Existing users backfill into the default community; profile APIs and CLI output stay unchanged. | Add tests for same pubkey with different profile/NIP-05 in two communities and for NIP-05 same local part on two hosts. | diff --git a/docs/nips/NIP-FI.md b/docs/nips/NIP-FI.md index 5482140d72..f4242d5c6a 100644 --- a/docs/nips/NIP-FI.md +++ b/docs/nips/NIP-FI.md @@ -983,10 +983,10 @@ A relay SHOULD advertise core support in NIP-11 as: A multi-community relay MAY additionally publish a host-specific top-level `requires_nip_fi` boolean. This expresses mandatory admission evidence, separately -from support for the protocol. In Buzz it is the stored community requirement OR -global enforce; capability is advertised when global mode evaluates OR that -requirement is true. Required hosts therefore retain both existing capability -fields and the descriptor above. Optional shadow hosts still advertise capability. +from support for the protocol. Capability is advertised when the relay evaluates +NIP-FI evidence for that host or the host requires it. Required hosts therefore +retain both existing capability fields and the descriptor above; hosts that +evaluate evidence without requiring it still advertise capability. Root NIP-11 and `/info` MUST agree and use `Cache-Control: no-store`. An unknown or non-serving Host returns generic 404; unavailable host policy returns 503. diff --git a/docs/operator-nip-fi-bindings.md b/docs/operator-nip-fi-bindings.md index 15a2278b0b..fe1a926765 100644 --- a/docs/operator-nip-fi-bindings.md +++ b/docs/operator-nip-fi-bindings.md @@ -178,8 +178,9 @@ snapshot loads in `off`, but every `BUZZ_NIP_FI_RESOLVER_*` and Set `BUZZ_NIP_FI_MODE=shadow`. Each pod now loads the snapshot before any listener binds, refreshes it every 30 s, and records what enforce would decide -without refusing anything. Shadow labels database-source records -`community="bound"` or `"unmapped"`, never a host. +without refusing anything in communities whose effective policy is optional; +stored-Required and cohort communities still enforce. Shadow labels +database-source records `community="bound"` or `"unmapped"`, never a host. - Go, held for at least a day of normal traffic: - `time() - buzz_nip_fi_binding_snapshot_loaded_timestamp_seconds` stays @@ -194,13 +195,71 @@ without refusing anything. Shadow labels database-source records for its token owner. - No-go: any of these fails. Return to `off` and investigate. +### Staged enforce + +To enforce for a growing share of communities before switching the whole relay, +keep `BUZZ_NIP_FI_MODE=shadow` and set `BUZZ_NIP_FI_ENFORCE_PERCENT`, an integer +from 0 to 100 (default 0). It is read once at startup, so each change is a +rollout; a malformed or out-of-range value refuses startup. + +- It acts only in `shadow`. In `off` it has no effect, and `enforce` ignores it + because every community already enforces. +- A community stored as Optional enforces when its bucket is below the + percentage. The bucket is the SHA-256 digest of the community UUID's 16 + RFC 4122 bytes, with the digest's first 8 bytes read as a big-endian `u64`, + mod 100. The bucket never changes for a community, so raising the + percentage only adds communities, and lowering it removes the most recently + added ones. +- A community stored as Required enforces at any percentage. +- An enforcing community gets the same treatment as a stored-Required one: + logins without valid evidence are refused, its NIP-11 document reports + `requires_nip_fi: true`, and open sockets without valid evidence are closed. + Its stored flag does not change. +- A required admission, stored Required or inside the cohort, is refused when + the receiving pod holds an active deny for the key. A revocation closes open + connections only in `enforce`; in `shadow` an open connection stays until its + deadline. Stored-Required communities already behave this way. +- Denies are stored in Redis and restored on restart, but a healthy pod + learns of new ones through best-effort pub/sub and can miss one. See + [Revocation during a deploy](#revocation-during-a-deploy). + +Raise the percentage in steps, holding each one for normal traffic. + +- Go: the shadow signals keep holding, the `nip-fi enforce deny` lines on log + target `buzz_relay::nip_fi_enforce` are only what you expect to deny, and + login 503s stay at their shadow baseline. +- No-go: set `BUZZ_NIP_FI_ENFORCE_PERCENT=0` and investigate. + +A rollback is a full rollout too: pods run mixed percentages until it +finishes. There is no per-community exemption, so removing one community +means lowering the percentage to its bucket or below, which also drops every +community in a higher bucket. + ### Enforce -Set `BUZZ_NIP_FI_MODE=enforce`. Watch the same signals, plus the rate of 503 -responses on login. +Set `BUZZ_NIP_FI_MODE=enforce` and leave `BUZZ_NIP_FI_ENFORCE_PERCENT` at 100. +It has no effect in `enforce`. Follow +[Switching shadow → enforce](#switching-shadow--enforce) so shadow-accepted +disconnects carry over. +Watch the same signals, plus the rate of 503 responses on login. - Go: the shadow signals keep holding, and 503s stay at their shadow baseline. -- No-go: logins return 503 or are refused unexpectedly. Set `mode=off` (below). +- No-go: logins return 503 or are refused unexpectedly. Set `mode=shadow` and + lower `BUZZ_NIP_FI_ENFORCE_PERCENT` to the last known-good value. A mode-only + rollback at 100 still requires every community: it restores only the staged + revocation behavior, not optional admission. Stored-Required communities stay + required either way. Never roll back with `mode=off`: `off` also turns off + stored-Required enforcement. In the same rollout, unset + `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS` or set it to `false`: `true` is + invalid in `shadow` and the pods refuse to start. + + Shadow pods restore active denies from both stores. Those denies still + reject admission for stored-Required and remaining cohort communities; + optional communities only record the would-deny verdict. Shadow does not + close existing sessions. When returning to `enforce`, set + `BUZZ_NIP_FI_ACCEPT_SHADOW_DISCONNECTS=true` and follow + [Switching shadow → enforce](#switching-shadow--enforce) again, measuring the + bridge-retention interval from the latest shadow pods. ### Alerts diff --git a/docs/operator-nip-fi-upgrade.md b/docs/operator-nip-fi-upgrade.md index 95652d65fa..b7c52e4692 100644 --- a/docs/operator-nip-fi-upgrade.md +++ b/docs/operator-nip-fi-upgrade.md @@ -67,12 +67,18 @@ read its status or retry that exact file. A committed replay never reapplies pol Inspect `mode` and `effective_required` separately from the stored flag. `enforce` keeps FI required after disable; `off` suspends FI after enable. -`shadow` follows the stored flag. An enable receipt remains pending even after -local sweeps, since it cannot certify fleet-wide connection closure. Required -host caches can over-restrict for their remaining one-second lease after disable. -A racing sweep may close one last non-FI socket; it can reconnect under optional -policy. FI-admitted sockets retain their finite deadline. Re-enable repeats the -optional-lease drain and existing periodic revalidation. +`shadow` follows the stored flag, and also requires FI for communities inside +the `BUZZ_NIP_FI_ENFORCE_PERCENT` cohort; a stored disable does not take a +community out of the cohort, only lowering the percentage does. An enable +receipt remains pending even after local sweeps, since it cannot certify +fleet-wide connection closure. Required host caches can over-restrict for their +remaining one-second lease after disable. When the effective policy becomes +optional, a racing sweep may close one last non-FI socket; it can reconnect +under optional policy. A community inside the cohort, or any community under +global `enforce`, stays required: its non-FI sockets keep closing on +revalidation, and reconnects still need FI. FI-admitted sockets retain their +finite deadline. Re-enable repeats the optional-lease drain and existing +periodic revalidation. The old `nip-fi-upgrade` command and endpoint are removed. Requests to that route now return 404. Recover historical receipts with `nip-fi-policy status