mirror of
https://github.com/block/buzz.git
synced 2026-11-24 02:02:07 +00:00
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>
271 lines
11 KiB
Rust
271 lines
11 KiB
Rust
//! The one cached NIP-FI assertion the headless adapter session holds for its
|
||
//! relay: one `exp` parser and one refresh rule. The Buzz desktop link keeps
|
||
//! no copy; the desktop app's cache is the only owner of its assertions.
|
||
|
||
use tokio::sync::Mutex;
|
||
|
||
use crate::error::CliError;
|
||
|
||
/// Refresh at least this long before expiry.
|
||
const REFRESH_MARGIN_SECS: u64 = 30;
|
||
|
||
/// Fetches per [`CachedAssertion::get`] before an assertion that arrives with
|
||
/// no local lifetime left is reported instead of retried.
|
||
const ACQUIRE_ATTEMPTS: usize = 3;
|
||
|
||
/// A fetched assertion and the monotonic time ([`monotonic_now`]) the
|
||
/// request that returned it was sent.
|
||
pub(crate) type Fetched = Option<(String, u64)>;
|
||
|
||
/// An evidence link's current assertion, or its answer that it has none.
|
||
#[derive(Default)]
|
||
pub(crate) struct CachedAssertion(Mutex<Option<(Option<String>, Receipt)>>);
|
||
|
||
/// When a cached answer arrived, on both clocks, and how long it may be
|
||
/// reused (monotonic seconds).
|
||
#[derive(Clone, Copy)]
|
||
struct Receipt {
|
||
monotonic: u64,
|
||
wall: u64,
|
||
budget: u64,
|
||
}
|
||
|
||
impl Receipt {
|
||
/// Still reusable at `monotonic` and `wall`. The monotonic clock stops
|
||
/// while the computer sleeps, so the wall clock bounds it too; a wall
|
||
/// clock set back counts as no time passed.
|
||
fn usable(self, monotonic: u64, wall: u64) -> bool {
|
||
let elapsed = monotonic
|
||
.saturating_sub(self.monotonic)
|
||
.max(wall.saturating_sub(self.wall));
|
||
elapsed < self.budget
|
||
}
|
||
}
|
||
|
||
impl CachedAssertion {
|
||
/// The cached answer until its refresh point, else `fetch`'s. A fetched
|
||
/// assertion must be a compact JWS with `exp` and `iat`, and must have
|
||
/// local lifetime left; one with none is fetched again, a bounded number
|
||
/// of times. `None` is kept until the next command. Concurrent callers
|
||
/// share one fetch.
|
||
pub(crate) async fn get<F, Fut>(&self, fetch: F) -> Result<Option<String>, CliError>
|
||
where
|
||
F: Fn() -> Fut,
|
||
Fut: std::future::Future<Output = Result<Fetched, CliError>>,
|
||
{
|
||
let mut cached = self.0.lock().await;
|
||
if let Some((assertion, receipt)) = cached.as_ref() {
|
||
if receipt.usable(monotonic_now(), unix_now()) {
|
||
return Ok(assertion.clone());
|
||
}
|
||
}
|
||
*cached = None;
|
||
for _ in 0..ACQUIRE_ATTEMPTS {
|
||
let Some((jws, request_start)) = fetch().await? else {
|
||
let forever = Receipt {
|
||
monotonic: 0,
|
||
wall: 0,
|
||
budget: u64::MAX,
|
||
};
|
||
*cached = Some((None, forever));
|
||
return Ok(None);
|
||
};
|
||
let claims = jws_claims(&jws)
|
||
.filter(|c| c.lifetime.is_some())
|
||
.ok_or_else(|| {
|
||
CliError::Auth("the evidence source returned an unreadable assertion".into())
|
||
})?;
|
||
let (receipt, wall) = (monotonic_now(), unix_now());
|
||
let deadline = local_deadline(request_start, receipt, wall, claims);
|
||
if deadline > receipt {
|
||
let budget = refresh_at(receipt, deadline) - receipt;
|
||
let at = Receipt {
|
||
monotonic: receipt,
|
||
wall,
|
||
budget,
|
||
};
|
||
*cached = Some((Some(jws.clone()), at));
|
||
return Ok(Some(jws));
|
||
}
|
||
}
|
||
Err(CliError::Auth(format!(
|
||
"the evidence source returned {ACQUIRE_ATTEMPTS} assertions with no lifetime left; \
|
||
check that this computer's clock is correct"
|
||
)))
|
||
}
|
||
}
|
||
|
||
/// The local monotonic deadline of an assertion whose request was sent at
|
||
/// `request_start` and answered at `receipt` (monotonic seconds), with the
|
||
/// wall clock at `wall_at_receipt`: the issuer's lifetime counted from the
|
||
/// send, capped by `exp` against the local wall clock. The first term keeps a
|
||
/// skewed local clock from stretching the token; the second keeps a short
|
||
/// session-capped token from outliving its `exp`. A deadline at or before
|
||
/// `receipt` means no lifetime is left. `claims.lifetime` must be present.
|
||
fn local_deadline(request_start: u64, receipt: u64, wall_at_receipt: u64, claims: Claims) -> u64 {
|
||
let by_exp = receipt + claims.exp.saturating_sub(wall_at_receipt);
|
||
let by_lifetime = request_start + claims.lifetime.unwrap_or(0);
|
||
by_exp.min(by_lifetime)
|
||
}
|
||
|
||
/// Refresh at the earlier of half-life and [`REFRESH_MARGIN_SECS`] before
|
||
/// `exp`; when that margin is already past, at half-life, so a short-lived
|
||
/// assertion is not fetched again on every request.
|
||
pub(crate) fn refresh_at(now: u64, exp: u64) -> u64 {
|
||
let half_life = now + exp.saturating_sub(now) / 2;
|
||
match exp.saturating_sub(REFRESH_MARGIN_SECS) {
|
||
early if early > now => early.min(half_life),
|
||
_ => half_life,
|
||
}
|
||
}
|
||
|
||
/// The `exp` claim of a structurally valid compact JWS: three non-empty
|
||
/// unpadded base64url segments, a JSON-object header naming `alg`, and a
|
||
/// JSON-object payload with an integer `exp`. The relay verifies the
|
||
/// signature; the CLI only refuses output it could not present or refresh.
|
||
pub(crate) fn jws_exp(token: &str) -> Option<u64> {
|
||
jws_claims(token).map(|c| c.exp)
|
||
}
|
||
|
||
/// The `exp` claim of an assertion and, when it has a numeric `iat`, its
|
||
/// issuer lifetime `exp − iat` in whole seconds.
|
||
#[derive(Clone, Copy)]
|
||
struct Claims {
|
||
exp: u64,
|
||
lifetime: Option<u64>,
|
||
}
|
||
|
||
/// [`jws_exp`]'s structural check, also returning the lifetime.
|
||
fn jws_claims(token: &str) -> Option<Claims> {
|
||
use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine};
|
||
let mut segments = token.split('.');
|
||
let (Some(header), Some(payload), Some(signature), None) = (
|
||
segments.next(),
|
||
segments.next(),
|
||
segments.next(),
|
||
segments.next(),
|
||
) else {
|
||
return None;
|
||
};
|
||
let json = |segment: &str| -> Option<serde_json::Map<String, serde_json::Value>> {
|
||
serde_json::from_slice(&URL_SAFE_NO_PAD.decode(segment).ok()?).ok()
|
||
};
|
||
if signature.is_empty() || URL_SAFE_NO_PAD.decode(signature).is_err() {
|
||
return None;
|
||
}
|
||
json(header)?.get("alg")?.as_str()?;
|
||
let payload = json(payload)?;
|
||
Some(Claims {
|
||
exp: payload.get("exp")?.as_u64()?,
|
||
lifetime: lifetime(&payload),
|
||
})
|
||
}
|
||
|
||
/// `max(0, floor(exp − iat))`. `iat` is a NumericDate, so it may be
|
||
/// fractional (`exp` is already an integer here); rounding down never
|
||
/// stretches the token.
|
||
fn lifetime(payload: &serde_json::Map<String, serde_json::Value>) -> Option<u64> {
|
||
let exp = payload.get("exp")?.as_f64()?;
|
||
let iat = payload.get("iat")?.as_f64()?;
|
||
Some((exp - iat).floor().max(0.0) as u64)
|
||
}
|
||
|
||
/// Whole seconds on a monotonic clock, for local deadlines a wall-clock
|
||
/// change cannot move.
|
||
pub(crate) fn monotonic_now() -> u64 {
|
||
static START: std::sync::OnceLock<std::time::Instant> = std::sync::OnceLock::new();
|
||
let now = START
|
||
.get_or_init(std::time::Instant::now)
|
||
.elapsed()
|
||
.as_secs();
|
||
#[cfg(test)]
|
||
let now = now + test_clock::SKEW.with(std::cell::Cell::get);
|
||
now
|
||
}
|
||
|
||
pub(crate) fn unix_now() -> u64 {
|
||
let now = std::time::SystemTime::now()
|
||
.duration_since(std::time::UNIX_EPOCH)
|
||
.map(|d| d.as_secs())
|
||
.unwrap_or(0);
|
||
#[cfg(test)]
|
||
let now = test_clock::FROZEN.with(std::cell::Cell::get).unwrap_or(now)
|
||
+ test_clock::SKEW.with(std::cell::Cell::get);
|
||
now
|
||
}
|
||
|
||
/// A clock tests move forward instead of sleeping. Per thread, so it moves
|
||
/// only for the test (and its current-thread runtime) that advances it.
|
||
#[cfg(test)]
|
||
pub(crate) mod test_clock {
|
||
thread_local! {
|
||
pub(super) static FROZEN: std::cell::Cell<Option<u64>> = const { std::cell::Cell::new(None) };
|
||
pub(super) static SKEW: std::cell::Cell<u64> = const { std::cell::Cell::new(0) };
|
||
}
|
||
/// Pin this thread's clock to `at`, so reads on either side of a
|
||
/// wall-clock second boundary agree; `advance` still moves it.
|
||
pub(crate) fn freeze(at: u64) {
|
||
FROZEN.with(|frozen| frozen.set(Some(at)));
|
||
}
|
||
pub(crate) fn advance(secs: u64) {
|
||
SKEW.with(|skew| skew.set(skew.get() + secs));
|
||
}
|
||
/// Move only this thread's frozen wall clock, as a sleep does while the
|
||
/// monotonic clock stands still. Requires [`freeze`].
|
||
pub(crate) fn advance_wall(secs: u64) {
|
||
FROZEN.with(|frozen| frozen.set(Some(frozen.get().expect("freeze first") + secs)));
|
||
}
|
||
}
|
||
|
||
#[cfg(test)]
|
||
mod tests {
|
||
use super::*;
|
||
|
||
#[test]
|
||
fn refresh_is_at_the_earlier_of_half_life_and_the_margin() {
|
||
assert_eq!(refresh_at(1_000, 1_300), 1_150, "long-lived: half-life");
|
||
assert_eq!(refresh_at(1_000, 1_060), 1_030);
|
||
assert_eq!(refresh_at(1_000, 1_040), 1_010, "short-lived: the margin");
|
||
assert_eq!(refresh_at(1_000, 1_020), 1_010, "margin past: half-life");
|
||
assert_eq!(refresh_at(1_000, 1_001), 1_000);
|
||
}
|
||
|
||
#[test]
|
||
fn the_deadline_counts_the_lifetime_from_the_request_start() {
|
||
let claims = |iat, exp| Claims {
|
||
exp,
|
||
lifetime: Some(exp - iat),
|
||
};
|
||
// Issuer clock: iat 10_000, exp 10_180. The reply took 20 s.
|
||
// A local clock 120 s slow would read 180 + 120 s left by `exp`;
|
||
// the lifetime from the request start caps it.
|
||
assert_eq!(local_deadline(0, 20, 9_900, claims(10_000, 10_180)), 180);
|
||
// A local clock 120 s fast: `exp` leaves 40 s past receipt, the tighter bound.
|
||
assert_eq!(local_deadline(0, 20, 10_140, claims(10_000, 10_180)), 60);
|
||
// A sleep: the wall clock jumps 1 hour, the monotonic clock doesn't.
|
||
let at = Receipt {
|
||
monotonic: 20,
|
||
wall: 10_140,
|
||
budget: 20,
|
||
};
|
||
assert!(at.usable(20, 10_140) && !at.usable(20, 10_140 + 3_600));
|
||
}
|
||
|
||
#[test]
|
||
fn jws_exp_needs_a_compact_jws_with_alg_and_exp() {
|
||
let payload = "eyJleHAiOjE3OTAwMDAzMDB9"; // {"exp":1790000300}
|
||
let header = "eyJhbGciOiJFUzI1NiJ9"; // {"alg":"ES256"}
|
||
assert_eq!(
|
||
jws_exp(&format!("{header}.{payload}.c2ln")),
|
||
Some(1_790_000_300)
|
||
);
|
||
assert_eq!(jws_exp(&format!("e30.{payload}.c2ln")), None, "no alg");
|
||
assert_eq!(jws_exp(&format!("{header}.{payload}")), None);
|
||
assert_eq!(jws_exp(&format!("{header}.{payload}.c2ln.x")), None);
|
||
// A fractional `iat` is a valid NumericDate; the lifetime rounds down.
|
||
let fractional = "eyJpYXQiOjE3OTAwMDAwMDAuNSwiZXhwIjoxNzkwMDAwMzAwfQ"; // {"iat":1790000000.5,"exp":1790000300}
|
||
let claims = jws_claims(&format!("{header}.{fractional}.c2ln")).unwrap();
|
||
assert_eq!((claims.exp, claims.lifetime), (1_790_000_300, Some(299)));
|
||
}
|
||
}
|