Skip to content

Commit 272daca

Browse files
Duncanwpfleger96
andcommitted
fix(buzz-auth): complete SSRF policy, cancellation-safe permit, and invariant tests
Network policy (buzz-core): - Rename is_private_ip → is_not_global_unicast; is_private_ip alias preserved for unowned callers. Registry source: IANA IPv4/IPv6 Special-Purpose Address Space (registries last updated 2025-10-09, retrieved 2026-08-31; URLs in source doc comment). - Implement the IANA deny/exception table: outer predicate denies ranges whose registry entry is non-global or blank; explicit globally-reachable exceptions carved out inside otherwise-denied envelopes. IPv4 embedded in IPv4-mapped, IPv4-compatible, NAT64 well-known (64:ff9b::/96), and SIIT IPv4-translated space is evaluated recursively against the IPv4 table — registry global=True on the IPv6 wrapper does not bypass the embedded-address check. - IPv4: add 192.0.0.0/24 IETF Protocol Assignments (global=False) with globally- reachable exceptions 192.0.0.9 (PCP anycast, RFC 7723) and 192.0.0.10 (TURN anycast, RFC 8155); add 192.88.99.0/24 deprecated 6to4 relay anycast (global=None — conservative posture: block). - IPv6: replace individual Teredo/benchmarking/ORCHID checks with the 2001::/23 IETF Protocol Assignments envelope (global=False). Globally-reachable exceptions inside the /23 are allowed: 2001:1::1/2/3 (PCP/TURN/DNS-SD anycast), 2001:3::/32 (AMT), 2001:4:112::/48 (AS112-v6), 2001:20::/28 (ORCHIDv2, global=True), 2001:30::/28 (DETs, global=True). Add 100:0:0:1::/64 dummy prefix (RFC 9780), 3fff::/20 documentation (RFC 9637), 5f00::/16 SRv6 SIDs (RFC 9252). 2001:db8::/32 (outside 2001::/23) remains a separate check. - Consumer audit: buzz-workflow (CallWebhook) and desktop link_preview use the is_private_ip alias; the stricter predicate closes all new ranges for both callers. Cancellation-safe refresh permit (buzz-auth): - Per-issuer OwnedMutexGuard spans the complete fetch and state commit; cancelled callers release the permit on drop — no manual flag to poison. - ScriptedFetcher replaces BlockingFetcher + SequencedFetcher: a VecDeque of FetchStep{entered, release} makes call order self-documenting without comments. - concurrent_refresh_coalesces_without_second_fetch: entered barrier proves permit ownership before the second call; assert call_count == 1. - aborted_first_caller_releases_permit_for_next_caller: pending_step returns the release sender, which is held until after abort — task is genuinely blocked (not resolved via error path) when cancelled. assert call_count == 2. Central invariant regressions (buzz-auth): - expired_snapshot_never_served_after_hard_deadline: hard-deadline expiry closes both the async and synchronous snapshot paths. - two_issuer_keys_and_generations_are_isolated: advancing A's document advances A's generation only; B's key binding and generation are unchanged. Architecture docs (ARCHITECTURE.md): - Update is_private_ip function-table entry to is_not_global_unicast with compat alias. - Rewrite SSRF Protection section: deny/exception-table framing, embedded-IPv4 recursive evaluation, all three audited callers. Co-authored-by: Will Pfleger <[email protected]> Signed-off-by: Will Pfleger <[email protected]>
1 parent 8194e62 commit 272daca

4 files changed

Lines changed: 724 additions & 287 deletions

File tree

‎ARCHITECTURE.md‎

Lines changed: 4 additions & 6 deletions
Original file line numberDiff line numberDiff line change
@@ -361,7 +361,7 @@ pub const ALL_KINDS: &[u32] // 80 entries (KIND_AUTH excluded — never stored)
361361
|----------|---------|
362362
| `filters_match(filters, event)` | OR across filters, AND within each filter. Includes NIP-01 prefix matching on event IDs. |
363363
| `verify_event(event)` | Schnorr signature + SHA-256 ID check. CPU-bound — callers use `spawn_blocking`. |
364-
| `is_private_ip(ip)` | SSRF protection: IPv4 unspecified/loopback/private/link-local/CGNAT/benchmarking/broadcast + IPv6 loopback/ULA/link-local/multicast/documentation + IPv4-mapped IPv6. |
364+
| `is_not_global_unicast(ip)` | SSRF protection: starts from IANA deny/exception table — denies ranges whose registry entry is non-global or blank, carves out explicit global exceptions inside denied envelopes, and evaluates embedded IPv4 recursively. Registries last updated 2025-10-09. Compat alias: `is_private_ip`. |
365365

366366
**Does NOT:** store events, make network calls, spawn tasks, or depend on any async runtime.
367367

@@ -746,12 +746,10 @@ Every security-sensitive operation uses an explicit, verified pattern. No implic
746746
747747
### SSRF Protection
748748
749-
`is_private_ip()` in `buzz-core` covers:
750-
- IPv4: unspecified (0.0.0.0/8), loopback (127.0.0.0/8), private (10/8, 172.16/12, 192.168/16), link-local (169.254/16), CGNAT (100.64/10), benchmarking (198.18/15), broadcast (255.255.255.255)
751-
- IPv6: loopback (::1), ULA (fc00::/7), link-local (fe80::/10), multicast (ff00::/8), documentation (2001:db8::/32)
752-
- IPv4-mapped IPv6 (::ffff:0:0/96) — recursively checks the embedded IPv4 address
749+
`is_not_global_unicast(ip)` (compat alias `is_private_ip`) in `buzz-core` starts from the IANA deny/exception table: denies ranges whose IPv4 or IPv6 Special-Purpose Address Space registry entry is non-global or blank (registries last updated 2025-10-09), carves out explicit globally-reachable exceptions inside otherwise-denied envelopes (e.g., PCP/TURN/DNS-SD anycast inside 2001::/23), and evaluates IPv4 embedded in IPv4-mapped, IPv4-compatible, and NAT64 well-known (64:ff9b::/96) space recursively against the IPv4 table. SIIT IPv4-translated (::ffff:0:0:0/96) follows the same recursive path. The local-use NAT64 prefix (64:ff9b:1::/48) is blocked wholesale. Conservative posture: `None`/blank entries are treated as non-global.
753750
754-
Applied in: `buzz-workflow` (CallWebhook action), `buzz-core` (shared utility).
751+
Applied in: `buzz-auth` (JWKS boundary), `buzz-workflow` (CallWebhook action),
752+
desktop `link_preview` (SSRF check).
755753
756754
### Audit Integrity
757755

‎crates/buzz-auth/src/nip_fi/jwks/mod.rs‎

Lines changed: 27 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -27,7 +27,7 @@
2727
2828
use super::config::MAX_JWKS_KEYS;
2929
use super::verifier::{AssertionKeySet, IssuerKeySource};
30-
use buzz_core::network::is_private_ip;
30+
use buzz_core::network::is_not_global_unicast;
3131
use chrono::{DateTime, Duration, Utc};
3232
use futures_util::StreamExt as _;
3333
use jsonwebtoken::jwk::JwkSet;
@@ -73,12 +73,12 @@ pub fn validate_jwks_uri(uri: &str) -> Result<(), JwksFetchError> {
7373
}
7474
// Reject bare private/reserved IP targets at construction time.
7575
if let Some(url::Host::Ipv4(addr)) = parsed.host() {
76-
if is_private_ip(&std::net::IpAddr::V4(addr)) {
76+
if is_not_global_unicast(&std::net::IpAddr::V4(addr)) {
7777
return Err(JwksFetchError::InvalidUri);
7878
}
7979
}
8080
if let Some(url::Host::Ipv6(addr)) = parsed.host() {
81-
if is_private_ip(&std::net::IpAddr::V6(addr)) {
81+
if is_not_global_unicast(&std::net::IpAddr::V6(addr)) {
8282
return Err(JwksFetchError::InvalidUri);
8383
}
8484
}
@@ -104,7 +104,7 @@ pub(crate) async fn resolve_and_check_ssrf(
104104
) -> Result<std::net::IpAddr, JwksFetchError> {
105105
// Fast path: if the host is already a parsed IP literal, skip the resolver.
106106
if let Ok(ip) = host.parse::<std::net::IpAddr>() {
107-
if is_private_ip(&ip) {
107+
if is_not_global_unicast(&ip) {
108108
return Err(JwksFetchError::InvalidUri);
109109
}
110110
return Ok(ip);
@@ -126,7 +126,7 @@ pub(crate) async fn resolve_and_check_ssrf(
126126
return Err(JwksFetchError::NetworkError);
127127
}
128128
for ip in &addrs {
129-
if is_private_ip(ip) {
129+
if is_not_global_unicast(ip) {
130130
return Err(JwksFetchError::InvalidUri);
131131
}
132132
}
@@ -147,16 +147,18 @@ struct IssuerState {
147147
snapshot: Option<CachedSnapshot>,
148148
/// Advances only when `content_digest` changes; never wraps (saturating).
149149
generation_counter: u64,
150-
/// True while a refresh task owns the fetch lock. Prevents thundering-herd.
151-
refresh_in_flight: bool,
150+
/// Owned permit for in-flight refresh. Held across the complete fetch +
151+
/// state commit; dropped automatically if the caller future is cancelled.
152+
/// `try_lock_owned()` succeeds iff no refresh is in progress.
153+
refresh_permit: Arc<tokio::sync::Mutex<()>>,
152154
}
153155

154156
impl IssuerState {
155157
fn new() -> Self {
156158
Self {
157159
snapshot: None,
158160
generation_counter: 0,
159-
refresh_in_flight: false,
161+
refresh_permit: Arc::new(tokio::sync::Mutex::new(())),
160162
}
161163
}
162164
}
@@ -230,7 +232,7 @@ pub trait JwksFetcher: super::verifier::sealed::Sealed + Send + Sync + 'static {
230232
///
231233
/// Per-fetch boundary enforcement:
232234
/// - hostname DNS is resolved and every address checked against
233-
/// `buzz_core::network::is_private_ip` before the request is sent;
235+
/// `buzz_core::network::is_not_global_unicast` before the request is sent;
234236
/// - the request is pinned to the validated address to prevent DNS rebinding
235237
/// TOCTOU (the OS resolver is called once per fetch, not once per URL);
236238
/// - the complete operation (resolution, connect, headers, body streaming) is
@@ -464,9 +466,11 @@ impl<F: JwksFetcher> ProductionJwksSource<F> {
464466
/// Returns the cached snapshot for `issuer`, refreshing inline if stale.
465467
/// Returns `None` when no live snapshot is available and the fetch fails.
466468
///
467-
/// If a refresh is already in flight for this issuer, returns the current
468-
/// snapshot rather than blocking — coalesces concurrent callers. Drops
469-
/// both locks before the async fetch so other issuers are not blocked.
469+
/// Coalesces concurrent callers: a second call while a refresh is in
470+
/// flight returns the current snapshot immediately rather than starting a
471+
/// second fetch. The refresh permit is an RAII guard — if this future is
472+
/// cancelled while DNS, HTTP, or streaming is pending, the guard drops and
473+
/// the permit is released, so the next caller can start a new fetch.
470474
pub async fn get_snapshot(&self, issuer: &str) -> Option<AssertionKeySet> {
471475
let states = self.states.read().await;
472476
let state_mutex = states.get(issuer)?;
@@ -493,26 +497,31 @@ impl<F: JwksFetcher> ProductionJwksSource<F> {
493497
return state.snapshot.as_ref().map(|c| c.key_set.clone());
494498
}
495499

496-
if state.refresh_in_flight {
497-
return state.snapshot.as_ref().map(|c| c.key_set.clone());
498-
}
500+
// Try to acquire the per-issuer refresh permit. Failure means another
501+
// caller is already fetching; return the current snapshot rather than
502+
// starting a second fetch.
503+
let permit = match Arc::clone(&state.refresh_permit).try_lock_owned() {
504+
Ok(g) => g,
505+
Err(_) => return state.snapshot.as_ref().map(|c| c.key_set.clone()),
506+
};
499507

500-
state.refresh_in_flight = true;
501508
let prev_digest = state.snapshot.as_ref().map(|c| c.content_digest);
502509
let prev_generation = state.generation_counter;
503510
drop(state);
504511
drop(states);
505512

506513
let fresh = self.fetch_fresh(issuer, prev_digest, prev_generation).await;
507514

515+
// Re-acquire state to commit and release the permit atomically.
508516
let states = self.states.read().await;
509517
if let Some(state_mutex) = states.get(issuer) {
510518
let mut st = state_mutex.lock().await;
511-
st.refresh_in_flight = false;
512519
if let Some((ref cached, new_generation)) = fresh {
513520
st.generation_counter = new_generation;
514521
st.snapshot = Some(cached.clone());
515522
}
523+
// Drop the permit only after the state commit is visible.
524+
drop(permit);
516525
let now2 = Utc::now();
517526
return st
518527
.snapshot
@@ -521,6 +530,7 @@ impl<F: JwksFetcher> ProductionJwksSource<F> {
521530
.map(|c| c.key_set.clone());
522531
}
523532

533+
drop(permit);
524534
None
525535
}
526536
}

0 commit comments

Comments
 (0)