diff --git a/pkgs/id/crates/id-web/src/routes.rs b/pkgs/id/crates/id-web/src/routes.rs index c0c7717e0b..5ace3f79df 100644 --- a/pkgs/id/crates/id-web/src/routes.rs +++ b/pkgs/id/crates/id-web/src/routes.rs @@ -3347,6 +3347,104 @@ mod upload_router_tests { assert!(state.seitan.is_verified(&uid)); } + /// The `arena` world's own live directory, through its actor. + async fn seitan_world(state: &AppState) -> id_worlds::world_hub::WorldLease { + state + .world + .as_ref() + .unwrap() + .lease(Some("arena"), None) + .await + .unwrap() + } + + #[tokio::test] + async fn seitan_admit_lands_in_the_live_world_directory() { + // #8538 (a)+(b): an account created in the world's own + // directory (not the server-config one) admits without + // `unknown_account`, and `AccountVerified` lands in the world's + // live directory, the one capability authorization consults. + let (app, state, _dir, _endpoint, _docs) = + seitan_app(crate::SeitanState::default(), false).await; + let uid = seitan_account_key(); + { + let world = seitan_world(&state).await; + world + .service() + .world() + .apply_directory_entry(id_worlds::directory::DirectoryEntry::AccountKeyed { + id: uid.clone(), + name: "joiner".to_owned(), + }) + .await + .unwrap(); + assert_eq!( + world + .service() + .world() + .directory_account(&uid) + .await + .unwrap(), + Some(false) + ); + } + let token = id_directory::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let proof = id_directory::seitan::accept::sign(&token, &uid, 1, seitan_now_ms()).unwrap(); + let admitted = seitan_admit(&app, &proof).await; + assert_eq!(admitted.status(), StatusCode::OK); + let world = seitan_world(&state).await; + assert_eq!( + world + .service() + .world() + .directory_account(&uid) + .await + .unwrap(), + Some(true), + "AccountVerified must land in the live world directory" + ); + assert!(!state.seitan.is_verified(&uid)); + } + + #[tokio::test] + async fn seitan_admit_for_an_account_in_both_directories_verifies_only_the_world() { + // #8538: when both directories hold the account, the world's + // live directory is authoritative and the only one appended + // to, so the two never disagree about which one admitted it. + let (app, state, _dir, _endpoint, _docs) = + seitan_app(crate::SeitanState::default(), true).await; + let uid = seitan_account_key(); + seitan_world(&state) + .await + .service() + .world() + .apply_directory_entry(id_worlds::directory::DirectoryEntry::AccountKeyed { + id: uid.clone(), + name: "joiner".to_owned(), + }) + .await + .unwrap(); + let token = id_directory::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let proof = id_directory::seitan::accept::sign(&token, &uid, 1, seitan_now_ms()).unwrap(); + let admitted = seitan_admit(&app, &proof).await; + assert_eq!(admitted.status(), StatusCode::OK); + assert_eq!( + seitan_world(&state) + .await + .service() + .world() + .directory_account(&uid) + .await + .unwrap(), + Some(true) + ); + assert!(!state.seitan.is_verified(&uid)); + } + #[tokio::test] async fn seitan_invite_registration_requires_the_admin_secret() { // Minting an invite without the admin secret (or with the diff --git a/pkgs/id/crates/id-web/src/seitan.rs b/pkgs/id/crates/id-web/src/seitan.rs index bfaa2cf101..d262a5ec58 100644 --- a/pkgs/id/crates/id-web/src/seitan.rs +++ b/pkgs/id/crates/id-web/src/seitan.rs @@ -17,8 +17,15 @@ //! order matters, per the design: checks that do not consume the //! invite (parse, registry lookup, the directory account check) run //! before [`Invite::admit`], and on success the `AccountVerified` -//! entry is appended to the server's directory before the 200 -//! response is returned. +//! entry is appended before the 200 response is returned. +//! +//! Which directory (#8538): when the invite's world is hosted by this +//! server, admission binds to that world's live directory — the one +//! capability authorization consults. The account check consults the +//! world directory first and the server-config directory second, and +//! `AccountVerified` lands in exactly one of them: the world's when it +//! holds the account, otherwise the server-config directory. A world +//! this server does not host keeps the server-config binding. //! //! The registry is v1 in-memory state beside the server config: a //! restart drops unredeemed invites, which then refuse as unknown. @@ -56,11 +63,11 @@ struct RegisteredInvite { #[derive(Debug)] struct SeitanInner { invites: HashMap, - /// The server's directory: the accounts an admitted `uid` must - /// name, and the journal an admission appends `AccountVerified` - /// to. In `id serve` this is the directory beside the groups log - /// (the server-config directory journal); the default state holds - /// an empty in-memory one. + /// The server-config directory: consulted after the invite world's + /// own directory, and the journal an admission appends + /// `AccountVerified` to when that world's directory does not hold + /// the account (#8538). In `id serve` this is the directory beside + /// the groups log; the default state holds an empty in-memory one. directory: Directory, /// The freshness window every admit is checked under, resolved /// once by the caller (`serve_freshness_window` in serve). @@ -301,38 +308,96 @@ pub(crate) async fn seitan_admit_handler( Err(_) => return error_response(StatusCode::BAD_REQUEST, "malformed"), }; let window = state.seitan.window(); - let mut inner = state.seitan.inner.lock().unwrap_or_else(|e| e.into_inner()); - if !inner.invites.contains_key(&fields.invite_id.to_hex()) { - return error_response(StatusCode::NOT_FOUND, "unknown_invite"); - } + let invite_id = fields.invite_id.to_hex(); + let world = { + let inner = state.seitan.inner.lock().unwrap_or_else(|e| e.into_inner()); + match inner.invites.get(&invite_id) { + Some(registered) => registered.world.clone(), + None => return error_response(StatusCode::NOT_FOUND, "unknown_invite"), + } + }; + // #8538: the directory an admission lands in is the one capability + // authorization consults. When the invite's world is hosted here, + // that is the world's own live directory; the server-config + // directory is the binding only for a world this server does not + // host. A world that exists but cannot be reached right now is a + // 503 before anything is consumed, never a silent fallback. + let lease = match state.world.as_ref() { + None => None, + Some(hub) => match hub.lease(Some(&world), None).await { + Ok(lease) => Some(lease), + Err(ResolveError::UnknownWorld) => None, + Err(ResolveError::Busy | ResolveError::TooManyWorlds | ResolveError::Unavailable) => { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + Err(_) => None, + }, + }; // The account check runs before `admit`, from the parsed fields, // so an unknown account does not consume the invite: the joiner - // can retry once the account exists. - if inner.directory.account(&fields.uid).is_none() { - return error_response(StatusCode::FORBIDDEN, "unknown_account"); - } - let Some(registered) = inner.invites.get_mut(&fields.invite_id.to_hex()) else { - return error_response(StatusCode::NOT_FOUND, "unknown_invite"); + // can retry once the account exists. The world's directory is + // consulted first and the server-config directory second, so an + // account known to either is admitted. + let in_world = match &lease { + None => false, + Some(lease) => match lease.service().world().directory_account(&fields.uid).await { + Ok(account) => account.is_some(), + Err(error) => { + tracing::warn!( + "[seitan] world {world} directory unavailable for admission: {error:#}" + ); + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + }, }; - let admitted = match registered.invite.admit(&proof, now_ms(), window) { - Ok(admitted) => admitted, - Err(reject) => { - let reason = reject_reason(&reject); - let status = if matches!(reject, Reject::Malformed) { - StatusCode::BAD_REQUEST - } else { - StatusCode::FORBIDDEN - }; - return error_response(status, reason); + let admitted = { + let mut inner = state.seitan.inner.lock().unwrap_or_else(|e| e.into_inner()); + if !in_world && inner.directory.account(&fields.uid).is_none() { + return error_response(StatusCode::FORBIDDEN, "unknown_account"); + } + let Some(registered) = inner.invites.get_mut(&invite_id) else { + return error_response(StatusCode::NOT_FOUND, "unknown_invite"); + }; + match registered.invite.admit(&proof, now_ms(), window) { + Ok(admitted) => admitted, + Err(reject) => { + let reason = reject_reason(&reject); + let status = if matches!(reject, Reject::Malformed) { + StatusCode::BAD_REQUEST + } else { + StatusCode::FORBIDDEN + }; + return error_response(status, reason); + } } }; - let world = registered.world.clone(); // Append before responding: the 200 means the membership change - // is in the directory journal. If the append fails after a - // successful admit, the invite stays consumed in memory - // (single-use safety wins over retry convenience, matching the - // seitan threat notes) and the failure is a loud 500. - if let Err(error) = inner.directory.verify_account(Actor::Server, &admitted.uid) { + // is in the directory journal. `AccountVerified` goes to exactly + // one directory: the world's own when it holds the account (never + // also the server journal, which would recreate the split this + // binding removes), otherwise the server-config directory. If the + // append fails after a successful admit, the invite stays consumed + // in memory (single-use safety wins over retry convenience, + // matching the seitan threat notes) and the failure is a loud 500. + let appended = match (&lease, in_world) { + (Some(lease), true) => lease + .service() + .world() + .apply_directory_entry(id_worlds::directory::DirectoryEntry::AccountVerified { + id: admitted.uid.clone(), + }) + .await + .map(|()| ()), + _ => state + .seitan + .inner + .lock() + .unwrap_or_else(|e| e.into_inner()) + .directory + .verify_account(Actor::Server, &admitted.uid) + .map(|_| ()), + }; + if let Err(error) = appended { tracing::error!( "[seitan] admission for {} consumed its invite but the directory append failed: {error:#}", admitted.uid diff --git a/pkgs/id/crates/id-worlds/src/world/actor.rs b/pkgs/id/crates/id-worlds/src/world/actor.rs index 544b153301..295b4922ed 100644 --- a/pkgs/id/crates/id-worlds/src/world/actor.rs +++ b/pkgs/id/crates/id-worlds/src/world/actor.rs @@ -80,6 +80,7 @@ impl WorldCommand { Self::DelegateToFriend { .. } => "DelegateToFriend", Self::Directory { .. } => "Directory", Self::ApplyDirectory { .. } => "ApplyDirectory", + Self::DirectoryAccount { .. } => "DirectoryAccount", Self::Revoke { .. } => "Revoke", Self::RevokeAuthorized { .. } => "RevokeAuthorized", Self::ParticipantId { .. } => "ParticipantId", @@ -173,6 +174,14 @@ pub(crate) enum WorldCommand { entry: crate::directory::DirectoryEntry, reply: oneshot::Sender>, }, + /// Whether the world's directory holds `account`, and if so + /// whether it is verified (#8538). Refused on a replica, like + /// `ApplyDirectory`: the answer exists so a caller can apply an + /// entry next, and a replica never applies one. + DirectoryAccount { + account: String, + reply: oneshot::Sender>>, + }, Revoke { participant_id: u64, /// The moderator participant who ordered the revoke, for the audit @@ -1126,6 +1135,15 @@ impl WorldActor { .and_then(|()| self.core.directory_mut().apply(&entry)); let _ = reply.send(result); } + WorldCommand::DirectoryAccount { account, reply } => { + let result = self.check_not_replica().map(|()| { + let directory = self.core.directory(); + directory + .account(&account) + .map(|_| directory.is_verified(&account)) + }); + let _ = reply.send(result); + } WorldCommand::Revoke { participant_id, by, diff --git a/pkgs/id/crates/id-worlds/src/world/handle.rs b/pkgs/id/crates/id-worlds/src/world/handle.rs index c01d7b580f..7c2cf68a05 100644 --- a/pkgs/id/crates/id-worlds/src/world/handle.rs +++ b/pkgs/id/crates/id-worlds/src/world/handle.rs @@ -1381,6 +1381,24 @@ impl WorldHandle { .context("world actor dropped directory apply response")? } + /// Whether this world's directory holds `account` — `None` when it + /// does not, otherwise whether the account is verified (#8538). This + /// is the directory capability authorization consults. Fails on a + /// read-only replica, which never applies a local directory entry. + pub async fn directory_account(&self, account: impl Into) -> Result> { + let (reply, response) = oneshot::channel(); + self.commands + .send(WorldCommand::DirectoryAccount { + account: account.into(), + reply, + }) + .await + .map_err(|_| anyhow::anyhow!("world actor is closed"))?; + response + .await + .context("world actor dropped directory account response")? + } + /// Revoke an active capability and everything delegated from it. pub async fn revoke(&self, participant_id: u64) -> Result { self.revoke_by(participant_id, None).await