Files
buzz/crates/buzz-auth/src/lib.rs
Will Pfleger df21064800 feat(auth): tolerate client clocks up to 120 s off (#9485)
Lets clients whose clocks are up to 120 s off sign in to NIP-FI
communities and stay connected.

**Relay**
- NIP-42 AUTH and NIP-98 HTTP Auth accept `created_at` within ±120 s,
using a shared `buzz_auth::TIMESTAMP_TOLERANCE_SECS`. This covers relay
login, audio admission, bridge, admin, invites, NIP-FI policy and Git.
- `DEFAULT_REPLAY_TTL_SECS` goes from 120 to 250 s: a 2 × 120 s window,
plus 1 s for the inclusive whole-second bounds, plus a 9 s budget for
the clock difference between relay pods. A compile-time assert checks
the arithmetic. The 9 s is an operational assumption about NTP-synced
pods, and the doc comment says so. No `deploy/` override exists.
- Media (kind 24242):
- Both modes accept `created_at` up to 120 s in the future and an
`expiration` greater than `now − 120`.
  - Strict: the 120 s age limit and the 60 s lifetime cap.
  - Permissive: keeps its 3600 s age allowance and has no lifetime cap.
- `buzz-auth` and `buzz-media` read the time through a `wall_now()` that
tests can pin (a `#[cfg(test)]` thread-local), so boundary tests are
exact.
- Git transport: comments only. It still reuses one proof per session,
so the reuse window now matches ±120 s.

**CLI**
- The desktop-provider lane asks the desktop app for the assertion every
time and keeps no copy, so the desktop's cache owns each token's
deadline. It looks the token up again after signing and sends that one,
so a provider may hand out a new token on every call.
- The direct-mint cache sets its deadline to `min(request_start + (exp −
iat), receipt + (exp − local_now))`, on a monotonic clock.
`request_start` is when the attempt that got the reply was sent, not the
start of the retry loop.
- An assertion with no local lifetime left is never returned or sent.
The cache asks again, up to 3 times, then fails with an auth error that
points at the computer's clock. An assertion without a readable `iat` is
refused. `iat` may be fractional (a NumericDate); the lifetime is
`max(0, floor(exp − iat))` whole seconds.

**Cache reuse (CLI, Flutter, iOS):** each cached token records when it
arrived on both the monotonic and the wall clock. It is reused only
while `max(monotonic elapsed, wall elapsed)` since arrival is under its
budget (`refresh point − receipt`, on the monotonic clock). A negative
wall elapsed counts as 0. The monotonic clocks used here stop while the
device sleeps, so the wall clock ends reuse after a sleep; setting the
wall clock back can't stretch a token, because the monotonic bound still
applies.

**Mobile**
- Flutter `HostedRelayAuth`: the same lifetime rule, on a monotonic
clock, for async acquisition and for the synchronous `cachedHeaders`
media path. A token with no local lifetime left is never sent: issuance
is retried up to 3 times, then fails as `unavailable`. A token without a
readable `iat` fails as `invalidResponse`.
- Flutter refusal hint: the account client reads `Date` when a 403's
headers arrive, before the body (`boundedHttpResponse` gains an
`onHeaders` callback). The 403 stays `AccountFailure.denied` even if its
body is then lost, late or too large. The hint is stored with the
refusal it explains (`HostedRelayAuth.failureClockHint`), cleared when
that community next gets a token or the account session changes, and
left alone by other communities' issuance. The account client records a
403's hint only for the acquisition whose own request was refused
(`BuilderlabAccountClient.observingRefusals`), so an unrelated account
call, such as the organization key backup, never supplies a sign-in's
hint. When the offset is over 115 s, the reconnect and organization
banners add "Your device's clock looks about N minutes off, which can
cause this. Check your date and time settings."
- iOS `BuzzRelayAssertionIssuer`: the same lifetime rule, on
`systemUptime`. An assertion without a readable `iat` is refused.
- iOS push enrollment: a new grant's window starts 120 s in the past, so
`not_before = now − 120` and `expires_at = now − 120 + lifetime`. A fast
phone then neither signs a `not_before` the gateway hasn't reached nor
goes over its 30-day maximum. A resumed journal resubmits the
installation expiry it already attested, byte for byte. The delegation,
which is signed fresh each time, expires at the earlier of that expiry
and `not_before + lifetime`, so a journal written by an older client on
a fast phone still gets a grant the gateway accepts. The saved grant
records the delegation's expiry.
- Flutter and iOS already sign a fresh proof with a `nonce` on every
issuer attempt, so their retries needed no change.

**Specs:** NIP-FA proof bounds (120 s old / 120 s future), plus NIP-FI
Git (`±120s`), media freshness, the media read residual and the media
trace row.

`desktop/` is untouched.

Not exercised live: Git clone/push, audio join and push delivery with a
skewed client clock.

---------

Signed-off-by: Will Pfleger <wpfleger@block.xyz>
Signed-off-by: Tom Brow <tomb@squareup.com>
Co-authored-by: Hayt <211b96e6a2b7f45fd4047988976c7bbbeeda0c15f3ae7b32eec20834b5a55118@buzz.block.builderlab.xyz>
Co-authored-by: Tom Brow <tomb@block.xyz>
Co-authored-by: Tom Brow <tomb@squareup.com>
2026-11-16 12:17:14 -05:00

298 lines
11 KiB
Rust
Raw Blame History

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

#![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, ClientSubjectPosture, CommandError, CommandIssuerPolicy,
CommandPolicyError, CommandReplayGuard, CommandResult, CommandVerifier, CommunityBinding,
CommunityBindingError, ConfidentialAssertion, CrossPodMergeResult, DenialClass, DenySetFull,
FederatedAssertionVerifier, FederatedIdentity, FederatedIdentityDiscovery, FreshnessClass,
HttpJwksFetcher, IssuerCapacity, IssuerJwksConfig, IssuerKeySource, IssuerPolicy,
IssuerPolicyError, IssuerRegistry, JwksFetchError, JwksFetcher, JwksSourceContract,
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)));
}
}