diff --git a/README.md b/README.md index 510943b9e..aa57fd1f3 100644 --- a/README.md +++ b/README.md @@ -64,6 +64,9 @@ Generate a persistent RSA key with `just generate-key /absolute/path/key.pem` (u OpenSSL CLI; piqueld generates its own, see `infra/README.md`). Keep the same key and ID across restarts. Replacing the only configured key invalidates issued tokens; overlapping signing-key rotation is not implemented. +It also changes the decoy passkey IDs that username sign-in returns for unknown +usernames, while real accounts keep theirs, so comparing responses from before and +after a replacement reveals which usernames exist. Provider callback URLs are `/login/github/callback` and `/login/google/callback` on the auth origin. GitHub uses `read:user user:email`; Google uses `openid email profile`. diff --git a/apps/auth-service/src/config.rs b/apps/auth-service/src/config.rs index ae44a6a35..7852a27f1 100644 --- a/apps/auth-service/src/config.rs +++ b/apps/auth-service/src/config.rs @@ -1,8 +1,11 @@ //! Validated startup configuration, grouped by application. +use crate::passkey::DecoyKey; use ipnet::IpNet; use piquel_auth_protocol::{Provider, oauth::Scope}; -use piquel_common::{ConfigurationError, Origin, PublicUrl, SecretReference, Variable}; +use piquel_common::{ + ConfigurationError, Origin, PublicUrl, SecretBytes, SecretReference, Variable, +}; use piquel_crypto::{Digest, Rs256Key, Secret}; use piquel_repository::{BootstrapOidcClient, DatabaseConfig}; use serde::Deserialize; @@ -21,6 +24,8 @@ const MAX_SIGNING_KEY_ID_LENGTH: usize = 128; const DEFAULT_SIGNING_KEY_ID: &str = "primary"; /// Separates refresh digests from every other use of the persistent PEM bytes. const REFRESH_DIGEST_CONTEXT: &[u8] = b"piquel-refresh-token-digest-v1"; +/// Separates the passkey decoy key from every other use of the persistent PEM bytes. +const PASSKEY_DECOY_CONTEXT: &[u8] = b"piquel-passkey-decoy-credential-v1"; /// Default number of pooled authentication connections. const DATABASE_POOL_SIZE: u32 = 10; /// Maximum startup wait for a pooled database connection. @@ -60,10 +65,16 @@ pub(crate) struct PasskeyConfig { pub origin: Origin, /// Registration admission policy. pub invite_required: bool, + /// Domain-separated key for the stable decoy credentials of unknown usernames. + pub decoy_key: DecoyKey, } impl PasskeyConfig { - /// Reads the passkey policy and validates that the origin has a domain RP ID. - pub(crate) fn from_environment(origin: &Origin) -> Result { + /// Reads the passkey policy, validates that the origin has a domain RP ID and + /// derives the decoy key from the persistent PEM key. + pub(crate) fn from_environment( + origin: &Origin, + persistent_key: &SecretBytes, + ) -> Result { if !matches!(origin.as_url().host(), Some(url::Host::Domain(_))) { return Err(PUBLIC_BASE_URL .invalid("must use a domain name for WebAuthn, e.g. https://auth.piquel.fr")); @@ -71,6 +82,10 @@ impl PasskeyConfig { Ok(Self { origin: origin.clone(), invite_required: INVITE_REQUIRED.flag(true)?, + decoy_key: DecoyKey::new(AuthConfig::derive_key( + persistent_key, + PASSKEY_DECOY_CONTEXT, + )?), }) } } @@ -169,15 +184,11 @@ pub(crate) struct OidcConfig { } impl OidcConfig { - /// Loads the required persistent key and statically reviewed clients. - pub(crate) fn from_environment(origin: &Origin) -> Result { - let reference: SecretReference = KEY_PROVIDER.parse()?; - let secret = reference.resolve().map_err(|source| { - KEY_PROVIDER.error( - "must resolve to an RSA private PEM key of at least 2048 bits", - source, - ) - })?; + /// Parses the persistent signing key and loads statically reviewed clients. + pub(crate) fn from_environment( + origin: &Origin, + secret: &SecretBytes, + ) -> Result { let pem = secret .utf8() .map_err(|source| KEY_PROVIDER.error("must contain UTF-8 PEM", source))?; @@ -198,10 +209,7 @@ impl OidcConfig { source, ) })?; - let refresh_key = - Secret::derive(secret.expose_secret(), REFRESH_DIGEST_CONTEXT).map_err(|source| { - KEY_PROVIDER.error("could not derive the refresh-token key", source) - })?; + let refresh_key = AuthConfig::derive_key(secret, REFRESH_DIGEST_CONTEXT)?; let clients = Self::clients()?; let public_redirects = clients .iter() @@ -392,15 +400,32 @@ impl AuthConfig { pub fn from_environment() -> Result { let origin: Origin = PUBLIC_BASE_URL.parse()?; let settings_url: PublicUrl = SETTINGS_URL.parse_or(DEFAULT_SETTINGS_URL)?; + let persistent_key: SecretReference = KEY_PROVIDER.parse()?; + let persistent_key = persistent_key.resolve().map_err(|source| { + KEY_PROVIDER.error( + "must resolve to an RSA private PEM key of at least 2048 bits", + source, + ) + })?; Ok(Self { public_listener: PUBLIC_LISTENER.parse_or(DEFAULT_PUBLIC_LISTENER)?, - passkey: PasskeyConfig::from_environment(&origin)?, + passkey: PasskeyConfig::from_environment(&origin, &persistent_key)?, federation: FederationConfig::from_environment(&origin, &settings_url)?, - oidc: OidcConfig::from_environment(&origin)?, + oidc: OidcConfig::from_environment(&origin, &persistent_key)?, trusted_proxies: Self::trusted_proxies()?, }) } + /// Derives a service key from the persistent PEM bytes under its own `context`, + /// so each key is stable across restarts and replicas but independent of the others. + fn derive_key( + persistent_key: &SecretBytes, + context: &[u8], + ) -> Result { + Secret::derive(persistent_key.expose_secret(), context) + .map_err(|source| KEY_PROVIDER.error("could not derive a key from the PEM key", source)) + } + /// Uses the operator override, then piqueld's ingress ranges, then no trusted peers. fn trusted_proxies() -> Result, ConfigurationError> { let (variable, value) = if let Some(value) = TRUSTED_PROXIES.optional()? { diff --git a/apps/auth-service/src/passkey/ceremonies.rs b/apps/auth-service/src/passkey/ceremonies.rs index 9d2b3e503..7de639714 100644 --- a/apps/auth-service/src/passkey/ceremonies.rs +++ b/apps/auth-service/src/passkey/ceremonies.rs @@ -84,6 +84,9 @@ pub(super) enum Ceremony { Register(RegistrationCeremony), /// Username-based authentication. Login(LoginCeremony), + /// Username-based authentication for a username without an active account or + /// passkey. It holds no `WebAuthn` state, so its finish can never succeed. + Decoy, /// Discoverable account-picker authentication. Discover(DiscoverCeremony), /// Settings authorization for the initiating session. @@ -97,7 +100,7 @@ impl Ceremony { pub(super) const fn kind(&self) -> CeremonyKind { match self { Self::Register(_) => CeremonyKind::Registration, - Self::Login(_) | Self::Discover(_) => CeremonyKind::Authentication, + Self::Login(_) | Self::Decoy | Self::Discover(_) => CeremonyKind::Authentication, Self::Manage(_) => CeremonyKind::PurposeAuthentication, Self::Enroll(_) => CeremonyKind::Enrollment, } @@ -106,7 +109,7 @@ impl Ceremony { /// Derives the existing-account binding; signup has no account row yet. const fn user_id(&self) -> Option { match self { - Self::Register(_) | Self::Discover(_) => None, + Self::Register(_) | Self::Decoy | Self::Discover(_) => None, Self::Login(state) => Some(state.user_id), Self::Manage(state) => Some(state.user_id), Self::Enroll(state) => Some(state.user_id), @@ -116,7 +119,7 @@ impl Ceremony { /// Derives the initiating-session binding for settings operations. const fn session_id(&self) -> Option { match self { - Self::Register(_) | Self::Login(_) | Self::Discover(_) => None, + Self::Register(_) | Self::Login(_) | Self::Decoy | Self::Discover(_) => None, Self::Manage(state) => Some(state.session_id), Self::Enroll(state) => Some(state.session_id), } @@ -164,6 +167,8 @@ ceremony_state!(EnrollmentCeremony, Enroll, Enrollment); pub(super) enum AuthenticationCeremony { /// Account identified by username before the challenge. Login(LoginCeremony), + /// Username without an active account or passkey; always rejected. + Decoy, /// Account identified by the authenticator's response. Discover(DiscoverCeremony), } @@ -174,6 +179,7 @@ impl CeremonyState for AuthenticationCeremony { fn extract(ceremony: Ceremony) -> Option { match ceremony { Ceremony::Login(state) => Some(Self::Login(state)), + Ceremony::Decoy => Some(Self::Decoy), Ceremony::Discover(state) => Some(Self::Discover(state)), Ceremony::Register(_) | Ceremony::Manage(_) | Ceremony::Enroll(_) => None, } diff --git a/apps/auth-service/src/passkey/decoy.rs b/apps/auth-service/src/passkey/decoy.rs new file mode 100644 index 000000000..3aace434d --- /dev/null +++ b/apps/auth-service/src/passkey/decoy.rs @@ -0,0 +1,111 @@ +//! Stable decoy credentials, so username sign-in does not reveal which accounts exist. +//! +//! A username without an active account or passkey still receives a challenge listing +//! credentials. They are derived from the username with a server key, so they stay the +//! same across requests, restarts and replicas, as a real account's credentials do. +//! Nobody holds their private keys, and their ceremony fails at finish regardless. + +use piquel_crypto::{CryptoError, Digest, Secret}; +use webauthn_rs_proto::AllowCredentials; + +/// Credential type of every `WebAuthn` descriptor, as webauthn-rs writes it. +const PUBLIC_KEY_CREDENTIAL_TYPE: &str = "public-key"; +/// Decoy credential counts, each equally likely: most accounts hold one passkey. +const DECOY_COUNTS: [u8; 4] = [1, 1, 1, 2]; +/// Decoy credential ID lengths, each equally likely. Common synced passkeys use 16 +/// (such as Google Password Manager) or 20 bytes (iCloud Keychain); others use 32. +/// Decoys hide accounts whose credentials match these shapes, so keep them close to +/// the real mix. No decoy lists transports: webauthn-rs keeps them only from packed or +/// TPM attestation, and browsers replace both with `none`, which passkey registration requests. +const DECOY_ID_LENGTHS: [usize; 3] = [16, 20, 32]; +/// Input under a username's key that selects its decoy count and ID lengths. Credential +/// IDs use one-byte inputs instead, so ID bytes are independent of the chosen shape. +const DECOY_SHAPE_INPUT: &[u8] = b"shape"; + +// Each ID is a prefix of one digest, and the shape digest holds the count byte followed +// by one length byte per credential, so the indexing in `DecoyKey::credentials` is in bounds. +const _: () = { + let mut index = 0; + while index < DECOY_ID_LENGTHS.len() { + assert!(DECOY_ID_LENGTHS[index] <= Digest::LENGTH); + index += 1; + } + index = 0; + while index < DECOY_COUNTS.len() { + assert!((DECOY_COUNTS[index] as usize) < Digest::LENGTH); + index += 1; + } +}; + +/// HMAC key deriving the decoy credentials of usernames without an active account or +/// passkey. It must be derived from persistent key material, so decoys stay stable. +#[derive(Clone)] +pub(crate) struct DecoyKey(Secret); + +impl DecoyKey { + /// Wraps a key reserved for decoy credentials. + pub(crate) const fn new(key: Secret) -> Self { + Self(key) + } + + /// Returns the stable `allowCredentials` for `username`. + /// + /// # Errors + /// + /// Returns [`CryptoError`] if the HMAC provider fails. + pub(crate) fn credentials(&self, username: &str) -> Result, CryptoError> { + let key = Secret::derive(self.0.as_bytes(), username.as_bytes())?; + let shape = Digest::hmac(key.as_bytes(), DECOY_SHAPE_INPUT)?; + let [count, lengths @ ..] = shape.as_bytes(); + (0..DECOY_COUNTS[usize::from(*count) % DECOY_COUNTS.len()]) + .map(|index| { + let length = DECOY_ID_LENGTHS + [usize::from(lengths[usize::from(index)]) % DECOY_ID_LENGTHS.len()]; + Ok(AllowCredentials { + type_: PUBLIC_KEY_CREDENTIAL_TYPE.into(), + id: Digest::hmac(key.as_bytes(), &[index])?.as_bytes()[..length] + .to_vec() + .into(), + transports: None, + }) + }) + .collect() + } +} + +/// Decoy shapes without a database. +#[cfg(test)] +mod tests { + use super::{DECOY_COUNTS, DECOY_ID_LENGTHS, DecoyKey, PUBLIC_KEY_CREDENTIAL_TYPE}; + use piquel_crypto::Secret; + use std::collections::HashSet; + use webauthn_rs_proto::AllowCredentials; + + /// Across many usernames, decoys use every configured count and ID length and + /// nothing else, and a username always gets the same decoys. + #[test] + fn decoys_use_exactly_the_configured_shapes() { + let key = DecoyKey::new(Secret::generate().expect("key")); + let (mut counts, mut lengths) = (HashSet::new(), HashSet::new()); + for index in 0..256 { + let username = format!("user_{index}"); + let ids = |decoys: &[AllowCredentials]| { + decoys + .iter() + .map(|decoy| decoy.id.clone()) + .collect::>() + }; + let decoys = key.credentials(&username).expect("decoys"); + let repeated = key.credentials(&username).expect("decoys"); + assert_eq!(ids(&decoys), ids(&repeated)); + counts.insert(u8::try_from(decoys.len()).expect("count")); + for decoy in decoys { + assert_eq!(decoy.type_, PUBLIC_KEY_CREDENTIAL_TYPE); + assert!(decoy.transports.is_none()); + lengths.insert(decoy.id.len()); + } + } + assert_eq!(counts, DECOY_COUNTS.into_iter().collect()); + assert_eq!(lengths, DECOY_ID_LENGTHS.into_iter().collect()); + } +} diff --git a/apps/auth-service/src/passkey/error.rs b/apps/auth-service/src/passkey/error.rs index 8f974bfbe..f77ef5fc4 100644 --- a/apps/auth-service/src/passkey/error.rs +++ b/apps/auth-service/src/passkey/error.rs @@ -56,7 +56,7 @@ pub(super) enum PasskeyError { /// A discoverable credential returned an invalid account handle. #[error("invalid discoverable account handle")] InvalidUserHandle(#[source] InvalidValue), - /// Username-based authentication must not reveal account availability. + /// A decoy ceremony finished: the username has no active account or passkey. #[error("account unavailable for passkey authentication")] AccountUnavailable, /// The account, or the credential it signed with, was disabled or removed. @@ -104,7 +104,7 @@ pub(super) enum PasskeyError { /// Creating a browser session failed. #[error(transparent)] Session(#[from] SessionError), - /// Generating a browser-binding secret failed. + /// Generating a browser-binding secret or deriving decoy credentials failed. #[error(transparent)] Crypto(#[from] CryptoError), } @@ -158,18 +158,15 @@ impl From for ApiError { error @ PasskeyError::SessionChanged => error .rejected("Your session changed during this passkey request. Please start again."), // WebAuthn's reasons stay in the logs: some fail before possession is proven, - // so showing them would reveal which credentials an account has. - error @ PasskeyError::Webauthn(_) => { + // so showing them would reveal which credentials an account has. A decoy + // ceremony gets the same answer as an unregistered passkey, so finishing + // one reveals no more than starting it. + error @ (PasskeyError::Webauthn(_) | PasskeyError::AccountUnavailable) => { error.rejected("This passkey could not be verified. Please try again.") } error @ PasskeyError::InvalidUserHandle(_) => { error.rejected("This passkey does not belong to a Piquel account.") } - // The same answer whether the account is missing or has no passkey: the - // username field reveals no more than it must. - error @ PasskeyError::AccountUnavailable => { - error.rejected("No passkey is available for this username.") - } error @ PasskeyError::UserVerificationRequired => error .rejected("Your authenticator must verify you with a PIN, fingerprint or face."), error @ PasskeyError::CounterRegression => error.rejected( diff --git a/apps/auth-service/src/passkey/mod.rs b/apps/auth-service/src/passkey/mod.rs index f6183432e..0ba9905c2 100644 --- a/apps/auth-service/src/passkey/mod.rs +++ b/apps/auth-service/src/passkey/mod.rs @@ -14,6 +14,7 @@ use piquel_auth_protocol::{AuthenticationMethod, TokenId, UserId}; use piquel_crypto::Secret; use piquel_repository::{ AuditAction, Database, DatabaseError, DatabaseTransaction, InsertPasskey, InsertUser, + StoredPasskey, }; use serde_json::Value; use std::sync::Arc; @@ -22,6 +23,9 @@ use webauthn_rs_proto::ResidentKeyRequirement; /// Typed challenge payloads and browser binding. mod ceremonies; +/// Stable decoy credentials for usernames without an active account or passkey. +mod decoy; +pub(crate) use decoy::DecoyKey; /// Passkey failures and their browser response mapping. mod error; /// Validated names and browser request/response bodies. @@ -48,6 +52,8 @@ pub struct PasskeyApplication { webauthn: Arc, /// Whether ordinary registration needs an invitation. invite_required: bool, + /// Derives the decoy credentials of unknown usernames. + decoy_key: DecoyKey, } /// Nominal management lifetime, matching the repository's two-minute grant. @@ -76,6 +82,7 @@ impl PasskeyApplication { .build()?, ), invite_required: config.invite_required, + decoy_key: config.decoy_key.clone(), }) } @@ -161,11 +168,12 @@ impl PasskeyApplication { /// Decodes the account's active passkeys for `WebAuthn`. async fn keys(&self, user_id: UserId) -> Result, PasskeyError> { - self.database - .passkeys() - .list_active(user_id) - .await? - .into_iter() + Self::decode(self.database.passkeys().list_active(user_id).await?) + } + + /// Decodes stored passkey rows into `WebAuthn` credentials. + fn decode(keys: Vec) -> Result, PasskeyError> { + keys.into_iter() .map(|key| { serde_json::from_value(key.credential).map_err(PasskeyError::StoredCredential) }) @@ -400,6 +408,11 @@ impl PasskeyApplication { } /// Starts username-based authentication or lets the authenticator identify the account. + /// + /// A username without an active account or passkey gets the same response as one + /// with them: one lookup query, a stored ceremony and a challenge built by the same + /// call, listing stable decoy credentials. That ceremony fails at finish like an + /// unregistered passkey, so the username field reveals no account. async fn start_login( State(app): State, headers: HeaderMap, @@ -407,20 +420,25 @@ impl PasskeyApplication { ) -> Result { let (ceremony, challenge) = if let Some(username) = input.username.filter(|username| !username.is_empty()) { - let user = app + let keys = app .database - .users() - .find_active_by_username(&username) - .await? - .ok_or(PasskeyError::AccountUnavailable)?; - let (challenge, state) = app + .passkeys() + .list_active_by_username(&username) + .await?; + let user_id = keys.first().map(|key| key.user_id); + let (mut challenge, state) = app .webauthn - .start_passkey_authentication(&app.keys(user.id).await?) + .start_passkey_authentication(&Self::decode(keys)?) .map_err(PasskeyError::Webauthn)?; - let ceremony = Ceremony::Login(LoginCeremony { - user_id: user.id, - state, - }); + let ceremony = if let Some(user_id) = user_id { + Ceremony::Login(LoginCeremony { user_id, state }) + } else { + challenge.public_key.allow_credentials = app + .decoy_key + .credentials(&username) + .map_err(PasskeyError::Crypto)?; + Ceremony::Decoy + }; (ceremony, challenge) } else { let (mut challenge, state) = app @@ -449,6 +467,7 @@ impl PasskeyApplication { .finish_passkey_authentication(&input.credential, &state) .map_err(PasskeyError::Webauthn)?, ), + AuthenticationCeremony::Decoy => return Err(PasskeyError::AccountUnavailable.into()), AuthenticationCeremony::Discover(DiscoverCeremony { state }) => { let (uuid, _) = app .webauthn diff --git a/apps/auth-service/src/passkey/tests.rs b/apps/auth-service/src/passkey/tests.rs index d5927ac72..489589739 100644 --- a/apps/auth-service/src/passkey/tests.rs +++ b/apps/auth-service/src/passkey/tests.rs @@ -147,6 +147,7 @@ impl Fixture { .parse::() .expect("origin"), invite_required: false, + decoy_key: DecoyKey::new(Secret::generate().expect("decoy key")), }, ) .expect("passkey app"); @@ -219,13 +220,16 @@ impl Fixture { let response = self.request(path, Method::POST, cookies, body).await; assert_eq!(response.status(), StatusCode::OK); let cookie = Self::cookie(&response); - let value = serde_json::from_slice( + (Self::json(response).await, cookie) + } + /// Reads a response's JSON body. + async fn json(response: Response) -> Value { + serde_json::from_slice( &to_bytes(response.into_body(), MAX_RESPONSE_BYTES) .await .expect("body"), ) - .expect("JSON"); - (value, cookie) + .expect("JSON") } /// Extracts the cookie pair from a response for the next simulated browser request. fn cookie(response: &Response) -> String { @@ -518,3 +522,90 @@ async fn ceremonies_require_browser_binding_and_management_requires_the_same_ses assert_eq!(keys.len(), 1); assert_eq!(keys[0].friendly_name, "Renamed twice"); } + +/// Checks that a username without an account gets a stable challenge shaped like a +/// real account's, and that finishing it fails exactly like an unregistered passkey. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn unknown_usernames_get_stable_decoys_that_fail_like_unregistered_passkeys() { + let fixture = Fixture::new().await; + let unknown = format!("none_{}", &TokenId::new().to_string()[24..]); + let start = |username: &str| { + fixture.start( + "/webauthn/authenticate/start", + "", + json!({"username":username}), + ) + }; + let (known, known_browser) = start(&fixture.username).await; + let (decoy, decoy_browser) = start(&unknown).await; + // Apart from the fresh challenge and the credential list, the options are identical. + let options = |started: &Value| { + let mut options = started["public_key"].clone(); + options["publicKey"]["challenge"].take(); + options["publicKey"]["allowCredentials"].take(); + options + }; + assert_eq!(options(&known), options(&decoy)); + let credentials = |started: &Value| { + started["public_key"]["publicKey"]["allowCredentials"] + .as_array() + .expect("allowCredentials") + .clone() + }; + let real = &credentials(&known)[0]; + let fields = |value: &Value| -> Vec { + value + .as_object() + .expect("descriptor") + .keys() + .cloned() + .collect() + }; + for credential in credentials(&decoy) { + assert_eq!(fields(&credential), fields(real)); + assert_eq!(credential["type"], real["type"]); + } + assert_eq!(credentials(&decoy), credentials(&start(&unknown).await.0)); + assert_ne!( + credentials(&decoy), + credentials(&start(&format!("{unknown}x")).await.0) + ); + + // A passkey the server never registered, standing in for any guess at the account. + let (challenge, _) = fixture + .app + .webauthn + .start_passkey_registration(UserId::new().as_uuid(), "stranger", "Stranger", None) + .expect("registration"); + let mut stranger = WebauthnAuthenticator::new(SoftPasskey::new(true)); + let id = stranger + .do_registration(fixture.origin.clone(), challenge) + .expect("software registration") + .raw_id; + let mut failures = Vec::new(); + for (started, browser) in [(known, known_browser), (decoy, decoy_browser)] { + let mut challenge: RequestChallengeResponse = + serde_json::from_value(started["public_key"].clone()).expect("challenge"); + challenge.public_key.allow_credentials = vec![webauthn_rs_proto::AllowCredentials { + type_: "public-key".into(), + id: id.clone(), + transports: None, + }]; + let assertion = stranger + .do_authentication(fixture.origin.clone(), challenge) + .expect("software assertion"); + let response = fixture + .request( + "/webauthn/authenticate/finish", + Method::POST, + &browser, + json!({"ceremony_id":started["ceremony_id"],"credential":assertion}), + ) + .await; + assert!(response.headers().get(header::SET_COOKIE).is_none()); + failures.push((response.status(), Fixture::json(response).await)); + } + assert_eq!(failures[0].0, StatusCode::BAD_REQUEST); + assert_eq!(failures[0], failures[1]); +} diff --git a/crates/crypto/src/lib.rs b/crates/crypto/src/lib.rs index e98ac66bd..03e170931 100644 --- a/crates/crypto/src/lib.rs +++ b/crates/crypto/src/lib.rs @@ -127,6 +127,8 @@ impl fmt::Debug for Secret { #[derive(Clone, Copy, Debug, PartialEq, Eq)] pub struct Digest([u8; SECRET_BYTES]); impl Digest { + /// Byte length of every digest. + pub const LENGTH: usize = SECRET_BYTES; /// Computes SHA-256 over arbitrary bytes. #[must_use] pub fn sha256(value: &[u8]) -> Self { diff --git a/crates/database/.sqlx/query-d9952c239924fe4e4600dd84197e70ee6288e5d14ae6039e00d1434839217d39.json b/crates/database/.sqlx/query-d9952c239924fe4e4600dd84197e70ee6288e5d14ae6039e00d1434839217d39.json new file mode 100644 index 000000000..7b0d57e7f --- /dev/null +++ b/crates/database/.sqlx/query-d9952c239924fe4e4600dd84197e70ee6288e5d14ae6039e00d1434839217d39.json @@ -0,0 +1,52 @@ +{ + "db_name": "PostgreSQL", + "query": "SELECT\n p.id AS \"id: TokenId\", p.credential_id, p.user_id AS \"user_id: UserId\",\n p.credential, p.friendly_name, p.revoked_at\n FROM passkey_credentials p\n JOIN users u ON u.id = p.user_id\n WHERE u.username = $1\n AND u.status = 'active'\n AND p.revoked_at IS NULL\n ORDER BY p.created_at", + "describe": { + "columns": [ + { + "ordinal": 0, + "name": "id: TokenId", + "type_info": "Uuid" + }, + { + "ordinal": 1, + "name": "credential_id", + "type_info": "Bytea" + }, + { + "ordinal": 2, + "name": "user_id: UserId", + "type_info": "Uuid" + }, + { + "ordinal": 3, + "name": "credential", + "type_info": "Jsonb" + }, + { + "ordinal": 4, + "name": "friendly_name", + "type_info": "Text" + }, + { + "ordinal": 5, + "name": "revoked_at", + "type_info": "Timestamptz" + } + ], + "parameters": { + "Left": [ + "Text" + ] + }, + "nullable": [ + false, + false, + false, + false, + false, + true + ] + }, + "hash": "d9952c239924fe4e4600dd84197e70ee6288e5d14ae6039e00d1434839217d39" +} diff --git a/crates/database/src/repositories/passkeys.rs b/crates/database/src/repositories/passkeys.rs index 8061e84d1..e463a8c24 100644 --- a/crates/database/src/repositories/passkeys.rs +++ b/crates/database/src/repositories/passkeys.rs @@ -137,6 +137,36 @@ impl PasskeyRepository<'_> { ) } + /// Lists the unrevoked credentials of the active account named `username`, + /// oldest first. A missing, inactive or passkey-less account returns none, + /// in the same single query, so callers cannot tell those cases apart. + /// + /// # Errors + /// + /// Returns [`DatabaseError`] if the query fails or a row is invalid. + pub async fn list_active_by_username( + &mut self, + username: &str, + ) -> Result, DatabaseError> { + run!( + self, + fetch_all, + sqlx::query_as!( + StoredPasskey, + r#"SELECT + p.id AS "id: TokenId", p.credential_id, p.user_id AS "user_id: UserId", + p.credential, p.friendly_name, p.revoked_at + FROM passkey_credentials p + JOIN users u ON u.id = p.user_id + WHERE u.username = $1 + AND u.status = 'active' + AND p.revoked_at IS NULL + ORDER BY p.created_at"#, + username, + ) + ) + } + /// Finds an unrevoked credential and locks it until the transaction ends, /// so authentication rechecks it before updating. /// @@ -346,3 +376,58 @@ impl PasskeyRepository<'_> { ) } } + +/// Username lookups against a running database. +#[cfg(test)] +mod tests { + use super::{InsertPasskey, PasskeyRepository}; + use crate::Database; + use piquel_auth_protocol::{TokenId, UserId}; + + /// A disabled account and an account whose only passkey is revoked list no + /// credentials, like a username nobody holds. + #[tokio::test] + #[ignore = "requires a disposable TEST_DATABASE_URL"] + async fn username_lookup_hides_disabled_accounts_and_revoked_passkeys() { + let pool = Database::test_pool().await; + let mut passkeys = PasskeyRepository::from_pool(&pool); + for disable in [true, false] { + let user = UserId::new(); + let username = format!("passkey_{user}"); + sqlx::query("INSERT INTO users(id,username,display_name) VALUES($1,$2,'Passkey test')") + .bind(user.as_uuid()) + .bind(&username) + .execute(&pool) + .await + .expect("user"); + let key = passkeys + .insert(&InsertPasskey { + id: TokenId::new(), + credential_id: user.as_uuid().as_bytes().to_vec(), + user_id: user, + credential: serde_json::json!({}), + friendly_name: "Passkey test".into(), + }) + .await + .expect("passkey"); + let listed = || async { + PasskeyRepository::from_pool(&pool) + .list_active_by_username(&username) + .await + .expect("lookup") + .len() + }; + assert_eq!(listed().await, 1); + if disable { + sqlx::query("UPDATE users SET status = 'disabled' WHERE id = $1") + .bind(user.as_uuid()) + .execute(&pool) + .await + .expect("disable"); + } else { + assert!(passkeys.revoke(key.id, user).await.expect("revoke")); + } + assert_eq!(listed().await, 0, "disable: {disable}"); + } + } +}