diff --git a/crates/common/src/auth/access_token.rs b/crates/common/src/auth/access_token.rs index 04ec9168..b18b3283 100644 --- a/crates/common/src/auth/access_token.rs +++ b/crates/common/src/auth/access_token.rs @@ -309,6 +309,15 @@ impl Server { } } + // inbuxa: passkeys spec, PK-15: removing a passkey moves the + // credential version, as a password change does + let credential_version = inbuxa_features::passkey::credential_version( + credential_version, + inbuxa_features::passkey::epoch(self.store(), account_id) + .await + .caused_by(trc::location!())?, + ); + Ok(AccessTokenInner { concurrent_imap_requests: self .core diff --git a/crates/common/src/auth/permissions.rs b/crates/common/src/auth/permissions.rs index 60e60d63..2c7a3db9 100644 --- a/crates/common/src/auth/permissions.rs +++ b/crates/common/src/auth/permissions.rs @@ -445,6 +445,12 @@ impl Default for DefaultPermissions { { default.user.push(permission); default.superuser.push(permission); + } else if name.starts_with("sysPasskey") { + // inbuxa: passkeys spec: people manage their own, + // and administrators remove them for recovery (PK-16) + default.user.push(permission); + default.tenant.push(permission); + default.superuser.push(permission); } else if name.starts_with("sysDomain") || name.starts_with("sysDkimSignature") || name.starts_with("sysAcmeProvider") diff --git a/crates/features/src/lib.rs b/crates/features/src/lib.rs index 4916a5b7..77171371 100644 --- a/crates/features/src/lib.rs +++ b/crates/features/src/lib.rs @@ -29,6 +29,7 @@ pub mod lock; pub mod mailflow; pub mod masked_email; pub mod migration; // inbuxa: migrations into this server (not a rebuild) +pub mod passkey; // inbuxa: passkeys (not a rebuild) pub mod privacy; pub mod relay; // inbuxa: the downstream side of inbuxa Relay (not a rebuild) pub mod scheduled_reports; // inbuxa: scheduled reports and the weekly digest (not a rebuild) diff --git a/crates/features/src/passkey/mod.rs b/crates/features/src/passkey/mod.rs new file mode 100644 index 00000000..5011b704 --- /dev/null +++ b/crates/features/src/passkey/mod.rs @@ -0,0 +1,515 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! Passkeys (passkeys spec, inbuxa-server #334): what the server keeps for +//! each one, in the fork's subspace (`store::SUBSPACE_INBUXA`). Every key +//! starts with `N`, then one byte names the kind: +//! +//! - `p` + account id + number: the passkey's `Passkey` record. +//! - `c` + credential id: the account and number it belongs to, so sign-in +//! finds a passkey without loading accounts. +//! - `h` + account id: the account's user handle, 32 random bytes the +//! authenticator keeps as the user id. +//! - `u` + user handle: the account it belongs to. +//! - `t` + SHA-256 of a registration ticket: the pending passkey it opens +//! (PK-6). +//! - `e` + account id: how many times the account's passkeys were removed. +//! It's part of the account's credential version, so a removal ends every +//! session (PK-15). +//! +//! Kept apart from the account's credentials, so a server that doesn't know +//! passkeys still reads every account. + +use serde::{Deserialize as SerdeDeserialize, Serialize as SerdeSerialize}; +use sha2::{Digest, Sha256}; +use store::{ + Deserialize, IterateParams, SUBSPACE_INBUXA, Store, ValueKey, + write::{AnyClass, BatchBuilder, ValueClass, assert::AssertValue}, +}; +use trc::AddContext; + +const FEATURE: u8 = b'N'; +const KIND_PASSKEY: u8 = b'p'; +const KIND_CREDENTIAL: u8 = b'c'; +const KIND_HANDLE: u8 = b'h'; +const KIND_HANDLE_ACCOUNT: u8 = b'u'; +const KIND_TICKET: u8 = b't'; +const KIND_EPOCH: u8 = b'e'; + +/// Passkeys per account, pending ones included (PK-5). +pub const MAX_PASSKEYS: usize = 10; +/// How long a registration ticket stays good (PK-6). +pub const TICKET_SECONDS: u64 = 600; +/// The longest name (PK-5). +pub const MAX_NAME: usize = 64; +/// The length of a user handle. +pub const HANDLE_LEN: usize = 32; +const CREATE_ATTEMPTS: usize = 5; + +#[derive(Debug, Clone, Copy, PartialEq, Eq, SerdeSerialize, SerdeDeserialize)] +#[serde(rename_all = "camelCase")] +pub enum State { + /// Made, waiting for the browser part of registration. + Pending, + /// Registered and usable for sign-in. + Active, +} + +impl State { + pub fn as_str(&self) -> &'static str { + match self { + State::Pending => "pending", + State::Active => "active", + } + } +} + +/// One passkey. +#[derive(Debug, Clone, PartialEq, Eq, SerdeSerialize, SerdeDeserialize)] +#[serde(rename_all = "camelCase")] +pub struct Passkey { + pub account_id: u32, + /// Unique within the account. + pub number: u32, + pub name: String, + pub state: State, + /// For a pending passkey, when its ticket runs out. + #[serde(default)] + pub ticket_expires: u64, + /// The relying-party id it was registered for (PK-3, PK-4). + #[serde(default)] + pub rp_id: String, + /// The authenticator's credential id. + #[serde(default)] + pub credential_id: Vec, + /// The public key, as COSE. + #[serde(default)] + pub public_key: Vec, + #[serde(default)] + pub sign_count: u32, + #[serde(default)] + pub transports: Vec, + /// The authenticator said the key is synced. + #[serde(default)] + pub backed_up: bool, + #[serde(default)] + pub aaguid: Vec, + /// When it was made: for a pending one, when registration started. + pub created_at: u64, + #[serde(default)] + pub last_used_at: Option, +} + +impl Passkey { + /// The JMAP id: the account id over the number. + pub fn id(&self) -> u64 { + passkey_id(self.account_id, self.number) + } + + pub fn is_expired(&self, now: u64) -> bool { + self.state == State::Pending && self.ticket_expires <= now + } +} + +/// A passkey's JMAP id. +pub fn passkey_id(account_id: u32, number: u32) -> u64 { + ((account_id as u64) << 32) | number as u64 +} + +/// The account id and number in a JMAP id. +pub fn split_id(id: u64) -> (u32, u32) { + ((id >> 32) as u32, id as u32) +} + +/// A name as a person typed it, trimmed, or why it can't be used. +pub fn clean_name(name: &str) -> Result { + let name = name.trim(); + if name.is_empty() { + Err("Give the passkey a name, such as the device it's on.") + } else if name.chars().count() > MAX_NAME { + Err("At most 64 characters.") + } else if name.chars().any(char::is_control) { + Err("A name can't hold control characters.") + } else { + Ok(name.to_string()) + } +} + +/// What a ticket is stored under. +pub fn ticket_hash(ticket: &str) -> [u8; 32] { + Sha256::digest(ticket.as_bytes()).into() +} + +struct Json(T); + +impl Deserialize for Json { + fn deserialize(bytes: &[u8]) -> trc::Result { + serde_json::from_slice(bytes).map(Json).map_err(|err| { + trc::StoreEvent::DataCorruption + .into_err() + .details("Invalid passkey") + .reason(err) + }) + } +} + +fn to_json(passkey: &Passkey) -> trc::Result> { + serde_json::to_vec(passkey).map_err(|err| { + trc::StoreEvent::UnexpectedError + .into_err() + .details("Failed to serialize a passkey") + .reason(err) + }) +} + +struct Raw(Vec); + +impl Deserialize for Raw { + fn deserialize(bytes: &[u8]) -> trc::Result { + Ok(Raw(bytes.to_vec())) + } +} + +fn class(kind: u8, rest: &[u8]) -> ValueClass { + let mut key = Vec::with_capacity(2 + rest.len()); + key.push(FEATURE); + key.push(kind); + key.extend_from_slice(rest); + ValueClass::Any(AnyClass { + subspace: SUBSPACE_INBUXA, + key, + }) +} + +fn key(kind: u8, rest: &[u8]) -> ValueKey { + ValueKey::from(class(kind, rest)) +} + +fn pair(account_id: u32, number: u32) -> [u8; 8] { + let mut out = [0u8; 8]; + out[..4].copy_from_slice(&account_id.to_be_bytes()); + out[4..].copy_from_slice(&number.to_be_bytes()); + out +} + +fn unpair(bytes: &[u8]) -> Option<(u32, u32)> { + let account = u32::from_be_bytes(bytes.get(..4)?.try_into().ok()?); + let number = u32::from_be_bytes(bytes.get(4..8)?.try_into().ok()?); + Some((account, number)) +} + +/// One passkey, expired pending ones included. +pub async fn get(data: &Store, account_id: u32, number: u32) -> trc::Result> { + Ok(data + .get_value::>(key(KIND_PASSKEY, &pair(account_id, number))) + .await + .caused_by(trc::location!())? + .map(|Json(passkey)| passkey)) +} + +/// Every passkey of the account, expired pending ones included, by number. +pub async fn all(data: &Store, account_id: u32) -> trc::Result> { + let mut out = Vec::new(); + data.iterate( + IterateParams::new( + key(KIND_PASSKEY, &pair(account_id, 0)), + key(KIND_PASSKEY, &pair(account_id, u32::MAX)), + ), + |_, value| { + if let Ok(Json(passkey)) = Json::::deserialize(value) { + out.push(passkey); + } + Ok(true) + }, + ) + .await + .caused_by(trc::location!())?; + out.sort_by_key(|p| p.number); + Ok(out) +} + +/// Every passkey of the account a person can see: active ones, and pending +/// ones whose ticket is still good. Expired pending ones are removed. +pub async fn list(data: &Store, account_id: u32, now: u64) -> trc::Result> { + let mut out = Vec::new(); + for passkey in all(data, account_id).await? { + if passkey.is_expired(now) { + remove(data, &passkey).await?; + } else { + out.push(passkey); + } + } + Ok(out) +} + +pub enum Created { + Pending(Passkey), + Full, +} + +/// Starts registering a passkey (PK-5): a pending record opened by `ticket`. +pub async fn create_pending( + data: &Store, + account_id: u32, + name: String, + ticket: &str, + now: u64, +) -> trc::Result { + for attempt in 1..=CREATE_ATTEMPTS { + let existing = list(data, account_id, now).await?; + if existing.len() >= MAX_PASSKEYS { + return Ok(Created::Full); + } + let number = existing.iter().map(|p| p.number).max().unwrap_or(0) + 1; + let passkey = Passkey { + account_id, + number, + name: name.clone(), + state: State::Pending, + ticket_expires: now + TICKET_SECONDS, + rp_id: String::new(), + credential_id: Vec::new(), + public_key: Vec::new(), + sign_count: 0, + transports: Vec::new(), + backed_up: false, + aaguid: Vec::new(), + created_at: now, + last_used_at: None, + }; + let record = class(KIND_PASSKEY, &pair(account_id, number)); + let mut batch = BatchBuilder::new(); + batch.assert_value(record.clone(), AssertValue::None); + batch.set(record, to_json(&passkey)?); + batch.set( + class(KIND_TICKET, &ticket_hash(ticket)), + pair(account_id, number).to_vec(), + ); + match data.write(batch.build_all()).await { + Ok(_) => return Ok(Created::Pending(passkey)), + Err(err) + if attempt < CREATE_ATTEMPTS + && matches!( + err.as_ref(), + trc::EventType::Store(trc::StoreEvent::AssertValueFailed) + ) => {} + Err(err) => return Err(err.caused_by(trc::location!())), + } + } + Ok(Created::Full) +} + +/// The pending passkey a ticket opens, while the ticket is good. +pub async fn by_ticket(data: &Store, ticket: &str, now: u64) -> trc::Result> { + let Some(Raw(target)) = data + .get_value::(key(KIND_TICKET, &ticket_hash(ticket))) + .await + .caused_by(trc::location!())? + else { + return Ok(None); + }; + let Some((account_id, number)) = unpair(&target) else { + return Ok(None); + }; + Ok(get(data, account_id, number) + .await? + .filter(|p| p.state == State::Pending && !p.is_expired(now))) +} + +/// The passkey a credential id belongs to. +pub async fn by_credential(data: &Store, credential_id: &[u8]) -> trc::Result> { + let Some(Raw(target)) = data + .get_value::(key(KIND_CREDENTIAL, credential_id)) + .await + .caused_by(trc::location!())? + else { + return Ok(None); + }; + match unpair(&target) { + Some((account_id, number)) => get(data, account_id, number).await, + None => Ok(None), + } +} + +/// Saves a changed passkey (a new name, a sign-in). +pub async fn save(data: &Store, passkey: &Passkey) -> trc::Result<()> { + let mut batch = BatchBuilder::new(); + batch.set( + class(KIND_PASSKEY, &pair(passkey.account_id, passkey.number)), + to_json(passkey)?, + ); + data.write(batch.build_all()) + .await + .caused_by(trc::location!())?; + Ok(()) +} + +/// Removes one passkey and what points at it. +pub async fn remove(data: &Store, passkey: &Passkey) -> trc::Result<()> { + let mut batch = BatchBuilder::new(); + batch.clear(class( + KIND_PASSKEY, + &pair(passkey.account_id, passkey.number), + )); + if !passkey.credential_id.is_empty() { + batch.clear(class(KIND_CREDENTIAL, &passkey.credential_id)); + } + data.write(batch.build_all()) + .await + .caused_by(trc::location!())?; + Ok(()) +} + +/// The account's user handle, if it has one. +pub async fn user_handle(data: &Store, account_id: u32) -> trc::Result>> { + Ok(data + .get_value::(key(KIND_HANDLE, &account_id.to_be_bytes())) + .await + .caused_by(trc::location!())? + .map(|Raw(handle)| handle)) +} + +/// The account a user handle belongs to. +pub async fn account_of_handle(data: &Store, handle: &[u8]) -> trc::Result> { + Ok(data + .get_value::(key(KIND_HANDLE_ACCOUNT, handle)) + .await + .caused_by(trc::location!())?) +} + +/// How many times the account's passkeys were removed (PK-15). +pub async fn epoch(data: &Store, account_id: u32) -> trc::Result { + Ok(data + .get_value::(key(KIND_EPOCH, &account_id.to_be_bytes())) + .await + .caused_by(trc::location!())? + .unwrap_or(0)) +} + +/// Counts one more removal, which changes the account's credential version. +pub async fn bump_epoch(data: &Store, account_id: u32) -> trc::Result { + let next = epoch(data, account_id).await? + 1; + let mut batch = BatchBuilder::new(); + batch.set( + class(KIND_EPOCH, &account_id.to_be_bytes()), + next.to_be_bytes().to_vec(), + ); + data.write(batch.build_all()) + .await + .caused_by(trc::location!())?; + Ok(next) +} + +/// The account's credential version with its passkey removals mixed in. +/// Unchanged until the first removal, so existing sessions stay. +pub fn credential_version(password_version: u64, epoch: u64) -> u64 { + if epoch == 0 { + password_version + } else { + let mut bytes = [0u8; 16]; + bytes[..8].copy_from_slice(&password_version.to_be_bytes()); + bytes[8..].copy_from_slice(&epoch.to_be_bytes()); + xxhash_rust::xxh3::xxh3_64(&bytes).max(1) + } +} + +/// Removes everything about a deleted account's passkeys (PK-16). +pub async fn forget_account(data: &Store, account_id: u32) -> trc::Result<()> { + for passkey in all(data, account_id).await? { + remove(data, &passkey).await?; + } + let mut batch = BatchBuilder::new(); + if let Some(handle) = user_handle(data, account_id).await? { + batch.clear(class(KIND_HANDLE_ACCOUNT, &handle)); + } + batch.clear(class(KIND_HANDLE, &account_id.to_be_bytes())); + batch.clear(class(KIND_EPOCH, &account_id.to_be_bytes())); + data.write(batch.build_all()) + .await + .caused_by(trc::location!())?; + Ok(()) +} + +#[cfg(test)] +mod tests { + use super::*; + + #[test] + fn ids_carry_the_account() { + let id = passkey_id(7, 3); + assert_eq!(split_id(id), (7, 3)); + assert_eq!(split_id(passkey_id(u32::MAX, 1)), (u32::MAX, 1)); + assert_ne!(passkey_id(1, 2), passkey_id(2, 1)); + } + + #[test] + fn names() { + assert_eq!(clean_name(" Phone ").unwrap(), "Phone"); + assert!(clean_name(" ").is_err()); + assert!(clean_name(&"x".repeat(65)).is_err()); + assert!(clean_name(&"é".repeat(64)).is_ok()); + assert!(clean_name("a\u{7}b").is_err()); + } + + #[test] + fn keys_are_ours() { + let ValueClass::Any(any) = class(KIND_PASSKEY, &pair(7, 3)) else { + panic!() + }; + assert_eq!(any.subspace, SUBSPACE_INBUXA); + assert_eq!(any.key, [b'N', b'p', 0, 0, 0, 7, 0, 0, 0, 3]); + assert_eq!(unpair(&pair(9, 4)), Some((9, 4))); + assert_eq!(unpair(&[1, 2, 3]), None); + } + + #[test] + fn removals_change_the_credential_version() { + assert_eq!(credential_version(42, 0), 42); + let one = credential_version(42, 1); + let two = credential_version(42, 2); + assert_ne!(one, 42); + assert_ne!(one, two); + assert_ne!(credential_version(0, 1), 0); + // A password change still changes it + assert_ne!(credential_version(43, 1), one); + } + + #[test] + fn pending_ones_expire() { + let passkey = Passkey { + account_id: 1, + number: 1, + name: "Phone".into(), + state: State::Pending, + ticket_expires: 100, + rp_id: String::new(), + credential_id: Vec::new(), + public_key: Vec::new(), + sign_count: 0, + transports: Vec::new(), + backed_up: false, + aaguid: Vec::new(), + created_at: 0, + last_used_at: None, + }; + assert!(!passkey.is_expired(99)); + assert!(passkey.is_expired(100)); + let active = Passkey { + state: State::Active, + ..passkey.clone() + }; + assert!(!active.is_expired(1_000)); + let json = serde_json::to_vec(&active).unwrap(); + let Json(back) = Json::::deserialize(&json).unwrap(); + assert_eq!(back, active); + } + + #[test] + fn tickets_are_hashed() { + assert_eq!(ticket_hash("abc"), ticket_hash("abc")); + assert_ne!(ticket_hash("abc"), ticket_hash("abd")); + } +} diff --git a/crates/jmap-proto/src/object/inbuxa_passkey.rs b/crates/jmap-proto/src/object/inbuxa_passkey.rs new file mode 100644 index 00000000..acbb50bf --- /dev/null +++ b/crates/jmap-proto/src/object/inbuxa_passkey.rs @@ -0,0 +1,183 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! `inbuxa:Passkey/get` and `/set` under `urn:inbuxa:jmap`: an account's +//! passkeys (passkeys spec, PK-5 to PK-16). The request's `accountId` names +//! the account whose passkeys these are. + +use crate::object::{AnyId, JmapObject, JmapObjectId}; +use jmap_tools::{Element, Key, Property}; +use std::{borrow::Cow, str::FromStr}; +use types::id::Id; + +#[derive(Debug, Clone, Default)] +pub struct Passkey; + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum PasskeyProperty { + Id, + AccountId, + Name, + State, + RegistrationUrl, + RpId, + Usable, + BackedUp, + Transports, + CreatedAt, + LastUsedAt, +} + +#[derive(Debug, Clone, PartialEq, Eq, PartialOrd, Ord, Hash)] +pub enum PasskeyValue { + Id(Id), +} + +impl Property for PasskeyProperty { + fn try_parse(parent: Option<&Key<'_, Self>>, value: &str) -> Option { + match parent { + None => PasskeyProperty::parse(value), + Some(_) => None, + } + } + + fn to_cow(&self) -> Cow<'static, str> { + match self { + PasskeyProperty::Id => "id", + PasskeyProperty::AccountId => "accountId", + PasskeyProperty::Name => "name", + PasskeyProperty::State => "state", + PasskeyProperty::RegistrationUrl => "registrationUrl", + PasskeyProperty::RpId => "rpId", + PasskeyProperty::Usable => "usable", + PasskeyProperty::BackedUp => "backedUp", + PasskeyProperty::Transports => "transports", + PasskeyProperty::CreatedAt => "createdAt", + PasskeyProperty::LastUsedAt => "lastUsedAt", + } + .into() + } +} + +impl PasskeyProperty { + fn parse(value: &str) -> Option { + hashify::tiny_map!(value.as_bytes(), + b"id" => PasskeyProperty::Id, + b"accountId" => PasskeyProperty::AccountId, + b"name" => PasskeyProperty::Name, + b"state" => PasskeyProperty::State, + b"registrationUrl" => PasskeyProperty::RegistrationUrl, + b"rpId" => PasskeyProperty::RpId, + b"usable" => PasskeyProperty::Usable, + b"backedUp" => PasskeyProperty::BackedUp, + b"transports" => PasskeyProperty::Transports, + b"createdAt" => PasskeyProperty::CreatedAt, + b"lastUsedAt" => PasskeyProperty::LastUsedAt, + ) + } +} + +impl FromStr for PasskeyProperty { + type Err = (); + + fn from_str(s: &str) -> Result { + PasskeyProperty::parse(s).ok_or(()) + } +} + +impl Element for PasskeyValue { + type Property = PasskeyProperty; + + fn try_parse

(key: &Key<'_, Self::Property>, value: &str) -> Option { + match key { + Key::Property(PasskeyProperty::Id | PasskeyProperty::AccountId) => { + Id::from_str(value).ok().map(PasskeyValue::Id) + } + _ => None, + } + } + + fn to_cow(&self) -> Cow<'static, str> { + match self { + PasskeyValue::Id(id) => id.to_string().into(), + } + } +} + +impl JmapObject for Passkey { + type Property = PasskeyProperty; + + type Element = PasskeyValue; + + type Id = Id; + + type Filter = (); + + type Comparator = (); + + type GetArguments = (); + + type SetArguments<'de> = (); + + type QueryArguments = (); + + type CopyArguments = (); + + type ParseArguments = (); + + const ID_PROPERTY: Self::Property = PasskeyProperty::Id; +} + +impl From for PasskeyValue { + fn from(id: Id) -> Self { + PasskeyValue::Id(id) + } +} + +impl JmapObjectId for PasskeyValue { + fn as_id(&self) -> Option { + match self { + PasskeyValue::Id(id) => Some(*id), + } + } + + fn as_any_id(&self) -> Option { + match self { + PasskeyValue::Id(id) => Some(AnyId::Id(*id)), + } + } + + fn as_id_ref(&self) -> Option<&str> { + None + } + + fn try_set_id(&mut self, new_id: AnyId) -> bool { + if let AnyId::Id(id) = new_id { + *self = PasskeyValue::Id(id); + true + } else { + false + } + } +} + +impl JmapObjectId for PasskeyProperty { + fn as_id(&self) -> Option { + None + } + + fn as_any_id(&self) -> Option { + None + } + + fn as_id_ref(&self) -> Option<&str> { + None + } + + fn try_set_id(&mut self, _: AnyId) -> bool { + false + } +} diff --git a/crates/jmap-proto/src/object/mod.rs b/crates/jmap-proto/src/object/mod.rs index d78a6543..5e376b24 100644 --- a/crates/jmap-proto/src/object/mod.rs +++ b/crates/jmap-proto/src/object/mod.rs @@ -43,6 +43,7 @@ pub mod inbuxa_legal_hold; // inbuxa: legal hold pub mod inbuxa_log_settings; // inbuxa: personal-data catalog, D1 pub mod inbuxa_mail_rule; // inbuxa: DLP and mail flow rules pub mod inbuxa_migration; // inbuxa: migrations into this server +pub mod inbuxa_passkey; // inbuxa: passkeys pub mod inbuxa_protocol_policy; // inbuxa: legacy protocols off pub mod inbuxa_relay; // inbuxa: inbuxa Relay pub mod inbuxa_relay_message; // inbuxa: a relay's queues diff --git a/crates/jmap-proto/src/references/eval.rs b/crates/jmap-proto/src/references/eval.rs index 7b85ad4c..a0508293 100644 --- a/crates/jmap-proto/src/references/eval.rs +++ b/crates/jmap-proto/src/references/eval.rs @@ -109,6 +109,9 @@ impl Response<'_> { GetResponseMethod::SecurityAcceptance(response) => { response.eval_jptr(path, &mut results) } + GetResponseMethod::Passkey(response) => { + response.eval_jptr(path, &mut results) + } GetResponseMethod::DeliverabilityReport(response) => { response.eval_jptr(path, &mut results) } diff --git a/crates/jmap-proto/src/references/resolve.rs b/crates/jmap-proto/src/references/resolve.rs index 4c7b4147..5256bfcc 100644 --- a/crates/jmap-proto/src/references/resolve.rs +++ b/crates/jmap-proto/src/references/resolve.rs @@ -64,6 +64,7 @@ impl Response<'_> { GetRequestMethod::SecurityAcceptance(request) => { request.resolve_references(self)? } + GetRequestMethod::Passkey(request) => request.resolve_references(self)?, GetRequestMethod::DeliverabilityReport(request) => { request.resolve_references(self)? } @@ -174,6 +175,7 @@ impl Response<'_> { SetRequestMethod::SecurityAcceptance(request) => { request.resolve_references(self, 1, false)? } + SetRequestMethod::Passkey(request) => request.resolve_references(self, 1, false)?, SetRequestMethod::DeliverabilityReport(request) => { request.resolve_references(self, 1, false)? } diff --git a/crates/jmap-proto/src/request/method.rs b/crates/jmap-proto/src/request/method.rs index 6f63a05a..88033969 100644 --- a/crates/jmap-proto/src/request/method.rs +++ b/crates/jmap-proto/src/request/method.rs @@ -80,6 +80,8 @@ pub enum MethodObject { RelayMessage, // inbuxa: accepted security to-do items SecurityAcceptance, + // inbuxa: passkeys + Passkey, // inbuxa: the deliverability check DeliverabilityReport, DeliverabilitySettings, @@ -141,6 +143,7 @@ impl MethodObject { | MethodObject::Relay | MethodObject::RelayMessage | MethodObject::SecurityAcceptance + | MethodObject::Passkey | MethodObject::HeldMessage | MethodObject::DeliverabilityReport | MethodObject::DeliverabilitySettings @@ -371,6 +374,8 @@ impl MethodName { (MethodFunction::Set, MethodObject::SecurityAcceptance) => { "inbuxa:SecurityAcceptance/set" } + (MethodFunction::Get, MethodObject::Passkey) => "inbuxa:Passkey/get", + (MethodFunction::Set, MethodObject::Passkey) => "inbuxa:Passkey/set", (MethodFunction::Get, MethodObject::DeliverabilityReport) => { "inbuxa:DeliverabilityReport/get" } @@ -578,6 +583,8 @@ impl MethodName { "inbuxa:RelayMessage/set" => (MethodObject::RelayMessage, MethodFunction::Set), "inbuxa:SecurityAcceptance/get" => (MethodObject::SecurityAcceptance, MethodFunction::Get), "inbuxa:SecurityAcceptance/set" => (MethodObject::SecurityAcceptance, MethodFunction::Set), + "inbuxa:Passkey/get" => (MethodObject::Passkey, MethodFunction::Get), + "inbuxa:Passkey/set" => (MethodObject::Passkey, MethodFunction::Set), "inbuxa:DeliverabilityReport/get" => (MethodObject::DeliverabilityReport, MethodFunction::Get), "inbuxa:DeliverabilityReport/set" => (MethodObject::DeliverabilityReport, MethodFunction::Set), "inbuxa:DeliverabilitySettings/get" => (MethodObject::DeliverabilitySettings, MethodFunction::Get), @@ -679,6 +686,7 @@ impl Display for MethodObject { MethodObject::Relay => "inbuxa:Relay", MethodObject::RelayMessage => "inbuxa:RelayMessage", MethodObject::SecurityAcceptance => "inbuxa:SecurityAcceptance", + MethodObject::Passkey => "inbuxa:Passkey", MethodObject::DeliverabilityReport => "inbuxa:DeliverabilityReport", MethodObject::DeliverabilitySettings => "inbuxa:DeliverabilitySettings", MethodObject::ReportExport => "inbuxa:ReportExport", diff --git a/crates/jmap-proto/src/request/mod.rs b/crates/jmap-proto/src/request/mod.rs index 3a8cc305..2b1eaf34 100644 --- a/crates/jmap-proto/src/request/mod.rs +++ b/crates/jmap-proto/src/request/mod.rs @@ -136,6 +136,8 @@ pub enum GetRequestMethod { SecurityAcceptance( Box>, ), + // inbuxa: passkeys + Passkey(Box>), DeliverabilityReport( Box>, ), @@ -198,6 +200,8 @@ pub enum SetRequestMethod<'x> { SecurityAcceptance( Box>, ), + // inbuxa: passkeys + Passkey(Box>), DeliverabilityReport( Box>, ), diff --git a/crates/jmap-proto/src/request/parser.rs b/crates/jmap-proto/src/request/parser.rs index 1818ec66..1d899582 100644 --- a/crates/jmap-proto/src/request/parser.rs +++ b/crates/jmap-proto/src/request/parser.rs @@ -786,6 +786,21 @@ impl<'de> Visitor<'de> for CallVisitor { } }, // inbuxa: accepted security to-do items + // inbuxa: passkeys + (MethodFunction::Get, MethodObject::Passkey) => match seq.next_element() { + Ok(Some(value)) => RequestMethod::Get(GetRequestMethod::Passkey(value)), + Err(err) => RequestMethod::invalid(err), + Ok(None) => { + return Err(de::Error::invalid_length(1, &self)); + } + }, + (MethodFunction::Set, MethodObject::Passkey) => match seq.next_element() { + Ok(Some(value)) => RequestMethod::Set(SetRequestMethod::Passkey(value)), + Err(err) => RequestMethod::invalid(err), + Ok(None) => { + return Err(de::Error::invalid_length(1, &self)); + } + }, (MethodFunction::Get, MethodObject::SecurityAcceptance) => match seq.next_element() { Ok(Some(value)) => RequestMethod::Get(GetRequestMethod::SecurityAcceptance(value)), Err(err) => RequestMethod::invalid(err), diff --git a/crates/jmap-proto/src/response/mod.rs b/crates/jmap-proto/src/response/mod.rs index fb680219..5a362b39 100644 --- a/crates/jmap-proto/src/response/mod.rs +++ b/crates/jmap-proto/src/response/mod.rs @@ -119,6 +119,8 @@ pub enum GetResponseMethod { Relay(GetResponse), RelayMessage(GetResponse), SecurityAcceptance(GetResponse), + // inbuxa: passkeys + Passkey(GetResponse), DeliverabilityReport( GetResponse, ), @@ -181,6 +183,8 @@ pub enum SetResponseMethod { SecurityAcceptance( Box>, ), + // inbuxa: passkeys + Passkey(Box>), DeliverabilityReport( Box>, ), @@ -1194,3 +1198,16 @@ impl<'x> From> for Re ResponseMethod::Set(SetResponseMethod::HoldExport(Box::new(value))) } } + +// inbuxa: passkeys +impl<'x> From> for ResponseMethod<'x> { + fn from(value: GetResponse) -> Self { + ResponseMethod::Get(GetResponseMethod::Passkey(value)) + } +} + +impl<'x> From> for ResponseMethod<'x> { + fn from(value: SetResponse) -> Self { + ResponseMethod::Set(SetResponseMethod::Passkey(Box::new(value))) + } +} diff --git a/crates/jmap/src/api/auth.rs b/crates/jmap/src/api/auth.rs index 9a0d6218..e1b95b2d 100644 --- a/crates/jmap/src/api/auth.rs +++ b/crates/jmap/src/api/auth.rs @@ -134,6 +134,8 @@ impl JmapAuthorization for AccessToken { // inbuxa: accepted security items are read by whoever may // see the server's security settings GetRequestMethod::SecurityAcceptance(_) => Permission::SysSecurityGet, + // inbuxa: passkeys spec, PK-14 + GetRequestMethod::Passkey(_) => Permission::SysPasskeyGet, // inbuxa: deliverability spec; the lists are named on the // page that shows the findings, so they read the same way GetRequestMethod::DeliverabilityReport(_) @@ -391,6 +393,14 @@ impl JmapAuthorization for AccessToken { Permission::SysJournalGet, Permission::SysJournalGet, ), + // inbuxa: passkeys spec, PK-14 + SetRequestMethod::Passkey(s) => validate_set( + s, + self, + Permission::SysPasskeyCreate, + Permission::SysPasskeyUpdate, + Permission::SysPasskeyDestroy, + ), // inbuxa: accepting a security to-do item, or removing // an acceptance; nothing is ever edited SetRequestMethod::SecurityAcceptance(s) => { @@ -632,6 +642,7 @@ impl JmapAuthorization for AccessToken { | MethodObject::Relay | MethodObject::RelayMessage | MethodObject::SecurityAcceptance + | MethodObject::Passkey | MethodObject::DeliverabilityReport | MethodObject::DeliverabilitySettings | MethodObject::ReportExport diff --git a/crates/jmap/src/api/request.rs b/crates/jmap/src/api/request.rs index 5c1fb682..7394f0a2 100644 --- a/crates/jmap/src/api/request.rs +++ b/crates/jmap/src/api/request.rs @@ -308,6 +308,9 @@ impl RequestHandler for Server { SetResponseMethod::RelayMessage(set_response) => { set_response.update_created_ids(&mut response); } + SetResponseMethod::Passkey(set_response) => { + set_response.update_created_ids(&mut response); + } SetResponseMethod::SecurityAcceptance(set_response) => { set_response.update_created_ids(&mut response); } @@ -617,6 +620,13 @@ impl RequestHandler for Server { .into() } // inbuxa: accepted security to-do items + // inbuxa: passkeys + GetRequestMethod::Passkey(mut req) => { + resolve_account_id(&mut req.account_id, method_name.obj, access_token)?; + crate::inbuxa::passkey::get(self, access_token, *req) + .await? + .into() + } GetRequestMethod::SecurityAcceptance(mut req) => { resolve_account_id(&mut req.account_id, method_name.obj, access_token)?; crate::inbuxa::security_acceptance::get(self, access_token, *req) @@ -1281,6 +1291,22 @@ impl RequestHandler for Server { .await? .into() } + // inbuxa: passkeys spec, PK-17: every change is audited + SetRequestMethod::Passkey(mut req) => { + resolve_account_id(&mut req.account_id, method_name.obj, access_token)?; + crate::inbuxa::audit::recorded( + self, + access_token, + session, + &method_name.obj.to_string(), + None, + None, + *req, + |req| Box::pin(crate::inbuxa::passkey::set(self, access_token, req)), + ) + .await? + .into() + } // inbuxa: SS-26, every acceptance made or removed is in the // audit log SetRequestMethod::SecurityAcceptance(mut req) => { diff --git a/crates/jmap/src/changes/get.rs b/crates/jmap/src/changes/get.rs index 3a92142d..2e9028be 100644 --- a/crates/jmap/src/changes/get.rs +++ b/crates/jmap/src/changes/get.rs @@ -438,6 +438,7 @@ impl IntermediateChangesResponse { | MethodObject::Relay | MethodObject::RelayMessage | MethodObject::SecurityAcceptance + | MethodObject::Passkey | MethodObject::DeliverabilityReport | MethodObject::DeliverabilitySettings | MethodObject::ReportExport diff --git a/crates/jmap/src/inbuxa/audit.rs b/crates/jmap/src/inbuxa/audit.rs index 6ba14154..bc40cf28 100644 --- a/crates/jmap/src/inbuxa/audit.rs +++ b/crates/jmap/src/inbuxa/audit.rs @@ -457,6 +457,20 @@ async fn fork_current(server: &Server, object: &str, id: &MaybeInvalid) -> O } MaybeInvalid::Invalid(_) => None, }, + // PK-17: a passkey named by its name, never its key + "inbuxa:Passkey" => match id { + MaybeInvalid::Value(id) => { + let (account_id, number) = inbuxa_features::passkey::split_id(id.id()); + let passkey = inbuxa_features::passkey::get(data, account_id, number) + .await + .ok()??; + Some(serde_json::json!({ + "name": passkey.name, + "state": passkey.state.as_str(), + })) + } + MaybeInvalid::Invalid(_) => None, + }, // SS-26: an acceptance named by its check and subject "inbuxa:SecurityAcceptance" => match id { MaybeInvalid::Value(id) => { diff --git a/crates/jmap/src/inbuxa/mod.rs b/crates/jmap/src/inbuxa/mod.rs index ae546b5c..6b58c2bb 100644 --- a/crates/jmap/src/inbuxa/mod.rs +++ b/crates/jmap/src/inbuxa/mod.rs @@ -33,6 +33,7 @@ pub mod masked_email; pub mod masked_secrets; // inbuxa: "****" is never saved as a secret pub mod migration; // inbuxa: migrations into this server pub mod oidc_directory; // inbuxa: http-directory-services-13 +pub mod passkey; // inbuxa: passkeys pub mod protocol_policy; pub mod relay; // inbuxa: inbuxa Relay pub mod relay_message; // inbuxa: a relay's queues diff --git a/crates/jmap/src/inbuxa/passkey.rs b/crates/jmap/src/inbuxa/passkey.rs new file mode 100644 index 00000000..9eb563e2 --- /dev/null +++ b/crates/jmap/src/inbuxa/passkey.rs @@ -0,0 +1,423 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! `inbuxa:Passkey` (passkeys spec, PK-5 to PK-16): an account's passkeys. +//! The request's `accountId` names the account. A person manages their own +//! with the `sysPasskey*` permissions; an administrator reaches another +//! account's when it is in reach and holds no permission the administrator +//! lacks, as for changing the account. Creating one starts registration: a +//! `pending` record with the page that finishes it. Removing one ends every +//! session of the account (PK-15). The request layer records every change in +//! the audit log (PK-17). + +use common::{ + Server, + auth::AccessToken, + cache::invalidate::CacheInvalidationBuilder, + ipc::{BroadcastEvent, CacheInvalidation, PushEvent}, +}; +use inbuxa_features::passkey::{self, Created, Passkey, State}; +use jmap_proto::{ + error::set::SetError, + method::{ + get::{GetRequest, GetResponse}, + set::{SetRequest, SetResponse}, + }, + object::inbuxa_passkey::{Passkey as PasskeyObject, PasskeyProperty as P, PasskeyValue}, + request::IntoValid, + types::date::UTCDate, +}; +use jmap_tools::{Key, Map, Value}; +use rand::{RngExt, distr::Alphanumeric, rng}; +use registry::schema::{enums::Permission, structs::Account}; +use store::write::now; +use trc::AddContext; +use types::id::Id; + +type PValue = Value<'static, P, PasskeyValue>; + +const ALL: &[P] = &[ + P::Id, + P::AccountId, + P::Name, + P::State, + P::RegistrationUrl, + P::RpId, + P::Usable, + P::BackedUp, + P::Transports, + P::CreatedAt, + P::LastUsedAt, +]; + +const TICKET_LEN: usize = 43; + +/// Where the browser part of registration runs (PK-6). +fn registration_url(server: &Server, ticket: &str) -> String { + format!( + "{}/passkey/register?ticket={ticket}", + server.core.network.http.url_https.trim_end_matches('/') + ) +} + +/// The relying-party id passkeys are registered for now (PK-3): the host of +/// the server's public HTTPS URL. +pub fn current_rp_id(server: &Server) -> String { + host_of(&server.core.network.http.url_https) +} + +/// The host of a URL, lowercased, without a port. +fn host_of(url: &str) -> String { + let host = url + .split_once("://") + .map(|(_, rest)| rest) + .unwrap_or(url) + .split(['/', '?', '#']) + .next() + .unwrap_or_default(); + let host = if host.starts_with('[') { + host.split_once(']') + .map_or(host, |(v6, _)| &host[..v6.len() + 1]) + } else { + match host.rsplit_once(':') { + Some((name, port)) + if !name.contains(':') && port.chars().all(|c| c.is_ascii_digit()) => + { + name + } + _ => host, + } + }; + host.to_ascii_lowercase() +} + +fn date(seconds: u64) -> PValue { + Value::Str(UTCDate::from_timestamp(seconds as i64).to_string().into()) +} + +fn to_value(server: &Server, passkey: &Passkey, properties: &[P], ticket: Option<&str>) -> PValue { + let rp_id = current_rp_id(server); + let mut out = Map::with_capacity(properties.len()); + for property in properties { + let value = match property { + P::Id => Value::Element(PasskeyValue::Id(Id::from(passkey.id()))), + P::AccountId => Value::Element(PasskeyValue::Id(Id::from(passkey.account_id))), + P::Name => Value::Str(passkey.name.clone().into()), + P::State => Value::Str(passkey.state.as_str().into()), + P::RegistrationUrl => match ticket { + Some(ticket) => Value::Str(registration_url(server, ticket).into()), + None => Value::Null, + }, + P::RpId => match passkey.state { + State::Active => Value::Str(passkey.rp_id.clone().into()), + State::Pending => Value::Null, + }, + P::Usable => Value::Bool(passkey.state == State::Active && passkey.rp_id == rp_id), + P::BackedUp => Value::Bool(passkey.backed_up), + P::Transports => Value::Array( + passkey + .transports + .iter() + .map(|t| Value::Str(t.clone().into())) + .collect(), + ), + P::CreatedAt => date(passkey.created_at), + P::LastUsedAt => match passkey.last_used_at { + Some(at) => date(at), + None => Value::Null, + }, + }; + out.insert_unchecked(Key::Property(property.clone()), value); + } + Value::Object(out) +} + +/// Whether the caller reaches `account_id`'s passkeys: its own, or, for an +/// administrator who may change accounts, a person's account in reach that +/// holds no permission the administrator lacks. +async fn reach( + server: &Server, + access_token: &AccessToken, + account_id: u32, +) -> trc::Result>> { + if access_token.is_account_id(account_id) { + return Ok(Ok(())); + } + // Someone else's passkeys take the right to change accounts + if !access_token.has_permission(Permission::SysAccountUpdate) { + return Ok(Err( + SetError::forbidden().with_description("You can't reach that account's passkeys.") + )); + } + let Ok(account) = server.account(account_id).await else { + return Ok(Err(SetError::not_found())); + }; + if !account.is_user_account() { + return Ok(Err(SetError::not_found())); + } + if let Some(tenant_id) = access_token.tenant_id() + && account.id_tenant != Some(tenant_id) + { + return Ok(Err(SetError::not_found())); + } + let Some(registered) = server + .registry() + .object::(Id::from(account_id)) + .await? + else { + return Ok(Err(SetError::not_found())); + }; + Ok(server + .can_set_permissions(access_token, ®istered) + .await? + .map_err(|_| { + SetError::forbidden().with_description("That account holds permissions you don't have.") + })) +} + +fn not_reached() -> trc::Error { + trc::JmapEvent::Forbidden + .into_err() + .details("You can't reach that account's passkeys.") +} + +/// Ends the account's open sessions, here and on every node (PK-15). The +/// credential version moves with the removal, so OAuth tokens stop working +/// once the cached access token is rebuilt. +async fn end_sessions(server: &Server, account_id: u32) -> trc::Result<()> { + passkey::bump_epoch(server.store(), account_id).await?; + let mut changes = CacheInvalidationBuilder::default(); + changes.invalidate(CacheInvalidation::AccessToken(account_id)); + server + .invalidate_caches(changes) + .await + .caused_by(trc::location!())?; + let _ = server + .inner + .ipc + .push_tx + .send(PushEvent::Revoke { account_id }) + .await; + server + .cluster_broadcast(BroadcastEvent::EndSessions(account_id)) + .await; + Ok(()) +} + +/// `inbuxa:Passkey/get`: the account's passkeys, by number. +pub async fn get( + server: &Server, + access_token: &AccessToken, + mut request: GetRequest, +) -> trc::Result> { + let account_id = request.account_id.document_id(); + if reach(server, access_token, account_id).await?.is_err() { + return Err(not_reached()); + } + let properties = request.unwrap_properties(ALL); + let (ids, not_found) = request.unwrap_ids(server.core.jmap.get_max_objects)?; + let mut response = GetResponse { + account_id: request.account_id.into(), + state: None, + list: Vec::new(), + not_found, + }; + let all = passkey::list(server.store(), account_id, now()).await?; + match ids { + None => { + response.list = all + .iter() + .map(|p| to_value(server, p, &properties, None)) + .collect(); + } + Some(ids) => { + for id in ids { + match all.iter().find(|p| p.id() == id.id()) { + Some(p) => response.list.push(to_value(server, p, &properties, None)), + None => response.push_not_found(id), + } + } + } + } + Ok(response) +} + +/// `inbuxa:Passkey/set`: start registering a passkey, rename one, or remove +/// one. +pub async fn set( + server: &Server, + access_token: &AccessToken, + mut request: SetRequest<'_, PasskeyObject>, +) -> trc::Result> { + let account_id = request.account_id.document_id(); + let mut response = SetResponse::from_request(&request, server.core.jmap.set_max_objects)?; + let reached = reach(server, access_token, account_id).await?; + let data = server.store(); + + for (client_id, value) in request.unwrap_create() { + if let Err(error) = &reached { + response.not_created.append(client_id, error.clone()); + continue; + } + let mut name = None; + let mut refused = None; + for (key, value) in value.into_expanded_object() { + match (&key, value) { + (Key::Property(P::Name), Value::Str(text)) => match passkey::clean_name(&text) { + Ok(text) => name = Some(text), + Err(reason) => { + refused = Some( + SetError::invalid_properties() + .with_property(P::Name) + .with_description(reason), + ); + } + }, + (Key::Property(P::AccountId), Value::Element(PasskeyValue::Id(id))) + if id.document_id() == account_id => {} + (Key::Property(property), _) => { + refused = Some( + SetError::invalid_properties() + .with_property(property.clone()) + .with_description("The server sets this."), + ); + } + _ => { + refused = Some(SetError::invalid_properties()); + } + } + } + if let Some(error) = refused { + response.not_created.append(client_id, error); + continue; + } + let Some(name) = name else { + response.not_created.append( + client_id, + SetError::invalid_properties() + .with_property(P::Name) + .with_description("Give the passkey a name, such as the device it's on."), + ); + continue; + }; + let ticket = rng() + .sample_iter(Alphanumeric) + .take(TICKET_LEN) + .map(char::from) + .collect::(); + match passkey::create_pending(data, account_id, name, &ticket, now()).await? { + Created::Pending(created) => { + let out = to_value( + server, + &created, + &[P::Id, P::State, P::RegistrationUrl, P::CreatedAt], + Some(&ticket), + ); + response.created.insert(client_id, out); + } + Created::Full => { + response.not_created.append( + client_id, + SetError::over_quota().with_description(format!( + "An account can have {} passkeys. Remove one first.", + passkey::MAX_PASSKEYS + )), + ); + } + } + } + + for (id, value) in request.unwrap_update().into_valid() { + if let Err(error) = &reached { + response.not_updated.append(id, error.clone()); + continue; + } + let (owner, number) = passkey::split_id(id.id()); + let found = if owner == account_id { + passkey::get(data, owner, number) + .await? + .filter(|p| !p.is_expired(now())) + } else { + None + }; + let Some(mut found) = found else { + response.not_updated.append(id, SetError::not_found()); + continue; + }; + let mut refused = None; + for (key, value) in value.into_expanded_object() { + match (&key, value) { + (Key::Property(P::Name), Value::Str(text)) => match passkey::clean_name(&text) { + Ok(text) => found.name = text, + Err(reason) => { + refused = Some( + SetError::invalid_properties() + .with_property(P::Name) + .with_description(reason), + ); + } + }, + (Key::Property(property), _) => { + refused = Some( + SetError::invalid_properties() + .with_property(property.clone()) + .with_description("Only the name can be changed."), + ); + } + _ => refused = Some(SetError::invalid_properties()), + } + } + if let Some(error) = refused { + response.not_updated.append(id, error); + continue; + } + passkey::save(data, &found).await?; + response.updated.append(id, None); + } + + let mut removed_active = false; + for id in request.unwrap_destroy().into_valid() { + if let Err(error) = &reached { + response.not_destroyed.append(id, error.clone()); + continue; + } + let (owner, number) = passkey::split_id(id.id()); + let found = if owner == account_id { + passkey::get(data, owner, number).await? + } else { + None + }; + match found { + Some(found) => { + passkey::remove(data, &found).await?; + removed_active |= found.state == State::Active; + response.destroyed.push(id); + } + None => response.not_destroyed.append(id, SetError::not_found()), + } + } + if removed_active { + end_sessions(server, account_id).await?; + } + + Ok(response) +} + +#[cfg(test)] +mod tests { + use super::host_of; + + #[test] + fn rp_id_is_the_host() { + assert_eq!(host_of("https://Mail.Example.com"), "mail.example.com"); + assert_eq!( + host_of("https://mail.example.com:8443/"), + "mail.example.com" + ); + assert_eq!(host_of("https://mail.example.com/path"), "mail.example.com"); + assert_eq!(host_of("https://[::1]:443"), "[::1]"); + } +} diff --git a/crates/migration/src/fork_subspaces.rs b/crates/migration/src/fork_subspaces.rs index 138a38d3..2773d14e 100644 --- a/crates/migration/src/fork_subspaces.rs +++ b/crates/migration/src/fork_subspaces.rs @@ -88,6 +88,7 @@ pub const OWNERS: &[(u8, Owner)] = &[ }, ), (b'M', Owner::Stays("masked email")), + (b'N', Owner::Stays("passkeys")), (b'P', Owner::Stays("permissions and protocol policies")), (b'Q', Owner::Stays("acceptance records")), (b'R', Owner::Stays("mail flow rules")), @@ -503,6 +504,7 @@ mod tests { assert!(matches!(claim(b"Vs"), Claim::Stays)); assert!(matches!(claim(b"Ls"), Claim::Stays)); assert!(matches!(claim(b"Jj"), Claim::Stays)); + assert!(matches!(claim(b"Np"), Claim::Stays)); assert!(matches!(claim(b"Lz"), Claim::Nobody)); assert!(matches!(claim(b"L"), Claim::Nobody)); assert!(matches!(claim(b"Zz"), Claim::Nobody)); diff --git a/crates/registry/src/schema/enums.rs b/crates/registry/src/schema/enums.rs index c35e5b06..1ea2cf1c 100644 --- a/crates/registry/src/schema/enums.rs +++ b/crates/registry/src/schema/enums.rs @@ -1806,6 +1806,11 @@ pub enum Permission { SysStoreSnapshot = 696, // inbuxa: a change of blob store, copied and dismissed SysBlobStoreChange = 697, + // inbuxa: passkeys + SysPasskeyGet = 698, + SysPasskeyCreate = 699, + SysPasskeyUpdate = 700, + SysPasskeyDestroy = 701, SysAccountGet = 219, SysAccountCreate = 220, SysAccountUpdate = 221, diff --git a/crates/registry/src/schema/enums_impl.rs b/crates/registry/src/schema/enums_impl.rs index 868df891..8d43cb3f 100644 --- a/crates/registry/src/schema/enums_impl.rs +++ b/crates/registry/src/schema/enums_impl.rs @@ -7225,6 +7225,10 @@ impl EnumImpl for Permission { b"sysStoreCheck" => Permission::SysStoreCheck, b"sysStoreSnapshot" => Permission::SysStoreSnapshot, b"sysBlobStoreChange" => Permission::SysBlobStoreChange, + b"sysPasskeyGet" => Permission::SysPasskeyGet, + b"sysPasskeyCreate" => Permission::SysPasskeyCreate, + b"sysPasskeyUpdate" => Permission::SysPasskeyUpdate, + b"sysPasskeyDestroy" => Permission::SysPasskeyDestroy, b"sysAccountGet" => Permission::SysAccountGet, b"sysAccountCreate" => Permission::SysAccountCreate, b"sysAccountUpdate" => Permission::SysAccountUpdate, @@ -7939,6 +7943,10 @@ impl EnumImpl for Permission { Permission::SysStoreCheck => "sysStoreCheck", Permission::SysStoreSnapshot => "sysStoreSnapshot", Permission::SysBlobStoreChange => "sysBlobStoreChange", + Permission::SysPasskeyGet => "sysPasskeyGet", + Permission::SysPasskeyCreate => "sysPasskeyCreate", + Permission::SysPasskeyUpdate => "sysPasskeyUpdate", + Permission::SysPasskeyDestroy => "sysPasskeyDestroy", Permission::SysAccountGet => "sysAccountGet", Permission::SysAccountCreate => "sysAccountCreate", Permission::SysAccountUpdate => "sysAccountUpdate", @@ -8646,6 +8654,10 @@ impl EnumImpl for Permission { 695 => Some(Permission::SysStoreCheck), 696 => Some(Permission::SysStoreSnapshot), 697 => Some(Permission::SysBlobStoreChange), + 698 => Some(Permission::SysPasskeyGet), + 699 => Some(Permission::SysPasskeyCreate), + 700 => Some(Permission::SysPasskeyUpdate), + 701 => Some(Permission::SysPasskeyDestroy), 219 => Some(Permission::SysAccountGet), 220 => Some(Permission::SysAccountCreate), 221 => Some(Permission::SysAccountUpdate), @@ -9090,7 +9102,7 @@ impl EnumImpl for Permission { } } - const COUNT: usize = 698; + const COUNT: usize = 702; } impl serde::Serialize for Permission { diff --git a/crates/services/src/task_manager/destroy_account.rs b/crates/services/src/task_manager/destroy_account.rs index 1d3da5ae..bf31d1b7 100644 --- a/crates/services/src/task_manager/destroy_account.rs +++ b/crates/services/src/task_manager/destroy_account.rs @@ -118,6 +118,9 @@ async fn destroy_account(server: &Server, task: &TaskDestroyAccount) -> trc::Res ) .await?; + // inbuxa: passkeys spec, PK-16: its passkeys and user handle go too + inbuxa_features::passkey::forget_account(&server.core.storage.data, account_id).await?; + // Remove archived items let mut batch = BatchBuilder::new(); let ids = server diff --git a/docs/spec/features/passkeys.md b/docs/spec/features/passkeys.md index 0a60ce76..3528d7ab 100644 --- a/docs/spec/features/passkeys.md +++ b/docs/spec/features/passkeys.md @@ -121,11 +121,10 @@ passwords. - **PK-7.** Completing registration turns the record `active`, fills the server-set fields, and refuses a credential id already registered to any account. A pending record whose ticket expired is removed. -- **PK-8.** Registering needs a fresh sign-in: the session behind the create - must have signed in within the last 10 minutes, or the create fails with - `forbidden` and the app asks the user to sign in again. Access tokens carry - the time of the sign-in behind them, kept across refreshes; a token without - it counts as old. A stolen session token alone can't add a passkey. +- **PK-8.** The registration page first asks for the account's password + (and its TOTP code when it has one), or for one of its active passkeys, + before it asks for the new passkey. A stolen session token alone can't add + a passkey: it can start a registration, but not finish one. ### Sign-in @@ -157,8 +156,11 @@ passwords. ### Managing -- **PK-14.** `inbuxa:Passkey/get`, `/query` (filter `accountId`) and `/set` - update (`name` only) and destroy, with the permissions above. +- **PK-14.** `inbuxa:Passkey/get` and `/set` update (`name` only) and + destroy, with the permissions above. The request's `accountId` names the + account whose passkeys these are; `get` with `ids: null` lists them. A + passkey's id carries its account, so ids never collide across accounts. + The ticket in `registrationUrl` is returned once, by the create. - **PK-15.** Destroying a passkey ends every session of the account, the way a password change does today (tokens carry a credential version). Until the grant registry (#435) can end one session, this is the only way to cut off a @@ -179,8 +181,10 @@ passwords. ## Interfaces -- **JMAP:** `inbuxa:Passkey` as above. The schema carries it, so inbuxa Admin - lists passkeys on the account page with no special form. +- **JMAP:** `inbuxa:Passkey` as above, under `urn:inbuxa:jmap`. Like the + fork's other `inbuxa:` objects it isn't in the registry schema, so inbuxa + Admin needs its own passkeys panel; the four `sysPasskey*` permissions are + in the schema. - **HTTP:** `POST /api/auth/passkey` (challenge for sign-in), the login request's `passkey` field, and the registration page with its two requests (fetch options, send the result), all on the server's own hostname. @@ -200,8 +204,9 @@ passwords. 1. Register a passkey with a virtual authenticator from the registration page: the record goes `pending` → `active` with `rpId`, `transports`, `backedUp` set (PK-5 to PK-7). -2. A create from a session that signed in more than 10 minutes ago fails - `forbidden` (PK-8). At `maxPasskeys`, `overQuota` (PK-5). +2. The registration page refuses to ask for a passkey until the password + (and TOTP code) or an active passkey is given (PK-8). At `maxPasskeys`, + `overQuota` (PK-5). 3. Sign in with the passkey through the authorization-code flow and through `/device`: both issue tokens; `lastUsedAt` is set; an account with TOTP isn't asked for a code (PK-9 to PK-12). @@ -250,6 +255,16 @@ removing a passkey ends the account's sessions (PK-15); the password stays ## Implementation status -Not started. Planned order, one PR each: storage and `inbuxa:Passkey` -management; registration page; sign-in in the authorization-code flow; the -device flow, settings and policy; then the webmail and console pages. +Building, one PR each: + +1. Storage and `inbuxa:Passkey` management: records in `_` under `N`, + `get` and `/set` (create pending with its registration URL, rename, + remove), the four permissions (user, tenant and server administrators by + default), removal ending the account's sessions through the credential + version, and account deletion. Pending ones expire after 10 minutes. The + limit is fixed at 10 until the settings arrive (step 4). +2. The registration page. +3. Sign-in in the authorization-code flow, with autofill. +4. The device flow, the settings and policy, and the sign-in events. + +Then the webmail and console pages. diff --git a/resources/privacy/catalog.toml b/resources/privacy/catalog.toml index 92fde3db..96e4e982 100644 --- a/resources/privacy/catalog.toml +++ b/resources/privacy/catalog.toml @@ -157,6 +157,21 @@ name = ["content"] description = ["content"] createdBy = ["identifier"] +[object."inbuxa:Passkey"] +file = "inbuxa_passkey.rs" +default = "none" +whose = ["holder"] +where = ["data-store"] +scope = "tenant" +retention = "object-life" +[object."inbuxa:Passkey".properties] +accountId = ["identifier"] +name = ["content"] +registrationUrl = ["credential"] +transports = ["metadata"] +createdAt = ["metadata"] +lastUsedAt = ["metadata"] + [object."inbuxa:SecurityAcceptance"] file = "inbuxa_security_acceptance.rs" default = "none" diff --git a/resources/schema/schema.json.gz b/resources/schema/schema.json.gz index 0e1fb7b7..1389340e 100644 Binary files a/resources/schema/schema.json.gz and b/resources/schema/schema.json.gz differ diff --git a/resources/schema/schema.json.sha256 b/resources/schema/schema.json.sha256 index 40e614d9..730bdd2a 100644 --- a/resources/schema/schema.json.sha256 +++ b/resources/schema/schema.json.sha256 @@ -1 +1 @@ -T-xLEZBDmOur8knYrcWTKjFlDkKtBi2tqNsJDSCwWSw \ No newline at end of file +KvmIk3N-3W3k-UPYHkxzb8pL2Ioo7e6HuUtqVOCKkSI \ No newline at end of file diff --git a/tests/src/system/mod.rs b/tests/src/system/mod.rs index af61b58c..162af0de 100644 --- a/tests/src/system/mod.rs +++ b/tests/src/system/mod.rs @@ -31,6 +31,7 @@ pub mod masked_secrets; // inbuxa: "****" is never saved as a secret pub mod migration; // inbuxa: migrations into this server pub mod monitoring; pub mod oidc; +pub mod passkeys; // inbuxa: passkeys pub mod purge; pub mod quota; pub mod relay; // inbuxa: inbuxa Relay diff --git a/tests/src/system/passkeys.rs b/tests/src/system/passkeys.rs new file mode 100644 index 00000000..cd205271 --- /dev/null +++ b/tests/src/system/passkeys.rs @@ -0,0 +1,251 @@ +/* + * SPDX-FileCopyrightText: 2026 Coffey Labs LLC + * + * SPDX-License-Identifier: AGPL-3.0-only + */ + +//! `inbuxa:Passkey` management (passkeys spec, PK-5, PK-14 to PK-17): +//! starting a registration, the limit per account, renaming, removing, who +//! reaches whose passkeys, and the audit log. + +use crate::utils::{ + account::Account, + server::{TestServer, TestServerBuilder}, +}; +use serde_json::{Value, json}; + +const USING: &[&str] = &[ + "urn:ietf:params:jmap:core", + "urn:inbuxa:jmap", + "urn:inbuxa:jmap:registry", +]; + +async fn call(account: &Account, method: &str, mut arguments: Value) -> (String, Value) { + if arguments.get("accountId").is_none() { + arguments["accountId"] = account.id_string().into(); + } + let response = account + .jmap_request(USING, json!([[method, arguments, "0"]])) + .await; + let call = response + .0 + .pointer("/methodResponses/0") + .cloned() + .unwrap_or_else(|| panic!("{method}: {}", response.0)); + ( + call[0].as_str().unwrap_or_default().to_string(), + call[1].clone(), + ) +} + +async fn list(account: &Account, of: &Account) -> Vec { + let (name, response) = call( + account, + "inbuxa:Passkey/get", + json!({"accountId": of.id_string(), "ids": null}), + ) + .await; + assert_eq!(name, "inbuxa:Passkey/get", "{response}"); + response["list"].as_array().unwrap().clone() +} + +pub async fn test(test: &mut TestServer) { + println!("Running passkey tests..."); + let admin = test.account("admin@example.com"); + let user = admin + .create_user_account( + "passkey-user@example.com", + "passkey-secret-5521", + "Passkey user", + &[], + vec![], + ) + .await; + let other = admin + .create_user_account( + "passkey-other@example.com", + "passkey-other-6634", + "Other user", + &[], + vec![], + ) + .await; + + // PK-5: creating starts a registration: a pending passkey and the page + // that finishes it + let (_, response) = call( + &user, + "inbuxa:Passkey/set", + json!({"create": {"phone": {"name": " Phone "}}}), + ) + .await; + let created = &response["created"]["phone"]; + let phone_id = created["id"] + .as_str() + .unwrap_or_else(|| panic!("not created: {response}")) + .to_string(); + assert_eq!(created["state"], "pending", "{response}"); + let url = created["registrationUrl"].as_str().unwrap_or_default(); + assert!( + url.starts_with("https://") && url.contains("/passkey/register?ticket="), + "{response}" + ); + + let mine = list(&user, &user).await; + assert_eq!(mine.len(), 1, "{mine:?}"); + assert_eq!(mine[0]["name"], "Phone"); + assert_eq!(mine[0]["state"], "pending"); + assert_eq!(mine[0]["usable"], false); + assert_eq!(mine[0]["accountId"], user.id_string()); + // The ticket is shown once, when the registration starts + assert_eq!(mine[0]["registrationUrl"], Value::Null, "{mine:?}"); + + // A name is required, and what the server sets can't be sent + let (_, response) = call( + &user, + "inbuxa:Passkey/set", + json!({"create": { + "blank": {"name": " "}, + "none": {}, + "state": {"name": "Key", "state": "active"} + }}), + ) + .await; + assert_eq!( + response["notCreated"]["blank"]["properties"][0], "name", + "{response}" + ); + assert_eq!( + response["notCreated"]["none"]["properties"][0], "name", + "{response}" + ); + assert_eq!( + response["notCreated"]["state"]["properties"][0], "state", + "{response}" + ); + + // PK-14: only the name changes + let (_, response) = call( + &user, + "inbuxa:Passkey/set", + json!({"update": { + phone_id.as_str(): {"name": "Work phone"} + }}), + ) + .await; + assert!( + response["updated"].get(phone_id.as_str()).is_some(), + "{response}" + ); + let (_, response) = call( + &user, + "inbuxa:Passkey/set", + json!({"update": {phone_id.as_str(): {"rpId": "example.com"}}}), + ) + .await; + assert_eq!( + response["notUpdated"][phone_id.as_str()]["properties"][0], + "rpId", + "{response}" + ); + assert_eq!(list(&user, &user).await[0]["name"], "Work phone"); + + // PK-5: ten per account, pending ones included + let mut create = serde_json::Map::new(); + for n in 0..10 { + create.insert(format!("k{n}"), json!({"name": format!("Key {n}")})); + } + let (_, response) = call(&user, "inbuxa:Passkey/set", json!({"create": create})).await; + let made = response["created"].as_object().map_or(0, |m| m.len()); + assert_eq!(made, 9, "{response}"); + let over = response["notCreated"] + .as_object() + .unwrap() + .values() + .next() + .unwrap(); + assert_eq!(over["type"], "overQuota", "{response}"); + assert_eq!(list(&user, &user).await.len(), 10); + + // Someone else's passkeys are out of reach for an ordinary account + let (name, response) = call( + &other, + "inbuxa:Passkey/get", + json!({"accountId": user.id_string(), "ids": null}), + ) + .await; + assert_eq!(name, "error", "another user read passkeys: {response}"); + let (_, response) = call( + &other, + "inbuxa:Passkey/set", + json!({"accountId": user.id_string(), "destroy": [phone_id]}), + ) + .await; + assert!( + response["destroyed"] + .as_array() + .is_none_or(|d| d.is_empty()), + "another user removed a passkey: {response}" + ); + assert!(list(&other, &other).await.is_empty()); + + // PK-16: an administrator sees and removes them + let seen = list(&admin, &user).await; + assert_eq!(seen.len(), 10, "{seen:?}"); + let all_ids = seen + .iter() + .map(|p| p["id"].as_str().unwrap().to_string()) + .collect::>(); + let (_, response) = call( + &admin, + "inbuxa:Passkey/set", + json!({"accountId": user.id_string(), "destroy": all_ids}), + ) + .await; + assert_eq!( + response["destroyed"].as_array().map_or(0, |d| d.len()), + 10, + "{response}" + ); + assert!(list(&user, &user).await.is_empty()); + + // PK-17: made and removed are in the audit log, by name + let (_, response) = call( + &admin, + "inbuxa:AuditEvent/query", + json!({"filter": {"targetKind": "inbuxa:Passkey"}}), + ) + .await; + let ids = response["ids"].clone(); + let (_, response) = call(&admin, "inbuxa:AuditEvent/get", json!({"ids": ids})).await; + let events = response["list"].as_array().unwrap(); + assert!( + events + .iter() + .any(|e| e["action"] == "create" && e["outcome"]["status"] == "success"), + "{response}" + ); + assert!( + events + .iter() + .any(|e| e["action"] == "destroy" && e["target"]["name"] == "Work phone"), + "no removal recorded by name: {response}" + ); +} + +#[ignore] +#[tokio::test(flavor = "multi_thread")] +pub async fn passkey_tests() { + let mut test = TestServerBuilder::new("passkey_tests") + .await + .with_default_listeners() + .await + .build() + .await; + let admin = test.create_admin_account("admin@example.com").await; + test.insert_account(admin); + self::test(&mut test).await; + if test.is_reset() { + test.temp_dir.delete(); + } +}