From 7764569cf37cd23c0469439cd9f9d74e4b8df45d Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 19:48:06 -0600 Subject: [PATCH 1/3] Add pending identity state and door denial --- pkgs/idp-provider/src/doors.rs | 20 +++- pkgs/idp-provider/src/identities.rs | 153 ++++++++++++++++++++++++++-- pkgs/idp-provider/tests/doors.rs | 69 +++++++++++++ 3 files changed, 232 insertions(+), 10 deletions(-) diff --git a/pkgs/idp-provider/src/doors.rs b/pkgs/idp-provider/src/doors.rs index 7ad9da5c67..a34493833b 100644 --- a/pkgs/idp-provider/src/doors.rs +++ b/pkgs/idp-provider/src/doors.rs @@ -435,12 +435,24 @@ pub async fn door_callback( ); } - // Link state (#13415): active proceeds; unlinked is denied (an - // operator's unlink is never silently undone); never-seen is - // linked by this login, with the event in the identity history - // and the audit record. + // Link state (#13415/#13972): active proceeds; pending is denied + // without issuing a code; unlinked is denied (an operator's unlink + // is never silently undone); never-seen is linked by this login, + // with the event in the identity history and the audit record. match flow.identities.status(&name, &subject) { Ok(Some(ref s)) if s == "active" => {} + Ok(Some(ref s)) if s == "pending" => { + return denied( + flow, + &endpoint(&name), + "identity_pending", + &client_id, + &identity_key, + StatusCode::FORBIDDEN, + "access_denied", + "identity is registered and awaiting approval", + ); + } Ok(Some(_)) => { return denied( flow, diff --git a/pkgs/idp-provider/src/identities.rs b/pkgs/idp-provider/src/identities.rs index e83909e7c1..19cce02fda 100644 --- a/pkgs/idp-provider/src/identities.rs +++ b/pkgs/idp-provider/src/identities.rs @@ -7,10 +7,12 @@ //! every transition must be remembered. This store is that state: //! //! - `identities` — one row per (provider, subject): status -//! (`active` | `unlinked`), link/unlink timestamps. Rows are never +//! (`active` | `pending` | `unlinked`), link/unlink timestamps, +//! and pending-claim provenance. Rows are never //! hard-deleted while the account lives; unlinking flips status. //! - `identity_events` — append-only history (`seed` | `link` | -//! `relink` | `unlink`), protected by the same no-UPDATE / +//! `relink` | `unlink` | `register` | `approve` | `reject` | +//! `provision`), protected by the same no-UPDATE / //! no-DELETE triggers as the audit table, so the continuity of //! who-was-linked-when survives every later change. //! @@ -18,7 +20,7 @@ //! configured identity that the store has never seen is inserted as //! active with a `seed` event. After that the store is authoritative. -use rusqlite::Connection; +use rusqlite::{Connection, OptionalExtension}; use std::path::Path; use std::sync::Mutex; @@ -27,15 +29,17 @@ pub struct IdentityRow { pub provider: String, pub subject: String, pub account_id: String, - pub status: String, // "active" | "unlinked" + pub status: String, // "active" | "pending" | "unlinked" pub linked_at: i64, pub unlinked_at: Option, + pub claimed_via: Option, + pub claimed_at: Option, } #[derive(Clone, Debug, PartialEq, Eq)] pub struct IdentityEvent { pub ts_unix: i64, - pub event: String, // "seed" | "link" | "relink" | "unlink" + pub event: String, // seed | link | relink | unlink | register | approve | reject | provision pub provider: String, pub subject: String, pub account_id: String, @@ -76,6 +80,8 @@ impl IdentityStore { status TEXT NOT NULL, linked_at INTEGER NOT NULL, unlinked_at INTEGER, + claimed_via TEXT, + claimed_at INTEGER, PRIMARY KEY (provider, subject) ); CREATE TABLE IF NOT EXISTS identity_events ( @@ -97,6 +103,27 @@ impl IdentityStore { END;", ) .map_err(|e| format!("failed to initialise identity schema: {e}"))?; + // Existing runtime databases predate pending claims. Keep this + // migration additive so restarts preserve their rows. + for (column, declaration) in [("claimed_via", "TEXT"), ("claimed_at", "INTEGER")] { + let exists: bool = conn + .prepare("PRAGMA table_info(identities)") + .and_then(|mut stmt| { + stmt.query_map([], |row| row.get::<_, String>("name")) + .and_then(|rows| { + rows.collect::, _>>() + .map(|names| names.iter().any(|name| name == column)) + }) + }) + .map_err(|e| format!("failed to inspect identity schema: {e}"))?; + if !exists { + conn.execute( + &format!("ALTER TABLE identities ADD COLUMN {column} {declaration}"), + [], + ) + .map_err(|e| format!("failed to migrate identity schema: {e}"))?; + } + } Ok(IdentityStore { conn: Mutex::new(conn), }) @@ -197,6 +224,118 @@ impl IdentityStore { matches!(self.status(provider, subject), Ok(Some(ref s)) if s == "active") } + /// Register a previously unseen identity as pending. Claim provenance + /// and its timestamp remain on the row after approval or rejection. + pub fn register_pending( + &self, + provider: &str, + subject: &str, + account_id: &str, + claimed_via: &str, + ) -> Result { + let mut conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let tx = conn + .transaction() + .map_err(|e| format!("identity registration transaction failed: {e}"))?; + let now = crate::registry::now_unix(); + let inserted = tx + .execute( + "INSERT OR IGNORE INTO identities + (provider, subject, account_id, status, linked_at, unlinked_at, claimed_via, claimed_at) + VALUES (?1, ?2, ?3, 'pending', ?4, NULL, ?5, ?4)", + rusqlite::params![provider, subject, account_id, now, claimed_via], + ) + .map_err(|e| format!("pending identity registration failed: {e}"))?; + if inserted == 1 { + Self::record_event(&tx, "register", provider, subject, account_id, claimed_via)?; + } + tx.commit() + .map_err(|e| format!("identity registration commit failed: {e}"))?; + Ok(inserted == 1) + } + + pub fn approve_pending( + &self, + provider: &str, + subject: &str, + actor: &str, + ) -> Result { + self.transition_pending(provider, subject, "active", "approve", actor) + } + + pub fn reject_pending( + &self, + provider: &str, + subject: &str, + actor: &str, + ) -> Result { + self.transition_pending(provider, subject, "unlinked", "reject", actor) + } + + fn transition_pending( + &self, + provider: &str, + subject: &str, + status: &str, + event: &str, + actor: &str, + ) -> Result { + let mut conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let tx = conn + .transaction() + .map_err(|e| format!("identity transition transaction failed: {e}"))?; + let account_id: Option = tx + .query_row( + "SELECT account_id FROM identities WHERE provider = ?1 AND subject = ?2 AND status = 'pending'", + rusqlite::params![provider, subject], + |row| row.get(0), + ) + .optional() + .map_err(|e| format!("pending identity lookup failed: {e}"))?; + let Some(account_id) = account_id else { + return Ok(false); + }; + let now = crate::registry::now_unix(); + tx.execute( + "UPDATE identities SET status = ?1, linked_at = ?2, + unlinked_at = CASE WHEN ?1 = 'unlinked' THEN ?2 ELSE NULL END + WHERE provider = ?3 AND subject = ?4 AND status = 'pending'", + rusqlite::params![status, now, provider, subject], + ) + .map_err(|e| format!("pending identity transition failed: {e}"))?; + Self::record_event(&tx, event, provider, subject, &account_id, actor)?; + tx.commit() + .map_err(|e| format!("identity transition commit failed: {e}"))?; + Ok(true) + } + + /// Record the identity established as part of provisioning. Account + /// creation itself is deliberately outside this store. + pub fn record_provision( + &self, + provider: &str, + subject: &str, + account_id: &str, + actor: &str, + ) -> Result<(), String> { + let mut conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; + let tx = conn + .transaction() + .map_err(|e| format!("identity provision transaction failed: {e}"))?; + let now = crate::registry::now_unix(); + tx.execute( + "INSERT INTO identities + (provider, subject, account_id, status, linked_at, unlinked_at, claimed_via, claimed_at) + VALUES (?1, ?2, ?3, 'active', ?4, NULL, NULL, NULL)", + rusqlite::params![provider, subject, account_id, now], + ) + .map_err(|e| format!("provisioned identity insert failed: {e}"))?; + Self::record_event(&tx, "provision", provider, subject, account_id, actor)?; + tx.commit() + .map_err(|e| format!("identity provision commit failed: {e}"))?; + Ok(()) + } + /// Link an identity to the account. Returns the event recorded: /// `"link"` (first time), `"relink"` (was unlinked), or `"none"` /// (already active — no event written). @@ -312,7 +451,7 @@ impl IdentityStore { let conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; let mut stmt = conn .prepare( - "SELECT provider, subject, account_id, status, linked_at, unlinked_at + "SELECT provider, subject, account_id, status, linked_at, unlinked_at, claimed_via, claimed_at FROM identities ORDER BY provider, subject", ) .map_err(|e| format!("identity list query failed: {e}"))?; @@ -325,6 +464,8 @@ impl IdentityStore { status: row.get(3)?, linked_at: row.get(4)?, unlinked_at: row.get(5)?, + claimed_via: row.get(6)?, + claimed_at: row.get(7)?, }) }) .map_err(|e| format!("identity list query failed: {e}"))?; diff --git a/pkgs/idp-provider/tests/doors.rs b/pkgs/idp-provider/tests/doors.rs index dff1dea15b..2996f896ec 100644 --- a/pkgs/idp-provider/tests/doors.rs +++ b/pkgs/idp-provider/tests/doors.rs @@ -555,6 +555,75 @@ async fn google_door_full_loop_links_and_reaches_same_account() { assert_eq!(link_events, 1, "link recorded once"); } +#[tokio::test] +async fn pending_identity_is_acknowledged_without_issuing_a_code() { + let h = harness().await; + assert!(h + .identities + .register_pending("google", GOOGLE_SUB, "drew", "email-match") + .unwrap()); + + let resp = drive_door(&h, "google").await; + assert_eq!(resp.status(), StatusCode::FORBIDDEN); + assert!( + location(&resp).is_empty(), + "pending login must not redirect with a code" + ); + assert!(audit_has( + &h, + "door/google", + "denied", + "identity_pending", + &format!("google:{GOOGLE_SUB}") + )); + assert_eq!( + h.identities + .status("google", GOOGLE_SUB) + .unwrap() + .as_deref(), + Some("pending") + ); + assert_eq!(h.identities.events().unwrap()[0].event, "register"); +} + +#[test] +fn identity_history_records_pending_disposition_and_provisioning_events() { + let store = IdentityStore::open(None).unwrap(); + assert!(store + .register_pending("google", "approved-sub", "drew", "session-add") + .unwrap()); + assert!(store + .approve_pending("google", "approved-sub", "established-session") + .unwrap()); + assert!(store + .register_pending("microsoft", "rejected-sub", "drew", "email-match") + .unwrap()); + assert!(store + .reject_pending("microsoft", "rejected-sub", "established-session") + .unwrap()); + store + .record_provision("github", "new-sub", "new-account", "provisioner") + .unwrap(); + + let events = store.events().unwrap(); + assert_eq!( + events + .iter() + .map(|event| event.event.as_str()) + .collect::>(), + ["register", "approve", "register", "reject", "provision"] + ); + let approved = store + .list() + .unwrap() + .into_iter() + .find(|row| row.subject == "approved-sub") + .unwrap(); + assert_eq!(approved.status, "active"); + assert_eq!(approved.claimed_via.as_deref(), Some("session-add")); + assert!(approved.claimed_at.is_some()); +} + #[tokio::test] async fn github_door_full_loop_reaches_same_account() { let h = harness().await; From 7ed78b6631159d0bf62d60f71eb77bb555d7543a Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 19:51:44 -0600 Subject: [PATCH 2/3] Document pending identity status and actors --- pkgs/idp-provider/src/identities.rs | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/pkgs/idp-provider/src/identities.rs b/pkgs/idp-provider/src/identities.rs index 19cce02fda..6db9e1c205 100644 --- a/pkgs/idp-provider/src/identities.rs +++ b/pkgs/idp-provider/src/identities.rs @@ -43,7 +43,7 @@ pub struct IdentityEvent { pub provider: String, pub subject: String, pub account_id: String, - pub actor: String, // "config-seed" | "door-login" | "operator-cli" + pub actor: String, // e.g. config-seed, door-login, operator-cli, established-session } pub struct IdentityStore { @@ -197,7 +197,7 @@ impl IdentityStore { } /// Current link status of an identity: `Some("active")`, - /// `Some("unlinked")`, or `None` if the store has never seen it. + /// `Some("pending")`, `Some("unlinked")`, or `None` if unseen. pub fn status(&self, provider: &str, subject: &str) -> Result, String> { let conn = self.conn.lock().map_err(|_| "identity lock poisoned")?; let mut stmt = conn From 76530ecbc9355d177c1fbdcddade1f584220e899 Mon Sep 17 00:00:00 2001 From: Drewry Pope Date: Mon, 23 Nov 2026 19:57:26 -0600 Subject: [PATCH 3/3] Check pending register event without relying on seed order --- pkgs/idp-provider/tests/doors.rs | 7 ++++++- 1 file changed, 6 insertions(+), 1 deletion(-) diff --git a/pkgs/idp-provider/tests/doors.rs b/pkgs/idp-provider/tests/doors.rs index 2996f896ec..a9ea21d6c3 100644 --- a/pkgs/idp-provider/tests/doors.rs +++ b/pkgs/idp-provider/tests/doors.rs @@ -583,7 +583,12 @@ async fn pending_identity_is_acknowledged_without_issuing_a_code() { .as_deref(), Some("pending") ); - assert_eq!(h.identities.events().unwrap()[0].event, "register"); + assert!(h + .identities + .events() + .unwrap() + .iter() + .any(|e| e.event == "register")); } #[test]