From 524f2c288faaf24e51984effd6f365acacf52e73 Mon Sep 17 00:00:00 2001 From: repo-worker-code-k Date: Tue, 10 Nov 2026 22:24:43 -0600 Subject: [PATCH 1/2] feat(id): seitan admission path for id serve (#8487) --- pkgs/id/src/commands/serve.rs | 56 +++++ pkgs/id/src/web/mod.rs | 16 ++ pkgs/id/src/web/routes.rs | 211 ++++++++++++++++ pkgs/id/src/web/seitan.rs | 343 +++++++++++++++++++++++++++ pkgs/id/tests/web_router_security.rs | 1 + 5 files changed, 627 insertions(+) create mode 100644 pkgs/id/src/web/seitan.rs diff --git a/pkgs/id/src/commands/serve.rs b/pkgs/id/src/commands/serve.rs index 7d010630b2..23c9e82422 100644 --- a/pkgs/id/src/commands/serve.rs +++ b/pkgs/id/src/commands/serve.rs @@ -1158,6 +1158,18 @@ fn serve_pull_policy(started: Option<&StartedServerConfig>) -> crate::pull_polic }) } +/// The freshness window seitan admission serves under (#8487): the loaded +/// server config's `[policy] freshness_window_seconds`, resolved through +/// [`crate::server_config::ServerConfig::freshness`], when a config was +/// loaded, else [`crate::seitan::DEFAULT_WINDOW`] — so a `serve` without +/// `--server-config` behaves exactly as before. +#[cfg(feature = "world")] +fn serve_freshness_window(started: Option<&StartedServerConfig>) -> std::time::Duration { + started.map_or(crate::seitan::DEFAULT_WINDOW, |started| { + started.config.freshness().window() + }) +} + /// The world protocol serve registers for a hub: the loaded operator /// config's #2247 budget policy when a server config was given, the /// coded defaults when none was. Before this wire, the budgets @@ -1934,6 +1946,21 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { WebContentTarget::Program(world) => Some(world.clone()), }) .collect(); + // #8487: the seitan admission state the web surface + // serves: the freshness window resolved from the loaded + // server config (the code default without one), and the + // server-config directory journal beside the groups log + // opened after provisioning persisted into it, so the + // admit path's account check sees the provisioned + // accounts and its `AccountVerified` appends land in the + // same journal. + #[cfg(feature = "world")] + let seitan_state = crate::web::SeitanState::new( + crate::directory::Directory::open(&server_config_directory_path(&groups_log))?, + serve_freshness_window(started_server_config.as_ref()), + ); + #[cfg(not(feature = "world"))] + let seitan_state = crate::web::SeitanState::default(); let web_routers = crate::web::web_routers( store_handle.clone(), Some(peer_discovery.clone()), @@ -1947,6 +1974,7 @@ pub async fn cmd_serve(opts: ServeOptions) -> Result<()> { event_events.as_ref().map(Arc::clone), surfaces, Some(groups_log.clone()), + seitan_state, ) .await?; for ((listener_addr, listener, target), web_router) in @@ -3753,6 +3781,34 @@ mod tests { let _ = std::fs::remove_dir_all(&dir); } + /// #8487: without a server config, seitan admission serves under + /// the code default window (5 minutes), exactly as before. + #[cfg(feature = "world")] + #[test] + fn serve_freshness_window_defaults_without_a_config() { + assert_eq!( + serve_freshness_window(None), + crate::seitan::DEFAULT_WINDOW + ); + } + + /// #8487: the live admission path takes its window from the + /// loaded config's `[policy] freshness_window_seconds`, not from + /// the code default. + #[cfg(feature = "world")] + #[test] + fn serve_freshness_window_reads_the_configured_window() { + let dir = serve_config_dir("freshness-window"); + let path = dir.join("server.toml"); + std::fs::write(&path, "[policy]\nfreshness_window_seconds = 60\n").unwrap(); + let started = start_server_config(&path).unwrap(); + assert_eq!( + serve_freshness_window(Some(&started)), + std::time::Duration::from_secs(60) + ); + let _ = std::fs::remove_dir_all(&dir); + } + // #2247: the loaded [budgets] must reach the world protocol serve // registers, not just the parser. diff --git a/pkgs/id/src/web/mod.rs b/pkgs/id/src/web/mod.rs index b460ab5f74..8690c0d9e0 100644 --- a/pkgs/id/src/web/mod.rs +++ b/pkgs/id/src/web/mod.rs @@ -55,6 +55,7 @@ mod identity; mod markdown; mod routes; mod security; +mod seitan; mod tags_ws; mod templates; pub mod world_ws; @@ -82,6 +83,7 @@ pub use identity::IdentityStore; #[doc(hidden)] pub use identity::crash_gate; pub use routes::{create_program_router, create_router, create_router_for_app}; +pub use seitan::SeitanState; pub use security::WebSecurity; pub use templates::{AssetUrls, render_page}; @@ -257,6 +259,12 @@ pub struct AppState { /// (`id serve` passes its `--groups-log` resolution); `None` reads /// the default `groups.jsonl`, as the group CLI does. pub groups_log: Option, + /// Seitan admission state for `/api/seitan/*` (#8487): the invite + /// registry, the directory admissions append to, and the freshness + /// window. `id serve` replaces the default (empty in-memory + /// directory, default window) with the server-config directory + /// journal and the configured window; see [`SeitanState`]. + pub seitan: SeitanState, } impl std::fmt::Debug for AppState { @@ -274,6 +282,7 @@ impl std::fmt::Debug for AppState { .field("world", &self.world) .field("cookie_secure", &self.cookie_secure) .field("groups_log", &self.groups_log) + .field("seitan", &self.seitan) .finish() } } @@ -343,6 +352,7 @@ impl AppState { program_world: None, cookie_secure: false, groups_log: None, + seitan: SeitanState::default(), }) } } @@ -438,6 +448,7 @@ pub async fn web_router( cookie_secure, None, groups_log, + SeitanState::default(), )) } @@ -474,6 +485,7 @@ pub async fn web_router_with_local_events( cookie_secure, None, groups_log, + SeitanState::default(), )) } @@ -501,6 +513,7 @@ pub async fn web_routers( local_events: Option>>, surfaces: Vec>, groups_log: Option, + seitan: SeitanState, ) -> anyhow::Result> { let state = match local_events { Some(events) => { @@ -538,6 +551,7 @@ pub async fn web_routers( cookie_secure, surface, groups_log.clone(), + seitan.clone(), ) }) .collect()) @@ -556,9 +570,11 @@ fn finish_router( cookie_secure: bool, surface: Option, groups_log: Option, + seitan: SeitanState, ) -> Router { state.world = world; state.groups_log = groups_log; + state.seitan = seitan; state.cookie_secure = cookie_secure; let security = WebSecurity { cookie_secure, diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 14e254c4cd..9baec00a14 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -609,6 +609,9 @@ fn create_router_inner(state: AppState) -> Router { .route("/api/tags/search", get(super::tags_ws::search_tags_handler)) // Identity API routes .route("/api/identity/register", post(identity_register_handler)) + // Seitan admission API (#8487) + .route("/api/seitan/invite", post(super::seitan::seitan_invite_handler)) + .route("/api/seitan/admit", post(super::seitan::seitan_admit_handler)) .route("/api/identity/me", get(identity_me_handler)) .route("/api/identity/name", post(identity_update_name_handler)) // WebSocket for collaboration @@ -2071,6 +2074,214 @@ mod upload_router_tests { assert_eq!(root.status(), StatusCode::NOT_FOUND); } + // ---- Seitan admission (#8487) ---- + + fn seitan_hex(bytes: &[u8]) -> String { + bytes.iter().map(|b| format!("{b:02x}")).collect() + } + + fn seitan_now_ms() -> u64 { + u64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap() + .as_millis(), + ) + .unwrap() + } + + async fn seitan_response_json(response: Response) -> serde_json::Value { + serde_json::from_slice(&to_bytes(response.into_body(), usize::MAX).await.unwrap()).unwrap() + } + + /// The account a seitan proof names in these tests: a keyed + /// account whose id is its public key's hex, as provisioning + /// records it. Returns (key hex, uid) — the same string here. + fn seitan_account_key() -> String { + seitan_hex( + ed25519_dalek::SigningKey::from_bytes(&[7; 32]) + .verifying_key() + .as_bytes(), + ) + } + + /// A router over a state whose seitan state is `seitan` (with the + /// test account already keyed into its directory when + /// `with_account`), hosting world `arena` under admin `s3cret`. + async fn seitan_app( + seitan: crate::web::SeitanState, + with_account: bool, + ) -> (Router, AppState, tempfile::TempDir, Endpoint, Docs) { + let (_, mut state, dir, endpoint, docs) = router_with_state().await; + if with_account { + seitan.sign_up_keyed(&seitan_account_key(), "joiner").unwrap(); + } + state.seitan = seitan; + state.world = Some(hub_with_world("arena", Some("s3cret"))); + let app = create_router(state.clone(), WebSecurity::default()); + (app, state, dir, endpoint, docs) + } + + async fn seitan_register(app: &Router, token: &str, admin: Option<&str>) -> Response { + let mut builder = Request::builder() + .method("POST") + .uri("/api/seitan/invite") + .header("content-type", "application/json"); + if let Some(admin) = admin { + builder = builder.header("x-world-admin-token", admin); + } + let body = serde_json::json!({ + "token": token, + "world": "arena", + "expires_ms": seitan_now_ms() + 3_600_000, + }) + .to_string(); + app.clone() + .oneshot(builder.body(Body::from(body)).unwrap()) + .await + .unwrap() + } + + async fn seitan_admit(app: &Router, proof: &crate::seitan::Proof) -> Response { + let body = serde_json::json!({ + "message": seitan_hex(&proof.message), + "signature": seitan_hex(&proof.signature), + }) + .to_string(); + app.clone() + .oneshot( + Request::builder() + .method("POST") + .uri("/api/seitan/admit") + .header("content-type", "application/json") + .body(Body::from(body)) + .unwrap(), + ) + .await + .unwrap() + } + + #[tokio::test] + async fn seitan_admit_happy_path_under_a_configured_window() { + // (a) A non-default window (10 min, not the 5-minute default) + // is exercised at the boundary: a proof signed 8 minutes + // before the invite was created is outside the default window + // and inside the configured one, and it admits. + let seitan = crate::web::SeitanState::new( + crate::directory::Directory::new(), + std::time::Duration::from_mins(10), + ); + let (app, state, _dir, _endpoint, _docs) = seitan_app(seitan, true).await; + let token = crate::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let uid = seitan_account_key(); + let proof = crate::seitan::accept::sign( + &token, + &uid, + 1, + seitan_now_ms().saturating_sub(480_000), + ) + .unwrap(); + let admitted = seitan_admit(&app, &proof).await; + assert_eq!(admitted.status(), StatusCode::OK); + let body = seitan_response_json(admitted).await; + assert_eq!(body["uid"], uid); + assert_eq!(body["world"], "arena"); + assert!( + state.seitan.is_verified(&uid), + "AccountVerified must land in the directory before the 200" + ); + } + + #[tokio::test] + async fn seitan_admit_refuses_a_stale_proof_through_the_live_path() { + // (b) Under a 1-minute configured window, a proof signed 5 + // minutes before the invite was created refuses `stale`. + let seitan = crate::web::SeitanState::new( + crate::directory::Directory::new(), + std::time::Duration::from_mins(1), + ); + let (app, _state, _dir, _endpoint, _docs) = seitan_app(seitan, true).await; + let token = crate::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let proof = crate::seitan::accept::sign( + &token, + &seitan_account_key(), + 1, + seitan_now_ms().saturating_sub(300_000), + ) + .unwrap(); + let refused = seitan_admit(&app, &proof).await; + assert_eq!(refused.status(), StatusCode::FORBIDDEN); + assert_eq!(seitan_response_json(refused).await["reason"], "stale"); + } + + #[tokio::test] + async fn seitan_admit_no_config_default_window_admits_a_fresh_proof() { + // (c) The default state (no server config) admits a fresh + // proof under the 5-minute default window. + let (app, _state, _dir, _endpoint, _docs) = + seitan_app(crate::web::SeitanState::default(), true).await; + let token = crate::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let proof = crate::seitan::accept::sign(&token, &seitan_account_key(), 1, seitan_now_ms()) + .unwrap(); + let admitted = seitan_admit(&app, &proof).await; + assert_eq!(admitted.status(), StatusCode::OK); + } + + #[tokio::test] + async fn seitan_admit_unknown_invite_is_404() { + // (d) A proof for a token that was never registered names an + // invite the registry does not hold. + let (app, _state, _dir, _endpoint, _docs) = + seitan_app(crate::web::SeitanState::default(), true).await; + let token = crate::seitan::Token::generate(); + let proof = crate::seitan::accept::sign(&token, &seitan_account_key(), 1, seitan_now_ms()) + .unwrap(); + let refused = seitan_admit(&app, &proof).await; + assert_eq!(refused.status(), StatusCode::NOT_FOUND); + assert_eq!(seitan_response_json(refused).await["reason"], "unknown_invite"); + } + + #[tokio::test] + async fn seitan_admit_unknown_account_is_403_and_does_not_consume_the_invite() { + // (e) The account check runs before `admit`: an unknown uid + // refuses 403, and the same proof succeeds once the account + // exists — the invite was not consumed by the refusal. + let seitan = crate::web::SeitanState::default(); + let (app, state, _dir, _endpoint, _docs) = seitan_app(seitan.clone(), false).await; + let token = crate::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let uid = seitan_account_key(); + let proof = crate::seitan::accept::sign(&token, &uid, 1, seitan_now_ms()).unwrap(); + let refused = seitan_admit(&app, &proof).await; + assert_eq!(refused.status(), StatusCode::FORBIDDEN); + assert_eq!(seitan_response_json(refused).await["reason"], "unknown_account"); + + state.seitan.sign_up_keyed(&uid, "joiner").unwrap(); + let admitted = seitan_admit(&app, &proof).await; + assert_eq!(admitted.status(), StatusCode::OK); + 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 + // wrong one) is refused, like POST /api/world/invite. + let (app, _state, _dir, _endpoint, _docs) = + seitan_app(crate::web::SeitanState::default(), false).await; + let token = crate::seitan::Token::generate(); + let no_secret = seitan_register(&app, token.as_str(), None).await; + assert_eq!(no_secret.status(), StatusCode::UNAUTHORIZED); + let wrong_secret = seitan_register(&app, token.as_str(), Some("wrong")).await; + assert_eq!(wrong_secret.status(), StatusCode::UNAUTHORIZED); + } + #[tokio::test] async fn public_entry_point_honours_a_configured_binding() { // A host that has already read its app manifest selects the diff --git a/pkgs/id/src/web/seitan.rs b/pkgs/id/src/web/seitan.rs new file mode 100644 index 0000000000..1b171c534a --- /dev/null +++ b/pkgs/id/src/web/seitan.rs @@ -0,0 +1,343 @@ +//! Seitan admission on the serve web surface (#8487, design recorded on +//! the issue by task 14857). +//! +//! Two routes, registered by [`super::routes`]: +//! +//! - `POST /api/seitan/invite` — registration, gated by the same +//! admin-secret check that gates `POST /api/world/invite` (the hub's +//! admin token, consulted through the same lease + `admin_ok` flow). +//! The body names the token, the one world the invite joins, and its +//! expiry; the server builds the [`Invite`] and keeps it in the +//! registry. The response carries only the invite ID — the token is +//! never stored (an `Invite` keeps only ID + public key + expiry, by +//! construction) and never logged. +//! - `POST /api/seitan/admit` — unauthenticated; the signed proof is +//! the credential. The body is `{message, signature}`, both hex (the +//! router's existing encoding for keys and signatures). Handler +//! 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. +//! +//! The registry is v1 in-memory state beside the server config: a +//! restart drops unredeemed invites, which then refuse as unknown. +//! Invites are short-lived (expiry plus a minutes-scale freshness +//! window) and re-registration is one admin call, so persistence is a +//! named follow-up only if operations ever need it. + +use std::collections::HashMap; +use std::fmt; +use std::sync::{Arc, Mutex}; +use std::time::{Duration, SystemTime, UNIX_EPOCH}; + +use axum::{ + Json, + extract::State, + http::{HeaderMap, StatusCode}, + response::{IntoResponse, Response}, +}; +use serde::{Deserialize, Serialize}; + +use crate::directory::{Actor, Directory}; +use crate::seitan::{Invite, Proof, Reject, Token}; +use crate::world_hub::ResolveError; + +use super::AppState; + +/// One registered invite: the world it joins, bound at registration +/// and never taken from the proof, plus the invite itself. +#[derive(Debug)] +struct RegisteredInvite { + world: String, + invite: Invite, +} + +#[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. + directory: Directory, + /// The freshness window every admit is checked under, resolved + /// once by the caller (`serve_freshness_window` in serve). + window: Option, +} + +/// The serve web surface's seitan admission state: the invite +/// registry plus the directory and freshness window admissions run +/// against. Cloneable — every clone shares the one registry, like the +/// rest of [`AppState`]'s shared handles. +#[derive(Clone)] +pub struct SeitanState { + inner: Arc>, +} + +impl Default for SeitanState { + fn default() -> Self { + Self { + inner: Arc::new(Mutex::new(SeitanInner { + invites: HashMap::new(), + directory: Directory::new(), + window: None, + })), + } + } +} + +impl fmt::Debug for SeitanState { + fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result { + let inner = self.inner.lock().unwrap_or_else(|e| e.into_inner()); + f.debug_struct("SeitanState") + .field("invites", &inner.invites.len()) + .field("window", &inner.window) + .finish_non_exhaustive() + } +} + +impl SeitanState { + /// Admission state over a caller-opened directory and the + /// resolved freshness window. + #[must_use] + pub fn new(directory: Directory, window: Duration) -> Self { + Self { + inner: Arc::new(Mutex::new(SeitanInner { + invites: HashMap::new(), + directory, + window: Some(window), + })), + } + } + + /// The window admits are checked under: the configured one, or + /// [`crate::seitan::DEFAULT_WINDOW`] for the default (no-config) + /// state, so a serve without a server config behaves exactly as + /// before. + #[must_use] + pub fn window(&self) -> Duration { + self.inner + .lock() + .unwrap_or_else(|e| e.into_inner()) + .window + .unwrap_or(crate::seitan::DEFAULT_WINDOW) + } + + /// Whether the directory currently marks `account` verified — + /// the visible effect of a landed admission. + #[must_use] + pub fn is_verified(&self, account: &str) -> bool { + self.inner + .lock() + .unwrap_or_else(|e| e.into_inner()) + .directory + .is_verified(account) + } + + /// Create a keyed account in the admission directory. Startup + /// provisioning already writes the journal this state opens in + /// `id serve`; this entry point is for tests, which build the + /// directory the way provisioning does. + #[cfg(test)] + pub(crate) fn sign_up_keyed( + &self, + key: &str, + name: &str, + ) -> anyhow::Result { + self.inner + .lock() + .unwrap_or_else(|e| e.into_inner()) + .directory + .sign_up_keyed(key, name) + } +} + +fn now_ms() -> u64 { + u64::try_from( + SystemTime::now() + .duration_since(UNIX_EPOCH) + .unwrap_or_default() + .as_millis(), + ) + .unwrap_or(u64::MAX) +} + +fn error_response(status: StatusCode, reason: &str) -> Response { + ( + status, + Json(serde_json::json!({ "error": reason, "reason": reason })), + ) + .into_response() +} + +/// Registration body: the token (shown to the joiner only), the one +/// world the invite joins, and the invite's expiry in milliseconds +/// since the Unix epoch. +#[derive(Debug, Deserialize)] +pub(crate) struct SeitanInviteRequest { + token: String, + world: String, + expires_ms: u64, +} + +#[derive(Debug, Serialize)] +struct SeitanInviteResponse { + invite_id: String, +} + +/// `POST /api/seitan/invite` — see the module docs. +pub(crate) async fn seitan_invite_handler( + State(state): State, + headers: HeaderMap, + Json(request): Json, +) -> Response { + let Some(hub) = state.world.as_ref() else { + return StatusCode::NOT_FOUND.into_response(); + }; + let supplied = headers + .get("x-world-admin-token") + .and_then(|value| value.to_str().ok()); + // The same gate as POST /api/world/invite: a lease for the named + // world (a valid admin token may create it), then the admin check + // itself. + match hub.lease(Some(&request.world), supplied).await { + Ok(_lease) => {} + Err(ResolveError::Busy | ResolveError::TooManyWorlds) => { + return StatusCode::SERVICE_UNAVAILABLE.into_response(); + } + Err(_) => return StatusCode::NOT_FOUND.into_response(), + } + if !supplied.is_some_and(|token| hub.admin_ok(token)) { + return error_response(StatusCode::UNAUTHORIZED, "unauthorized"); + } + let token = match Token::parse(&request.token) { + Ok(token) => token, + Err(error) => { + return error_response(StatusCode::BAD_REQUEST, &format!("invalid token: {error}")); + } + }; + let invite = match Invite::create(&token, now_ms(), request.expires_ms) { + Ok(invite) => invite, + Err(error) => { + tracing::error!("[seitan] invite derivation failed: {error:#}"); + return error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal"); + } + }; + let invite_id = invite.id().to_hex(); + state + .seitan + .inner + .lock() + .unwrap_or_else(|e| e.into_inner()) + .invites + .insert( + invite_id.clone(), + RegisteredInvite { + world: request.world, + invite, + }, + ); + Json(SeitanInviteResponse { invite_id }).into_response() +} + +/// Admit body: the signed accept message and its Ed25519 signature, +/// both hex. +#[derive(Debug, Deserialize)] +pub(crate) struct SeitanAdmitRequest { + message: String, + signature: String, +} + +#[derive(Debug, Serialize)] +struct SeitanAdmitResponse { + uid: String, + eldest_seqno: u64, + world: String, +} + +/// The refusal `reason` string for a [`Reject`], per the design's +/// failure table. +fn reject_reason(reject: &Reject) -> &'static str { + match reject { + Reject::Malformed => "malformed", + Reject::UnknownInvite => "unknown_invite", + Reject::Revoked => "revoked", + Reject::Expired => "expired", + Reject::Used => "used", + Reject::Stale(_) => "stale", + Reject::FromFuture(_) => "from_future", + Reject::BadKey => "bad_key", + Reject::BadSignature => "bad_signature", + } +} + +/// `POST /api/seitan/admit` — see the module docs for the check +/// order and why it matters. +pub(crate) async fn seitan_admit_handler( + State(state): State, + Json(request): Json, +) -> Response { + let (Some(message), Some(signature_bytes)) = ( + crate::world_session::decode_hex(&request.message), + crate::world_session::decode_hex(&request.signature), + ) else { + return error_response(StatusCode::BAD_REQUEST, "malformed"); + }; + let Ok(signature) = <[u8; 64]>::try_from(signature_bytes.as_slice()) else { + return error_response(StatusCode::BAD_REQUEST, "malformed"); + }; + let proof = Proof { message, signature }; + // Parse first: an unparseable proof is a 400 and names no invite, + // so nothing else can be checked — and nothing is consumed. + let fields = match crate::seitan::accept::parse(&proof.message) { + Ok(fields) => fields, + 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"); + } + // 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"); + }; + 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 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) { + tracing::error!( + "[seitan] admission for {} consumed its invite but the directory append failed: {error:#}", + admitted.uid + ); + return error_response(StatusCode::INTERNAL_SERVER_ERROR, "internal"); + } + Json(SeitanAdmitResponse { + uid: admitted.uid, + eldest_seqno: admitted.eldest_seqno, + world, + }) + .into_response() +} diff --git a/pkgs/id/tests/web_router_security.rs b/pkgs/id/tests/web_router_security.rs index 6e73f1b092..108352afbc 100644 --- a/pkgs/id/tests/web_router_security.rs +++ b/pkgs/id/tests/web_router_security.rs @@ -199,6 +199,7 @@ async fn every_public_router_constructor_enforces_its_security_policy() { None, vec![None, Some("arena".to_owned())], None, + web::SeitanState::default(), ) .await .unwrap(); From 19f991214aa36f6eed926e6a587a3bdf5143c012 Mon Sep 17 00:00:00 2001 From: repo-worker-tmp-code-b Date: Tue, 10 Nov 2026 22:44:32 -0600 Subject: [PATCH 2/2] fix(id): preserve seitan single-use state on duplicate registration (#8487) Codex P2 on PR #8529: registration unconditionally inserted a fresh Invite (used: None) under the same deterministic invite ID, so a retried or duplicated registration after redemption reset the single-use state and the same token could admit another account. Registration now preserves an existing registry entry (entry().or_insert): idempotent for retries, and a genuinely new invite uses a new token. Regression test: seitan_duplicate_registration_does_not_reset_single_use_state (register, admit, re-register, same proof refuses used). --- pkgs/id/src/web/routes.rs | 24 ++++++++++++++++++++++++ pkgs/id/src/web/seitan.rs | 19 ++++++++++++------- 2 files changed, 36 insertions(+), 7 deletions(-) diff --git a/pkgs/id/src/web/routes.rs b/pkgs/id/src/web/routes.rs index 9baec00a14..a351157fd4 100644 --- a/pkgs/id/src/web/routes.rs +++ b/pkgs/id/src/web/routes.rs @@ -2282,6 +2282,30 @@ mod upload_router_tests { assert_eq!(wrong_secret.status(), StatusCode::UNAUTHORIZED); } + #[tokio::test] + async fn seitan_duplicate_registration_does_not_reset_single_use_state() { + // Codex P2 on PR #8529: a retried registration after the + // invite was redeemed must not replace the consumed invite + // with a fresh one — the same proof refuses `used`, it does + // not admit a second time. + let (app, _state, _dir, _endpoint, _docs) = + seitan_app(crate::web::SeitanState::default(), true).await; + let token = crate::seitan::Token::generate(); + let registered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(registered.status(), StatusCode::OK); + let proof = + crate::seitan::accept::sign(&token, &seitan_account_key(), 1, seitan_now_ms()).unwrap(); + let admitted = seitan_admit(&app, &proof).await; + assert_eq!(admitted.status(), StatusCode::OK); + + let reregistered = seitan_register(&app, token.as_str(), Some("s3cret")).await; + assert_eq!(reregistered.status(), StatusCode::OK); + + let refused = seitan_admit(&app, &proof).await; + assert_eq!(refused.status(), StatusCode::FORBIDDEN); + assert_eq!(seitan_response_json(refused).await["reason"], "used"); + } + #[tokio::test] async fn public_entry_point_honours_a_configured_binding() { // A host that has already read its app manifest selects the diff --git a/pkgs/id/src/web/seitan.rs b/pkgs/id/src/web/seitan.rs index 1b171c534a..0f79ff54a4 100644 --- a/pkgs/id/src/web/seitan.rs +++ b/pkgs/id/src/web/seitan.rs @@ -226,19 +226,24 @@ pub(crate) async fn seitan_invite_handler( } }; let invite_id = invite.id().to_hex(); + // Registration is idempotent for an invite ID the registry + // already holds (Codex P2 on PR #8529): the ID is deterministic + // for a token, and `Invite::create` starts with `used: None`, so + // replacing an existing entry on a retried or duplicated + // registration would reset a redeemed invite's single-use state + // (and could silently rebind its world). Preserve the existing + // entry; a genuinely new invite uses a new token. state .seitan .inner .lock() .unwrap_or_else(|e| e.into_inner()) .invites - .insert( - invite_id.clone(), - RegisteredInvite { - world: request.world, - invite, - }, - ); + .entry(invite_id.clone()) + .or_insert(RegisteredInvite { + world: request.world, + invite, + }); Json(SeitanInviteResponse { invite_id }).into_response() }