diff --git a/crates/features/src/audit/record.rs b/crates/features/src/audit/record.rs index bdbc47cb..d8a8b758 100644 --- a/crates/features/src/audit/record.rs +++ b/crates/features/src/audit/record.rs @@ -99,6 +99,8 @@ pub enum Via { }, /// The recovery administrator from the server's own configuration. Recovery, + /// A passkey (passkeys spec, PK-11). + Passkey, /// A migration's run, acting for the administrator who started it /// (migrations spec, MG-10). Migration { diff --git a/crates/http/src/api/mod.rs b/crates/http/src/api/mod.rs index 8acf8548..e2d4f02e 100644 --- a/crates/http/src/api/mod.rs +++ b/crates/http/src/api/mod.rs @@ -66,6 +66,12 @@ impl ManagementApi for Server { let path = req.uri().path().split('/').skip(2).collect::>(); match path.first().copied().unwrap_or_default() { + // inbuxa: passkeys spec, PK-10: a sign-in challenge + "auth" if is_post && path.get(1).copied() == Some("passkey") => { + self.is_http_anonymous_request_allowed(session.remote_ip) + .await?; + crate::auth::passkey::challenge(self).await + } "auth" if is_post => { self.is_http_anonymous_request_allowed(session.remote_ip) .await?; diff --git a/crates/http/src/auth/oauth/auth.rs b/crates/http/src/auth/oauth/auth.rs index 453bea5d..679da598 100644 --- a/crates/http/src/auth/oauth/auth.rs +++ b/crates/http/src/auth/oauth/auth.rs @@ -100,7 +100,10 @@ pub trait OAuthApiHandler: Sync + Send { pub enum LoginRequest { #[serde(rename_all = "camelCase")] AuthCode { + // 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)] @@ -120,6 +123,9 @@ pub enum LoginRequest { state: Option, #[serde(default)] resource: Vec, + // inbuxa: passkeys spec, PK-11: an assertion in place of the password + #[serde(default, skip_serializing_if = "Option::is_none")] + passkey: Option, }, #[serde(rename_all = "camelCase")] AuthDevice { @@ -191,6 +197,7 @@ impl OAuthApiHandler for Server { code_challenge, code_challenge_method, resource, + passkey, .. } => { // Validate clientId @@ -306,19 +313,25 @@ impl OAuthApiHandler for Server { } }; - // 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-11) + 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) => { // Registry-backed clients are validated once the account is known if stateless_client.is_none() diff --git a/crates/http/src/auth/passkey.rs b/crates/http/src/auth/passkey.rs index 0b2ecea0..61d7a344 100644 --- a/crates/http/src/auth/passkey.rs +++ b/crates/http/src/auth/passkey.rs @@ -4,7 +4,10 @@ * SPDX-License-Identifier: AGPL-3.0-only */ -//! inbuxa: passkey registration (passkeys spec, PK-6 to PK-8). +//! inbuxa: passkeys (passkeys spec): registration (PK-6 to PK-8) and +//! sign-in (PK-9 to PK-12). +//! +//! Registration: //! //! `inbuxa:Passkey/set` create hands back a URL to `/passkey/register` with //! a single-use ticket. That page posts here twice: @@ -18,6 +21,12 @@ //! //! What `start` began waits in the in-memory store under the ticket, so any //! node can answer `finish`, and it's deleted as it's read: it's good once. +//! Instead of the password, `start` takes one of the account's active +//! passkeys. +//! +//! Sign-in: `POST /api/auth/passkey` hands out a challenge (PK-10), kept in +//! the in-memory store for two minutes and good once; the login request then +//! carries the browser's assertion in place of a name and password (PK-11). use common::{ KV_PASSKEY_CEREMONY, Server, @@ -25,22 +34,36 @@ use common::{ }; 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 serde::{Deserialize, Serialize}; use store::{ dispatch::lookup::KeyValue, - rand::{RngExt, rng}, + rand::{RngExt, distr::Alphanumeric, rng}, write::now, }; use trc::AddContext; use webauthn_rs::prelude::{ - CreationChallengeResponse, Credential, CredentialID, PasskeyRegistration, - RegisterPublicKeyCredential, Url, Uuid, Webauthn, WebauthnBuilder, + CreationChallengeResponse, Credential, CredentialID, DiscoverableAuthentication, + PasskeyRegistration, PublicKeyCredential, RegisterPublicKeyCredential, + RequestChallengeResponse, Url, Uuid, Webauthn, WebauthnBuilder, WebauthnError, }; use webauthn_rs_proto::ResidentKeyRequirement; /// How long the browser has between `start` and `finish`. const CEREMONY_SECONDS: u64 = 300; +/// How long a sign-in challenge lasts (PK-10). +const CHALLENGE_SECONDS: u64 = 120; +const CHALLENGE_ID_LEN: usize = 32; + +/// What the browser answered a sign-in challenge with. +#[derive(Debug, Clone, Serialize, Deserialize)] +#[serde(rename_all = "camelCase")] +pub struct PasskeyAssertion { + pub challenge_id: String, + pub credential: Box, +} #[derive(Debug, Deserialize)] #[serde(tag = "step", rename_all = "camelCase")] @@ -48,9 +71,13 @@ pub enum RegisterRequest { #[serde(rename_all = "camelCase")] Start { ticket: String, + #[serde(default)] password: String, #[serde(default)] mfa_token: Option, + /// One of the account's passkeys, in place of the password (PK-8). + #[serde(default)] + passkey: Option, }, #[serde(rename_all = "camelCase")] Finish { @@ -117,7 +144,233 @@ pub fn relying_party(server: &Server) -> trc::Result<(Webauthn, String)> { } fn ceremony_key(ticket: &str) -> Vec { - KeyValue::<()>::build_key(KV_PASSKEY_CEREMONY, passkey::ticket_hash(ticket)) + let mut key = vec![b'r']; + key.extend_from_slice(&passkey::ticket_hash(ticket)); + KeyValue::<()>::build_key(KV_PASSKEY_CEREMONY, key) +} + +fn challenge_key(id: &str) -> Vec { + let mut key = vec![b'a']; + key.extend_from_slice(id.as_bytes()); + KeyValue::<()>::build_key(KV_PASSKEY_CEREMONY, key) +} + +/// A sign-in challenge between the two requests. +#[derive(Serialize, Deserialize)] +struct SignInCeremony { + rp_id: String, + state: DiscoverableAuthentication, +} + +#[derive(Serialize)] +#[serde(rename_all = "camelCase")] +struct ChallengeResponse { + challenge_id: String, + options: Box, +} + +/// PK-10: a challenge for the login page or the registration page. The +/// 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)?; + let (options, state) = webauthn + .start_discoverable_authentication() + .map_err(|err| { + trc::AuthEvent::Error + .into_err() + .details("Failed to start a passkey sign-in") + .reason(err) + })?; + let challenge_id = rng() + .sample_iter(Alphanumeric) + .take(CHALLENGE_ID_LEN) + .map(char::from) + .collect::(); + let ceremony = serde_json::to_string(&SignInCeremony { rp_id, state }).map_err(|err| { + trc::StoreEvent::UnexpectedError + .into_err() + .details("Failed to serialize a passkey sign-in") + .reason(err) + })?; + server + .in_memory_store() + .key_set( + KeyValue::new(challenge_key(&challenge_id), ceremony.into_bytes()) + .expires(CHALLENGE_SECONDS), + ) + .await?; + Ok(JsonResponse::new(ChallengeResponse { + challenge_id, + options: Box::new(options), + }) + .no_cache() + .into_http_response()) +} + +fn refused(reason: &'static str) -> trc::Error { + trc::AuthEvent::Failed + .into_err() + .details("Passkey sign-in refused") + .reason(reason) +} + +/// PK-11, PK-12: signs in with a passkey. Failures count toward the same +/// limits and blocking as a wrong password, and a passkey needs no TOTP code. +pub async fn sign_in( + server: &Server, + session: &HttpSessionData, + assertion: &PasskeyAssertion, +) -> trc::Result { + let result = check_assertion(server, session, assertion) + .await + .and_then(|token| { + // AL-2: a locked account fails as a wrong passkey does + if token.is_locked() { + Err(refused("Account is locked").ctx(trc::Key::AccountId, token.account_id())) + } else { + token.assert_has_permission(Permission::Authenticate) + } + }); + let request = AuthRequest { + credentials: Credentials::Bearer { + username: None, + token: String::new(), + }, + session_id: session.session_id, + remote_ip: session.remote_ip, + }; + match result { + Ok(token) => { + trc::event!( + Auth(trc::AuthEvent::Success), + AccountId = token.account_id(), + SpanId = session.session_id, + Type = "passkey", + ); + // AU-1.4, AU-1.5 + server.audit_sign_in(&request, &token).await; + Ok(token) + } + Err(err) => { + if matches!(err.as_ref(), trc::EventType::Auth(trc::AuthEvent::Failed)) + && server.has_auth_fail2ban() + && server.is_auth_fail2banned(session.remote_ip, None).await? + { + Err(trc::SecurityEvent::AuthenticationBan + .into_err() + .ctx(trc::Key::RemoteIp, session.remote_ip)) + } else { + Err(err.ctx(trc::Key::RemoteIp, session.remote_ip)) + } + } + } +} + +async fn check_assertion( + server: &Server, + session: &HttpSessionData, + assertion: &PasskeyAssertion, +) -> trc::Result { + // PK-10: good once + if assertion.challenge_id.len() != CHALLENGE_ID_LEN { + return Err(refused("Unknown passkey challenge")); + } + let key = challenge_key(&assertion.challenge_id); + let Some(ceremony) = server + .in_memory_store() + .key_get::(key.clone()) + .await? + else { + return Err(refused("Unknown, used or expired passkey challenge")); + }; + server.in_memory_store().key_delete(key).await?; + let ceremony = serde_json::from_str::(&ceremony).map_err(|err| { + trc::StoreEvent::DataCorruption + .into_err() + .details("Invalid passkey sign-in") + .reason(err) + })?; + let (webauthn, rp_id) = relying_party(server)?; + if rp_id != ceremony.rp_id { + return Err(refused("The relying-party id changed during sign-in")); + } + + // The account by user handle, the passkey by credential id: both must agree + let credential = &assertion.credential; + let (handle, credential_id) = webauthn + .identify_discoverable_authentication(credential) + .map_err(|_| refused("No user handle in the passkey's answer"))?; + let Some(mut record) = passkey::by_credential(server.store(), credential_id) + .await? + .filter(|p| p.state == passkey::State::Active) + else { + return Err(refused("Unknown passkey")); + }; + if passkey::account_of_handle(server.store(), handle.as_bytes()).await? + != Some(record.account_id) + { + return Err(refused("The passkey belongs to another 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( + refused("The passkey was registered for another relying-party id") + .ctx(trc::Key::AccountId, record.account_id), + ); + } + let mut stored = serde_json::from_slice::(&record.public_key) + .map_err(|err| { + trc::StoreEvent::DataCorruption + .into_err() + .details("Invalid stored passkey") + .reason(err) + })?; + + // The signature, the origin (PK-2), user verification and the counter + let result = match webauthn.finish_discoverable_authentication_v2( + credential, + ceremony.state, + Credential::from(stored.clone()), + ) { + Ok(result) => result, + Err(WebauthnError::CredentialPossibleCompromise) => { + trc::event!( + Auth(trc::AuthEvent::Failed), + 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", + ); + return Err(refused("Passkey counter went backwards") + .ctx(trc::Key::AccountId, record.account_id)); + } + Err(err) => { + return Err(refused("The passkey's answer didn't check out") + .ctx(trc::Key::AccountId, record.account_id) + .details(err.to_string())); + } + }; + + // Keep the new counter and flags, and when it was last used + stored.update_credential(&result); + record.sign_count = result.counter(); + record.backed_up = result.backup_state(); + record.last_used_at = Some(now()); + record.public_key = serde_json::to_vec(&stored).map_err(|err| { + trc::StoreEvent::UnexpectedError + .into_err() + .details("Failed to serialize a passkey") + .reason(err) + })?; + passkey::save(server.store(), &record).await?; + + server + .access_token(record.account_id) + .await + .and_then(|token| AccessToken::new(token, session.remote_ip)) + .map(|token| token.with_origin(Via::Passkey)) } pub trait PasskeyRegistrationHandler: Sync + Send { @@ -142,7 +395,8 @@ impl PasskeyRegistrationHandler for Server { ticket, password, mfa_token, - } => start(self, session, &ticket, password, mfa_token).await?, + passkey, + } => start(self, session, &ticket, password, mfa_token, passkey).await?, RegisterRequest::Finish { ticket, credential } => { finish(self, &ticket, &credential).await? } @@ -157,6 +411,7 @@ async fn start( ticket: &str, password: String, mfa_token: Option, + assertion: Option, ) -> trc::Result { let Some(pending) = passkey::by_ticket(server.store(), ticket, now()).await? else { return Ok(RegisterResponse::Expired); @@ -166,20 +421,26 @@ async fn start( .await .caused_by(trc::location!())?; - // PK-8: the password (and code) first. The sign-in limits and the - // failure counting are the ones every sign-in goes through. - let access_token: AccessToken = match server - .authenticate(&AuthRequest { - credentials: Credentials::Basic { - username: account.name.to_string(), - secret: password, - mfa_token, - }, - session_id: session.session_id, - remote_ip: session.remote_ip, - }) - .await - { + // PK-8: the password (and code), or an active passkey, first. The + // sign-in limits and the failure counting are the ones every sign-in + // goes through. + let signed_in = match &assertion { + Some(assertion) => sign_in(server, session, assertion).await, + None => { + server + .authenticate(&AuthRequest { + credentials: Credentials::Basic { + username: account.name.to_string(), + secret: password, + mfa_token, + }, + session_id: session.session_id, + remote_ip: session.remote_ip, + }) + .await + } + }; + let access_token: AccessToken = match signed_in { Ok(access_token) => access_token, Err(err) => { return match *err.as_ref() { @@ -195,7 +456,10 @@ async fn start( }; } }; - if access_token.account_id() != pending.account_id { + // An app password is for one app, not for adding ways to sign in + if access_token.account_id() != pending.account_id + || matches!(access_token.origin(), Some(Via::AppPassword { .. })) + { return Ok(RegisterResponse::Failure); } diff --git a/docs/spec/features/passkeys.md b/docs/spec/features/passkeys.md index 75360c96..87ffa720 100644 --- a/docs/spec/features/passkeys.md +++ b/docs/spec/features/passkeys.md @@ -268,10 +268,15 @@ Building, one PR each: `POST /api/passkey/register` with a `start` step (ticket and password, plus the TOTP code when the account has one; anonymous, limited like the other sign-in requests) and a `finish` step. What `start` began waits in - the in-memory store for up to 5 minutes and is good once. Until sign-in - with a passkey exists (step 3), the page asks for the password only; the - "or an active passkey" of PK-8 comes with it. -3. Sign-in in the authorization-code flow, with autofill. + the in-memory store for up to 5 minutes and is good once. +3. Sign-in in the authorization-code flow: `POST /api/auth/passkey` for a + challenge, the login request's `passkey` field (`challengeId` and the + browser's assertion) in place of the name and password, autofill on the + username field and a "Sign in with a passkey" button. The registration + page takes an active passkey instead of the password (PK-8), and an app + 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. Then the webmail and console pages. diff --git a/resources/html-templates/login.html b/resources/html-templates/login.html index d4b000cb..024d4fd3 100644 --- a/resources/html-templates/login.html +++ b/resources/html-templates/login.html @@ -283,6 +283,13 @@ transform: none; } + /* INBUXA (#334): the passkey button, under the main one */ + .btn.secondary { + background: transparent; + color: var(--text); + border: 1px solid var(--border); + } + [hidden] { display: none !important; } @@ -313,7 +320,7 @@
-
@@ -332,6 +339,7 @@ pattern="\d{6}" autocomplete="one-time-code">
+
@@ -538,7 +546,13 @@ ? 'Sign in to approve this device.' : 'Enter your credentials to continue'); } - showError('Invalid username or password. Please try again.'); + if (usedPasskey) { + usedPasskey = false; + showError('That passkey didn\'t sign you in. Try again, or use your password.'); + startAutofill(); + } else { + showError('Invalid username or password. Please try again.'); + } return; default: console.log('Unknown login response type:', resp); @@ -549,6 +563,7 @@ function submitLogin(e) { if (e) e.preventDefault(); clearAlert(); + usedPasskey = false; var creds; if (inMfa) { @@ -622,6 +637,108 @@ $('login-form').addEventListener('submit', submitLogin); + // INBUXA (#334): passkeys (passkeys spec PK-9 to PK-11). The + // browser's autofill offers them on the username field, and the + // button asks for one directly. Each try fetches a challenge that + // is good once, for two minutes. + var usedPasskey = false; + var autofill = null; + var canPasskey = !isDevice && window.PublicKeyCredential && navigator.credentials && + typeof navigator.credentials.get === 'function' && window.AbortController; + + function fromB64(s) { + s = s.replace(/-/g, '+').replace(/_/g, '/'); + while (s.length % 4) s += '='; + var bin = atob(s), out = new Uint8Array(bin.length); + for (var i = 0; i < bin.length; i++) out[i] = bin.charCodeAt(i); + return out.buffer; + } + function toB64(buf) { + var bytes = new Uint8Array(buf), bin = ''; + for (var i = 0; i < bytes.length; i++) bin += String.fromCharCode(bytes[i]); + return btoa(bin).replace(/\+/g, '-').replace(/\//g, '_').replace(/=+$/, ''); + } + + function getPasskey(mediation, signal) { + return fetch('/api/auth/passkey', { + method: 'POST', + credentials: 'omit', + cache: 'no-store', + headers: { 'Accept': 'application/json' } + }).then(function (res) { + if (res.status !== 200) throw new Error('http ' + res.status); + return res.json(); + }).then(function (c) { + var pk = c.options.publicKey; + pk.challenge = fromB64(pk.challenge); + (pk.allowCredentials || []).forEach(function (a) { a.id = fromB64(a.id); }); + var opts = { publicKey: pk }; + if (mediation) opts.mediation = mediation; + if (signal) opts.signal = signal; + return navigator.credentials.get(opts).then(function (cred) { + var r = cred.response; + return { + challengeId: c.challengeId, + credential: { + id: cred.id, + rawId: toB64(cred.rawId), + type: cred.type, + response: { + authenticatorData: toB64(r.authenticatorData), + clientDataJSON: toB64(r.clientDataJSON), + signature: toB64(r.signature), + userHandle: r.userHandle ? toB64(r.userHandle) : null + }, + extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {} + } + }; + }); + }); + } + + function signInWithPasskey(assertion) { + clearAlert(); + usedPasskey = true; + var body = buildRequest({ account_name: '', account_secret: '' }, null); + delete body.accountName; + delete body.accountSecret; + body.passkey = assertion; + postLogin(body); + } + + function startAutofill() { + if (!canPasskey || !PublicKeyCredential.isConditionalMediationAvailable) return; + PublicKeyCredential.isConditionalMediationAvailable().then(function (ok) { + if (!ok) return; + if (autofill) autofill.abort(); + var mine = new AbortController(); + autofill = mine; + // A challenge lasts two minutes: ask for a new one before then + var renew = setTimeout(function () { if (autofill === mine) startAutofill(); }, 110000); + getPasskey('conditional', mine.signal).then(function (assertion) { + clearTimeout(renew); + autofill = null; + signInWithPasskey(assertion); + }, function () { clearTimeout(renew); }); + }, function () {}); + } + + if (canPasskey) { + show($('passkey-btn')); + $('passkey-btn').addEventListener('click', function () { + if (autofill) { autofill.abort(); autofill = null; } + clearAlert(); + getPasskey(null, null).then(signInWithPasskey, function (err) { + console.log('Passkey sign-in did not finish:', err); + if (!err || (err.name !== 'NotAllowedError' && err.name !== 'AbortError')) { + showError('Passkeys aren\'t available right now. Use your password.'); + } + startAutofill(); + }); + }); + startAutofill(); + } + // Digit-only filter on OTP and auto-submit on 6 digits. $('otp').addEventListener('input', function () { this.value = this.value.replace(/\D/g, ''); diff --git a/resources/html-templates/login.html.min b/resources/html-templates/login.html.min index f0b78892..0fb39cd0 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 a842b4b7..4ab658ba 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/html-templates/passkey.html b/resources/html-templates/passkey.html index 4895bb91..6cada6ff 100644 --- a/resources/html-templates/passkey.html +++ b/resources/html-templates/passkey.html @@ -283,6 +283,12 @@ transform: none; } + .btn.secondary { + background: transparent; + color: var(--text); + border: 1px solid var(--border); + } + [hidden] { display: none !important; } @@ -326,6 +332,7 @@ pattern="\d{6}" autocomplete="one-time-code"> + @@ -467,20 +474,45 @@ }); } - function submit(e) { - if (e) e.preventDefault(); - clearAlert(); - var password = $('password').value; - if (!password) { showError('Enter your password.'); return; } - var otp = $('otp').value.trim(); - var body = { step: 'start', ticket: ticket, password: password }; - if (!$('field-otp').hidden) { - if (!/^\d{6}$/.test(otp)) { showError('Enter the 6-digit code.'); return; } - body.mfaToken = otp; - } + function getPasskey() { + return fetch('/api/auth/passkey', { + method: 'POST', + credentials: 'omit', + cache: 'no-store', + headers: { 'Accept': 'application/json' } + }).then(function (res) { + if (res.status !== 200) throw new Error('http ' + res.status); + return res.json(); + }).then(function (c) { + var pk = c.options.publicKey; + pk.challenge = fromB64(pk.challenge); + (pk.allowCredentials || []).forEach(function (a) { a.id = fromB64(a.id); }); + return navigator.credentials.get({ publicKey: pk }).then(function (cred) { + var r = cred.response; + return { + challengeId: c.challengeId, + credential: { + id: cred.id, + rawId: toB64(cred.rawId), + type: cred.type, + response: { + authenticatorData: toB64(r.authenticatorData), + clientDataJSON: toB64(r.clientDataJSON), + signature: toB64(r.signature), + userHandle: r.userHandle ? toB64(r.userHandle) : null + }, + extensions: cred.getClientExtensionResults ? cred.getClientExtensionResults() : {} + } + }; + }); + }); + } + + function begin(body, viaPasskey) { var btn = $('submit-btn'); btn.disabled = true; - post(body).then(function (json) { + $('passkey-btn').disabled = true; + return post(body).then(function (json) { switch (json.type) { case 'options': $('account').value = json.accountName; @@ -504,7 +536,11 @@ expired(); return; default: - showError(!$('field-otp').hidden ? 'The password or code is wrong.' : 'The password is wrong.'); + if (viaPasskey) { + showError('That passkey isn\'t one of this account\'s. Use your password.'); + } else { + showError(!$('field-otp').hidden ? 'The password or code is wrong.' : 'The password is wrong.'); + } $('otp').value = ''; } }).catch(function (err) { @@ -518,7 +554,40 @@ } console.log('Passkey registration failed:', err); showError('Temporary server failure. If the problem persists, contact your administrator.'); - }).then(function () { btn.disabled = false; }); + }).then(function () { + btn.disabled = false; + $('passkey-btn').disabled = false; + }); + } + + function submit(e) { + if (e) e.preventDefault(); + clearAlert(); + var password = $('password').value; + if (!password) { showError('Enter your password.'); return; } + var otp = $('otp').value.trim(); + var body = { step: 'start', ticket: ticket, password: password }; + if (!$('field-otp').hidden) { + if (!/^\d{6}$/.test(otp)) { showError('Enter the 6-digit code.'); return; } + body.mfaToken = otp; + } + begin(body, false); + } + + // PK-8: an active passkey of the account instead of the password + if (navigator.credentials.get) { + show($('passkey-btn')); + $('passkey-btn').addEventListener('click', function () { + clearAlert(); + getPasskey().then(function (assertion) { + begin({ step: 'start', ticket: ticket, passkey: assertion }, true); + }, function (err) { + console.log('Passkey sign-in did not finish:', err); + if (!err || (err.name !== 'NotAllowedError' && err.name !== 'AbortError')) { + showError('Passkeys aren\'t available right now. Use your password.'); + } + }); + }); } $('passkey-form').addEventListener('submit', submit); diff --git a/resources/html-templates/passkey.html.min b/resources/html-templates/passkey.html.min index 752f1e3f..c10cf2c6 100644 --- a/resources/html-templates/passkey.html.min +++ b/resources/html-templates/passkey.html.min @@ -1,481 +1 @@ - - - - - - - -Add a passkey · inbuxa - - - - -
-
- -
-

Add a passkey

-

Confirm it's you, then create the passkey on this device.

- -
- -
- - -
- - -
-
- - - + Add a passkey · inbuxa

Add a passkey

Confirm it's you, then create the passkey on this device.

\ No newline at end of file diff --git a/resources/html-templates/passkey.html.min.gz b/resources/html-templates/passkey.html.min.gz index c1e8fb06..926ec363 100644 Binary files a/resources/html-templates/passkey.html.min.gz and b/resources/html-templates/passkey.html.min.gz differ diff --git a/tests/src/system/oidc.rs b/tests/src/system/oidc.rs index ed5b102e..e8d2d0d9 100644 --- a/tests/src/system/oidc.rs +++ b/tests/src/system/oidc.rs @@ -352,6 +352,7 @@ pub async fn test(test: &mut TestServer) { code_challenge_method: Some("S256".to_string()), state: None, resource: vec![], + passkey: None, }) .await; assert_ne!( @@ -372,6 +373,7 @@ pub async fn test(test: &mut TestServer) { code_challenge_method: Some("S256".to_string()), state: None, resource: vec!["https://evil.example.com/jmap".to_string()], + passkey: None, }) .await; assert_ne!( @@ -394,6 +396,7 @@ pub async fn test(test: &mut TestServer) { code_challenge_method: method.map(str::to_string), state: None, resource: vec![], + passkey: None, }) .await; assert_ne!(status, 200, "PKCE method {method:?} must not be authorized"); @@ -432,6 +435,7 @@ pub async fn test(test: &mut TestServer) { code_challenge_method: challenge.map(|_| "S256".to_string()), state: None, resource: vec![], + passkey: None, }) .await; assert_eq!( @@ -459,6 +463,7 @@ pub async fn test(test: &mut TestServer) { code_challenge_method: Some("S256".to_string()), state: None, resource: vec!["https://mail.example.org/jmap/session".to_string()], + passkey: None, }, ) .await @@ -627,6 +632,7 @@ pub async fn test(test: &mut TestServer) { code_challenge_method: Some("S256".to_string()), state: None, resource: vec![], + passkey: None, }, ) .await @@ -1356,6 +1362,7 @@ async fn obtain_auth_code(http: &HttpRequest, client_id: &str, redirect_uri: &st code_challenge_method: None, state: None, resource: vec![], + passkey: None, }, ) .await diff --git a/tests/src/system/passkeys.rs b/tests/src/system/passkeys.rs index eb2fe750..622258a8 100644 --- a/tests/src/system/passkeys.rs +++ b/tests/src/system/passkeys.rs @@ -7,7 +7,8 @@ //! Passkeys (passkeys spec): `inbuxa:Passkey` management (PK-5, PK-14 to //! PK-17): starting a registration, the limit per account, renaming, //! removing, who reaches whose passkeys, and the audit log. Registration on -//! the server's page (PK-6 to PK-8), with a software authenticator. +//! the server's page (PK-6 to PK-8) and sign-in (PK-9 to PK-12), with a +//! software authenticator. use crate::utils::{ account::Account, @@ -251,6 +252,8 @@ pub async fn test(test: &mut TestServer) { pub struct SoftKey { pub key: EcdsaKeyPair, pub credential_id: Vec, + /// The account's user handle, as registration gave it (base64url). + pub user_handle: std::sync::Mutex, } impl SoftKey { @@ -261,11 +264,50 @@ impl SoftKey { key: EcdsaKeyPair::from_pkcs8(&ECDSA_P256_SHA256_ASN1_SIGNING, pkcs8.as_ref(), &rng) .unwrap(), credential_id: credential_id.to_vec(), + user_handle: Default::default(), } } + /// What `navigator.credentials.get` hands the page for a sign-in + /// challenge, with the given counter and origin. + pub fn get(&self, challenge: &Value, counter: u32, origin: &str) -> Value { + let client_data = json!({ + "type": "webauthn.get", + "challenge": challenge["options"]["publicKey"]["challenge"], + "origin": origin, + "crossOrigin": false + }) + .to_string(); + let mut auth_data = Sha256::digest(RP_ID.as_bytes()).to_vec(); + // UP, UV, backup eligible, backed up + auth_data.push(0x01 | 0x04 | 0x08 | 0x10); + auth_data.extend_from_slice(&counter.to_be_bytes()); + let mut signed = auth_data.clone(); + signed.extend_from_slice(&Sha256::digest(client_data.as_bytes())); + let signature = self.key.sign(&SystemRandom::new(), &signed).unwrap(); + let id = URL_SAFE_NO_PAD.encode(&self.credential_id); + json!({ + "challengeId": challenge["challengeId"], + "credential": { + "id": id, + "rawId": id, + "type": "public-key", + "response": { + "authenticatorData": URL_SAFE_NO_PAD.encode(&auth_data), + "clientDataJSON": URL_SAFE_NO_PAD.encode(client_data.as_bytes()), + "signature": URL_SAFE_NO_PAD.encode(signature.as_ref()), + "userHandle": self.user_handle.lock().unwrap().clone() + }, + "extensions": {} + } + }) + } + /// What `navigator.credentials.create` hands the page, for `options`. pub fn create(&self, options: &Value) -> Value { + if let Some(handle) = options["publicKey"]["user"]["id"].as_str() { + *self.user_handle.lock().unwrap() = handle.to_string(); + } let challenge = options["publicKey"]["challenge"].as_str().unwrap(); let client_data = json!({ "type": "webauthn.create", @@ -499,6 +541,131 @@ async fn registration(user: &Account) { })) .await; assert_eq!(response["type"], "refused", "{response}"); + + sign_in(user, &key).await; +} + +async fn new_challenge() -> Value { + let challenge = register_at("/api/auth/passkey", json!({})).await; + assert_eq!( + challenge["options"]["publicKey"]["rpId"], RP_ID, + "{challenge}" + ); + assert_eq!( + challenge["options"]["publicKey"]["userVerification"], "required", + "{challenge}" + ); + challenge +} + +async fn register_at(path: &str, body: Value) -> Value { + HttpRequest::new() + .post::(path, &body) + .await + .unwrap_or_else(|err| panic!("{path} {body}: {err}")) +} + +const PKCE_VERIFIER: &str = "dBjftJeZ4CVP-mB92K27uhbUJU1p1r_wW1gFWFOEjXk"; +const PKCE_CHALLENGE: &str = "E9Melhoa2OwvFrEMTJguCHaoeK1t8URWbuGJSstw-cM"; +const REDIRECT: &str = "com.example.app:/cb"; + +async fn login(client_id: &str, assertion: Value) -> Value { + register_at( + "/api/auth", + json!({ + "type": "authCode", + "clientId": client_id, + "redirectUri": REDIRECT, + "codeChallenge": PKCE_CHALLENGE, + "codeChallengeMethod": "S256", + "passkey": assertion + }), + ) + .await +} + +/// PK-9 to PK-12: sign-in in the authorization-code flow. +async fn sign_in(user: &Account, key: &SoftKey) { + let client = HttpRequest::with_credentials( + 8899, + "admin@example.com", + "these_pretzels_are_making_me_thirsty", + ) + .post::("/auth/register", &json!({"redirect_uris": [REDIRECT]})) + .await + .unwrap(); + let client_id = client["client_id"] + .as_str() + .unwrap_or_else(|| panic!("{client}")) + .to_string(); + + // A passkey signs in on its own and the code works + let challenge = new_challenge().await; + let assertion = key.get(&challenge, 5, ORIGIN); + let response = login(&client_id, assertion.clone()).await; + assert_eq!(response["type"], "authenticated", "{response}"); + let code = response["client_code"].as_str().unwrap().to_string(); + let token = reqwest::Client::builder() + .danger_accept_invalid_certs(true) + .build() + .unwrap() + .post("https://127.0.0.1:8899/auth/token") + .form(&[ + ("grant_type", "authorization_code"), + ("code", code.as_str()), + ("client_id", client_id.as_str()), + ("redirect_uri", REDIRECT), + ("code_verifier", PKCE_VERIFIER), + ]) + .send() + .await + .unwrap() + .json::() + .await + .unwrap(); + assert!(token["access_token"].is_string(), "{token}"); + let laptop = list(user, user) + .await + .into_iter() + .find(|p| p["name"] == "Laptop") + .unwrap(); + assert!(laptop["lastUsedAt"].is_string(), "{laptop}"); + + // PK-10: a challenge is good once + let response = login(&client_id, assertion).await; + assert_eq!(response["type"], "failure", "{response}"); + + // PK-11: a counter that didn't go up fails + let challenge = new_challenge().await; + let response = login(&client_id, key.get(&challenge, 5, ORIGIN)).await; + assert_eq!(response["type"], "failure", "{response}"); + + // PK-2: another origin fails + let challenge = new_challenge().await; + let response = login(&client_id, key.get(&challenge, 9, "https://evil.example")).await; + assert_eq!(response["type"], "failure", "{response}"); + + // An unknown passkey fails + let stranger = SoftKey::new(b"soft-key-stranger-01"); + *stranger.user_handle.lock().unwrap() = key.user_handle.lock().unwrap().clone(); + let challenge = new_challenge().await; + let response = login(&client_id, stranger.get(&challenge, 1, ORIGIN)).await; + assert_eq!(response["type"], "failure", "{response}"); + + // Still signs in with a higher counter + let challenge = new_challenge().await; + let response = login(&client_id, key.get(&challenge, 6, ORIGIN)).await; + assert_eq!(response["type"], "authenticated", "{response}"); + + // PK-8: the registration page takes the account's passkey instead of + // the password, and not someone else's + let (_, ticket) = start_registration(user, "Second").await; + let challenge = new_challenge().await; + let response = register(json!({ + "step": "start", "ticket": ticket, "passkey": key.get(&challenge, 7, ORIGIN) + })) + .await; + assert_eq!(response["type"], "options", "{response}"); } #[ignore]