mirror of
https://github.com/block/buzz.git
synced 2026-11-30 21:21:48 +00:00
## Summary Builds on #9860 (merged as `c0932db19c`). A NIP-FI disconnect command can now carry `revoke_through` (C), an integral NumericDate. With C, the relay refuses and closes only assertions whose verified signed `iat` is at or before C, until `until`. Tokens issued after C are admitted straight away. Without C, the deny covers the whole key, as before. - **Spec:** `docs/nips/NIP-FI.md` adds the `revoke_through` claim and a Deny scope section (admission, close scope, merging, records, the issuer's duty) with a behavioral oracle. The existing deny, command-algorithm, oracle and security text now carry scope. The deny set's storage text is #9860's (shared storage, restored before admission); this PR adds no wire claim or storage schema to the spec. - **Parsing:** a `revoke_through` that is `null`, nonnumeric, fractional or unrepresentable is rejected as `evidence_rejected` before any state changes. - **Verified `iat`:** `VerifiedAssertion::issued_at()` comes from the time-checked `iat`, not from profile evidence. `NipFiSession` records it at registration. - **One predicate:** `DenyScope::covers` compares the full verified instant (fractional `iat` included) against C. It decides admission (WebSocket and HTTP, with asserted key and owner checked separately) and every close scan (root and audio registries, the command route, cross-pod delivery, shadow accounting). - **Merge:** `DenyEntry::merge` takes the later `until`. Whole-key beats a cutoff, two cutoffs merge to the larger C, and expired entries contribute nothing. Activity is read from a clock sampled inside the issuer shard lock, so an entry that expires while a merge waits contributes nothing. A past-`until` command still does its scoped close without changing an active entry. The close scope widens to any stronger active entry, and a poisoned shard closes the whole key. - **Bus:** `NipFiDisconnect.revoke_through` is optional. A message without it means whole-key. - **Durable cutoff (Redis):** the cutoff lives in its own per-issuer hash, `<deny prefix>-revoke-through:<sha256(iss)>`, field `pubkey_hex`, value C. The exact-`until` hash keeps only `secs:nanos`. One accept script merges `until` and scope by the same rule as `DenyEntry::merge` and gives all three keys one expiry. It judges whether the command and the stored entry are still active by Redis `TIME` as it runs, not by the authentication clock. Before any write it checks the target's stored cutoff by restore's rule: a disconnect over an unreadable one returns `unreadable`, `try_claim` fails (`503`), the claim stays unused and nothing is recorded. Restore judges expiry when it merges. Restore reads both hashes in one script and joins them before merging, looking deny keys up in a set (linear at capacity), so a missing cutoff field is a whole-key deny. A cutoff that isn't an integer, or names no deny, is `reason="unreadable"`. As in #9860, one bad record does not hide the others: restore still applies every readable deny (a deny under a malformed cutoff as the whole key; an orphan cutoff adds nothing) and then fails, so admission stays closed. `LoadDenies` and `LoadDeniesError::Unreadable { readable }` now carry `DenyEntry`, and a restore counts a same-`until` scope widening as changed, so it closes the sessions it newly covers. - **Runbook:** `docs/operator-nip-fi-bindings.md` names the cutoff hash and how to clear a bad cutoff. It warns that deleting an orphaned cutoff leaves no deny at all, and that a disconnect over a bad stored cutoff fails until it is cleared. ## Deploy and rollback Deploy this to every relay pod before any issuer sends `revoke_through`. Until then, a pod still on the old build ignores the claim and blocks the whole key, so the agent stays locked out until its old token expires. Rolling a relay back to #9860 is safe. That build reads only the exact-`until` hash, which this PR writes in the same format, so it restores every cutoff as a whole-key deny and never fails its restore on this data. It ignores `revoke_through` in commands and bus messages, and every accept it makes clears the target's stored cutoff, so its whole-key revokes are never narrowed by a cutoff this build stored. All of this only over-blocks: agents wait for their old tokens to expire instead of getting back in at once. ## Testing Behavior tests cover old and fresh tokens at admission and in close scans, redelivery leaving fresh root and audio sessions open, cross-pod delivery, an owner whole-key deny blocking a fresh agent token, same-deadline scope changes in both orders, an expired whole-key entry followed by a cutoff, past-`until` commands, invalid `revoke_through` values, legacy bus messages, fractional `iat` at C and C + 0.5 through real verification, replay-claim waits that cross an entry's expiry, and root/audio handler straddle cases where the signed `iat` differs from registration time. Each of these was checked to fail when the code it guards is broken: - the route's published bus message keeps the cutoff on another pod (fails if `nip_fi_disconnect_message` drops `revoke_through`); - a cutoff command over an active whole-key entry closes a fresh session (fails if the route skips close-scope widening); - a poisoned shard's close scope is whole-key; - shadow `would_close` ends only sessions issued at or before C; - a cutoff in Redis restores as a cutoff (fails if the accept script stops writing the cutoff hash), and #9860's reader, taken from its final head `02627cce`, decodes the same record as a whole-key deny; - #9860's writer, copied verbatim from `02627cce`, writing over a stored cutoff with an equal or shorter `until`, then a fresh restore by this build, gives a whole-key deny; - a full revoke that expires between authentication and its Redis write neither widens a cutoff nor, once stored and expired, overrides one (fails with the authentication clock); - a whole key that is live when restore reads and expired when it merges gives way to the stored cutoff (the load is gated, not slept; fails if restore merges at the pre-read time); - the Redis merge matches `DenyEntry::merge` for whole-over-cutoff, cutoff-over-whole, two cutoffs under a shorter or longer `until`, and an expired whole key (fails if a whole-key write stops clearing the cutoff); - pruning clears an expired entry's cutoff, from a fixture seeded already expired in one atomic step; - a same-`until` scope widening is `Merged`, not `Unchanged` (fails if the change test compares `until` only); - a cutoff that isn't an integer, is out of range or has no deny fails the restore as `unreadable`; - a malformed cutoff leaves its deny restorable as the whole key, an orphan cutoff adds nothing, and a good cutoff still scopes its key, while the load still fails as `unreadable`; - a disconnect over a complete active deny whose stored cutoff is fractional or out of range fails with the claim unused and the index (with scores), exact and cutoff hashes unchanged (fails with the accept script's check removed); the script's bounds are pinned to chrono's range. - through the real Redis load and restore, a readable deny next to a bad record keeps its cutoff: a session issued at C is closed, one issued after C stays open, and admission stays fenced (fails if the partial payload drops scope). --------- Signed-off-by: Will Pfleger <wpfleger@block.xyz> Co-authored-by: Duncan <dcfd242e557282d7a1e2cf2e6877522682f1e5c6156dc92ca7d90eaedd3b0f95@buzz.block.builderlab.xyz>
299 lines
11 KiB
Rust
299 lines
11 KiB
Rust
#![deny(unsafe_code)]
|
||
#![warn(missing_docs)]
|
||
//! `buzz-auth` — Authentication and authorization for the Buzz relay.
|
||
//!
|
||
//! ## Auth paths
|
||
//!
|
||
//! | Path | Transport | Description |
|
||
//! |------|-----------|-------------|
|
||
//! | NIP-42 | WebSocket | Challenge/response; client signs kind:22242 event |
|
||
//! | NIP-98 | HTTP | Signed kind:27235 event in `Authorization: Nostr` header |
|
||
//!
|
||
//! ## Security invariants
|
||
//!
|
||
//! - **AUTH events (kind:22242) are NEVER stored or logged.**
|
||
//! - All paths produce an [`AuthContext`] bound to the connection.
|
||
//! - No JWT validation, no token management, no IdP runtime dependency.
|
||
|
||
/// Channel access checking trait and helpers.
|
||
pub mod access;
|
||
/// Authentication error types.
|
||
pub mod error;
|
||
/// NIP-42 challenge–response authentication.
|
||
pub mod nip42;
|
||
/// NIP-98 HTTP Auth verification (kind:27235).
|
||
pub mod nip98;
|
||
/// NIP-98 replay protection — shared, community-scoped, atomic seen-set.
|
||
pub mod nip98_replay;
|
||
/// NIP-FI federated-identity assertion verifier and contracts.
|
||
pub mod nip_fi;
|
||
/// Per-connection rate limiting.
|
||
pub mod rate_limit;
|
||
/// OAuth scope parsing and enforcement.
|
||
pub mod scope;
|
||
|
||
/// How far a signed event's `created_at` may differ from server time, in
|
||
/// either direction, for NIP-42 AUTH and NIP-98 HTTP Auth.
|
||
pub const TIMESTAMP_TOLERANCE_SECS: u64 = 120;
|
||
|
||
/// Unix seconds now, as the verifiers see it. Tests pin it with
|
||
/// [`test_clock::pinned`].
|
||
fn wall_now() -> u64 {
|
||
#[cfg(test)]
|
||
if let Some(now) = test_clock::NOW.with(std::cell::Cell::get) {
|
||
return now;
|
||
}
|
||
nostr::Timestamp::now().as_secs()
|
||
}
|
||
|
||
#[cfg(test)]
|
||
pub(crate) mod test_clock {
|
||
thread_local! {
|
||
pub(crate) static NOW: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||
}
|
||
|
||
/// Runs `f` with the verifiers' clock fixed at `now`.
|
||
pub(crate) fn pinned<T>(now: u64, f: impl FnOnce() -> T) -> T {
|
||
NOW.with(|c| c.set(Some(now)));
|
||
let out = f();
|
||
NOW.with(|c| c.set(None));
|
||
out
|
||
}
|
||
}
|
||
|
||
pub use access::{check_read_access, check_write_access, require_scope, ChannelAccessChecker};
|
||
pub use error::AuthError;
|
||
pub use nip42::{generate_challenge, verify_nip42_event};
|
||
pub use nip98::verify_nip98_event;
|
||
pub use nip98_replay::{
|
||
nip98_replay_key, nip98_replay_key_for_scope, Nip98ReplayGuard, DEFAULT_REPLAY_TTL_SECS,
|
||
MAX_REPLAY_TTL_SECS,
|
||
};
|
||
pub use rate_limit::{
|
||
ip_rate_limit_key, rate_limit_key, LimitType, RateLimitConfig, RateLimitResult, RateLimiter,
|
||
};
|
||
pub use scope::{parse_scopes, Scope};
|
||
|
||
pub use nip_fi::{
|
||
command_replay_key, validate_nip_fi_config, AssertionKeySet, AssertionPolicyId, BindRefusal,
|
||
CanonicalCapabilities, ClaimOutcome, ClientSubjectPosture, CommandClaim, CommandError,
|
||
CommandIssuerPolicy, CommandPolicyError, CommandReplayGuard, CommandResult, CommandVerifier,
|
||
CommunityBinding, CommunityBindingError, ConfidentialAssertion, CrossPodMergeResult,
|
||
DenialClass, DenyEntry, DenyScope, DenySetFull, DenyStatus, FederatedAssertionVerifier,
|
||
FederatedIdentity, FederatedIdentityDiscovery, FreshnessClass, HttpJwksFetcher, IssuerCapacity,
|
||
IssuerJwksConfig, IssuerKeySource, IssuerPolicy, IssuerPolicyError, IssuerRegistry,
|
||
JwksFetchError, JwksFetcher, JwksSourceContract, LoadDenies, LoadDeniesError, NipFiDenyMap,
|
||
NipFiMode, NipFiStartupError, ProductionJwksSource, ProvisionBindingError,
|
||
ProvisionBindingPolicy, RevalidationDependencies, SubjectClass, SubjectClassContract,
|
||
TokenClass, TransportContractId, VerifiedAssertion, VerifierError, VerifyAssertion,
|
||
CLIENT_ATTACHED_HEADER, COMMAND_JWT_TYP, MAX_COMMAND_AGE_SECONDS, NOSTR_OWNER_PUBKEY_CLAIM,
|
||
NOSTR_PUBKEY_CLAIM, OAUTH_CLIENT_ID_CLAIM,
|
||
};
|
||
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use access::MockAccessChecker;
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use nip98_replay::AlwaysFreshReplayGuard;
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use nip_fi::jwks::ScriptedJwksFetcher;
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use nip_fi::InMemoryCommandReplayGuard;
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use nip_fi::StaticIssuerKeySource;
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use nip_fi::ToggleJwksFetcher;
|
||
#[cfg(any(test, feature = "test-utils"))]
|
||
pub use rate_limit::AlwaysAllowRateLimiter;
|
||
|
||
/// How the connection was authenticated.
|
||
#[derive(Debug, Clone, PartialEq, Eq)]
|
||
pub enum AuthMethod {
|
||
/// NIP-42 challenge/response — Schnorr signature over kind:22242.
|
||
Nip42,
|
||
/// NIP-98 HTTP Auth — Schnorr signature over kind:27235.
|
||
Nip98,
|
||
}
|
||
|
||
/// The result of a successful authentication, bound to a connection.
|
||
#[derive(Debug, Clone)]
|
||
pub struct AuthContext {
|
||
/// The authenticated Nostr public key.
|
||
pub pubkey: nostr::PublicKey,
|
||
/// Permission scopes granted to this connection.
|
||
pub scopes: Vec<Scope>,
|
||
/// Channel restriction (reserved for future per-channel access control).
|
||
///
|
||
/// `None` means unrestricted.
|
||
pub channel_ids: Option<Vec<uuid::Uuid>>,
|
||
/// How the connection was authenticated.
|
||
pub auth_method: AuthMethod,
|
||
/// NIP-OA verified owner pubkey (if authenticated via owner attestation).
|
||
///
|
||
/// `None` for direct relay members or non-NIP-OA auth paths.
|
||
/// Set by the relay membership gate when NIP-OA fallback succeeds.
|
||
pub agent_owner_pubkey: Option<nostr::PublicKey>,
|
||
}
|
||
|
||
impl AuthContext {
|
||
/// Returns `true` if this context includes the given [`Scope`].
|
||
pub fn has_scope(&self, scope: &Scope) -> bool {
|
||
self.scopes.contains(scope)
|
||
}
|
||
}
|
||
|
||
/// Top-level authentication configuration, typically loaded from the relay's TOML config file.
|
||
#[derive(Debug, Clone, Default, serde::Serialize, serde::Deserialize)]
|
||
pub struct AuthConfig {
|
||
/// Per-user and per-IP rate limit thresholds.
|
||
#[serde(default)]
|
||
pub rate_limits: RateLimitConfig,
|
||
}
|
||
|
||
/// Simplified auth service — NIP-42 and NIP-98 only.
|
||
/// No JWT validation, no token management, no IdP runtime dependency.
|
||
#[derive(Debug, Clone)]
|
||
pub struct AuthService {
|
||
config: AuthConfig,
|
||
}
|
||
|
||
impl AuthService {
|
||
/// Create a new `AuthService` with the given configuration.
|
||
pub fn new(config: AuthConfig) -> Self {
|
||
Self { config }
|
||
}
|
||
|
||
/// Return a reference to the auth configuration.
|
||
pub fn config(&self) -> &AuthConfig {
|
||
&self.config
|
||
}
|
||
|
||
/// Verify a NIP-42 AUTH event and return an [`AuthContext`].
|
||
///
|
||
/// Pure cryptographic verification — no network calls, no JWT, no tokens.
|
||
pub async fn verify_auth_event(
|
||
&self,
|
||
auth_event: nostr::Event,
|
||
expected_challenge: &str,
|
||
relay_url: &str,
|
||
) -> Result<AuthContext, AuthError> {
|
||
// Verify NIP-42 signature (spawn_blocking for CPU-bound Schnorr verify)
|
||
let event_clone = auth_event.clone();
|
||
let challenge_owned = expected_challenge.to_string();
|
||
let relay_owned = relay_url.to_string();
|
||
tokio::task::spawn_blocking(move || {
|
||
verify_nip42_event(&event_clone, &challenge_owned, &relay_owned)
|
||
})
|
||
.await
|
||
.map_err(|_| AuthError::Internal("spawn_blocking panicked".into()))??;
|
||
|
||
// In pure Nostr mode, all authenticated connections get full scopes.
|
||
// Per-channel access is enforced by the relay's membership checks (NIP-29).
|
||
Ok(AuthContext {
|
||
pubkey: auth_event.pubkey,
|
||
scopes: Scope::all_known(),
|
||
channel_ids: None,
|
||
auth_method: AuthMethod::Nip42,
|
||
agent_owner_pubkey: None, // Set later by relay membership gate if NIP-OA
|
||
})
|
||
}
|
||
}
|
||
|
||
/// Derive a deterministic Nostr pubkey from a username string.
|
||
///
|
||
/// Uses `SHA-256("buzz-test-key:{username}")` as the secret key material.
|
||
/// This matches the derivation used by the desktop's `set_test_identity` function,
|
||
/// allowing the relay to resolve usernames to Nostr pubkeys in dev mode.
|
||
///
|
||
/// # ⚠️ SECURITY — Dev/test only
|
||
///
|
||
/// This function is gated behind `#[cfg(any(test, feature = "dev"))]`
|
||
/// and **must never be compiled into a production release build**.
|
||
///
|
||
/// - The derived keys are deterministic and predictable from the username alone.
|
||
/// - Any attacker who knows a username can compute the corresponding private key.
|
||
#[cfg(any(test, feature = "dev"))]
|
||
pub fn derive_pubkey_from_username(username: &str) -> Result<nostr::PublicKey, AuthError> {
|
||
use sha2::{Digest, Sha256};
|
||
let seed = format!("buzz-test-key:{username}");
|
||
let hash: [u8; 32] = Sha256::digest(seed.as_bytes()).into();
|
||
let secret_key = nostr::SecretKey::from_slice(&hash)
|
||
.map_err(|e| AuthError::Internal(format!("key derivation failed: {e}")))?;
|
||
Ok(nostr::Keys::new(secret_key).public_key())
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
use nostr::{EventBuilder, Keys, Kind, RelayUrl};
|
||
|
||
fn make_auth_event(keys: &Keys, challenge: &str, relay_url: &str) -> nostr::Event {
|
||
let url = RelayUrl::parse(relay_url).expect("valid url");
|
||
EventBuilder::auth(challenge, url)
|
||
.sign_with_keys(keys)
|
||
.expect("signing failed")
|
||
}
|
||
|
||
fn test_service() -> AuthService {
|
||
AuthService::new(AuthConfig::default())
|
||
}
|
||
|
||
#[test]
|
||
fn auth_context_scope_check() {
|
||
let keys = Keys::generate();
|
||
let ctx = AuthContext {
|
||
pubkey: keys.public_key(),
|
||
scopes: vec![Scope::MessagesRead, Scope::ChannelsRead],
|
||
channel_ids: None,
|
||
auth_method: AuthMethod::Nip42,
|
||
agent_owner_pubkey: None,
|
||
};
|
||
assert!(ctx.has_scope(&Scope::MessagesRead));
|
||
assert!(!ctx.has_scope(&Scope::MessagesWrite));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn nip42_auth_succeeds() {
|
||
let keys = Keys::generate();
|
||
let challenge = generate_challenge();
|
||
let relay = "wss://relay.example.com";
|
||
let event = make_auth_event(&keys, &challenge, relay);
|
||
|
||
let ctx = test_service()
|
||
.verify_auth_event(event, &challenge, relay)
|
||
.await
|
||
.expect("NIP-42 auth should succeed");
|
||
|
||
assert_eq!(ctx.pubkey, keys.public_key());
|
||
assert_eq!(ctx.auth_method, AuthMethod::Nip42);
|
||
assert!(ctx.has_scope(&Scope::MessagesRead));
|
||
assert!(ctx.has_scope(&Scope::MessagesWrite));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn wrong_challenge_rejected() {
|
||
let keys = Keys::generate();
|
||
let challenge = generate_challenge();
|
||
let relay = "wss://relay.example.com";
|
||
let event = make_auth_event(&keys, &challenge, relay);
|
||
|
||
let result = test_service()
|
||
.verify_auth_event(event, "wrong-challenge", relay)
|
||
.await;
|
||
assert!(matches!(result, Err(AuthError::ChallengeMismatch)));
|
||
}
|
||
|
||
#[tokio::test]
|
||
async fn wrong_kind_rejected() {
|
||
let keys = Keys::generate();
|
||
let event = EventBuilder::new(Kind::TextNote, "not auth")
|
||
.tags([])
|
||
.sign_with_keys(&keys)
|
||
.expect("sign");
|
||
|
||
let result = test_service()
|
||
.verify_auth_event(event, &generate_challenge(), "wss://relay.example.com")
|
||
.await;
|
||
assert!(matches!(result, Err(AuthError::InvalidSignature)));
|
||
}
|
||
}
|