Skip to content

armgit / xerj

Public Imported from GitHub
0

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.

feat(console-auth): add POST /auth/magic/issue invite endpoint + harden recovery redeem

xerj-org545f1f1a3996
diff --git a/engine/crates/xerj-console-api/src/auth/magic.rs b/engine/crates/xerj-console-api/src/auth/magic.rs
index 14e69c356..ed6df65fe 100644
--- a/engine/crates/xerj-console-api/src/auth/magic.rs
+++ b/engine/crates/xerj-console-api/src/auth/magic.rs
@@ -1,4 +1,11 @@
-//! Magic-link redemption.
+//! Magic-link issue + redemption.
+//!
+//! `POST /auth/magic/issue { email, role }`
+//!
+//! An owner or admin mints a single-use invite link for `email`. If no
+//! user with that email exists yet a `pending` row is provisioned so the
+//! invitee flips to `active` once they enrol a passkey. The raw token is
+//! returned exactly once; only its `sha256` is persisted.
//!
//! `POST /auth/magic/redeem { token }`
//!
@@ -14,7 +21,7 @@ use rand::RngCore;
use serde::{Deserialize, Serialize};
use serde_json::json;
-use crate::auth::{audit, rate_limit, store};
+use crate::auth::{audit, rate_limit, store, AuthSession};
use crate::bootstrap::sha256_hex;
use crate::error::{ConsoleApiError, ConsoleResult};
use crate::indices;
@@ -23,6 +30,153 @@ use crate::state::{ConsoleState, EnrollmentSession};
use crate::time::{now_epoch_ms, now_iso, parse_iso};
const ENROLL_TTL_MS: i64 = 30 * 60 * 1000;
+/// How long an admin-issued invite link stays valid before it must be
+/// re-minted. Invites travel out-of-band (email/chat) so they get a much
+/// longer window than the in-session enrollment handoff.
+const INVITE_TTL_MS: i64 = 72 * 60 * 60 * 1000; // 72 hours
+/// Roles an operator is allowed to grant when issuing an invite. Anything
+/// outside this set is rejected rather than written verbatim into a user
+/// row, so a typo can't mint an unrecognised (and therefore unchecked)
+/// privilege string.
+const INVITE_ROLES: &[&str] = &["owner", "admin", "editor", "viewer"];
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Issue (admin-only invite minting)
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[derive(Debug, Deserialize)]
+pub struct IssueBody {
+ pub email: String,
+ pub role: String,
+}
+
+#[derive(Debug, Serialize)]
+pub struct IssueResponse {
+ /// The raw token — returned exactly once. Only its `sha256` is stored,
+ /// so this is the operator's single chance to hand it to the invitee.
+ pub token: String,
+ /// Host-relative setup link the operator can forward; the origin is
+ /// supplied by whatever server rendered the console.
+ pub link: String,
+ pub user_id: String,
+ pub email: String,
+ pub role: String,
+ pub purpose: String,
+ pub expires_at: String,
+}
+
+/// `POST /auth/magic/issue { email, role }` — an owner or admin mints a
+/// 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`).
+pub async fn issue(
+ State(state): State<ConsoleState>,
+ session: AuthSession,
+ headers: HeaderMap,
+ Json(body): Json<IssueBody>,
+) -> ConsoleResult<Response> {
+ // Only owners and admins may invite.
+ match session.user.role.as_str() {
+ "owner" | "admin" => {}
+ _ => {
+ return Err(ConsoleApiError::Forbidden(
+ "only an owner or admin may issue invites".into(),
+ ));
+ }
+ }
+
+ let email = body.email.trim().to_ascii_lowercase();
+ if email.is_empty() || !email.contains('@') {
+ return Err(ConsoleApiError::BadRequest(
+ "a valid email is required".into(),
+ ));
+ }
+ let role = body.role.trim();
+ if !INVITE_ROLES.contains(&role) {
+ return Err(ConsoleApiError::BadRequest(format!("unknown role: {role}")));
+ }
+ // Privilege ceiling: only an owner may grant the owner role, so an admin
+ // can't quietly mint a peer with more authority than themselves.
+ if role == "owner" && session.user.role != "owner" {
+ return Err(ConsoleApiError::Forbidden(
+ "only an owner may invite another owner".into(),
+ ));
+ }
+
+ // Provision or look up the invitee. Re-inviting an existing address reuses
+ // that row (and its current role) rather than duplicating the user or
+ // silently escalating them via the invite.
+ let now = now_iso();
+ let user = match store::find_user_by_email(&state.engine, &email).await? {
+ Some(u) => u,
+ None => {
+ let u = store::User {
+ id: uuid::Uuid::new_v4().to_string(),
+ email: email.clone(),
+ display_name: String::new(),
+ role: role.to_string(),
+ status: store::UserStatus::Pending,
+ created_at: now.clone(),
+ last_seen_at: None,
+ };
+ store::upsert_user(&state.engine, &u).await?;
+ u
+ }
+ };
+ let user_id = user.id;
+
+ // Mint a random 32-byte URL-safe token; persist only its sha256.
+ let mut token_bytes = [0u8; 32];
+ rand::thread_rng().fill_bytes(&mut token_bytes);
+ let token = base64::engine::general_purpose::URL_SAFE_NO_PAD.encode(token_bytes);
+ let token_hash = sha256_hex(token.as_bytes());
+
+ let now_ms = now_epoch_ms();
+ let expires_at = crate::time::epoch_ms_to_iso(now_ms + INVITE_TTL_MS);
+
+ let link = store::MagicLink {
+ id: token_hash.clone(),
+ purpose: "invite".to_string(),
+ user_id: Some(user_id.clone()),
+ email: Some(email.clone()),
+ role: role.to_string(),
+ created_by: session.user.id.clone(),
+ created_at: now,
+ expires_at: expires_at.clone(),
+ used_at: None,
+ };
+ store::put_magic_link(&state.engine, &link).await?;
+
+ let ip = ip_from_headers(&headers);
+ audit::record(
+ &state.engine,
+ &session.user.id,
+ "magic-issued",
+ indices::MAGIC_LINKS,
+ Some(&token_hash),
+ Some(&ip),
+ Some(json!({ "purpose": "invite", "invitee": user_id.clone(), "role": role })),
+ )
+ .await;
+
+ let setup_link = format!("/_xerj-console/setup#token={token}");
+ Ok(ok(
+ IssueResponse {
+ token,
+ link: setup_link,
+ user_id,
+ email,
+ role: role.to_string(),
+ purpose: "invite".to_string(),
+ expires_at,
+ },
+ None,
+ ))
+}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Redeem
+// ─────────────────────────────────────────────────────────────────────────────
#[derive(Debug, Deserialize)]
pub struct RedeemBody {
@@ -117,10 +271,21 @@ pub async fn redeem(
(uid, link.email.clone())
}
"recovery" => {
- // Reserved for v1.1 — same shape as invite.
+ // Same shape as invite: the account was provisioned when the
+ // link was minted. Harden the redemption identically — refuse
+ // if the target row vanished between mint and redeem so a
+ // leaked recovery link can never resurrect a deleted account
+ // (and thereby hand an attacker a fresh enrollment session for
+ // a user the admin already removed).
let uid = link.user_id.clone().ok_or_else(|| {
ConsoleApiError::Internal("recovery link without user_id".into())
})?;
+ if store::get_user(&state.engine, &uid).await?.is_none() {
+ audit_redeem_failed(&state, "recovery-user-gone", &ip);
+ return Err(ConsoleApiError::Unauthorized(
+ "invalid or expired link".into(),
+ ));
+ }
(uid, link.email.clone())
}
other => {
diff --git a/engine/crates/xerj-console-api/src/router.rs b/engine/crates/xerj-console-api/src/router.rs
index a3278c996..9842945cb 100644
--- a/engine/crates/xerj-console-api/src/router.rs
+++ b/engine/crates/xerj-console-api/src/router.rs
@@ -52,6 +52,11 @@ 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) ───────────────
+ .route(
+ "/_xerj-console/api/v1/auth/magic/issue",
+ post(auth::magic::issue),
+ )
.route(
"/_xerj-console/api/v1/auth/passkey/begin",
post(auth::passkey::begin),
@@ -141,6 +146,7 @@ pub fn known_routes() -> &'static [&'static str] {
"/_xerj-console/*rest",
"/_xerj-console/api/v1/cluster/info",
"/_xerj-console/api/v1/auth/magic/redeem",
+ "/_xerj-console/api/v1/auth/magic/issue",
"/_xerj-console/api/v1/auth/passkey/begin",
"/_xerj-console/api/v1/auth/passkey/finish",
"/_xerj-console/api/v1/auth/login/begin",
diff --git a/engine/crates/xerj-console-api/tests/phase2_auth_flow.rs b/engine/crates/xerj-console-api/tests/phase2_auth_flow.rs
index 945394c59..e4ea57b62 100644
--- a/engine/crates/xerj-console-api/tests/phase2_auth_flow.rs
+++ b/engine/crates/xerj-console-api/tests/phase2_auth_flow.rs
@@ -24,7 +24,11 @@ use serde_json::{json, Value};
use tempfile::TempDir;
use tower::ServiceExt;
use xerj_common::config::Config;
-use xerj_console_api::{state::ClusterMode, xerj_console_router, ConsoleState};
+use xerj_console_api::{
+ auth::{sessions, store},
+ state::ClusterMode,
+ xerj_console_router, ConsoleState,
+};
use xerj_engine::Engine;
async fn boot() -> (Engine, Router, TempDir, String) {
@@ -72,6 +76,54 @@ fn post_json(path: &str, body: Value) -> Request<Body> {
.unwrap()
}
+fn post_json_cookie(path: &str, body: Value, cookie: &str) -> Request<Body> {
+ Request::builder()
+ .method("POST")
+ .uri(path)
+ .header("content-type", "application/json")
+ .header("cookie", cookie)
+ .body(Body::from(body.to_string()))
+ .unwrap()
+}
+
+/// Boot a console with a single active user of the given role plus a signed
+/// session cookie for them, bypassing the WebAuthn dance the same way the
+/// phase-3 suite does. Returns the engine (for direct store assertions), the
+/// router, the cookie header value, and the temp dir (kept alive by the
+/// caller so the data dir isn't reaped mid-test).
+async fn boot_with_role(role: &str) -> (Engine, Router, String, TempDir) {
+ let dir = TempDir::new().unwrap();
+ let mut cfg = Config::default();
+ cfg.server.data_dir = dir.path().to_str().unwrap().to_string();
+ let engine = Engine::new(cfg).expect("engine");
+ let outcome = xerj_console_api::bootstrap::run(&engine, dir.path(), "http://localhost:9200")
+ .await
+ .expect("bootstrap");
+ let state = ConsoleState::new(
+ engine.clone(),
+ "local".into(),
+ outcome.master_key,
+ ClusterMode::Standalone,
+ );
+
+ let user = store::User {
+ id: format!("{role}-test"),
+ email: format!("{role}@example.com"),
+ display_name: role.to_string(),
+ role: role.to_string(),
+ status: store::UserStatus::Active,
+ created_at: xerj_console_api::time::now_iso(),
+ last_seen_at: Some(xerj_console_api::time::now_iso()),
+ };
+ store::upsert_user(&engine, &user).await.unwrap();
+ let (_session, signed) = sessions::mint_session(&state, &user.id, "passkey", None, None)
+ .await
+ .unwrap();
+ let cookie = format!("xerj_session={signed}");
+
+ (engine, xerj_console_router(state), cookie, dir)
+}
+
#[tokio::test]
async fn magic_redeem_with_bootstrap_token_returns_enrollment_session() {
let (_engine, router, _dir, token) = boot().await;
@@ -353,6 +405,7 @@ async fn known_routes_grew() {
assert!(routes.len() >= 10, "phase 2 must register 10+ routes");
for required in &[
"/_xerj-console/api/v1/auth/magic/redeem",
+ "/_xerj-console/api/v1/auth/magic/issue",
"/_xerj-console/api/v1/auth/passkey/begin",
"/_xerj-console/api/v1/auth/passkey/finish",
"/_xerj-console/api/v1/auth/login/begin",
@@ -364,3 +417,122 @@ async fn known_routes_grew() {
assert!(routes.contains(required), "missing route: {required}");
}
}
+
+// ─────────────────────────────────────────────────────────────────────────────
+// Magic-link issue (admin invite)
+// ─────────────────────────────────────────────────────────────────────────────
+
+#[tokio::test]
+async fn magic_issue_as_admin_provisions_pending_invitee_and_redeems() {
+ let (engine, router, cookie, _dir) = boot_with_role("admin").await;
+
+ // Admin mints an invite for a brand-new address.
+ let r = router
+ .clone()
+ .oneshot(post_json_cookie(
+ "/_xerj-console/api/v1/auth/magic/issue",
+ json!({ "email": "[email protected]", "role": "editor" }),
+ &cookie,
+ ))
+ .await
+ .unwrap();
+ let (status, body) = body_json(r).await;
+ assert_eq!(status, 200, "issue: {body}");
+ let token = body["data"]["token"].as_str().unwrap().to_string();
+ assert!(token.len() > 30, "token looks too short: {body}");
+ assert_eq!(body["data"]["role"], "editor");
+ assert_eq!(body["data"]["purpose"], "invite");
+ assert_eq!(body["data"]["email"], "[email protected]");
+ assert!(
+ body["data"]["link"]
+ .as_str()
+ .unwrap()
+ .contains("/setup#token="),
+ "issue must return a setup link: {body}"
+ );
+
+ // A *pending* invitee row now exists with the requested role.
+ let invitee = store::find_user_by_email(&engine, "[email protected]")
+ .await
+ .unwrap()
+ .expect("invitee must be provisioned");
+ assert_eq!(invitee.status, store::UserStatus::Pending);
+ assert_eq!(invitee.role, "editor");
+
+ // The freshly-issued token redeems into an enrollment session bound to
+ // the invited identity. (The invitee only flips to active once they
+ // finish enrolling a passkey, which needs a real authenticator, so this
+ // is as far as a server-only test can drive it.)
+ let r = router
+ .clone()
+ .oneshot(post_json(
+ "/_xerj-console/api/v1/auth/magic/redeem",
+ json!({ "token": token }),
+ ))
+ .await
+ .unwrap();
+ let (status, body) = body_json(r).await;
+ assert_eq!(status, 200, "redeem: {body}");
+ assert_eq!(body["data"]["role"], "editor");
+ assert_eq!(body["data"]["email"], "[email protected]");
+ assert!(
+ body["data"]["enrollment_session_id"]
+ .as_str()
+ .unwrap()
+ .len()
+ > 30
+ );
+
+ // Single-use: the invite cannot be redeemed a second time.
+ let r = router
+ .oneshot(post_json(
+ "/_xerj-console/api/v1/auth/magic/redeem",
+ json!({ "token": token }),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 401, "an issued invite must be single-use");
+}
+
+#[tokio::test]
+async fn magic_issue_requires_admin_or_owner() {
+ // An authenticated but under-privileged session must be forbidden.
+ let (_engine, router, cookie, _dir) = boot_with_role("viewer").await;
+ let r = router
+ .oneshot(post_json_cookie(
+ "/_xerj-console/api/v1/auth/magic/issue",
+ json!({ "email": "[email protected]", "role": "viewer" }),
+ &cookie,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 403, "a viewer must not be able to invite");
+}
+
+#[tokio::test]
+async fn magic_issue_admin_cannot_grant_owner() {
+ // Privilege ceiling: an admin cannot mint an owner-role invite.
+ let (_engine, router, cookie, _dir) = boot_with_role("admin").await;
+ let r = router
+ .oneshot(post_json_cookie(
+ "/_xerj-console/api/v1/auth/magic/issue",
+ json!({ "email": "[email protected]", "role": "owner" }),
+ &cookie,
+ ))
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 403, "admin must not be able to mint an owner");
+}
+
+#[tokio::test]
+async fn magic_issue_without_session_returns_401() {
+ let (_engine, router, _cookie, _dir) = boot_with_role("admin").await;
+ let r = router
+ .oneshot(post_json(
+ "/_xerj-console/api/v1/auth/magic/issue",
+ json!({ "email": "[email protected]", "role": "viewer" }),
+ ))
+ .await
+ .unwrap();
+ assert_eq!(r.status(), 401, "unauthenticated issue must be rejected");
+}