diff --git a/Cargo.lock b/Cargo.lock index 105a657d..46c5d2e3 100644 --- a/Cargo.lock +++ b/Cargo.lock @@ -4596,6 +4596,7 @@ dependencies = [ "mail-parser", "nlp", "p256 0.13.2", + "psl", "rand 0.10.3", "registry", "reqwest 0.13.5", diff --git a/crates/features/src/passkey/mod.rs b/crates/features/src/passkey/mod.rs index dbea9802..25493bb5 100644 --- a/crates/features/src/passkey/mod.rs +++ b/crates/features/src/passkey/mod.rs @@ -39,7 +39,8 @@ 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). +/// Passkeys per account, pending ones included, unless `maxPasskeys` says +/// otherwise (PK-5). pub const MAX_PASSKEYS: usize = 10; /// How long a registration ticket stays good (PK-6). pub const TICKET_SECONDS: u64 = 600; @@ -251,17 +252,19 @@ pub enum Created { Full, } -/// Starts registering a passkey (PK-5): a pending record opened by `ticket`. +/// Starts registering a passkey (PK-5): a pending record opened by `ticket`, +/// while the account has fewer than `max`. pub async fn create_pending( data: &Store, account_id: u32, name: String, ticket: &str, now: u64, + max: usize, ) -> trc::Result { for attempt in 1..=CREATE_ATTEMPTS { let existing = list(data, account_id, now).await?; - if existing.len() >= MAX_PASSKEYS { + if existing.len() >= max { return Ok(Created::Full); } let number = existing.iter().map(|p| p.number).max().unwrap_or(0) + 1; diff --git a/crates/http/src/auth/oauth/auth.rs b/crates/http/src/auth/oauth/auth.rs index 679da598..cabba2b0 100644 --- a/crates/http/src/auth/oauth/auth.rs +++ b/crates/http/src/auth/oauth/auth.rs @@ -129,12 +129,18 @@ pub enum LoginRequest { }, #[serde(rename_all = "camelCase")] AuthDevice { + // inbuxa: empty when a passkey signs in + #[serde(default)] account_name: String, + #[serde(default)] account_secret: String, #[serde(skip_serializing_if = "Option::is_none")] #[serde(default)] mfa_token: Option, code: String, + // inbuxa: passkeys spec, PK-9: an assertion in place of the password + #[serde(default, skip_serializing_if = "Option::is_none")] + passkey: Option, }, } @@ -408,6 +414,7 @@ impl OAuthApiHandler for Server { account_secret, mfa_token, code, + passkey, } => { // Obtain code let mut result = LoginResponse::Failure; @@ -423,19 +430,25 @@ impl OAuthApiHandler for Server { .unarchive::() .caused_by(trc::location!())?; if oauth.status == OAuthStatus::Pending { - // Authenticate - match self - .authenticate(&AuthRequest { - credentials: Credentials::Basic { - username: account_name, - secret: account_secret, - mfa_token, - }, - session_id: session.session_id, - remote_ip: session.remote_ip, - }) - .await - { + // Authenticate (inbuxa: or a passkey, PK-9) + let authenticated = match &passkey { + Some(assertion) => { + crate::auth::passkey::sign_in(self, session, assertion).await + } + None => { + self.authenticate(&AuthRequest { + credentials: Credentials::Basic { + username: account_name, + secret: account_secret, + mfa_token, + }, + session_id: session.session_id, + remote_ip: session.remote_ip, + }) + .await + } + }; + match authenticated { Ok(access_token) => { let new_oauth_code = OAuthCode { status: OAuthStatus::Authorized, diff --git a/crates/http/src/auth/passkey.rs b/crates/http/src/auth/passkey.rs index 61d7a344..a74f9cbf 100644 --- a/crates/http/src/auth/passkey.rs +++ b/crates/http/src/auth/passkey.rs @@ -36,7 +36,8 @@ use directory::Credentials; use http_proto::{HttpResponse, HttpSessionData, JsonResponse, ToHttpResponse}; use inbuxa_features::audit::Via; use inbuxa_features::passkey::{self, Activated, HANDLE_LEN, Passkey}; -use registry::schema::enums::Permission; +use jmap::inbuxa::passkey::{allowed_for, settings}; +use registry::schema::{enums::Permission, structs::Authentication}; use serde::{Deserialize, Serialize}; use store::{ dispatch::lookup::KeyValue, @@ -122,10 +123,14 @@ struct Ceremony { state: PasskeyRegistration, } -/// The WebAuthn relying party for this server (PK-3): the host of its public -/// HTTPS URL, which is also the only origin it accepts. -pub fn relying_party(server: &Server) -> trc::Result<(Webauthn, String)> { - let rp_id = jmap::inbuxa::passkey::current_rp_id(server); +/// The WebAuthn relying party for this server (PK-3): `passkeyRpId` or the +/// host of its public HTTPS URL. That URL is the only origin it accepts +/// (PK-2). +pub fn relying_party( + server: &Server, + settings: &Authentication, +) -> trc::Result<(Webauthn, String)> { + let rp_id = jmap::inbuxa::passkey::current_rp_id(server, settings); let origin = Url::parse(&server.core.network.http.url_https).map_err(|err| { trc::AuthEvent::Error .into_err() @@ -137,12 +142,18 @@ pub fn relying_party(server: &Server) -> trc::Result<(Webauthn, String)> { .map_err(|err| { trc::AuthEvent::Error .into_err() - .details("Passkeys need the server's public URL to name a host.") + .details("Passkeys need the server's public URL to name a host within the relying-party id.") .reason(err) })?; Ok((webauthn, rp_id)) } +fn turned_off() -> RegisterResponse { + RegisterResponse::Refused { + reason: "Passkeys are turned off for this account.".to_string(), + } +} + fn ceremony_key(ticket: &str) -> Vec { let mut key = vec![b'r']; key.extend_from_slice(&passkey::ticket_hash(ticket)); @@ -173,7 +184,12 @@ struct ChallengeResponse { /// options name no credentials: the browser offers the passkeys it holds for /// this relying party. pub async fn challenge(server: &Server) -> trc::Result { - let (webauthn, rp_id) = relying_party(server)?; + // PK-9: offered when they're allowed server-wide + let settings = settings(server).await?; + if !settings.passkeys_allowed { + return Err(trc::ResourceEvent::NotFound.into_err()); + } + let (webauthn, rp_id) = relying_party(server, &settings)?; let (options, state) = webauthn .start_discoverable_authentication() .map_err(|err| { @@ -261,7 +277,10 @@ pub async fn sign_in( .into_err() .ctx(trc::Key::RemoteIp, session.remote_ip)) } else { - Err(err.ctx(trc::Key::RemoteIp, session.remote_ip)) + // PK-18: auth.failed, told apart from a password by its type + Err(err + .ctx(trc::Key::RemoteIp, session.remote_ip) + .ctx(trc::Key::Type, "passkey")) } } } @@ -291,7 +310,8 @@ async fn check_assertion( .details("Invalid passkey sign-in") .reason(err) })?; - let (webauthn, rp_id) = relying_party(server)?; + let settings = settings(server).await?; + let (webauthn, rp_id) = relying_party(server, &settings)?; if rp_id != ceremony.rp_id { return Err(refused("The relying-party id changed during sign-in")); } @@ -313,6 +333,11 @@ async fn check_assertion( return Err(refused("The passkey belongs to another account") .ctx(trc::Key::AccountId, record.account_id)); } + // PK-12, PK-13: switched off for the account, or its directory signs it in + if !allowed_for(server, &settings, record.account_id).await? { + return Err(refused("Passkeys are turned off for this account") + .ctx(trc::Key::AccountId, record.account_id)); + } // PK-4: a passkey works only for the relying-party id it was made for if record.rp_id != rp_id { return Err( @@ -336,12 +361,13 @@ async fn check_assertion( ) { Ok(result) => result, Err(WebauthnError::CredentialPossibleCompromise) => { + // PK-18 trc::event!( - Auth(trc::AuthEvent::Failed), + Auth(trc::AuthEvent::PasskeyCounter), AccountId = record.account_id, Id = passkey::passkey_id(record.account_id, record.number), SpanId = session.session_id, - Details = "Passkey counter went backwards: the passkey may be cloned", + Details = "The passkey may have been copied", ); return Err(refused("Passkey counter went backwards") .ctx(trc::Key::AccountId, record.account_id)); @@ -416,6 +442,11 @@ async fn start( let Some(pending) = passkey::by_ticket(server.store(), ticket, now()).await? else { return Ok(RegisterResponse::Expired); }; + // PK-12, PK-13 + let settings = settings(server).await?; + if !allowed_for(server, &settings, pending.account_id).await? { + return Ok(turned_off()); + } let account = server .account(pending.account_id) .await @@ -463,7 +494,7 @@ async fn start( return Ok(RegisterResponse::Failure); } - let (webauthn, rp_id) = relying_party(server)?; + let (webauthn, rp_id) = relying_party(server, &settings)?; let fresh = rng().random::<[u8; HANDLE_LEN]>(); let handle = passkey::ensure_user_handle(server.store(), pending.account_id, fresh).await?; let user_id = Uuid::from_slice(&handle).map_err(|err| { @@ -563,7 +594,11 @@ async fn finish( return Ok(RegisterResponse::Expired); }; - let (webauthn, rp_id) = relying_party(server)?; + let settings = settings(server).await?; + if !allowed_for(server, &settings, pending.account_id).await? { + return Ok(turned_off()); + } + let (webauthn, rp_id) = relying_party(server, &settings)?; if rp_id != ceremony.rp_id { return Ok(RegisterResponse::Expired); } diff --git a/crates/jmap/Cargo.toml b/crates/jmap/Cargo.toml index 03e3ffe6..7e5c56c2 100644 --- a/crates/jmap/Cargo.toml +++ b/crates/jmap/Cargo.toml @@ -46,6 +46,7 @@ tokio-tungstenite = "0.30" tungstenite = "0.30" chrono = "0.4" rand = "0.10.2" +psl = "2" # inbuxa: passkeys, the relying-party id check rkyv = { version = "0.8.18", features = ["little_endian"] } hashify = "0.2" diff --git a/crates/jmap/src/inbuxa/passkey.rs b/crates/jmap/src/inbuxa/passkey.rs index 9eb563e2..7a25c2c7 100644 --- a/crates/jmap/src/inbuxa/passkey.rs +++ b/crates/jmap/src/inbuxa/passkey.rs @@ -32,7 +32,11 @@ use jmap_proto::{ }; use jmap_tools::{Key, Map, Value}; use rand::{RngExt, distr::Alphanumeric, rng}; -use registry::schema::{enums::Permission, structs::Account}; +use registry::schema::{ + enums::Permission, + prelude::{Object, ObjectInner, Property}, + structs::{Account, Authentication, Domain, Tenant}, +}; use store::write::now; use trc::AddContext; use types::id::Id; @@ -63,10 +67,124 @@ fn registration_url(server: &Server, ticket: &str) -> String { ) } -/// 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 passkey settings on `x:Authentication`. +pub async fn settings(server: &Server) -> trc::Result { + Ok(server + .registry() + .object::(Id::singleton()) + .await + .caused_by(trc::location!())? + .unwrap_or_default()) +} + +/// The relying-party id passkeys are registered for now (PK-3): +/// `passkeyRpId`, or the host of the server's public HTTPS URL. +pub fn current_rp_id(server: &Server, settings: &Authentication) -> String { + settings + .passkey_rp_id + .as_deref() + .map(|id| id.trim().trim_end_matches('.').to_ascii_lowercase()) + .filter(|id| !id.is_empty()) + .unwrap_or_else(|| host_of(&server.core.network.http.url_https)) +} + +/// PK-3: whether `rp_id` may be the relying-party id for a server reached at +/// `url`: its host, or a registrable parent of it, never a public suffix. +pub fn check_rp_id(url: &str, rp_id: &str) -> Result<(), &'static str> { + let host = host_of(url); + let rp_id = rp_id.trim().trim_end_matches('.').to_ascii_lowercase(); + if rp_id.is_empty() || rp_id.starts_with('.') || rp_id.contains(['/', ':', '@', ' ']) { + return Err("Give a domain name, such as example.com."); + } + if host != rp_id && !host.ends_with(&format!(".{rp_id}")) { + return Err("It must be the host of the server's public URL or a parent domain of it."); + } + if rp_id == "localhost" { + return Ok(()); + } + match psl::suffix(rp_id.as_bytes()) { + Some(suffix) if suffix.as_bytes() != rp_id.as_bytes() => Ok(()), + _ => Err("A public suffix such as com or co.uk can't be used."), + } +} + +/// PK-3: a new or changed `passkeyRpId` must fit the server's public URL; +/// `invalidProperties` names it otherwise. +pub fn check_write( + server: &Server, + old: Option<&Object>, + new: &Object, +) -> Result<(), SetError> { + let ObjectInner::Authentication(auth) = &new.inner else { + return Ok(()); + }; + let Some(rp_id) = auth.passkey_rp_id.as_deref() else { + return Ok(()); + }; + let unchanged = old.is_some_and(|old| { + matches!(&old.inner, ObjectInner::Authentication(o) if o.passkey_rp_id.as_deref() == Some(rp_id)) + }); + if unchanged { + return Ok(()); + } + check_rp_id(&server.core.network.http.url_https, rp_id).map_err(|reason| { + SetError::invalid_properties() + .with_property(Property::PasskeyRpId) + .with_description(reason) + }) +} + +/// PK-12, PK-13: whether the account may add passkeys and sign in with +/// them. Not on an external directory; then the server, the account's +/// tenant and its domain can each switch them off. +pub async fn allowed_for( + server: &Server, + settings: &Authentication, + account_id: u32, +) -> trc::Result { + if !settings.passkeys_allowed { + return Ok(false); + } + let account = server + .account(account_id) + .await + .caused_by(trc::location!())?; + let domain = match account.name.rsplit_once('@') { + Some((_, domain)) => server.domain(domain).await?, + None => None, + }; + // PK-13: the directory owns sign-in + let directory = domain + .as_ref() + .and_then(|domain| domain.id_directory) + .or(settings.directory_id.map(|id| id.document_id())); + if directory.is_some() { + return Ok(false); + } + if let Some(domain) = &domain + && let Some(object) = server + .registry() + .object::(Id::from(domain.id)) + .await + .caused_by(trc::location!())? + && !object.passkeys_allowed + { + return Ok(false); + } + let tenant = account + .id_tenant + .or(domain.as_ref().and_then(|domain| domain.id_tenant)); + if let Some(tenant) = tenant + && let Some(object) = server + .registry() + .object::(Id::from(tenant)) + .await + .caused_by(trc::location!())? + && !object.passkeys_allowed + { + return Ok(false); + } + Ok(true) } /// The host of a URL, lowercased, without a port. @@ -98,8 +216,13 @@ 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); +fn to_value( + server: &Server, + rp_id: &str, + passkey: &Passkey, + properties: &[P], + ticket: Option<&str>, +) -> PValue { let mut out = Map::with_capacity(properties.len()); for property in properties { let value = match property { @@ -225,18 +348,21 @@ pub async fn get( list: Vec::new(), not_found, }; + let rp_id = current_rp_id(server, &settings(server).await?); 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)) + .map(|p| to_value(server, &rp_id, 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)), + Some(p) => response + .list + .push(to_value(server, &rp_id, p, &properties, None)), None => response.push_not_found(id), } } @@ -256,6 +382,9 @@ pub async fn set( 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(); + let settings = settings(server).await?; + let rp_id = current_rp_id(server, &settings); + let mut allowed = None; for (client_id, value) in request.unwrap_create() { if let Err(error) = &reached { @@ -303,15 +432,29 @@ pub async fn set( ); continue; }; + // PK-12, PK-13 + let allowed = match allowed { + Some(allowed) => allowed, + None => *allowed.insert(allowed_for(server, &settings, account_id).await?), + }; + if !allowed { + response.not_created.append( + client_id, + SetError::forbidden().with_description("Passkeys are turned off for this account."), + ); + 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? { + let max = settings.max_passkeys.clamp(1, 100) as usize; + match passkey::create_pending(data, account_id, name, &ticket, now(), max).await? { Created::Pending(created) => { let out = to_value( server, + &rp_id, &created, &[P::Id, P::State, P::RegistrationUrl, P::CreatedAt], Some(&ticket), @@ -322,8 +465,7 @@ pub async fn set( response.not_created.append( client_id, SetError::over_quota().with_description(format!( - "An account can have {} passkeys. Remove one first.", - passkey::MAX_PASSKEYS + "An account can have {max} passkeys. Remove one first." )), ); } @@ -408,7 +550,7 @@ pub async fn set( #[cfg(test)] mod tests { - use super::host_of; + use super::{check_rp_id, host_of}; #[test] fn rp_id_is_the_host() { @@ -420,4 +562,20 @@ mod tests { assert_eq!(host_of("https://mail.example.com/path"), "mail.example.com"); assert_eq!(host_of("https://[::1]:443"), "[::1]"); } + + // PK-3: the host or a registrable parent of it, never a public suffix + #[test] + fn rp_id_must_fit_the_public_url() { + let url = "https://mail.example.co.uk"; + assert!(check_rp_id(url, "mail.example.co.uk").is_ok()); + assert!(check_rp_id(url, "example.co.uk").is_ok()); + assert!(check_rp_id(url, "Example.CO.uk.").is_ok()); + assert!(check_rp_id(url, "co.uk").is_err()); + assert!(check_rp_id(url, "uk").is_err()); + assert!(check_rp_id(url, "other.co.uk").is_err()); + assert!(check_rp_id(url, "ample.co.uk").is_err()); + assert!(check_rp_id(url, "https://example.co.uk").is_err()); + assert!(check_rp_id(url, "").is_err()); + assert!(check_rp_id("https://localhost:8899", "localhost").is_ok()); + } } diff --git a/crates/jmap/src/registry/set.rs b/crates/jmap/src/registry/set.rs index 9685d0d7..4a68b253 100644 --- a/crates/jmap/src/registry/set.rs +++ b/crates/jmap/src/registry/set.rs @@ -685,6 +685,13 @@ impl RegistrySet for Server { continue 'outer; } + // inbuxa: passkeys spec, PK-3: a usable relying-party id + if let Err(err) = crate::inbuxa::passkey::check_write(self, before, &new_object) + { + set.failed(modification, err); + continue 'outer; + } + // inbuxa: AI-12, AI-18: the classifier and its models follow their rules match inbuxa_features::ai::writes::check(self.registry(), &new_object).await? { Ok(()) => {} diff --git a/crates/registry/src/inbuxa_tests.rs b/crates/registry/src/inbuxa_tests.rs index 46b50fc6..cc65f32b 100644 --- a/crates/registry/src/inbuxa_tests.rs +++ b/crates/registry/src/inbuxa_tests.rs @@ -12,8 +12,9 @@ use crate::{ enums::{LogFormat, MtaRouteType, OidcOpaqueTokens}, prelude::{ObjectImpl, ObjectInner, ObjectType}, structs::{ - Bootstrap, Directory, DirectoryBootstrap, Domain, Enterprise, MtaRoute, MtaRouteCommon, - MtaRouteInbuxaRelay, OidcDirectory, SpamSettings, Tenant, Tracer, TracerLog, + Authentication, Bootstrap, Directory, DirectoryBootstrap, Domain, Enterprise, MtaRoute, + MtaRouteCommon, MtaRouteInbuxaRelay, OidcDirectory, SpamSettings, Tenant, Tracer, + TracerLog, }, }, types::{EnumImpl, map::Map}, @@ -174,6 +175,11 @@ fn inbuxa_relay_routes_are_stored_after_the_others() { fn without_last_field(object: &T, version: u8) -> Vec { let mut unset = Vec::new(); None::.pickle(&mut unset); + without_tail(object, &unset, version) +} + +/// `object` saved at `version`, before the fields pickled as `tail`. +fn without_tail(object: &T, unset: &[u8], version: u8) -> Vec { let mut bytes = object.to_pickled_vec(); assert!(bytes.ends_with(&unset)); bytes.truncate(bytes.len() - unset.len()); @@ -200,12 +206,16 @@ fn logos_saved_before_dark_mode_read_back_without_a_dark_logo() { logo_url: Some("https://example.org/server.png".to_string()), ..Default::default() }; + // The passkey switch is stored after the dark logo + let mut unset = Vec::new(); + None::.pickle(&mut unset); + true.pickle(&mut unset); assert_eq!( - read(ObjectType::Domain, &without_last_field(&domain, 1)), + read(ObjectType::Domain, &without_tail(&domain, &unset, 1)), ObjectInner::Domain(domain.clone()) ); assert_eq!( - read(ObjectType::Tenant, &without_last_field(&tenant, 0)), + read(ObjectType::Tenant, &without_tail(&tenant, &unset, 0)), ObjectInner::Tenant(tenant.clone()) ); assert_eq!( @@ -333,3 +343,73 @@ fn spam_settings_saved_before_qr_codes_read_back_with_scanning_off() { ObjectInner::SpamSettings(settings) ); } + +// passkeys spec: settings, domains and tenants saved before the passkey +// settings read back with passkeys allowed and the limit at 10; saved now, +// with what was set +#[test] +fn passkey_settings_saved_before_read_back_allowed() { + let auth = Authentication { + password_min_length: 12, + max_app_passwords: Some(3), + ..Default::default() + }; + let mut unset = Vec::new(); + true.pickle(&mut unset); + None::.pickle(&mut unset); + 10u64.pickle(&mut unset); + let read_back = read(ObjectType::Authentication, &without_tail(&auth, &unset, 0)); + assert_eq!(read_back, ObjectInner::Authentication(auth.clone())); + let ObjectInner::Authentication(read_back) = read_back else { + unreachable!() + }; + assert!(read_back.passkeys_allowed); + assert_eq!(read_back.max_passkeys, 10); + + let domain = Domain { + name: "example.org".to_string(), + logo_dark: Some("https://example.org/dark.png".to_string()), + ..Default::default() + }; + let tenant = Tenant { + name: "t".to_string(), + ..Default::default() + }; + let mut unset = Vec::new(); + true.pickle(&mut unset); + assert_eq!( + read(ObjectType::Domain, &without_tail(&domain, &unset, 2)), + ObjectInner::Domain(domain.clone()) + ); + assert_eq!( + read(ObjectType::Tenant, &without_tail(&tenant, &unset, 1)), + ObjectInner::Tenant(tenant.clone()) + ); + + let auth = Authentication { + passkeys_allowed: false, + passkey_rp_id: Some("example.org".to_string()), + max_passkeys: 3, + ..auth + }; + let domain = Domain { + passkeys_allowed: false, + ..domain + }; + let tenant = Tenant { + passkeys_allowed: false, + ..tenant + }; + assert_eq!( + read(ObjectType::Authentication, &auth.to_pickled_vec()), + ObjectInner::Authentication(auth) + ); + assert_eq!( + read(ObjectType::Domain, &domain.to_pickled_vec()), + ObjectInner::Domain(domain) + ); + assert_eq!( + read(ObjectType::Tenant, &tenant.to_pickled_vec()), + ObjectInner::Tenant(tenant) + ); +} diff --git a/crates/registry/src/schema/properties.rs b/crates/registry/src/schema/properties.rs index 2d9954ce..48444539 100644 --- a/crates/registry/src/schema/properties.rs +++ b/crates/registry/src/schema/properties.rs @@ -998,6 +998,10 @@ pub enum Property { LogoUrlDark = 942, // inbuxa: #401, links in QR codes ScanQrCodes = 943, + // inbuxa: passkeys spec, the settings + PasskeysAllowed = 944, + PasskeyRpId = 945, + MaxPasskeys = 946, RequireClientRegistration = 615, RequireScopes = 608, RequireTls = 525, diff --git a/crates/registry/src/schema/properties_impl.rs b/crates/registry/src/schema/properties_impl.rs index 2c5b5d68..1f214f53 100644 --- a/crates/registry/src/schema/properties_impl.rs +++ b/crates/registry/src/schema/properties_impl.rs @@ -870,6 +870,9 @@ impl EnumImpl for Property { b"logoUrl" => Property::LogoUrl, b"logoDark" => Property::LogoDark, b"logoUrlDark" => Property::LogoUrlDark, + b"passkeysAllowed" => Property::PasskeysAllowed, + b"passkeyRpId" => Property::PasskeyRpId, + b"maxPasskeys" => Property::MaxPasskeys, b"loiterBanPeriod" => Property::LoiterBanPeriod, b"loiterBanRate" => Property::LoiterBanRate, b"lossy" => Property::Lossy, @@ -1819,6 +1822,9 @@ impl EnumImpl for Property { Property::LogoUrl => "logoUrl", Property::LogoDark => "logoDark", Property::LogoUrlDark => "logoUrlDark", + Property::PasskeysAllowed => "passkeysAllowed", + Property::PasskeyRpId => "passkeyRpId", + Property::MaxPasskeys => "maxPasskeys", Property::LoiterBanPeriod => "loiterBanPeriod", Property::LoiterBanRate => "loiterBanRate", Property::Lossy => "lossy", @@ -3048,6 +3054,9 @@ impl EnumImpl for Property { 941 => Some(Property::LogoDark), 942 => Some(Property::LogoUrlDark), 943 => Some(Property::ScanQrCodes), + 944 => Some(Property::PasskeysAllowed), + 945 => Some(Property::PasskeyRpId), + 946 => Some(Property::MaxPasskeys), 615 => Some(Property::RequireClientRegistration), 608 => Some(Property::RequireScopes), 525 => Some(Property::RequireTls), @@ -3259,7 +3268,7 @@ impl EnumImpl for Property { } } - const COUNT: usize = 944; + const COUNT: usize = 947; } impl serde::Serialize for Property { diff --git a/crates/registry/src/schema/structs.rs b/crates/registry/src/schema/structs.rs index e81adc19..2f8a169f 100644 --- a/crates/registry/src/schema/structs.rs +++ b/crates/registry/src/schema/structs.rs @@ -488,6 +488,13 @@ pub struct Authentication { pub max_app_passwords: Option, #[serde(rename = "maxApiKeys")] pub max_api_keys: Option, + // inbuxa: passkeys spec, the settings + #[serde(rename = "passkeysAllowed")] + pub passkeys_allowed: bool, + #[serde(rename = "passkeyRpId")] + pub passkey_rp_id: Option, + #[serde(rename = "maxPasskeys")] + pub max_passkeys: u64, } #[derive(Debug, Clone, PartialEq, Eq, Serialize, Deserialize)] @@ -2740,6 +2747,9 @@ pub struct Domain { // inbuxa: branding BT-27 #[serde(rename = "logoDark")] pub logo_dark: Option, + // inbuxa: passkeys spec: an off switch for this level's accounts + #[serde(rename = "passkeysAllowed")] + pub passkeys_allowed: bool, #[serde(rename = "certificateManagement")] pub certificate_management: CertificateManagement, #[serde(rename = "dkimManagement")] @@ -5880,6 +5890,9 @@ pub struct Tenant { // inbuxa: branding BT-27 #[serde(rename = "logoDark")] pub logo_dark: Option, + // inbuxa: passkeys spec: an off switch for this level's accounts + #[serde(rename = "passkeysAllowed")] + pub passkeys_allowed: bool, #[serde(rename = "roles")] pub roles: Roles, #[serde(rename = "permissions")] diff --git a/crates/registry/src/schema/structs_impl.rs b/crates/registry/src/schema/structs_impl.rs index 5dca3c6d..8f9bcc97 100644 --- a/crates/registry/src/schema/structs_impl.rs +++ b/crates/registry/src/schema/structs_impl.rs @@ -3303,7 +3303,8 @@ impl RegistryJsonPropertyPatch for AsnResource { impl ObjectImpl for Authentication { const FLAGS: u64 = OBJ_SINGLETON; - const VERSION: u8 = 0; + // inbuxa: 1: passkeysAllowed, passkeyRpId, maxPasskeys (passkeys spec) + const VERSION: u8 = 1; const OBJECT: ObjectType = ObjectType::Authentication; fn validate(&self, errors: &mut Vec) -> bool { @@ -3364,6 +3365,18 @@ impl ObjectImpl for Authentication { errors.push(ValidationError::min_value(Property::MaxApiKeys, 1)); } } + if let Some(value) = &self.passkey_rp_id { + if value.is_empty() { + errors.push(ValidationError::required(Property::PasskeyRpId)); + } + } + let value = &self.max_passkeys; + if *value < 1 { + errors.push(ValidationError::min_value(Property::MaxPasskeys, 1)); + } + if *value > 100 { + errors.push(ValidationError::max_value(Property::MaxPasskeys, 100)); + } errors.len() == neb } @@ -3398,6 +3411,9 @@ impl Pickle for Authentication { self.password_default_expiry.pickle(out); self.max_app_passwords.pickle(out); self.max_api_keys.pickle(out); + self.passkeys_allowed.pickle(out); + self.passkey_rp_id.pickle(out); + self.max_passkeys.pickle(out); } fn unpickle(stream: &mut crate::pickle::PickledStream<'_>) -> Option { @@ -3414,6 +3430,12 @@ impl Pickle for Authentication { this.password_default_expiry = Pickle::unpickle(stream)?; this.max_app_passwords = Pickle::unpickle(stream)?; this.max_api_keys = Pickle::unpickle(stream)?; + // inbuxa: passkeys spec, stored from version 1 + if stream.version() >= 1 { + this.passkeys_allowed = Pickle::unpickle(stream)?; + this.passkey_rp_id = Pickle::unpickle(stream)?; + this.max_passkeys = Pickle::unpickle(stream)?; + } Some(this) } } @@ -3433,13 +3455,16 @@ impl Default for Authentication { password_default_expiry: Default::default(), max_app_passwords: Some(5u64), max_api_keys: Some(5u64), + passkeys_allowed: true, + passkey_rp_id: Default::default(), + max_passkeys: 10u64, } } } impl IntoValue for Authentication { fn into_value(self) -> JmapValue<'static> { - let mut map = jmap_tools::Map::with_capacity(14); + let mut map = jmap_tools::Map::with_capacity(17); map.insert_unchecked(Property::DirectoryId, self.directory_id.into_value()); map.insert_unchecked( Property::DefaultUserRoleIds, @@ -3482,6 +3507,12 @@ impl IntoValue for Authentication { self.max_app_passwords.into_value(), ); map.insert_unchecked(Property::MaxApiKeys, self.max_api_keys.into_value()); + map.insert_unchecked( + Property::PasskeysAllowed, + self.passkeys_allowed.into_value(), + ); + map.insert_unchecked(Property::PasskeyRpId, self.passkey_rp_id.into_value()); + map.insert_unchecked(Property::MaxPasskeys, self.max_passkeys.into_value()); JmapValue::Object(map) } } @@ -3515,6 +3546,9 @@ impl RegistryJsonPropertyPatch for Authentication { } Some(Property::MaxAppPasswords) => self.max_app_passwords.patch(pointer, value), Some(Property::MaxApiKeys) => self.max_api_keys.patch(pointer, value), + Some(Property::PasskeysAllowed) => self.passkeys_allowed.patch(pointer, value), + Some(Property::PasskeyRpId) => self.passkey_rp_id.patch(pointer, value), + Some(Property::MaxPasskeys) => self.max_passkeys.patch(pointer, value), Some(Property::Type) => Ok(MaybeUnpatched::Unpatched { property: Property::Type, value, @@ -19839,8 +19873,8 @@ impl RegistryJsonPropertyPatch for DnsServerYandexCloud { impl ObjectImpl for Domain { const FLAGS: u64 = OBJ_FILTER_TENANT | OBJ_SEQ_ID; - // inbuxa: 2: logoDark (branding BT-27) - const VERSION: u8 = 2; + // inbuxa: 2: logoDark (branding BT-27); 3: passkeysAllowed (passkeys) + const VERSION: u8 = 3; const OBJECT: ObjectType = ObjectType::Domain; fn validate(&self, errors: &mut Vec) -> bool { @@ -19946,6 +19980,7 @@ impl Pickle for Domain { self.report_address_uri.pickle(out); self.allow_scim_provisioning.pickle(out); self.logo_dark.pickle(out); + self.passkeys_allowed.pickle(out); } fn unpickle(stream: &mut crate::pickle::PickledStream<'_>) -> Option { @@ -19972,6 +20007,10 @@ impl Pickle for Domain { if stream.version() >= 2 { this.logo_dark = Pickle::unpickle(stream)?; } + // inbuxa: passkeys spec, stored from version 3 + if stream.version() >= 3 { + this.passkeys_allowed = Pickle::unpickle(stream)?; + } Some(this) } } @@ -19986,6 +20025,7 @@ impl Default for Domain { description: Default::default(), logo: Default::default(), logo_dark: Default::default(), + passkeys_allowed: true, certificate_management: Default::default(), dkim_management: Default::default(), dns_management: Default::default(), @@ -20010,6 +20050,10 @@ impl IntoValue for Domain { map.insert_unchecked(Property::Description, self.description.into_value()); map.insert_unchecked(Property::Logo, self.logo.into_value()); map.insert_unchecked(Property::LogoDark, self.logo_dark.into_value()); + map.insert_unchecked( + Property::PasskeysAllowed, + self.passkeys_allowed.into_value(), + ); map.insert_unchecked( Property::CertificateManagement, self.certificate_management.into_value(), @@ -20054,6 +20098,7 @@ impl RegistryJsonPropertyPatch for Domain { Some(Property::Description) => self.description.patch(pointer, value), Some(Property::Logo) => self.logo.patch(pointer, value), Some(Property::LogoDark) => self.logo_dark.patch(pointer, value), + Some(Property::PasskeysAllowed) => self.passkeys_allowed.patch(pointer, value), Some(Property::CertificateManagement) => { self.certificate_management.patch(pointer, value) } @@ -44514,8 +44559,8 @@ impl RegistryJsonPropertyPatch for TaskTlsReport { impl ObjectImpl for Tenant { const FLAGS: u64 = OBJ_SEQ_ID; - // inbuxa: 1: logoDark (branding BT-27) - const VERSION: u8 = 1; + // inbuxa: 1: logoDark (branding BT-27); 2: passkeysAllowed (passkeys) + const VERSION: u8 = 2; const OBJECT: ObjectType = ObjectType::Tenant; fn validate(&self, errors: &mut Vec) -> bool { @@ -44560,6 +44605,7 @@ impl Pickle for Tenant { self.permissions.pickle(out); self.quotas.pickle(out); self.logo_dark.pickle(out); + self.passkeys_allowed.pickle(out); } fn unpickle(stream: &mut crate::pickle::PickledStream<'_>) -> Option { @@ -44574,6 +44620,10 @@ impl Pickle for Tenant { if stream.version() >= 1 { this.logo_dark = Pickle::unpickle(stream)?; } + // inbuxa: passkeys spec, stored from version 2 + if stream.version() >= 2 { + this.passkeys_allowed = Pickle::unpickle(stream)?; + } Some(this) } } @@ -44585,6 +44635,7 @@ impl Default for Tenant { created_at: Default::default(), logo: Default::default(), logo_dark: Default::default(), + passkeys_allowed: true, roles: Default::default(), permissions: Default::default(), quotas: Default::default(), @@ -44599,6 +44650,10 @@ impl IntoValue for Tenant { map.insert_unchecked(Property::CreatedAt, self.created_at.into_value()); map.insert_unchecked(Property::Logo, self.logo.into_value()); map.insert_unchecked(Property::LogoDark, self.logo_dark.into_value()); + map.insert_unchecked( + Property::PasskeysAllowed, + self.passkeys_allowed.into_value(), + ); map.insert_unchecked(Property::Roles, self.roles.into_value()); map.insert_unchecked(Property::Permissions, self.permissions.into_value()); map.insert_unchecked(Property::Quotas, self.quotas.into_value()); @@ -44617,6 +44672,7 @@ impl RegistryJsonPropertyPatch for Tenant { Some(Property::CreatedAt) => pointer.assert_server_set(), Some(Property::Logo) => self.logo.patch(pointer, value), Some(Property::LogoDark) => self.logo_dark.patch(pointer, value), + Some(Property::PasskeysAllowed) => self.passkeys_allowed.patch(pointer, value), Some(Property::Roles) => self.roles.patch(pointer, value), Some(Property::Permissions) => self.permissions.patch(pointer, value), Some(Property::Quotas) => self.quotas.patch(pointer, value), diff --git a/crates/trc/src/event/enums.rs b/crates/trc/src/event/enums.rs index 494e0dec..b12b7745 100644 --- a/crates/trc/src/event/enums.rs +++ b/crates/trc/src/event/enums.rs @@ -15,10 +15,11 @@ // (audit-hold-lock spec, AU-3, AU-8); 649 is cluster.node-id-reassigned; // 650 to 659 are inbuxa Relay's (relay spec, RL-23, RL-T23); 660 is // store.blob-read-through; 661 is smtp.directory-no-answer (#364); 662 is -// spam.result (#397); 663 is queue.message-subject (inbuxa-admin #228). +// spam.result (#397); 663 is queue.message-subject (inbuxa-admin #228); +// 664 is auth.passkey-counter (passkeys spec, PK-18). // TOTAL_EVENT_COUNT sizes the collector's per-event tables, so it is one // more than the highest id; the test below holds it to the variant list -pub const TOTAL_EVENT_COUNT: usize = 664; +pub const TOTAL_EVENT_COUNT: usize = 665; pub const TOTAL_METRIC_COUNT: usize = 369; #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] @@ -129,6 +130,9 @@ pub enum AuthEvent { CredentialExpired = 276, // inbuxa: legacy-protocols LP-6 LegacyProtocolRefused = 642, + /// inbuxa: passkeys spec, PK-18: a passkey's counter didn't go up, so it + /// may have been copied + PasskeyCounter = 664, } #[derive(Debug, Clone, Copy, PartialEq, Eq, Hash)] diff --git a/crates/trc/src/event/enums_impl.rs b/crates/trc/src/event/enums_impl.rs index aa324ec5..6a6a2665 100644 --- a/crates/trc/src/event/enums_impl.rs +++ b/crates/trc/src/event/enums_impl.rs @@ -69,6 +69,8 @@ impl EventType { b"auth.client-registration" => EventType::Auth(AuthEvent::ClientRegistration), // inbuxa: legacy-protocols LP-6 b"auth.legacy-protocol-refused" => EventType::Auth(AuthEvent::LegacyProtocolRefused), + // inbuxa: passkeys spec, PK-18 + b"auth.passkey-counter" => EventType::Auth(AuthEvent::PasskeyCounter), b"auth.error" => EventType::Auth(AuthEvent::Error), b"auth.warning" => EventType::Auth(AuthEvent::Warning), b"auth.credential-expired" => EventType::Auth(AuthEvent::CredentialExpired), @@ -748,6 +750,8 @@ impl EventType { EventType::Auth(AuthEvent::ClientRegistration) => "auth.client-registration", // inbuxa: legacy-protocols LP-6 EventType::Auth(AuthEvent::LegacyProtocolRefused) => "auth.legacy-protocol-refused", + // inbuxa: passkeys spec, PK-18 + EventType::Auth(AuthEvent::PasskeyCounter) => "auth.passkey-counter", EventType::Auth(AuthEvent::Error) => "auth.error", EventType::Auth(AuthEvent::Warning) => "auth.warning", EventType::Auth(AuthEvent::CredentialExpired) => "auth.credential-expired", @@ -1568,6 +1572,8 @@ impl EventType { EventType::Auth(AuthEvent::ClientRegistration) => 555, // inbuxa: legacy-protocols LP-6 EventType::Auth(AuthEvent::LegacyProtocolRefused) => 642, + // inbuxa: passkeys spec, PK-18 + EventType::Auth(AuthEvent::PasskeyCounter) => 664, EventType::Auth(AuthEvent::Error) => 34, EventType::Auth(AuthEvent::Warning) => 595, EventType::Auth(AuthEvent::CredentialExpired) => 276, @@ -2246,6 +2252,8 @@ impl EventType { 555 => Some(EventType::Auth(AuthEvent::ClientRegistration)), // inbuxa: legacy-protocols LP-6 642 => Some(EventType::Auth(AuthEvent::LegacyProtocolRefused)), + // inbuxa: passkeys spec, PK-18 + 664 => Some(EventType::Auth(AuthEvent::PasskeyCounter)), 34 => Some(EventType::Auth(AuthEvent::Error)), 595 => Some(EventType::Auth(AuthEvent::Warning)), 276 => Some(EventType::Auth(AuthEvent::CredentialExpired)), @@ -2976,6 +2984,8 @@ impl EventType { EventType::Auth(AuthEvent::ClientRegistration) => Level::Info, // inbuxa: legacy-protocols LP-6 EventType::Auth(AuthEvent::LegacyProtocolRefused) => Level::Info, + // inbuxa: passkeys spec, PK-18 + EventType::Auth(AuthEvent::PasskeyCounter) => Level::Warn, EventType::Calendar(CalendarEvent::AlarmSent) => Level::Info, EventType::Calendar(CalendarEvent::ItipMessageSent) => Level::Info, EventType::Calendar(CalendarEvent::ItipMessageReceived) => Level::Info, @@ -3357,6 +3367,8 @@ impl EventType { EventType::Auth(AuthEvent::LegacyProtocolRefused) => { "Legacy mail protocol sign-in refused" } + // inbuxa: passkeys spec, PK-18 + EventType::Auth(AuthEvent::PasskeyCounter) => "Passkey counter went backwards", EventType::Auth(AuthEvent::Error) => "Authentication error", EventType::Auth(AuthEvent::Warning) => "Authentication warning", EventType::Auth(AuthEvent::CredentialExpired) => "Credential expired", @@ -4148,6 +4160,8 @@ impl EventType { EventType::Auth(AuthEvent::LegacyProtocolRefused) => { "This server allows only inbuxa webmail and JMAP apps" } + // inbuxa: passkeys spec, PK-18 + EventType::Auth(AuthEvent::PasskeyCounter) => "Authentication failed", EventType::Auth(AuthEvent::Error) => "Authentication error", EventType::Auth(AuthEvent::CredentialExpired) => "Credential expired", EventType::Imap(ImapEvent::ConnectionStart) => "IMAP error", @@ -4485,6 +4499,8 @@ impl EventType { EventType::Auth(AuthEvent::ClientRegistration), // inbuxa: legacy-protocols LP-6 EventType::Auth(AuthEvent::LegacyProtocolRefused), + // inbuxa: passkeys spec, PK-18 + EventType::Auth(AuthEvent::PasskeyCounter), EventType::Auth(AuthEvent::Error), EventType::Auth(AuthEvent::Warning), EventType::Auth(AuthEvent::CredentialExpired), diff --git a/docs/spec/features/passkeys.md b/docs/spec/features/passkeys.md index 87ffa720..cc669399 100644 --- a/docs/spec/features/passkeys.md +++ b/docs/spec/features/passkeys.md @@ -67,12 +67,13 @@ Two indexes: credential id → passkey, and user handle → account. | Field | Default | Meaning | |---|---|---| -| `passkeys` | `allowed` | `allowed` or `disabled` server-wide (PK-12) | +| `passkeysAllowed` | true | Server-wide on/off switch (PK-12) | | `passkeyRpId` | null | The relying-party id. Null means the host of the server's public HTTPS URL (PK-3) | -| `maxPasskeys` | 10 | Per account | +| `maxPasskeys` | 10 | Per account, 1 to 100 | -Per domain and per tenant, `passkeys` can be set to `allowed` or `disabled`, -overriding the server's value; the most specific setting applies. +`x:Domain` and `x:Tenant` each have `passkeysAllowed` (default true) too. +These are off switches (decision 3): passkeys work for an account only when +the server, its tenant and its domain all allow them. ### Permissions @@ -245,7 +246,7 @@ Settled by John, 2026-11-18: later as an option, once browsers support it widely. 2. **A passkey signs in on its own** (PK-12): no TOTP code after it, because user verification is a second factor already. -3. **On by default** (`passkeys: allowed`), with off switches per server, +3. **On by default** (`passkeysAllowed: true`), with off switches per server, tenant and domain. Nobody gets a passkey without adding one. Also decided in this spec: passkeys stored apart from account credentials; @@ -256,7 +257,7 @@ removing a passkey ends the account's sessions (PK-15); the password stays ## Implementation status -Building, one PR each: +Built, one PR each: 1. Storage and `inbuxa:Passkey` management: records in `_` under `N`, `get` and `/set` (create pending with its registration URL, rename, @@ -277,6 +278,14 @@ Building, one PR each: password no longer opens it. Sign-ins by passkey are recorded with `via: passkey`, and raise `auth.success` with type `passkey`; a counter that didn't go up fails and is logged as a possible clone. -4. The device flow, the settings and policy, and the sign-in events. +4. The device flow (`authDevice` takes `passkey` too), the settings above + (`passkeyRpId` checked on write against the public URL and the public + suffix list), the external-directory rule (PK-13: an account whose domain, + or the server, signs in against a directory gets no passkeys), the + `auth.passkey-counter` event (id 664, warn), and failed passkey sign-ins + tagged `type: passkey`. The login page offers passkeys only when the + challenge endpoint answers (it's 404 when they're off server-wide). + +The server side is done. Then the webmail and console pages. diff --git a/resources/html-templates/login.html b/resources/html-templates/login.html index 024d4fd3..5fb5cfec 100644 --- a/resources/html-templates/login.html +++ b/resources/html-templates/login.html @@ -643,7 +643,7 @@ // is good once, for two minutes. var usedPasskey = false; var autofill = null; - var canPasskey = !isDevice && window.PublicKeyCredential && navigator.credentials && + var canPasskey = window.PublicKeyCredential && navigator.credentials && typeof navigator.credentials.get === 'function' && window.AbortController; function fromB64(s) { @@ -698,6 +698,11 @@ function signInWithPasskey(assertion) { clearAlert(); + if (isDevice && !($('device-code').value || '').trim()) { + showError('Please enter the device code.'); + startAutofill(); + return; + } usedPasskey = true; var body = buildRequest({ account_name: '', account_secret: '' }, null); delete body.accountName; @@ -724,7 +729,6 @@ } if (canPasskey) { - show($('passkey-btn')); $('passkey-btn').addEventListener('click', function () { if (autofill) { autofill.abort(); autofill = null; } clearAlert(); @@ -736,7 +740,17 @@ startAutofill(); }); }); - startAutofill(); + // Offered only when the server allows them (PK-9) + fetch('/api/auth/passkey', { + method: 'POST', + credentials: 'omit', + cache: 'no-store', + headers: { 'Accept': 'application/json' } + }).then(function (res) { + if (res.status !== 200) return; + show($('passkey-btn')); + startAutofill(); + }, function () {}); } // Digit-only filter on OTP and auto-submit on 6 digits. diff --git a/resources/html-templates/login.html.min b/resources/html-templates/login.html.min index 0fb39cd0..66bcf390 100644 --- a/resources/html-templates/login.html.min +++ b/resources/html-templates/login.html.min @@ -1 +1 @@ - Sign in · inbuxa

Sign in

Enter your credentials to continue

\ No newline at end of file + Sign in · inbuxa

Sign in

Enter your credentials to continue

\ No newline at end of file diff --git a/resources/html-templates/login.html.min.gz b/resources/html-templates/login.html.min.gz index 4ab658ba..fb121164 100644 Binary files a/resources/html-templates/login.html.min.gz and b/resources/html-templates/login.html.min.gz differ diff --git a/resources/schema/schema.json.gz b/resources/schema/schema.json.gz index 1389340e..f3fb9aba 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 730bdd2a..eb6ca3b0 100644 --- a/resources/schema/schema.json.sha256 +++ b/resources/schema/schema.json.sha256 @@ -1 +1 @@ -KvmIk3N-3W3k-UPYHkxzb8pL2Ioo7e6HuUtqVOCKkSI \ No newline at end of file +Axq6Sz1LhbEwKr-Oj1eqAOy888Ctnysw6fk34xP4MqI \ No newline at end of file diff --git a/tests/src/system/oidc.rs b/tests/src/system/oidc.rs index e8d2d0d9..50266670 100644 --- a/tests/src/system/oidc.rs +++ b/tests/src/system/oidc.rs @@ -1105,6 +1105,7 @@ pub async fn test(test: &mut TestServer) { account_secret: "this is a very strong password".to_string(), mfa_token: None, code: device_response.user_code.clone(), + passkey: None, }, ) .await @@ -1133,6 +1134,7 @@ pub async fn test(test: &mut TestServer) { account_secret: "this is a very strong password".to_string(), mfa_token: None, code: device_response.user_code.clone(), + passkey: None, }, ) .await diff --git a/tests/src/system/passkeys.rs b/tests/src/system/passkeys.rs index 622258a8..b20e0f11 100644 --- a/tests/src/system/passkeys.rs +++ b/tests/src/system/passkeys.rs @@ -16,6 +16,10 @@ use crate::utils::{ server::{TestServer, TestServerBuilder}, }; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; +use registry::schema::{ + prelude::{ObjectType, Property}, + structs::Authentication, +}; use ring::{ rand::SystemRandom, signature::{ECDSA_P256_SHA256_ASN1_SIGNING, EcdsaKeyPair, KeyPair}, @@ -245,7 +249,9 @@ pub async fn test(test: &mut TestServer) { "no removal recorded by name: {response}" ); - registration(&user).await; + let key = registration(&user).await; + let client_id = sign_in(&user, &key).await; + policy(&admin, &user, &key, &client_id).await; } /// A software authenticator: one P-256 key, user verification always done. @@ -427,7 +433,7 @@ async fn start_registration(user: &Account, name: &str) -> (String, String) { } /// PK-6 to PK-8: the registration page's two steps. -async fn registration(user: &Account) { +async fn registration(user: &Account) -> SoftKey { let (laptop_id, ticket) = start_registration(user, "Laptop").await; // The server serves the page itself @@ -541,8 +547,7 @@ async fn registration(user: &Account) { })) .await; assert_eq!(response["type"], "refused", "{response}"); - - sign_in(user, &key).await; + key } async fn new_challenge() -> Value { @@ -585,7 +590,7 @@ async fn login(client_id: &str, assertion: Value) -> Value { } /// PK-9 to PK-12: sign-in in the authorization-code flow. -async fn sign_in(user: &Account, key: &SoftKey) { +async fn sign_in(user: &Account, key: &SoftKey) -> String { let client = HttpRequest::with_credentials( 8899, "admin@example.com", @@ -666,6 +671,151 @@ async fn sign_in(user: &Account, key: &SoftKey) { })) .await; assert_eq!(response["type"], "options", "{response}"); + client_id +} + +/// The device flow, the settings and the off switches (PK-3, PK-5, PK-9, +/// PK-12). +async fn policy(admin: &Account, user: &Account, key: &SoftKey, client_id: &str) { + // PK-9: the device flow takes a passkey too + let device = reqwest::Client::builder() + .danger_accept_invalid_certs(true) + .build() + .unwrap() + .post("https://127.0.0.1:8899/auth/device") + .form(&[("client_id", client_id)]) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(); + let user_code = device["user_code"] + .as_str() + .unwrap_or_else(|| panic!("{device}")); + let challenge = new_challenge().await; + let response = register_at( + "/api/auth", + json!({"type": "authDevice", "code": user_code, "passkey": key.get(&challenge, 8, ORIGIN)}), + ) + .await; + assert_eq!(response["type"], "verified", "{response}"); + + // PK-5: maxPasskeys; the account has one passkey and two pending + admin + .registry_update_setting( + Authentication { + max_passkeys: 3, + ..Default::default() + }, + &[Property::MaxPasskeys], + ) + .await; + let (_, response) = call( + user, + "inbuxa:Passkey/set", + json!({"create": {"k": {"name": "Fourth"}}}), + ) + .await; + assert_eq!( + response["notCreated"]["k"]["type"], "overQuota", + "{response}" + ); + admin + .registry_update_setting( + Authentication { + max_passkeys: 10, + ..Default::default() + }, + &[Property::MaxPasskeys], + ) + .await; + + // PK-12: the domain's off switch stops adding and signing in + let domain_id = admin.find_or_create_domain("example.com").await; + admin + .registry_update_object( + ObjectType::Domain, + domain_id, + json!({"passkeysAllowed": false}), + ) + .await; + let (_, response) = call( + user, + "inbuxa:Passkey/set", + json!({"create": {"k": {"name": "Off"}}}), + ) + .await; + assert_eq!( + response["notCreated"]["k"]["type"], "forbidden", + "{response}" + ); + let challenge = new_challenge().await; + let response = login(client_id, key.get(&challenge, 9, ORIGIN)).await; + assert_eq!(response["type"], "failure", "{response}"); + admin + .registry_update_object( + ObjectType::Domain, + domain_id, + json!({"passkeysAllowed": true}), + ) + .await; + let challenge = new_challenge().await; + let response = login(client_id, key.get(&challenge, 10, ORIGIN)).await; + assert_eq!(response["type"], "authenticated", "{response}"); + + // PK-9: off server-wide, the login page isn't offered a challenge + admin + .registry_update_setting( + Authentication { + passkeys_allowed: false, + ..Default::default() + }, + &[Property::PasskeysAllowed], + ) + .await; + let refused = HttpRequest::new() + .post::("/api/auth/passkey", &json!({})) + .await; + assert!( + refused + .as_ref() + .map_or(true, |response| response["challengeId"].is_null()), + "{refused:?}" + ); + admin + .registry_update_setting( + Authentication { + passkeys_allowed: true, + ..Default::default() + }, + &[Property::PasskeysAllowed], + ) + .await; + + // PK-3: the relying-party id must fit the public URL + for bad in ["com", "example.com", "co.uk"] { + let (_, response) = call( + admin, + "x:Authentication/set", + json!({"update": {"singleton": {"passkeyRpId": bad}}}), + ) + .await; + assert_eq!( + response["notUpdated"]["singleton"]["properties"][0], "passkeyRpId", + "{bad}: {response}" + ); + } + let (_, response) = call( + admin, + "x:Authentication/set", + json!({"update": {"singleton": {"passkeyRpId": RP_ID}}}), + ) + .await; + assert!(response["updated"].get("singleton").is_some(), "{response}"); + let challenge = new_challenge().await; + let response = login(client_id, key.get(&challenge, 11, ORIGIN)).await; + assert_eq!(response["type"], "authenticated", "{response}"); } #[ignore]