AI search engine and MCP server for bots and agents. One Rust binary indexes code, docs, logs, JSONL/CSV and PDFs for BM25 full-text, vector and hybrid search, code search without grep, agent memory and RAG. Elasticsearch-compatible API; Corpus Hub serves hundreds of reference memory corpora.
Rust agent-memoryai-agentsbm25claude-codeclicode-searchcursordatabaseelasticsearchfull-text-searchhybrid-searchjsonllocal-firstmcpmcp-servermodel-context-protocolragrustsearch-enginevector-search
fix(console-api): require a passkey session to mint API tokens (CVE-2026-97406) (#2003)
xerj-org050a12e9ac66
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 4b4544163..52ce83de6 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Security++- **Console API: a bearer API token can no longer mint credentials**+ (CVE-2026-97406,+ [CERT VU#645818](https://kb.cert.org/vuls/id/645818), published 2026-10-20).+ `POST /_xerj-console/api/v1/auth/api-tokens` accepted any `AuthSession`, and+ a passkey cookie and `Authorization: Bearer <api token>` both resolved to+ that type. Holding one API token was enough to mint independent successors+ — revoking the parent left them working — and an owner token could issue+ an invitation, which the attacker redeemed in their own browser to enroll+ their own passkey. Creating and revoking API tokens, issuing invitations,+ deleting passkeys, and logout now require a passkey-backed browser session+ and return 403 for a bearer token. Ordinary console calls (`/me`, prefs,+ dashboards, and the other data routes) still accept bearer tokens. No+ token lineage is stored: the only insert of a new API token row refuses+ bearer auth before it writes, so a revoked token has no descendants.+### Fixed- `xerj search` and a plain-string `xerj_search` rank a file that containsdiff --git a/demo/DEMO_RUNBOOK.md b/demo/DEMO_RUNBOOK.mdindex 5017a91a3..28663aaf1 100644--- a/demo/DEMO_RUNBOOK.md+++ b/demo/DEMO_RUNBOOK.md@@ -418,7 +418,7 @@ The HTML version of the same flow lives at `landing/demo/index.html` §3.5 ("Cla- **Sessions.** Cookie-borne (`xerj_session=<id>.<hmac-sha256>`), HttpOnly, SameSite=Lax, Path=`/_xerj-console`, 12 h hard expiry, 30 min idle. Constant-time signature verification.- **Rate limiting.** Per-IP sliding window: 10 / minute, 100 / hour on `/auth/magic/redeem`, `/auth/login/begin`, `/auth/login/finish`. Over-limit returns 429 with no body — refuses to leak whether the email or token was valid.- **Audit log.** `magic-redeemed`, `passkey-enrolled`, `passkey-revoked`, `session-minted`, `session-revoked`, `magic-redeem-failed` all appended to `.xerj_audit` with `who`, `when`, `before`, `after`, `ip`, `ua`.-- **API tokens.** Off by default; can only be minted by a session that already has a passkey enrolled (`POST /_xerj-console/api/v1/auth/api-tokens` with `Authorization: Bearer <session>`). Revoking the last passkey cascades to revoking all tokens.+- **API tokens.** Off by default. Mint and revoke require a passkey-backed browser session (`Cookie: xerj_session=...` on `POST` and `DELETE /_xerj-console/api/v1/auth/api-tokens`). `Authorization: Bearer <api token>` authenticates ordinary console calls and is `403` on token mint, token revoke, invite issue, passkey deletion, and logout (CVE-2026-97406, [CERT VU#645818](https://kb.cert.org/vuls/id/645818)). A token cannot mint a successor, so revoking it leaves no working descendant. Deleting the last passkey is refused.- **SSO/SAML/OIDC.** Storage contract pinned (`.xerj_idp_config`); v1.1 ships the protocol handlers. Auto-provisions users on first SSO login but still requires a passkey before tokens.> **What the buyer takes away from Act 0:** "Onboarding is one click. There's no auth integration project." If they push on enterprise SSO, route to §0.4 last bullet — the contract is there, the handlers ship in v1.1.diff --git a/docs/SECURITY_MODEL.md b/docs/SECURITY_MODEL.mdindex 478a476e8..f7a1c33d0 100644--- a/docs/SECURITY_MODEL.md+++ b/docs/SECURITY_MODEL.md@@ -18,6 +18,7 @@ Primary sources:| Engine-side visibility funnel | `engine/crates/xerj-engine/src/index_guard.rs` || Privileges, roles, `role_descriptors` parsing | `engine/crates/xerj-engine/src/rbac.rs` || Console client identity and rate limiting | `engine/crates/xerj-console-api/src/client_ip.rs`, `.../auth/rate_limit.rs` |+| Console passkey session vs API token | `engine/crates/xerj-console-api/src/auth/sessions.rs` (`PasskeySession`) || Share links: records, claim route, claim limiter | `engine/crates/xerj-api/src/share.rs` || Share-link guest route allow-list | `engine/crates/xerj-api/src/authz.rs` (`guest_route_allowed`, `guest_body_denied`) || Cluster control-frame authentication | `engine/crates/xerj-cluster/src/auth.rs` |@@ -549,6 +550,71 @@ Note that `ClientIp` is also used for audit fields on endpoints that are notrate limited, for example passkey enrolment (`auth/passkey.rs:168`). Only thethree endpoints listed above charge a bucket.+## Console credentials: a passkey session is not an API token++CVE-2026-97406, [CERT VU#645818](https://kb.cert.org/vuls/id/645818)+(published 2026-10-20). Cookie sessions and `Authorization: Bearer <api token>`+both become an `AuthSession` (`auth/sessions.rs`). That is intentional for+ordinary console calls. It is not a passkey session. Handlers that mint a+credential or change identity extract `PasskeySession` instead+(`sessions.rs:298`, extractor at `sessions.rs:304`). The extractor authenticates+first, then calls `require_passkey_session` (`sessions.rs:169`). A missing+credential is 401. A valid API token, and a browser session whose `idp` is not+`"passkey"`, are 403. The body text is `PASSKEY_SESSION_REQUIRED`+(`sessions.rs:140`).++A passkey session is a `xerj_session` cookie whose `.xerj_sessions` row has+`idp: "passkey"` (`sessions.rs:250`). Login and enrollment mint that row with+`idp: "passkey"`. A bearer token is `SessionOrigin::ApiToken`+(`sessions.rs:393`); its `session_id` is the token hash, not a session id.+When both a cookie and a bearer header are present, the bearer wins+(`sessions.rs:194`): the request is not upgraded onto the cookie, so a token+cannot ride a passkey cookie through this gate.++Routes that require `PasskeySession`:++| Route | Handler | What a bearer token must not do |+|---|---|---|+| `POST /_xerj-console/api/v1/auth/api-tokens` | `auth/tokens.rs:73` | Mint a successor token |+| `DELETE /_xerj-console/api/v1/auth/api-tokens/:id` | `auth/tokens.rs:160` | Revoke a token |+| `POST /_xerj-console/api/v1/auth/magic/issue` | `auth/magic.rs:79` | Issue an invitation |+| `DELETE /_xerj-console/api/v1/auth/passkeys/:id` | `auth/me.rs:58` | Delete a passkey |+| `POST /_xerj-console/api/v1/auth/logout` | `auth/login.rs:218` | Revoke the browser session |++The refusal happens in the extractor, before the handler, so it writes nothing.+`put_api_token` (`auth/store.rs:285`) is how a new token row is stored, and the+only caller that inserts a new secret is `tokens::create`. There is no+`parent_id`. A bearer token cannot mint a descendant, so revoking a token+cannot leave one behind. `revoke_api_tokens_for_user` (`auth/store.rs:312`) is+not part of that path and is not called from passkey deletion.++These stay on `AuthSession`, so a bearer token still works: `GET /me`,+`GET /auth/passkeys`, `GET /auth/api-tokens` (metadata, no secret), prefs,+dashboards, saved views, data-source reads, `GET /knowledge`, and the+`/graph/*` reads.++Three credential-shaped routes do not take `AuthSession` at all, and a bearer+token does not unlock them:++- `POST /auth/magic/redeem` (`auth/magic.rs:200`) trusts the magic link. The+ invitee has no session yet. Requiring a passkey session here would break+ bootstrap. The stolen-token path into redeem was `magic/issue`, which is+ gated.+- `POST /auth/passkey/begin` and `/finish` trust the in-memory enrollment+ session that redeem creates. There is no handler that enrolls a passkey for+ the bearer token's user.+- `POST /auth/login/begin` and `/finish` are the WebAuthn ceremony.++No `/users` handler and no "revoke some other session" handler exist. Logout+revokes only the current passkey session.++Deleting the last passkey is refused with 409 (`auth/me.rs:73`). That is what+stops an account from holding API tokens and no passkey. It is not a cascade+that stamps `revoked_at` on the token rows.++The regression test is `tests/api_tokens_flow.rs`+(`bearer_token_cannot_mint_or_change_credentials`).+## Reach: what a fresh node exposes (issue #228)`server.bind_address` defaults to **`127.0.0.1`**. A node you start withoutdiff --git a/engine/crates/xerj-console-api/src/auth/login.rs b/engine/crates/xerj-console-api/src/auth/login.rsindex 4c115dcf3..7c8e4792f 100644--- a/engine/crates/xerj-console-api/src/auth/login.rs+++ b/engine/crates/xerj-console-api/src/auth/login.rs@@ -8,7 +8,8 @@//! - `POST /auth/login/finish { challenge_id, credential }`//! → validates the assertion, mints a session cookie.//!-//! Logout: `POST /auth/logout` revokes the current session.+//! Logout: `POST /auth/logout` revokes the current passkey session.+//! A bearer API token is 403 and does not revoke anything.use axum::{extract::State,@@ -216,7 +217,7 @@ pub async fn finish(pub async fn logout(State(state): State<ConsoleState>,- sess: sessions::AuthSession,+ sess: sessions::PasskeySession,) -> ConsoleResult<Response> {store::revoke_session(&state.engine, &sess.session_id, &now_iso()).await?;audit::record(diff --git a/engine/crates/xerj-console-api/src/auth/magic.rs b/engine/crates/xerj-console-api/src/auth/magic.rsindex accde5d67..77a89d69d 100644--- a/engine/crates/xerj-console-api/src/auth/magic.rs+++ b/engine/crates/xerj-console-api/src/auth/magic.rs@@ -21,7 +21,7 @@ use rand::RngCore;use serde::{Deserialize, Serialize};use serde_json::json;-use crate::auth::{audit, rate_limit, store, AuthSession};+use crate::auth::{audit, rate_limit, store, PasskeySession};use crate::bootstrap::sha256_hex;use crate::client_ip::ClientIp;use crate::error::{ConsoleApiError, ConsoleResult};@@ -70,9 +70,15 @@ pub struct IssueResponse {/// single-use invite link for `email`. When no user with that email exists/// we provision a `pending` row so the invitee flips to `active` the moment/// they redeem the link and enrol a passkey (`redeem` → `passkey/finish`).+///+/// The caller must be a [`PasskeySession`]. A bearer API token is 403+/// before any user or magic-link row is written (CVE-2026-97406): issuing+/// an invite was how a stolen owner token enrolled an attacker's passkey.+/// `redeem` stays unauthenticated — the link itself is the credential, and+/// the invitee has no session yet.pub async fn issue(State(state): State<ConsoleState>,- session: AuthSession,+ session: PasskeySession,ClientIp(ip): ClientIp,Json(body): Json<IssueBody>,) -> ConsoleResult<Response> {diff --git a/engine/crates/xerj-console-api/src/auth/me.rs b/engine/crates/xerj-console-api/src/auth/me.rsindex 1a7c9450d..de24465ed 100644--- a/engine/crates/xerj-console-api/src/auth/me.rs+++ b/engine/crates/xerj-console-api/src/auth/me.rs@@ -2,15 +2,19 @@//!//! These need the smallest possible auth surface to be usable: as soon//! as a session cookie exists, the SPA wants `/me` so it can render the-//! "logged in as …" header. Listing/deleting passkeys is here too-//! because a freshly-enrolled user immediately sees their credential-//! list on the settings screen.+//! "logged in as …" header. Listing passkeys is a metadata read and+//! accepts a bearer token. Deleting one is an identity change and+//! requires a passkey-backed browser session (CVE-2026-97406).use axum::{extract::State, response::Response};use serde::Serialize;use serde_json::json;-use crate::auth::{audit, sessions::AuthSession, store};+use crate::auth::{+ audit,+ sessions::{AuthSession, PasskeySession},+ store,+};use crate::error::{ConsoleApiError, ConsoleResult};use crate::indices;use crate::response::{no_content, ok};@@ -53,7 +57,7 @@ pub async fn list_passkeys(pub async fn delete_passkey(State(state): State<ConsoleState>,- sess: AuthSession,+ sess: PasskeySession,axum::extract::Path(credential_id): axum::extract::Path<String>,) -> ConsoleResult<Response> {// Caller can only delete their own passkeys.diff --git a/engine/crates/xerj-console-api/src/auth/mod.rs b/engine/crates/xerj-console-api/src/auth/mod.rsindex d1b75a0cc..b64e26765 100644--- a/engine/crates/xerj-console-api/src/auth/mod.rs+++ b/engine/crates/xerj-console-api/src/auth/mod.rs@@ -2,8 +2,10 @@//!//! Implements the design from `engine/docs/xerj-console-backend/API_DESIGN_v1.md`//! §3 — magic-link bootstrap → passkey enrolment → cookie session, with-//! returning-user passkey login. No passwords. API tokens (covered by a-//! later phase) require an enrolled passkey.+//! returning-user passkey login. No passwords. Minting an API token, issuing+//! an invitation, deleting a passkey, or logging out requires a+//! [`PasskeySession`]; a bearer API token is 403 on those routes+//! (CVE-2026-97406 / CERT VU#645818).pub mod audit;pub mod login;@@ -16,4 +18,4 @@ pub mod store;pub mod tokens;pub mod webauthn_setup;-pub use sessions::{AuthSession, OptionalAuthSession};+pub use sessions::{AuthSession, OptionalAuthSession, PasskeySession};diff --git a/engine/crates/xerj-console-api/src/auth/sessions.rs b/engine/crates/xerj-console-api/src/auth/sessions.rsindex babe115c2..174817fcc 100644--- a/engine/crates/xerj-console-api/src/auth/sessions.rs+++ b/engine/crates/xerj-console-api/src/auth/sessions.rs@@ -119,14 +119,68 @@ pub fn make_clear_cookie() -> Cookie<'static> {// Extractor// ─────────────────────────────────────────────────────────────────────────────-/// Authenticated session, extracted from the `xerj_session` cookie.+/// How this request authenticated.///-/// Use as a handler parameter to require authentication. Returns 401 on-/// missing cookie, bad signature, expired session, or revoked session.+/// A cookie session and an API token both become an [`AuthSession`], so+/// ordinary console reads and writes can accept either. They are not the+/// same credential. [`PasskeySession`] is the passkey-backed browser session+/// a handler must hold before it mints or changes credentials.+#[derive(Debug, Clone, PartialEq, Eq)]+pub enum SessionOrigin {+ /// `xerj_session` cookie. `idp` is the `.xerj_sessions` row's identity+ /// provider. Only `"passkey"` satisfies [`AuthSession::require_passkey_session`].+ BrowserSession { idp: String },+ /// `Authorization: Bearer <api token>`. `token_id` is `sha256(secret)`.+ ApiToken { token_id: String },+}++/// Stable text of the 403 returned when a credential-minting or+/// identity-changing handler is reached without a passkey-backed browser+/// session. The console tests and `docs/SECURITY_MODEL.md` quote it.+pub const PASSKEY_SESSION_REQUIRED: &str = concat!(+ "this operation requires a passkey-backed browser session; ",+ "API tokens cannot mint or change credentials"+);++/// Authenticated caller, from the `xerj_session` cookie or from+/// `Authorization: Bearer <api token>`.+///+/// Use as a handler parameter to require authentication. Returns 401 on a+/// missing credential, a bad signature, an expired or revoked session, or+/// an unknown or revoked token.+///+/// This type does **not** mean the caller presented a passkey. Credential+/// minting and identity changes take [`PasskeySession`] instead, which+/// returns 403 for a valid bearer token (CVE-2026-97406 / CERT VU#645818).#[derive(Debug, Clone)]pub struct AuthSession {pub session_id: String,pub user: store::User,+ pub origin: SessionOrigin,+}++impl AuthSession {+ /// Refuse unless this request presented a passkey-backed browser session.+ ///+ /// A valid API token is a 403, not a 401: the caller is authenticated+ /// and the operation is forbidden. Cookie sessions and bearer tokens+ /// used to resolve to the same `AuthSession`, so `POST /auth/api-tokens`+ /// would mint a successor that survived revocation of the parent.+ pub fn require_passkey_session(&self) -> ConsoleResult<()> {+ match &self.origin {+ SessionOrigin::BrowserSession { idp } if idp == "passkey" => Ok(()),+ other => Err(ConsoleApiError::Forbidden(refusal_message(other))),+ }+ }+}++fn refusal_message(origin: &SessionOrigin) -> String {+ match origin {+ SessionOrigin::ApiToken { .. } => PASSKEY_SESSION_REQUIRED.to_string(),+ SessionOrigin::BrowserSession { idp } => {+ format!("{PASSKEY_SESSION_REQUIRED} (this session's idp is {idp}, not passkey)")+ }+ }}#[axum::async_trait]@@ -138,9 +192,12 @@ impl FromRequestParts<ConsoleState> for AuthSession {state: &ConsoleState,) -> Result<Self, Self::Rejection> {// API clients authenticate with `Authorization: Bearer <token>`;- // browsers with a signed session cookie. Bearer wins when present so- // a token-carrying request is never silently downgraded to the- // (absent) cookie path.+ // browsers with a signed session cookie. Bearer wins when the header+ // is present, including when the token is invalid: a token-carrying+ // request is never upgraded onto a cookie that happens to be+ // attached. `PasskeySession` then refuses a *valid* bearer with 403.+ // Preferring the cookie whenever both are present would let that+ // request pass the passkey gate (CVE-2026-97406).if let Some(token) = bearer_token(&parts.headers) {return authenticate_bearer(state, &token).await;}@@ -187,7 +244,76 @@ impl FromRequestParts<ConsoleState> for AuthSession {// only the fresh record, skipping entirely if it is now revoked or gone.bump_last_seen(&state.engine, &session_id).await;- Ok(AuthSession { session_id, user })+ Ok(AuthSession {+ session_id,+ user,+ origin: SessionOrigin::BrowserSession { idp: session.idp },+ })+ }+}++/// Passkey-backed browser session.+///+/// Extract this instead of [`AuthSession`] for any handler that mints a+/// credential or changes identity. A missing credential is 401. A valid+/// `Authorization: Bearer` API token, and a browser session whose `idp` is+/// not `"passkey"`, are 403 with [`PASSKEY_SESSION_REQUIRED`]. The check+/// runs in the extractor, before the handler, so a refusal writes nothing.+///+/// # Handler classification+///+/// **Requires this type** (credential minting or identity change):+/// - `POST /auth/api-tokens` — mint an API token (`tokens::create`)+/// - `DELETE /auth/api-tokens/:id` — revoke an API token (`tokens::revoke`)+/// - `POST /auth/magic/issue` — mint an invitation (`magic::issue`)+/// - `DELETE /auth/passkeys/:id` — delete a passkey (`me::delete_passkey`)+/// - `POST /auth/logout` — revoke the current browser session (`login::logout`)+///+/// **[`AuthSession`] is enough** (ordinary console data; bearer tokens work):+/// - `GET /me`, `GET /auth/passkeys`, `GET /auth/api-tokens` (metadata only)+/// - `GET`/`PUT /prefs`+/// - dashboard and saved-view CRUD, including `_bulk`+/// - data-source connection, index, field, and search routes+/// - `GET /knowledge` and the `/graph/*` reads+///+/// **Not an [`AuthSession`] route.** These authorize with a different+/// credential, and a bearer token does not unlock them:+/// - `POST /auth/magic/redeem` — the magic link is the credential. The+/// invitee has no session yet; requiring one would break bootstrap.+/// A stolen API token cannot issue the link once `magic/issue` is gated.+/// - `POST /auth/passkey/begin` and `/finish` — the in-memory enrollment+/// session from redeem. There is no "enroll a passkey while holding an+/// API token" path.+/// - `POST /auth/login/begin` and `/finish` — WebAuthn, unauthenticated.+///+/// **No handler exists** for user/role management (`/users`) or for+/// revoking a session other than the current cookie via `logout`. A future+/// SSO cookie (`idp` other than `"passkey"`) fails this extractor, so it+/// cannot mint credentials either.+///+/// No API-token row records a parent. `tokens::create` is the only insert+/// of a new token, and it takes this type, so a bearer token cannot mint a+/// descendant for revocation to miss.+#[derive(Debug, Clone)]+pub struct PasskeySession {+ pub session_id: String,+ pub user: store::User,+}++#[axum::async_trait]+impl FromRequestParts<ConsoleState> for PasskeySession {+ type Rejection = ConsoleApiError;++ async fn from_request_parts(+ parts: &mut Parts,+ state: &ConsoleState,+ ) -> Result<Self, Self::Rejection> {+ let sess = AuthSession::from_request_parts(parts, state).await?;+ sess.require_passkey_session()?;+ Ok(PasskeySession {+ session_id: sess.session_id,+ user: sess.user,+ })}}@@ -257,12 +383,14 @@ async fn authenticate_bearer(if user.status != store::UserStatus::Active {return Err(ConsoleApiError::Unauthorized("user disabled".into()));}- // `session_id` is opaque to callers; for a token-authenticated request- // it is the token id (= hash). The cookie-only `logout` handler would- // just no-op against `.xerj_sessions` for such an id.+ // `session_id` is the token id (= hash), not a `.xerj_sessions` id.+ // `PasskeySession` refuses this origin before a credential handler runs,+ // so logout cannot treat the hash as a browser session to revoke.+ let token_id = token.id.clone();Ok(AuthSession {- session_id: token.id,+ session_id: token_id.clone(),user,+ origin: SessionOrigin::ApiToken { token_id },})}@@ -416,4 +544,55 @@ mod tests {assert!(after.revoked_at.is_none());assert_ne!(after.last_seen_at, before, "last_seen should advance");}++ fn user() -> store::User {+ store::User {+ id: "u".into(),+ email: "[email protected]".into(),+ display_name: String::new(),+ role: "owner".into(),+ status: store::UserStatus::Active,+ created_at: "2026-01-01T00:00:00.000Z".into(),+ last_seen_at: None,+ }+ }++ fn session_with(origin: SessionOrigin) -> AuthSession {+ AuthSession {+ session_id: "s".into(),+ user: user(),+ origin,+ }+ }++ #[test]+ fn a_passkey_browser_session_may_mint_credentials() {+ let sess = session_with(SessionOrigin::BrowserSession {+ idp: "passkey".into(),+ });+ assert!(sess.require_passkey_session().is_ok());+ }++ #[test]+ fn an_api_token_cannot_mint_credentials() {+ let sess = session_with(SessionOrigin::ApiToken {+ token_id: "hash".into(),+ });+ let err = sess.require_passkey_session().unwrap_err();+ assert!(matches!(err, ConsoleApiError::Forbidden(_)));+ assert!(+ err.to_string().contains(PASSKEY_SESSION_REQUIRED),+ "403 text must name the passkey-session rule, got {err}"+ );+ }++ #[test]+ fn a_non_passkey_browser_session_cannot_mint_credentials() {+ let sess = session_with(SessionOrigin::BrowserSession { idp: "oidc".into() });+ let err = sess.require_passkey_session().unwrap_err();+ assert!(matches!(err, ConsoleApiError::Forbidden(_)));+ let text = err.to_string();+ assert!(text.contains(PASSKEY_SESSION_REQUIRED), "{text}");+ assert!(text.contains("oidc"), "{text}");+ }}diff --git a/engine/crates/xerj-console-api/src/auth/store.rs b/engine/crates/xerj-console-api/src/auth/store.rsindex c0a6a0427..8926d4c0f 100644--- a/engine/crates/xerj-console-api/src/auth/store.rs+++ b/engine/crates/xerj-console-api/src/auth/store.rs@@ -276,6 +276,12 @@ pub struct ApiToken {pub revoked_at: Option<String>,}+/// Persist an API token row.+///+/// A new secret is inserted only from `tokens::create`, which takes a+/// `PasskeySession` and returns 403 for a bearer token before this runs+/// (CVE-2026-97406). `tokens::revoke` and [`revoke_api_tokens_for_user`]+/// call it to stamp `revoked_at` on a row that already exists.pub async fn put_api_token(engine: &Engine, token: &ApiToken) -> ConsoleResult<()> {let idx = engine.get_index(indices::API_TOKENS)?;let doc = serde_json::to_value(token)?;diff --git a/engine/crates/xerj-console-api/src/auth/tokens.rs b/engine/crates/xerj-console-api/src/auth/tokens.rsindex 30455ea66..408967127 100644--- a/engine/crates/xerj-console-api/src/auth/tokens.rs+++ b/engine/crates/xerj-console-api/src/auth/tokens.rs@@ -15,7 +15,13 @@//!//! Bearer authentication lives in `sessions.rs`: it hashes a presented//! `Authorization: Bearer <secret>` and looks up the non-revoked row minted-//! here, then authenticates as the token's owner.+//! here, then authenticates as the token's owner for ordinary console+//! calls. Minting (`create`) and revoking (`revoke`) take [`PasskeySession`].+//! A bearer token is 403 on both, before any write. That is the whole of+//! the lineage story for CVE-2026-97406: this module is the only place a+//! new `ApiToken` row is inserted, and the insert cannot be reached from+//! a token, so a revoked token has no descendants to cascade. There is no+//! `parent_id` column because that path does not exist.use axum::{extract::State, response::Response, Json};use base64::{engine::general_purpose::URL_SAFE_NO_PAD, Engine as _};@@ -23,7 +29,11 @@ use rand::RngCore;use serde::{Deserialize, Serialize};use serde_json::json;-use crate::auth::{audit, sessions::AuthSession, store};+use crate::auth::{+ audit,+ sessions::{AuthSession, PasskeySession},+ store,+};use crate::bootstrap::sha256_hex;use crate::error::{ConsoleApiError, ConsoleResult};use crate::indices;@@ -62,7 +72,7 @@ pub struct CreatedToken {pub async fn create(State(state): State<ConsoleState>,- sess: AuthSession,+ sess: PasskeySession,Json(body): Json<CreateBody>,) -> ConsoleResult<Response> {let name = body.name.trim().to_string();@@ -149,7 +159,7 @@ pub async fn list(State(state): State<ConsoleState>, sess: AuthSession) -> Consopub async fn revoke(State(state): State<ConsoleState>,- sess: AuthSession,+ sess: PasskeySession,axum::extract::Path(id): axum::extract::Path<String>,) -> ConsoleResult<Response> {// Look the token up by id (= hash). A token that does not exist, or onediff --git a/engine/crates/xerj-console-api/src/router.rs b/engine/crates/xerj-console-api/src/router.rsindex 5c29cca2d..fa473b7f3 100644--- a/engine/crates/xerj-console-api/src/router.rs+++ b/engine/crates/xerj-console-api/src/router.rs@@ -55,7 +55,8 @@ pub fn xerj_console_router(state: ConsoleState) -> Router {"/_xerj-console/api/v1/auth/magic/redeem",post(auth::magic::redeem),)- // ── API: invite issue (owner/admin session required) ───────────────+ // ── API: invite issue (owner/admin passkey session required) ───────+ // A bearer API token is 403. See `PasskeySession`..route("/_xerj-console/api/v1/auth/magic/issue",post(auth::magic::issue),@@ -77,6 +78,9 @@ pub fn xerj_console_router(state: ConsoleState) -> Router {post(auth::login::finish),)// ── API: session-protected ─────────────────────────────────────────+ // `PasskeySession` (bearer token → 403): logout, passkey delete,+ // api-token create and revoke. List routes and every data route+ // below accept a bearer token. See `auth::sessions::PasskeySession`..route("/_xerj-console/api/v1/auth/logout",post(auth::login::logout),diff --git a/engine/crates/xerj-console-api/tests/api_tokens_flow.rs b/engine/crates/xerj-console-api/tests/api_tokens_flow.rsindex 5c94d12af..35e6e7afe 100644--- a/engine/crates/xerj-console-api/tests/api_tokens_flow.rs+++ b/engine/crates/xerj-console-api/tests/api_tokens_flow.rs@@ -9,10 +9,16 @@//! authenticates a protected endpoint over Bearer.//!//! Proven here:-//! - `POST /auth/api-tokens` returns the plaintext secret exactly once.+//! - `POST /auth/api-tokens` returns the plaintext secret exactly once,+//! and only for a passkey-backed session cookie.//! - `GET /auth/api-tokens` lists only the hash/metadata — no plaintext.-//! - the plaintext used as `Authorization: Bearer` authenticates `/me`.-//! - `DELETE /auth/api-tokens/:id` revokes it → the same Bearer call 401s.+//! - the plaintext used as `Authorization: Bearer` authenticates `/me`+//! and other ordinary console calls.+//! - the same bearer token is 403 on credential minting and identity+//! changes (token create/revoke, invite issue, passkey delete, logout)+//! and those refusals write nothing (CVE-2026-97406 / CERT VU#645818).+//! - `DELETE /auth/api-tokens/:id` with the passkey cookie revokes it →+//! the same Bearer call 401s.//! - issuing a token without a session is rejected (401).use axum::{body::Body, http::Request, Router};@@ -221,3 +227,414 @@ async fn bogus_bearer_token_is_rejected() {"unknown bearer token must not authenticate");}++const TOKENS: &str = "/_xerj-console/api/v1/auth/api-tokens";++async fn call(+ router: &Router,+ method: &str,+ uri: &str,+ cookie: Option<&str>,+ bearer: Option<&str>,+ json_body: Option<Value>,+) -> (axum::http::StatusCode, Value) {+ let mut builder = Request::builder().method(method).uri(uri);+ if let Some(cookie) = cookie {+ builder = builder.header("cookie", cookie);+ }+ if let Some(bearer) = bearer {+ builder = builder.header("authorization", format!("Bearer {bearer}"));+ }+ let req = match json_body {+ Some(body) => builder+ .header("content-type", "application/json")+ .body(Body::from(body.to_string()))+ .unwrap(),+ None => builder.body(Body::empty()).unwrap(),+ };+ body_json(router.clone().oneshot(req).await.unwrap()).await+}++fn assert_passkey_required(status: axum::http::StatusCode, body: &Value, what: &str) {+ assert_eq!(+ status, 403,+ "{what} must refuse a non-passkey caller: {body}"+ );+ assert_eq!(body["error"]["code"], "forbidden", "{what}: {body}");+ let message = body["error"]["message"].as_str().unwrap_or("");+ assert!(+ message.contains(sessions::PASSKEY_SESSION_REQUIRED),+ "{what} 403 must name the passkey-session rule, got {body}"+ );+}++async fn seed_passkey(engine: &Engine, user_id: &str, id: &str) {+ store::put_passkey(+ engine,+ &store::StoredPasskey {+ id: id.into(),+ user_id: user_id.into(),+ name: id.into(),+ created_at: "2026-01-01T00:00:00.000Z".into(),+ last_used_at: None,+ blob: json!({}),+ },+ )+ .await+ .unwrap();+}++struct Issued {+ engine: Engine,+ router: Router,+ // Kept so the data directory outlives the engine.+ _dir: TempDir,+ user_id: String,+ cookie: String,+ plaintext: String,+ token_id: String,+}++/// Each `call` builds an axum `Router::oneshot` future. Several of those in+/// one async fn overflow the test thread's stack in a debug build, so the+/// CVE checks are separate tests that share this setup.+async fn issue_with_passkey_cookie() -> Issued {+ let (engine, state, router, dir) = boot().await;+ let (user_id, cookie) = seed_user_and_cookie(&engine, &state).await;+ seed_passkey(&engine, &user_id, "pk-laptop").await;+ seed_passkey(&engine, &user_id, "pk-phone").await;+ let (status, body) = call(+ &router,+ "POST",+ TOKENS,+ Some(&cookie),+ None,+ Some(json!({ "name": "ci-token", "scopes": ["read"] })),+ )+ .await;+ assert_eq!(status, 200, "passkey cookie must still mint: {body}");+ Issued {+ engine,+ router,+ _dir: dir,+ user_id,+ cookie,+ plaintext: body["data"]["token"].as_str().unwrap().to_string(),+ token_id: body["data"]["id"].as_str().unwrap().to_string(),+ }+}++/// CVE-2026-97406 / CERT VU#645818. A bearer token used to resolve to the+/// same `AuthSession` as a passkey cookie, so it could mint a successor+/// that survived revocation of the parent. Bearer alone, and bearer sent+/// together with the passkey cookie, are both 403 and insert nothing.+#[tokio::test]+async fn bearer_token_cannot_mint_a_successor() {+ // Boxed so this test's future does not embed the setup future. Several+ // `Router::oneshot` futures in one frame overflow the debug stack.+ let issued = Box::pin(issue_with_passkey_cookie()).await;++ for (label, cookie_hdr) in [+ ("bearer alone", None),+ (+ "bearer plus the passkey cookie",+ Some(issued.cookie.as_str()),+ ),+ ] {+ let name = format!("successor-{label}");+ let (status, body) = call(+ &issued.router,+ "POST",+ TOKENS,+ cookie_hdr,+ Some(&issued.plaintext),+ Some(json!({ "name": name })),+ )+ .await;+ assert_passkey_required(status, &body, label);+ }+ let stored = store::list_api_tokens_for_user(&issued.engine, &issued.user_id)+ .await+ .unwrap();+ assert_eq!(+ stored.len(),+ 1,+ "a refused mint must not insert a descendant: {stored:?}"+ );+ assert_eq!(stored[0].id, issued.token_id);+ assert!(stored[0].revoked_at.is_none());++ // An unknown bearer is 401, not the passkey-session 403.+ let (status, body) = call(+ &issued.router,+ "POST",+ TOKENS,+ None,+ Some("not-a-real-token"),+ Some(json!({ "name": "nope" })),+ )+ .await;+ assert_eq!(status, 401, "an unknown bearer is unauthenticated: {body}");+ assert_eq!(body["error"]["code"], "unauthorized");+}++/// Revoking a token, issuing an invitation, and deleting a passkey are the+/// same class of operation. A bearer token is 403 and the rows stay put.+/// The passkey cookie can still delete a passkey.+#[tokio::test]+async fn bearer_token_cannot_revoke_invite_or_delete_a_passkey() {+ // Boxed so this test's future does not embed the setup future. Several+ // `Router::oneshot` futures in one frame overflow the debug stack.+ let issued = Box::pin(issue_with_passkey_cookie()).await;++ let (status, body) = call(+ &issued.router,+ "DELETE",+ &format!("{TOKENS}/{}", issued.token_id),+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_passkey_required(status, &body, "revoke");+ let (status, body) = call(+ &issued.router,+ "GET",+ "/_xerj-console/api/v1/me",+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_eq!(+ status, 200,+ "refused revoke must leave the token working: {body}"+ );++ let (status, body) = call(+ &issued.router,+ "POST",+ "/_xerj-console/api/v1/auth/magic/issue",+ None,+ Some(&issued.plaintext),+ Some(json!({ "email": "[email protected]", "role": "owner" })),+ )+ .await;+ assert_passkey_required(status, &body, "invite issue");+ assert!(+ store::find_user_by_email(&issued.engine, "[email protected]")+ .await+ .unwrap()+ .is_none(),+ "a refused invite must not provision the invitee"+ );++ let (status, body) = call(+ &issued.router,+ "DELETE",+ "/_xerj-console/api/v1/auth/passkeys/pk-laptop",+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_passkey_required(status, &body, "passkey delete");+ let passkeys = store::list_passkeys_for_user(&issued.engine, &issued.user_id)+ .await+ .unwrap();+ assert_eq!(passkeys.len(), 2, "refused delete must keep both passkeys");++ // Two passkeys are enrolled, so the last-passkey guard does not fire.+ let (status, _) = call(+ &issued.router,+ "DELETE",+ "/_xerj-console/api/v1/auth/passkeys/pk-phone",+ Some(&issued.cookie),+ None,+ None,+ )+ .await;+ assert_eq!(status, 204, "passkey cookie must still delete a passkey");+}++/// Logout revokes the passkey session only. A bearer token cannot end that+/// session, and ending it does not revoke the token.+#[tokio::test]+async fn bearer_logout_does_not_revoke_the_passkey_session() {+ // Boxed so this test's future does not embed the setup future. Several+ // `Router::oneshot` futures in one frame overflow the debug stack.+ let issued = Box::pin(issue_with_passkey_cookie()).await;++ let (status, body) = call(+ &issued.router,+ "POST",+ "/_xerj-console/api/v1/auth/logout",+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_passkey_required(status, &body, "logout");+ let (status, body) = call(+ &issued.router,+ "GET",+ "/_xerj-console/api/v1/me",+ Some(&issued.cookie),+ None,+ None,+ )+ .await;+ assert_eq!(+ status, 200,+ "bearer logout must not revoke the passkey session: {body}"+ );++ let (status, _) = call(+ &issued.router,+ "POST",+ "/_xerj-console/api/v1/auth/logout",+ Some(&issued.cookie),+ None,+ None,+ )+ .await;+ assert_eq!(status, 200, "passkey cookie must still be able to log out");+ let (status, _) = call(+ &issued.router,+ "GET",+ "/_xerj-console/api/v1/me",+ Some(&issued.cookie),+ None,+ None,+ )+ .await;+ assert_eq!(status, 401, "logout must revoke the passkey session");+ let (status, _) = call(+ &issued.router,+ "GET",+ "/_xerj-console/api/v1/me",+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_eq!(+ status, 200,+ "logging out the browser session must not revoke the API token"+ );+}++/// Listing credential metadata and writing ordinary console data stay+/// available to a bearer token.+#[tokio::test]+async fn bearer_token_still_serves_ordinary_console_calls() {+ // Boxed so this test's future does not embed the setup future. Several+ // `Router::oneshot` futures in one frame overflow the debug stack.+ let issued = Box::pin(issue_with_passkey_cookie()).await;++ let (status, body) = call(+ &issued.router,+ "GET",+ TOKENS,+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_eq!(status, 200, "listing tokens is a metadata read: {body}");+ assert_eq!(body["data"]["tokens"].as_array().unwrap().len(), 1);+ assert!(+ !body.to_string().contains(&issued.plaintext),+ "plaintext secret leaked into the list response"+ );++ let (status, body) = call(+ &issued.router,+ "GET",+ "/_xerj-console/api/v1/auth/passkeys",+ None,+ Some(&issued.plaintext),+ None,+ )+ .await;+ assert_eq!(status, 200, "listing passkeys is a metadata read: {body}");+ assert_eq!(body["data"]["passkeys"].as_array().unwrap().len(), 2);++ let (status, body) = call(+ &issued.router,+ "PUT",+ "/_xerj-console/api/v1/prefs",+ None,+ Some(&issued.plaintext),+ Some(json!({ "theme": "light" })),+ )+ .await;+ assert_eq!(+ status, 200,+ "a data write must still accept a bearer token: {body}"+ );+ assert_eq!(body["data"]["theme"], "light");+}++/// A browser session that was not minted by a passkey assertion is the+/// same class of refusal. SSO cookies are not issued today; the idp check+/// is what will refuse them if they are.+#[tokio::test]+async fn non_passkey_browser_session_cannot_mint_an_api_token() {+ let (engine, state, router, _dir) = boot().await;+ let user = store::User {+ id: "u-oidc".into(),+ email: "[email protected]".into(),+ display_name: "Oidc".into(),+ role: "owner".into(),+ status: store::UserStatus::Active,+ created_at: "2026-01-01T00:00:00.000Z".into(),+ last_seen_at: None,+ };+ store::upsert_user(&engine, &user).await.unwrap();+ let (_sess, signed) = sessions::mint_session(&state, &user.id, "oidc", None, None)+ .await+ .unwrap();+ let cookie = format!("{}={signed}", sessions::COOKIE_NAME);++ let (status, body) = call(+ &router,+ "POST",+ TOKENS,+ Some(&cookie),+ None,+ Some(json!({ "name": "from-oidc" })),+ )+ .await;+ assert_passkey_required(status, &body, "oidc session");+ assert!(+ body["error"]["message"]+ .as_str()+ .unwrap_or("")+ .contains("oidc"),+ "the 403 must name the session idp: {body}"+ );+ assert!(+ store::list_api_tokens_for_user(&engine, &user.id)+ .await+ .unwrap()+ .is_empty(),+ "the refused mint must not insert a token"+ );++ // The same cookie still authenticates an ordinary read.+ let (status, body) = call(+ &router,+ "GET",+ "/_xerj-console/api/v1/me",+ Some(&cookie),+ None,+ None,+ )+ .await;+ assert_eq!(+ status, 200,+ "a non-passkey session is still a session: {body}"+ );+ assert_eq!(body["data"]["user"]["id"], user.id);+}diff --git a/engine/docs/xerj-console-backend/API_DESIGN_v1.md b/engine/docs/xerj-console-backend/API_DESIGN_v1.mdindex 98ee00504..49e918129 100644--- a/engine/docs/xerj-console-backend/API_DESIGN_v1.md+++ b/engine/docs/xerj-console-backend/API_DESIGN_v1.md@@ -58,7 +58,7 @@ Errors echo xerj's existing `XerjError` shape (HTTP-aligned status + structured### 2.3 Auth-All `_xerj-console/api/v1` routes (except the bootstrap and login endpoints documented in §3) require an authenticated session — passkey-backed by default, optionally upgraded to SSO/SAML/OIDC for enterprise. Bearer API tokens are accepted, but a token can only be minted by a session that has already enrolled a passkey. There is no password authentication anywhere, ever. The full flow — first-launch CLI magic link, passkey enrollment, login, admin-issued invites, API tokens, SSO — lives in **§3 · Authentication & Identity** below. Every write writes the calling principal into the audit log (`who`, `when`, `before`, `after`).+All `_xerj-console/api/v1` routes (except the bootstrap and login endpoints documented in §3) require an authenticated caller — a passkey-backed browser session by default, optionally an SSO/SAML/OIDC session for enterprise. Bearer API tokens are accepted on ordinary data routes. A token cannot mint another token, an invitation, or any other credential: those handlers require the passkey session cookie itself and answer `403` to `Authorization: Bearer`, even when the token is valid and its owner has a passkey enrolled (CVE-2026-97406, [CERT VU#645818](https://kb.cert.org/vuls/id/645818), published 2026-10-20). There is no password authentication anywhere, ever. The full flow — first-launch CLI magic link, passkey enrollment, login, admin-issued invites, API tokens, SSO — lives in **§3 · Authentication & Identity** below. Every write writes the calling principal into the audit log (`who`, `when`, `before`, `after`).### 2.4 Multi-tenancy@@ -134,7 +134,7 @@ The first frame is always a snapshot of the current state so the client doesn't* Default flow is **dead simple**: install xerj, run it, click the magic link the CLI prints, enroll a passkey, you're in.* **No passwords**, anywhere, ever. Not as a fallback, not for "service accounts", not in any form. The data model has no `password_hash` column.* **Enterprise upgrade** is OIDC / SAML / OAuth2 ("SSO"). Once the org admin wires SSO, new users no longer need a magic-link round-trip — the IdP becomes the issuer of identity.-* **API tokens** exist for scripting and CI, but a user can only mint one *after* they have enrolled at least one passkey. This stops the "I emailed myself a token from a brand-new account" bypass.+* **API tokens** exist for scripting and CI. Minting one requires the caller's passkey-backed browser session (the `xerj_session` cookie whose `.xerj_sessions` row has `idp: "passkey"`), not merely that the account has a passkey enrolled. `Authorization: Bearer <api token>` on `POST /auth/api-tokens` is `403`. A token therefore cannot mint a successor that would survive revocation of the parent (CVE-2026-97406, [CERT VU#645818](https://kb.cert.org/vuls/id/645818)). The passkey enrollment requirement still stops the "I emailed myself a token from a brand-new account" bypass: there is no password, and no token exists until a passkey session mints one.* **Inviting users** is a passkey-holder-only action. The invitation is itself a magic link, scoped to "set up your passkey", nothing else. An invite never grants access — it grants the right to enroll a credential that grants access.* Non-goal: TOTP / SMS / hardware-OTP fallbacks. Passkeys cover the device-bound and platform-bound cases already; adding more factors is more code, more compliance scope, and more user pain.@@ -180,7 +180,7 @@ POST /_xerj-console/api/v1/auth/magic/issue { email, role, ttl_→ { id, link, expires_at }```-* Caller must hold an `admin` (or `owner`) role and an active passkey-backed session.+* Caller must hold an `admin` (or `owner`) role and an active passkey-backed browser session (the `xerj_session` cookie, `idp: "passkey"`). A bearer API token is `403` here even for an owner. Issuing an invite is how a stolen owner token used to enroll an attacker's own passkey (CVE-2026-97406, [CERT VU#645818](https://kb.cert.org/vuls/id/645818)). `POST /auth/magic/redeem` stays unauthenticated: the link is the credential, and the invitee has no session yet.* `role` is one of `admin` / `editor` / `viewer` (see §3.6).* The server creates `.xerj_users` with `status: "pending"` and `.xerj_magic_links` with `purpose: "invite"`. The invitee's first action via the link is to enroll a passkey (same `passkey/begin` + `passkey/finish` dance as bootstrap), which flips their status to `active`.* A pending user with no enrolled passkey **cannot log in** — there is no other credential to authenticate with. If the invite expires, the admin re-issues; the user record stays pending.@@ -224,9 +224,10 @@ DELETE /_xerj-console/api/v1/auth/api-tokens/:id revoke```Gating:-* The caller must be authenticated by passkey **and** must have at least one passkey credential currently enrolled. If they later revoke their last passkey, all their API tokens are also revoked (cascading delete in `.xerj_api_tokens`).-* `scopes` is a subset of the caller's role — a `viewer` can only mint read-scoped tokens.-* Tokens are sent as `Authorization: Bearer xy_<id>_<secret>`. The server hashes the secret at write time; the row stores `sha256(secret)`, never the secret itself.+* `POST` (mint) and `DELETE` (revoke) require a passkey-backed browser session: the `xerj_session` cookie for a `.xerj_sessions` row with `idp: "passkey"`. `Authorization: Bearer <api token>` is `403` on both, including a valid token whose owner has a passkey enrolled. `GET` (metadata only, no secret) still accepts a bearer token. There is no `parent_id`: a bearer token is refused before any new row is written, so revoking a token cannot leave a working descendant minted from it (CVE-2026-97406, [CERT VU#645818](https://kb.cert.org/vuls/id/645818), published 2026-10-20). The same passkey-session rule applies to `POST /auth/magic/issue`, `DELETE /auth/passkeys/:id`, and `POST /auth/logout`.+* A browser session whose `idp` is not `passkey` (a future SSO session) is also `403` on these routes. Deleting the last passkey is refused (`409` — "cannot revoke your last passkey"). `store::revoke_api_tokens_for_user` exists and is not called from that path; the last-passkey refusal is what keeps an account from holding API tokens with no passkey.+* `scopes` is intended to be a subset of the caller's role — a `viewer` should only mint read-scoped tokens. The handler stores the `scopes` array it is given and does not check that subset today.+* Tokens are sent as `Authorization: Bearer <secret>`. The server hashes the secret at write time; the row's `_id` is `sha256(secret)`, never the secret itself. The secret is returned once, on `POST`.CLI binding: `xerj` reads a `XERJ_TOKEN` env var or `~/.xerj/credentials` for non-interactive contexts (CI, ops scripts, the runbook in `demo/`).