From 4e4b15a0b242ef248c02ffc9f5e10706a1f1e337 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 21:08:33 -0600 Subject: [PATCH 1/2] feat(id/web): non-destructive identity registration admission bound (#1766) - IdentityStore gains max_identities: register holds the clients write lock across bound check + redb persist + insert, so concurrent registrations cannot race past the cap; at capacity it returns the typed IdentityCapacityError and deletes nothing - Config: ID_WEB_MAX_IDENTITIES env (positive count or none), default 10000, invalid/zero values warn and fall back to the default; AppState wires configured_max_identities() through new_with_max_identities - Register handler maps the capacity error to an observable 503 identity_capacity_reached JSON body instead of a generic 500 - Existing identities are unaffected at capacity: verify_and_refresh never inserts and ignores the bound; records loaded at startup count toward it - Tests: at/beyond limit, 16-way concurrent race for 5 slots, refresh at capacity, restart at bound serves existing and refuses new - Issue #1766 stays open per its acceptance: lifecycle deletion / legacy records are a separate design --- pkgs/id/src/web/identity.rs | 216 ++++++++++++++++++++++++++++++++++-- pkgs/id/src/web/mod.rs | 7 +- pkgs/id/src/web/routes.rs | 16 +++ 3 files changed, 230 insertions(+), 9 deletions(-) diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index d77cc84925..5daede47d1 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -64,6 +64,79 @@ const MAX_NAME_LENGTH: usize = 64; /// Maximum token age before it's considered expired (30 days in seconds). const TOKEN_MAX_AGE_SECS: u64 = 30 * 24 * 60 * 60; +/// Default admission bound on registered web identities (#1766). +/// +/// Registration used to grow the identity store — the in-memory maps +/// AND the on-disk redb — without any bound. The bound refuses NEW +/// registrations at capacity; it never deletes existing records, and +/// already-registered identities keep authenticating and refreshing +/// tokens at capacity (a cap is an admission control, not a cleanup — +/// lifecycle deletion for legacy records is a separate design). +/// Sized for a personal dashboard: one identity per browser profile / +/// device / test run, with generous headroom. +pub const DEFAULT_MAX_IDENTITIES: usize = 10_000; + +/// Environment variable overriding [`DEFAULT_MAX_IDENTITIES`]: +/// a positive count, or `none` for unbounded. +pub const MAX_IDENTITIES_ENV: &str = "ID_WEB_MAX_IDENTITIES"; + +/// Registration refused because the identity store is at its +/// configured admission bound (#1766). The register handler maps this +/// to a 503 so a refused first visit is observable and explainable, +/// never a silent or generic failure. +#[derive(Debug, Clone, PartialEq, Eq)] +pub struct IdentityCapacityError { + /// The configured admission bound. + pub limit: usize, + /// How many identities were registered when the refusal happened. + pub registered: usize, +} + +impl std::fmt::Display for IdentityCapacityError { + fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result { + write!( + f, + "identity registration capacity reached ({}/{} identities); new registrations are refused — existing identities are unaffected and no records are deleted", + self.registered, self.limit + ) + } +} + +impl std::error::Error for IdentityCapacityError {} + +/// Resolve the configured identity admission bound (#1766): the +/// `ID_WEB_MAX_IDENTITIES` environment variable when set (`none` = +/// unbounded, otherwise a positive count), else +/// [`DEFAULT_MAX_IDENTITIES`]. An unparsable or zero value is a +/// configuration error an operator should hear about, so it logs a +/// warning and falls back to the default rather than silently +/// refusing every first visit. +pub fn configured_max_identities() -> Option { + match std::env::var(MAX_IDENTITIES_ENV) { + Err(_) => Some(DEFAULT_MAX_IDENTITIES), + Ok(raw) => { + let value = raw.trim(); + if value.eq_ignore_ascii_case("none") { + None + } else if let Ok(n) = value.parse::() { + if n == 0 { + tracing::warn!( + "[identity] {MAX_IDENTITIES_ENV}=0 would refuse every registration; falling back to the default bound {DEFAULT_MAX_IDENTITIES}" + ); + Some(DEFAULT_MAX_IDENTITIES) + } else { + Some(n) + } + } else { + tracing::warn!( + "[identity] {MAX_IDENTITIES_ENV}={raw:?} is not a count or 'none'; falling back to the default bound {DEFAULT_MAX_IDENTITIES}" + ); + Some(DEFAULT_MAX_IDENTITIES) + } + } + } +} + /// A client's identity information. #[derive(Debug, Clone, Serialize, Deserialize)] pub struct ClientIdentity { @@ -102,6 +175,13 @@ pub struct IdentityStore { signing_key: Arc, /// Ed25519 verifying key (derived from signing key, used to verify tokens). verifying_key: VerifyingKey, + /// Admission bound on registered identities (#1766): `Some(limit)` + /// refuses NEW registrations once `clients` holds `limit` entries. + /// Records loaded from disk at startup count toward the bound. + /// Existing identities are never removed to make room, and the + /// verify/refresh paths ignore the bound. `None` is unbounded + /// (ephemeral/test stores by default). + max_identities: Option, /// Encrypted redb file for persistent storage (`None` for ephemeral/test mode). db: Option>, } @@ -111,6 +191,7 @@ impl std::fmt::Debug for IdentityStore { f.debug_struct("IdentityStore") .field("clients", &self.clients) .field("signing_key", &"") + .field("max_identities", &self.max_identities) .field("db", &self.db.as_ref().map(|_| "")) .finish_non_exhaustive() } @@ -129,6 +210,19 @@ impl IdentityStore { /// * `secret_key` - 32-byte secret key (from iroh `SecretKey::to_bytes()`) /// * `db_path` - Path for the redb file (e.g., `.identity.redb`) pub async fn new(secret_key: [u8; 32], db_path: PathBuf) -> anyhow::Result { + Self::new_with_max_identities(secret_key, db_path, Some(DEFAULT_MAX_IDENTITIES)).await + } + + /// Create a new identity store backed by an encrypted redb file, + /// with an explicit admission bound (#1766): `Some(limit)` refuses + /// new registrations once `limit` identities are held — records + /// loaded from disk count toward it — and `None` is unbounded. + /// See [`IdentityStore::new`] for the storage description. + pub async fn new_with_max_identities( + secret_key: [u8; 32], + db_path: PathBuf, + max_identities: Option, + ) -> anyhow::Result { let (signing_key, enc_bytes) = derive_keys(&secret_key)?; let verifying_key = signing_key.verifying_key(); @@ -153,6 +247,7 @@ impl IdentityStore { name_watchers: Arc::new(RwLock::new(name_watchers_map)), signing_key: Arc::new(signing_key), verifying_key, + max_identities, db: Some(Arc::new(db)), }) } @@ -162,6 +257,14 @@ impl IdentityStore { /// Generates a random signing key. Identities are lost when the store /// is dropped. Used in tests and when persistence is not needed. pub fn new_ephemeral() -> Self { + Self::new_ephemeral_with_limit(None) + } + + /// Create an ephemeral identity store with an admission bound + /// (#1766): `Some(limit)` refuses new registrations once `limit` + /// identities are held; `None` is unbounded. The test seam for + /// capacity behavior. + pub fn new_ephemeral_with_limit(max_identities: Option) -> Self { let signing_key = SigningKey::generate(&mut rand::rng()); let verifying_key = signing_key.verifying_key(); Self { @@ -169,6 +272,7 @@ impl IdentityStore { name_watchers: Arc::new(RwLock::new(HashMap::new())), signing_key: Arc::new(signing_key), verifying_key, + max_identities, db: None, } } @@ -189,16 +293,33 @@ impl IdentityStore { updated_at: now, }; - // Persist to database first (if available) - if let Some(db) = &self.db { - let db = Arc::clone(db); - let record = identity.clone(); - run_blocking(move || db.create(&record)).await?; - } - - // Store the identity in memory + // Admission bound (#1766): hold the clients write lock across + // check + persist + insert, so concurrent registrations cannot + // race past the bound (the redb create used to happen before + // the in-memory insert with no lock spanning both, which would + // have made a count check racy). Registrations are rare, so + // verify/refresh readers waiting out one create is acceptable. + // At capacity the refusal is the typed IdentityCapacityError — + // existing records are never deleted to make room. { let mut clients = self.clients.write().await; + if let Some(limit) = self.max_identities { + let registered = clients.len(); + if registered >= limit { + tracing::warn!( + "[identity] Registration refused at capacity: {registered}/{limit} identities (admission bound, issue 1766)" + ); + return Err(IdentityCapacityError { limit, registered }.into()); + } + } + + // Persist to database first (if available) + if let Some(db) = &self.db { + let db = Arc::clone(db); + let record = identity.clone(); + run_blocking(move || db.create(&record)).await?; + } + clients.insert(client_id.clone(), identity.clone()); } @@ -994,6 +1115,85 @@ mod tests { assert!(store.verify_token_client_id(&alias).is_none()); } + #[tokio::test] + async fn test_register_admission_bound_at_and_beyond_limit() { + // #1766: at the bound the next registration is refused with + // the typed capacity error; nothing is deleted to make room. + let store = IdentityStore::new_ephemeral_with_limit(Some(2)); + store.register(Some("A".to_owned())).await.unwrap(); + store.register(Some("B".to_owned())).await.unwrap(); + let err = store.register(Some("C".to_owned())).await.unwrap_err(); + let cap = err + .downcast_ref::() + .expect("typed capacity error"); + assert_eq!(cap.limit, 2); + assert_eq!(cap.registered, 2); + assert_eq!(store.clients.read().await.len(), 2); + } + + #[tokio::test] + async fn test_register_admission_bound_concurrent_race() { + // #1766: many registrations racing for the last slots — + // exactly `limit` succeed, because check + persist + insert + // run under one write lock. + let store = Arc::new(IdentityStore::new_ephemeral_with_limit(Some(5))); + let mut handles = Vec::new(); + for i in 0..16 { + let s = Arc::clone(&store); + handles.push(tokio::spawn(async move { s.register(Some(format!("racer-{i}"))).await })); + } + let mut ok = 0; + let mut refused = 0; + for h in handles { + match h.await.unwrap() { + Ok(_) => ok += 1, + Err(e) => { + assert!(e.downcast_ref::().is_some()); + refused += 1; + } + } + } + assert_eq!(ok, 5); + assert_eq!(refused, 11); + assert_eq!(store.clients.read().await.len(), 5); + } + + #[tokio::test] + async fn test_refresh_at_capacity_still_works() { + // #1766 acceptance pin: the bound refuses NEW registrations + // only — an existing identity keeps verifying and refreshing + // its token at capacity. + let store = IdentityStore::new_ephemeral_with_limit(Some(1)); + let (token, identity) = store.register(Some("Alice".to_owned())).await.unwrap(); + assert!(store.register(Some("Bob".to_owned())).await.is_err()); + let (fresh, refreshed) = store.verify_and_refresh(&token).await.unwrap(); + assert_eq!(refreshed.client_id, identity.client_id); + assert!(store.verify_token(&fresh).await.is_some()); + } + + #[tokio::test] + async fn test_restart_at_bound_serves_existing_refuses_new() { + // #1766: records loaded from disk at startup count toward the + // bound — a store reopened at capacity admits nobody new but + // still serves (and refreshes) everyone it loaded. + let dir = tempfile::tempdir().unwrap(); + let path = dir.path().join("identities.redb"); + let secret = [7u8; 32]; + let store = IdentityStore::new_with_max_identities(secret, path.clone(), Some(1)) + .await + .unwrap(); + let (token, identity) = store.register(Some("Alice".to_owned())).await.unwrap(); + drop(store); + + let store = IdentityStore::new_with_max_identities(secret, path, Some(1)) + .await + .unwrap(); + let err = store.register(Some("Bob".to_owned())).await.unwrap_err(); + assert!(err.downcast_ref::().is_some()); + let (_, refreshed) = store.verify_and_refresh(&token).await.unwrap(); + assert_eq!(refreshed.client_id, identity.client_id); + } + #[tokio::test] async fn test_invalid_token() { let store = IdentityStore::new_ephemeral(); diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index 68dbd347c2..087853a5cd 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -243,7 +243,12 @@ impl AppState { tag_store, save_limiter: SaveRateLimiter::new(DEFAULT_SAVE_COOLDOWN), upload_name_lock: Arc::new(Mutex::new(())), - identity: IdentityStore::new(secret_key, identity_db_path).await?, + identity: IdentityStore::new_with_max_identities( + secret_key, + identity_db_path, + identity::configured_max_identities(), + ) + .await?, local_events, world: None, cookie_secure: false, diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index e8a6a7ea7c..754e237112 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -2971,6 +2971,22 @@ async fn identity_register_handler( .into_response() } Err(err) => { + // #1766: at the admission bound the refusal is a clear, + // observable 503 — not a generic 500 — and no existing + // identity is affected by it. + if let Some(cap) = err.downcast_ref::() { + tracing::warn!("[identity] Registration refused at capacity: {cap}"); + return ( + StatusCode::SERVICE_UNAVAILABLE, + Json(serde_json::json!({ + "error": "identity_capacity_reached", + "detail": cap.to_string(), + "limit": cap.limit, + "registered": cap.registered, + })), + ) + .into_response(); + } tracing::error!("[identity] Registration failed: {}", err); StatusCode::INTERNAL_SERVER_ERROR.into_response() } From 537e1d7201b084c6e4e3cbb844776bcf8f01f54e Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Sun, 1 Nov 2026 23:52:58 -0600 Subject: [PATCH 2/2] fix(id/web): keep registration admission accounting alive through the blocking write (#1766) MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit Codex P2 on PR #4143 (finding 4438590534): if the requesting future was cancelled while run_blocking was in flight, spawn_blocking still committed the record, but the clients guard dropped and the in-memory insert never happened — persisted records went uncounted and repeated cancellations could bypass the admission bound. The check + persist + insert critical section now runs in a detached tokio::spawn that owns the lock, the reservation, and the insert through completion of the blocking write; register only observes the outcome. IdentityCapacityError is returned as the root anyhow error exactly as before, so the routes downcast_ref check is unchanged. --- pkgs/id/src/web/identity.rs | 58 +++++++++++++++++++++++++++---------- 1 file changed, 42 insertions(+), 16 deletions(-) diff --git a/pkgs/id/src/web/identity.rs b/pkgs/id/src/web/identity.rs index 5daede47d1..193fdb0045 100644 --- a/pkgs/id/src/web/identity.rs +++ b/pkgs/id/src/web/identity.rs @@ -301,26 +301,52 @@ impl IdentityStore { // verify/refresh readers waiting out one create is acceptable. // At capacity the refusal is the typed IdentityCapacityError — // existing records are never deleted to make room. + // + // The critical section runs in a detached task (Codex P2 on + // PR #4143): spawn_blocking is not aborted when the awaiting + // future is cancelled, so a section owned by the caller's + // future could drop the lock with the record committed to disk + // but never inserted — the in-memory count would then + // under-count persisted records and repeated cancellations + // would bypass the bound (and the uncounted records would all + // load on restart). Detached, the section keeps the admission + // reservation and the in-memory accounting alive through + // completion of the blocking write, independently of the + // requesting future; awaiting the handle only observes the + // outcome. { - let mut clients = self.clients.write().await; - if let Some(limit) = self.max_identities { - let registered = clients.len(); - if registered >= limit { - tracing::warn!( - "[identity] Registration refused at capacity: {registered}/{limit} identities (admission bound, issue 1766)" - ); - return Err(IdentityCapacityError { limit, registered }.into()); + let clients = Arc::clone(&self.clients); + let db = self.db.clone(); + let max_identities = self.max_identities; + let record = identity.clone(); + let persist = tokio::spawn(async move { + let mut clients = clients.write().await; + if let Some(limit) = max_identities { + let registered = clients.len(); + if registered >= limit { + tracing::warn!( + "[identity] Registration refused at capacity: {registered}/{limit} identities (admission bound, issue 1766)" + ); + return Err(anyhow::Error::from(IdentityCapacityError { + limit, + registered, + })); + } } - } - // Persist to database first (if available) - if let Some(db) = &self.db { - let db = Arc::clone(db); - let record = identity.clone(); - run_blocking(move || db.create(&record)).await?; - } + // Persist to database first (if available) + if let Some(db) = &db { + let db = Arc::clone(db); + let record = record.clone(); + run_blocking(move || db.create(&record)).await?; + } - clients.insert(client_id.clone(), identity.clone()); + clients.insert(record.client_id.clone(), record); + Ok::<(), anyhow::Error>(()) + }); + persist + .await + .map_err(|e| anyhow::anyhow!("identity registration task failed: {e}"))??; } // Create a watch channel for name changes