From eb8cc8494404e3f7d1a0da2ad5f1cce486f834c7 Mon Sep 17 00:00:00 2001 From: piquel Date: Fri, 6 Nov 2026 14:11:24 +0100 Subject: [PATCH 1/2] feat(auth): password managers forget passkeys you remove Every account page tells the browser's password manager, by the WebAuthn Signal API's signalAllAcceptedCredentials, the credential ID of every passkey that still signs in: the rows sign-in itself checks against. The password manager then forgets the account's others, such as one removed in the settings, instead of offering a passkey that can only fail. --- README.md | 6 ++ apps/auth-service/assets/passkey.js | 58 ++++++----- apps/auth-service/src/passkey/settings.rs | 42 +++++++- apps/auth-service/src/web/account.rs | 3 +- apps/auth-service/src/web/admin/mod.rs | 1 - apps/auth-service/src/web/admin/settings.rs | 1 - apps/auth-service/src/web/settings/profile.rs | 1 - apps/auth-service/src/web/tests.rs | 97 ++++++++++++++++++- crates/ui/src/admin/lists.rs | 1 - crates/ui/src/admin/mod.rs | 2 + crates/ui/src/admin/users.rs | 2 - crates/ui/src/layout/mod.rs | 2 +- crates/ui/src/layout/sections.rs | 9 +- crates/ui/src/layout/signed_in.rs | 26 ++++- crates/ui/src/lib.rs | 5 +- tests/browser/README.md | 4 +- tests/browser/helpers.ts | 74 ++++++++++++++ tests/browser/settings.spec.ts | 9 ++ 18 files changed, 298 insertions(+), 45 deletions(-) diff --git a/README.md b/README.md index f31e59972..db6a9949d 100644 --- a/README.md +++ b/README.md @@ -697,6 +697,12 @@ explains how to choose a requirement and handle the challenge. offer an explicit Google Password Manager option for devices with Google services, never chosen automatically; a standard passkey or security key stays the default. Authentication supports the browser account picker and a handle fallback. +- Every account page tells the browser's password manager, by the WebAuthn Signal + API, the account's current handle and display name, and the credential ID of + every passkey that still signs in: the passkeys sign-in itself checks. Where the + browser supports it, its passkeys then show a new handle, and one removed in the + settings disappears from it instead of failing at sign-in. A security key keeps + its copy, which only fails. - An account's handle is its public identifier and login name, released as `preferred_username`: 3–32 characters of `[a-z0-9-]`, without a leading, trailing or double hyphen, so it is a valid DNS label. Signup trims and lowercases it, and diff --git a/apps/auth-service/assets/passkey.js b/apps/auth-service/assets/passkey.js index 3285f4689..1db71f68c 100644 --- a/apps/auth-service/assets/passkey.js +++ b/apps/auth-service/assets/passkey.js @@ -288,36 +288,43 @@ class Passkeys { .replace(/=+$/, ''); } /** - * Tells the browser's password manager the current handle and display name of the - * account whose ID is `id`, so its passkeys show them after a change (the WebAuthn - * Signal API). Does nothing where unsupported. - * @param {{ id: string; name: string; displayName: string }} account + * Tells the browser's password manager, by the WebAuthn Signal API, of the account + * whose ID is `id`: its current handle and display name, so its passkeys show them + * after a change, and `accepted`, the credential IDs of every passkey that still + * signs in to it, so it forgets the account's others, such as one removed. It + * forgets every passkey of the account `accepted` does not list, so the server + * lists them all, and without the list nothing is said of them. Does nothing where + * unsupported. + * @param {{ id: string; name: string; displayName: string; accepted?: string[] }} account * @returns {void} */ - static signal({ id, name, displayName }) { + static signal({ id, name, displayName, accepted }) { /** - * @typedef {(details: { - * rpId: string; - * userId: string; - * name: string; - * displayName: string; - * }) => Promise} SignalCurrentUserDetails + * @typedef {{ + * signalCurrentUserDetails?: (details: { + * rpId: string; + * userId: string; + * name: string; + * displayName: string; + * }) => Promise; + * signalAllAcceptedCredentials?: (credentials: { + * rpId: string; + * userId: string; + * allAcceptedCredentialIds: string[]; + * }) => Promise; + * }} Signals */ - const credentials = /** @type {{ signalCurrentUserDetails?: SignalCurrentUserDetails }} */ ( - /** @type {unknown} */ (PublicKeyCredential) - ); + const signals = /** @type {Signals} */ (/** @type {unknown} */ (PublicKeyCredential)); // Passkeys carry the account ID's 16 bytes as their user handle. const bytes = Uint8Array.from(id.replace(/-/g, '').match(/../g) ?? [], (byte) => parseInt(byte, 16) ); - credentials - .signalCurrentUserDetails?.({ - rpId: window.location.hostname, - userId: Passkeys.#encode(bytes.buffer), - name, - displayName - }) - .catch(() => undefined); + const account = { rpId: window.location.hostname, userId: Passkeys.#encode(bytes.buffer) }; + signals.signalCurrentUserDetails?.({ ...account, name, displayName }).catch(() => undefined); + if (accepted) + signals + .signalAllAcceptedCredentials?.({ ...account, allAcceptedCredentialIds: accepted }) + .catch(() => undefined); } /** * The credential descriptor `value` encodes. @@ -364,7 +371,9 @@ class Passkeys { * starts hidden, and shows once the browser can write to the clipboard. * - an element marked `data-passkey-user`, the signed-in account's ID, tells the * password manager the account's current `data-passkey-name` and - * `data-passkey-display-name`, so its passkeys show them after a change. + * `data-passkey-display-name`, so its passkeys show them after a change, and + * `data-passkey-credentials`, the space-separated credential IDs of every passkey + * that still signs in to it, so it forgets the others. * - an element marked `data-replace-url` makes its value the page's address: a page * answering a form with what only it may show, such as a secret, then reloads by * `GET`, never posting the form again. @@ -531,7 +540,8 @@ function wire(document) { Passkeys.signal({ id: account.passkeyUser, name: account.passkeyName ?? '', - displayName: account.passkeyDisplayName ?? '' + displayName: account.passkeyDisplayName ?? '', + accepted: account.passkeyCredentials?.split(' ').filter(Boolean) }); if (Passkeys.available()) for (const form of /** @type {NodeListOf} */ ( diff --git a/apps/auth-service/src/passkey/settings.rs b/apps/auth-service/src/passkey/settings.rs index fba2137cf..5fa4815ce 100644 --- a/apps/auth-service/src/passkey/settings.rs +++ b/apps/auth-service/src/passkey/settings.rs @@ -3,13 +3,36 @@ use super::{PasskeyApplication, PasskeyError, PasskeyName}; use crate::account::{AccountError, AccountService, Owner, Subject, Viewer}; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use piquel_common::{ - PasskeyId, + PasskeyId, UserId, events::{DomainEvent, RevocationReason}, protocol::api, }; +use piquel_ui::PasskeySignal; use webauthn_rs::prelude::*; +/// Every passkey that signs in to an account, which its pages tell the +/// password manager: it forgets the account's passkeys this does not list, so +/// one missing would be lost there. Only [`AccountService::accepted_passkeys`] +/// makes one, from the very rows sign-in checks assertions against. +#[derive(Debug)] +pub(crate) struct AcceptedPasskeys { + user: UserId, + /// Their credential IDs, in unpadded base64url. + credentials: Vec, +} + +impl AcceptedPasskeys { + /// What the account's pages tell the password manager. + pub(crate) fn signal(&self) -> PasskeySignal<'_> { + PasskeySignal { + user: self.user, + credentials: &self.credentials, + } + } +} + /// Passkey settings any administrator may also change: listing, renaming and /// removing. Only the owner adds a passkey, since it is a way to sign in. impl AccountService { @@ -47,6 +70,23 @@ impl AccountService { Ok(passkeys.into_iter().map(Into::into).collect()) } + /// Every passkey that signs in to the account: all its unrevoked ones, the + /// rows sign-in checks an assertion against. + pub(crate) async fn accepted_passkeys( + &self, + viewer: &Viewer, + ) -> Result { + viewer.authorize(&self.database).await?; + let keys = self.database.passkeys().list_active(viewer.user()).await?; + Ok(AcceptedPasskeys { + user: viewer.user(), + credentials: keys + .iter() + .map(|key| URL_SAFE_NO_PAD.encode(&key.credential_id)) + .collect(), + }) + } + /// Changes a passkey's label. A name grants nothing, so the owner needs no /// passkey confirmation. pub(crate) async fn rename_passkey( diff --git a/apps/auth-service/src/web/account.rs b/apps/auth-service/src/web/account.rs index 8ed0a033f..8501427fc 100644 --- a/apps/auth-service/src/web/account.rs +++ b/apps/auth-service/src/web/account.rs @@ -433,6 +433,7 @@ impl WebApplication { Err(error) => return Err(error.into()), }; let administrator = self.account.is_administrator(&viewer).await?; + let accepted = self.account.accepted_passkeys(&viewer).await?; let session = reader.owner().session_id(); let confirmed = reader.owner().was_passkey_confirmed(); // The preference forms come back here by GET, which a page answering a @@ -451,7 +452,6 @@ impl WebApplication { }; let picture = profile.picture.map(routes::pictures::of); let who = Who { - user: Some(reader.owner().user()), name: &profile.display_name, handle: profile.handle.as_str(), picture: picture.as_deref(), @@ -475,6 +475,7 @@ impl WebApplication { piquel_ui::account( nav: nav, who: who, + signal: accepted.signal(), trail: trail, title: title, home: page::settings::HOME, diff --git a/apps/auth-service/src/web/admin/mod.rs b/apps/auth-service/src/web/admin/mod.rs index bc84775d2..5b5d82f6a 100644 --- a/apps/auth-service/src/web/admin/mod.rs +++ b/apps/auth-service/src/web/admin/mod.rs @@ -723,7 +723,6 @@ impl AdminApplication { .unwrap_or_default(); let picture = admin.and_then(|admin| Self::picture(cx, admin.picture)); let administrator = admin.map(|admin| Who { - user: None, name: admin.handle.as_str(), handle: admin.handle.as_str(), picture: picture.as_deref(), diff --git a/apps/auth-service/src/web/admin/settings.rs b/apps/auth-service/src/web/admin/settings.rs index 491f10688..591d39265 100644 --- a/apps/auth-service/src/web/admin/settings.rs +++ b/apps/auth-service/src/web/admin/settings.rs @@ -170,7 +170,6 @@ pub(super) async fn profile(cx: &Cx, body: Body) -> Result { .map_or("", |refused| refused.form.reason.as_str()); let page = &App::here(cx); let who = Who { - user: None, name: &profile.display_name, handle: profile.handle.as_str(), picture: picture.as_deref(), diff --git a/apps/auth-service/src/web/settings/profile.rs b/apps/auth-service/src/web/settings/profile.rs index 001466bdf..440737ebc 100644 --- a/apps/auth-service/src/web/settings/profile.rs +++ b/apps/auth-service/src/web/settings/profile.rs @@ -199,7 +199,6 @@ impl AccountPage for Profile { let administrator = web.account.is_administrator(&viewer).await?; let picture = profile.picture.map(pictures::of); let who = Who { - user: None, name: &profile.display_name, handle: profile.handle.as_str(), picture: picture.as_deref(), diff --git a/apps/auth-service/src/web/tests.rs b/apps/auth-service/src/web/tests.rs index a1bc29aa4..0c3a57b6a 100644 --- a/apps/auth-service/src/web/tests.rs +++ b/apps/auth-service/src/web/tests.rs @@ -14,7 +14,7 @@ use crate::{ security::BrowserCookie, tests::{ Browser, OWN_PAGE, Replicas, WEB_ORIGIN, change, cookie, html, location, parameter, policy, - redirect, register, registration, + redirect, register, registration, unusable_passkey, }, }; use axum::{ @@ -22,10 +22,12 @@ use axum::{ http::{Method, Request, StatusCode, header}, response::Response, }; +use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use piquel_common::{ - ClientId, + ClientId, PasskeyId, clients::{ClientKind, ClientOwner, ClientRegistration}, }; +use piquel_repository::InsertPasskey; use piquel_ui::{DeviceChange, Section}; use serde::Serialize; use tower::ServiceExt; @@ -500,6 +502,97 @@ async fn account_pages_refuse_forms_they_do_not_know() { } } +/// Every account page tells the password manager every passkey that signs in to +/// the account, which forgets the account's passkeys a page does not list: all +/// its unrevoked ones, however many and whatever their bytes, and none other, +/// neither a removed one nor another account's. An account without any lists +/// none, so its password manager keeps none either. +#[tokio::test] +#[ignore = "requires TEST_DATABASE_URL"] +async fn account_pages_tell_the_password_manager_every_passkey() { + let replicas = Replicas::new().await; + let database = Replicas::database().await; + let browser = Browser::new_account(&database).await; + let app = browser + .register_app( + &database, + ClientKind::Confidential, + "https://signal.example", + ) + .await; + let mut pages: Vec<_> = super::settings::TABS + .iter() + .map(|(_, path)| (*path).to_owned()) + .chain(account_pages(&app).into_iter().map(|(path, _)| path)) + .collect(); + pages.sort(); + pages.dedup(); + let told = async |path: &str| { + let response = browser.visit(&replicas.a, path).await; + assert_eq!(response.status(), StatusCode::OK, "{path}"); + let page = html(response).await; + assert_eq!( + value_after(&page, r#"data-passkey-user=""#), + browser.user_id.to_string(), + "{path}" + ); + let mut told: Vec<_> = value_after(&page, r#"data-passkey-credentials=""#) + .split(' ') + .filter(|id| !id.is_empty()) + .map(str::to_owned) + .collect(); + told.sort(); + told + }; + assert_eq!(told(settings::HOME).await, Vec::::new()); + + // Credential IDs of the shortest and longest lengths WebAuthn allows, and + // bytes base64url writes as `-` and `_`. + let passkey = |user_id, length: usize, byte: u8| { + let mut credential_id = PasskeyId::new().as_uuid().as_bytes().to_vec(); + credential_id.resize(length, byte); + InsertPasskey { + credential_id, + ..unusable_passkey(user_id) + } + }; + let mut accepted = Vec::new(); + for (index, length) in [16, 17, 18, 64, 255, 1023] + .into_iter() + .cycle() + .take(12) + .enumerate() + { + let key = passkey(browser.user_id, length, [0xfb, 0xff][index % 2]); + database.passkeys().insert(&key).await.expect("passkey"); + accepted.push(key); + } + let removed = accepted.remove(3); + assert!( + database + .passkeys() + .revoke(removed.id, browser.user_id) + .await + .expect("revoke") + ); + let other = Browser::new_account(&database).await; + database + .passkeys() + .insert(&passkey(other.user_id, 32, 0xff)) + .await + .expect("another account's passkey"); + + let mut expected: Vec<_> = accepted + .iter() + .map(|key| URL_SAFE_NO_PAD.encode(&key.credential_id)) + .collect(); + expected.sort(); + assert_eq!(expected.len(), 11); + for path in &pages { + assert_eq!(told(path).await, expected, "{path}"); + } +} + /// Every page the router registers is one the security layer classifies as a page, /// and the other way around. #[test] diff --git a/crates/ui/src/admin/lists.rs b/crates/ui/src/admin/lists.rs index 0dc6f5915..27ae5dd55 100644 --- a/crates/ui/src/admin/lists.rs +++ b/crates/ui/src/admin/lists.rs @@ -70,7 +70,6 @@ pub async fn administrator_list<'a>(
    for row in rows { let who = Who { - user: None, name: row.administrator.handle.as_str(), handle: row.administrator.handle.as_str(), picture: row.picture.as_deref(), diff --git a/crates/ui/src/admin/mod.rs b/crates/ui/src/admin/mod.rs index a98105f5f..17dd25b97 100644 --- a/crates/ui/src/admin/mod.rs +++ b/crates/ui/src/admin/mod.rs @@ -273,6 +273,8 @@ pub async fn dashboard_frame<'a>( area_home: dashboard.home, groups: &groups, who: dashboard.administrator, + // Only the account's own pages on auth tell the password manager. + signal: None, me: dashboard.administrator.map(|_| dashboard.me), trail: &trail, page: dashboard.title, diff --git a/crates/ui/src/admin/users.rs b/crates/ui/src/admin/users.rs index a1b9dedfc..dae47b205 100644 --- a/crates/ui/src/admin/users.rs +++ b/crates/ui/src/admin/users.rs @@ -30,7 +30,6 @@ impl UserRow<'_> { /// The account, as an avatar shows it. pub(crate) fn who(&self) -> Who<'_> { Who { - user: None, name: &self.user.display_name, handle: self.user.handle.as_str(), picture: self.picture.as_deref(), @@ -162,7 +161,6 @@ pub async fn user_page<'a>( ) -> Result { let user = &detail.user; let who = Who { - user: None, name: &user.display_name, handle: user.handle.as_str(), picture, diff --git a/crates/ui/src/layout/mod.rs b/crates/ui/src/layout/mod.rs index 5bc565dc6..f7ebb750e 100644 --- a/crates/ui/src/layout/mod.rs +++ b/crates/ui/src/layout/mod.rs @@ -22,7 +22,7 @@ pub use frames::{Health, Policies, SOURCE, auth_shell, site_shell}; pub use html::{PreferenceChange, Preferences, Sidebar, Theme, Title, document}; pub use parts::{Pager, page_head}; pub use sections::{AccountNav, Section, account, signed_out}; -pub use signed_in::{Crumb, NavGroup, NavItem, Search, Shell, Who, shell}; +pub use signed_in::{Crumb, NavGroup, NavItem, PasskeySignal, Search, Shell, Who, shell}; pub(crate) use parts::{ Label, alert_notice, dialog, navigation, page_messages, pager, private_address, diff --git a/crates/ui/src/layout/sections.rs b/crates/ui/src/layout/sections.rs index 93ac36466..60e72bd51 100644 --- a/crates/ui/src/layout/sections.rs +++ b/crates/ui/src/layout/sections.rs @@ -2,7 +2,10 @@ //! pages in the shell: its sidebar, and what they show a browser that is not //! signed in. -use super::{Crumb, NavGroup, NavItem, Policies, Preferences, Shell, Who, page_messages, shell}; +use super::{ + Crumb, NavGroup, NavItem, PasskeySignal, Policies, Preferences, Shell, Who, page_messages, + shell, +}; use crate::{Messages, icons::Icon, settings::Tab}; use piquel_common::TraceId; use topcoat::{ @@ -63,7 +66,7 @@ pub struct AccountNav<'a> { } /// A signed-in page of `section`, in the account's shell: the sidebar of `nav` -/// for `who`, signing out by posting to `sign_out`, the preference forms posting +/// for `who`, whose passkey script tells the password manager `signal`, signing out by posting to `sign_out`, the preference forms posting /// to `preferences_action`, reversing `preferences`, and coming back to `here`, /// the page named `title` in the crumb after `trail`, the pages it is under, /// and the status bar linking Piquel's `policies`; an administrator's sidebar @@ -74,6 +77,7 @@ pub struct AccountNav<'a> { pub async fn account<'a>( nav: AccountNav<'a>, who: Who<'a>, + signal: PasskeySignal<'a>, #[default] trail: &'a [(Crumb<'a>, &'a str)], title: Crumb<'a>, home: &'a str, @@ -148,6 +152,7 @@ pub async fn account<'a>( }, groups: &groups, who: Some(who), + signal: Some(signal), me: Some(home), trail, page: title, diff --git a/crates/ui/src/layout/signed_in.rs b/crates/ui/src/layout/signed_in.rs index 1d23134a8..a2f69d307 100644 --- a/crates/ui/src/layout/signed_in.rs +++ b/crates/ui/src/layout/signed_in.rs @@ -40,8 +40,6 @@ pub struct NavGroup<'a> { /// Who is signed in, as the sidebar and top bar show them. #[derive(Clone, Copy, Debug)] pub struct Who<'a> { - /// Their account, which the passkey script tells the password manager. - pub user: Option, /// The name shown. pub name: &'a str, /// Their handle. @@ -75,6 +73,20 @@ impl Who<'_> { } } +/// What the passkey script tells the browser's password manager of the +/// signed-in account (the `WebAuthn` Signal API): its current handle and name, +/// from [`Who`], so its passkeys show them after a change, and which of its +/// passkeys still exist. +#[derive(Clone, Copy, Debug)] +pub struct PasskeySignal<'a> { + /// The account, the user handle its passkeys carry. + pub user: UserId, + /// The credential ID of every passkey of the account that still signs in, in + /// unpadded base64url. The password manager forgets the account's passkeys + /// this does not list, so it must never miss one. + pub credentials: &'a [String], +} + /// A search form the top bar shows, posting `name` to `action` by `GET`. #[derive(Clone, Copy, Debug)] pub struct Search<'a> { @@ -136,6 +148,9 @@ pub struct Shell<'a> { pub groups: &'a [NavGroup<'a>], /// Who is signed in, if the sidebar shows them. pub who: Option>, + /// What the password manager is told of the account signed in, on its own + /// pages only. + pub signal: Option>, /// Their own page, which the top bar's avatar links. pub me: Option<&'a str>, /// The pages between the area and the page in the crumb, each named and @@ -248,9 +263,10 @@ async fn sidebar<'a>(frame: &'a Shell<'a>) -> Result { if let Some(who) = frame.who {
    avatar(who: who)
    diff --git a/crates/ui/src/lib.rs b/crates/ui/src/lib.rs index 2d595a4ec..e7580a973 100644 --- a/crates/ui/src/lib.rs +++ b/crates/ui/src/lib.rs @@ -85,8 +85,9 @@ pub use developers::{ }; pub use form::{Alert, Checkbox, Lines, Messages, Notice, OUT_OF_DATE, Query, QueryError}; pub use layout::{ - AccountNav, Crumb, Health, Pager, Policies, PreferenceChange, Preferences, SOURCE, Search, - Section, Sidebar, Theme, Title, Who, account, auth_shell, document, signed_out, site_shell, + AccountNav, Crumb, Health, Pager, PasskeySignal, Policies, PreferenceChange, Preferences, + SOURCE, Search, Section, Sidebar, Theme, Title, Who, account, auth_shell, document, signed_out, + site_shell, }; pub use login::{ CallbackError, LinkKind, LoginChange, LoginQuery, PendingDestination, SignedIn, Step, sign_in, diff --git a/tests/browser/README.md b/tests/browser/README.md index 3bd5baaae..b333b3565 100644 --- a/tests/browser/README.md +++ b/tests/browser/README.md @@ -4,7 +4,9 @@ isolated database: tests create accounts and credentials. CI runs it against the debug binary `just rust build` makes, behind Caddy over HTTPS, as configured below. `settings.spec.ts` checks auth's own settings pages: renaming, adding and removing -passkeys, a passkey ceremony that fails, the passkey confirmation the passkey +passkeys, which each page then tells the password manager, listing exactly the +passkeys the virtual authenticators hold that still sign in, a passkey ceremony +that fails, the passkey confirmation the passkey script runs, devices, an email link's token and signing out. It also removes a connected app, which then asks for consent again; reports a passkey in the security history as not the owner's, which signs out another device holding the diff --git a/tests/browser/helpers.ts b/tests/browser/helpers.ts index ad8a30b96..ac99a21e7 100644 --- a/tests/browser/helpers.ts +++ b/tests/browser/helpers.ts @@ -57,6 +57,80 @@ export async function addPasskeys( return { cdp, authenticatorId }; } +/** What a page told the password manager of an account's passkeys. */ +type AcceptedCredentials = { + rpId: string; + /** The account's user handle, in unpadded base64url. */ + userId: string; + /** The credential ID of every passkey that still signs in, in unpadded base64url. */ + allAcceptedCredentialIds: string[]; + /** Why Chromium refused the signal, if it did. */ + refused?: string; +}; + +/** + * Records, on every page `context` loads from now on, what it tells the password + * manager by `PublicKeyCredential.signalAllAcceptedCredentials`, once Chromium's + * own has answered, so a call Chromium refuses says why. + */ +export async function recordAcceptedCredentials(context: BrowserContext): Promise { + await context.addInitScript(() => { + type Signal = (options: AcceptedCredentials) => Promise; + const credentials = PublicKeyCredential as unknown as { + signalAllAcceptedCredentials?: Signal; + }; + const own = credentials.signalAllAcceptedCredentials?.bind(PublicKeyCredential); + const told: AcceptedCredentials[] = []; + (window as unknown as { told: AcceptedCredentials[] }).told = told; + credentials.signalAllAcceptedCredentials = async (options) => { + const call = { ...options, allAcceptedCredentialIds: [...options.allAcceptedCredentialIds] }; + try { + await own?.(options); + } catch (error) { + call.refused = String(error); + throw error; + } finally { + told.push(call); + } + }; + }); +} + +/** + * Expects the page `page` shows to have told the password manager, once its + * passkey script ran, that the passkeys the authenticators `authenticatorIds` + * hold, and only those, still sign in, under their own RP ID and user handle. + */ +export async function expectAccepted( + page: Page, + cdp: CDPSession, + ...authenticatorIds: string[] +): Promise { + const held = ( + await Promise.all( + authenticatorIds.map((authenticatorId) => + cdp.send('WebAuthn.getCredentials', { authenticatorId }) + ) + ) + ).flatMap(({ credentials }) => credentials); + const base64url = (value: string) => Buffer.from(value, 'base64').toString('base64url'); + // Waits for the call, which the page makes once its passkey script runs. + const told = await ( + await page.waitForFunction(() => + (window as unknown as { told?: AcceptedCredentials[] }).told?.at(-1) + ) + ).jsonValue(); + if (!told) throw new Error('The page told the password manager nothing.'); + expect(held.length).toBeGreaterThan(0); + expect({ ...told, allAcceptedCredentialIds: told.allAcceptedCredentialIds.toSorted() }).toEqual({ + rpId: held[0].rpId, + userId: base64url(held[0].userHandle ?? ''), + allAcceptedCredentialIds: held + .map((credential) => base64url(credential.credentialId)) + .toSorted() + }); +} + /** * Runs `command`, a deployment's CLI named by an environment variable such as * `E2E_GRANT_ADMIN`, with `args` appended, and returns what it printed. diff --git a/tests/browser/settings.spec.ts b/tests/browser/settings.spec.ts index 677cdf2ec..6d75e2477 100644 --- a/tests/browser/settings.spec.ts +++ b/tests/browser/settings.spec.ts @@ -4,6 +4,8 @@ import { addSecondPasskey, authorization, consent, + expectAccepted, + recordAcceptedCredentials, serveClient, signUp } from './helpers'; @@ -11,12 +13,16 @@ import { /** Runs against auth's own settings pages, with Chromium's virtual passkey authenticator. */ test('settings on auth: passkeys, devices, an email link and signing out', async ({ browser }) => { const context = await browser.newContext(); + await recordAcceptedCredentials(context); const page = await context.newPage(); const { cdp, authenticatorId } = await addPasskeys(context, page); let assertions = 0; cdp.on('WebAuthn.credentialAsserted', () => (assertions += 1)); const username = `settings-${Date.now().toString(36)}`; await signUp(page, username, 'First passkey'); + // Each page tells the password manager every passkey that still signs in, so it + // forgets the others: it lists the passkeys the authenticators hold, as they do. + await expectAccepted(page, cdp, authenticatorId); // The settings open on the overview; the sidebar leads to the sign-in methods. await page.getByRole('link', { name: 'Sign-in methods', exact: true }).click(); await expect(page).toHaveURL('/settings/sign-in'); @@ -56,6 +62,7 @@ test('settings on auth: passkeys, devices, an email link and signing out', async await page.getByRole('button', { name: 'Create the passkey', exact: true }).click(); await expect(page.getByText('The passkey was added.')).toBeVisible(); await expect(page.getByText('Second passkey', { exact: true })).toBeVisible(); + await expectAccepted(page, cdp, authenticatorId, second.authenticatorId); // The session confirmed with a passkey moments ago, so the page asks for no new // confirmation. Mark the form as a page with a lapsed one would, to run it. @@ -72,6 +79,8 @@ test('settings on auth: passkeys, devices, an email link and signing out', async await page.getByRole('button', { name: 'Confirm removal', exact: true }).click(); await expect(page.getByText('The passkey was removed.')).toBeVisible(); await expect(page.getByText('Second passkey', { exact: true })).toHaveCount(0); + // Only the first authenticator's passkey still signs in. + await expectAccepted(page, cdp, authenticatorId); // The passkey script confirmed with a passkey before posting. expect(assertions).toBeGreaterThan(asserted); From d441bb4b20735b2e03a8b82d19a48389ef075764 Mon Sep 17 00:00:00 2001 From: piquel Date: Fri, 6 Nov 2026 14:23:28 +0100 Subject: [PATCH 2/2] refactor(auth): only the owner's own pages build the passkey list --- apps/auth-service/src/passkey/settings.rs | 48 ++++++----------------- apps/auth-service/src/web/account.rs | 11 ++++-- crates/ui/src/layout/sections.rs | 5 ++- 3 files changed, 22 insertions(+), 42 deletions(-) diff --git a/apps/auth-service/src/passkey/settings.rs b/apps/auth-service/src/passkey/settings.rs index 5fa4815ce..6fde8ea9c 100644 --- a/apps/auth-service/src/passkey/settings.rs +++ b/apps/auth-service/src/passkey/settings.rs @@ -5,34 +5,12 @@ use super::{PasskeyApplication, PasskeyError, PasskeyName}; use crate::account::{AccountError, AccountService, Owner, Subject, Viewer}; use base64::{Engine, engine::general_purpose::URL_SAFE_NO_PAD}; use piquel_common::{ - PasskeyId, UserId, + PasskeyId, events::{DomainEvent, RevocationReason}, protocol::api, }; -use piquel_ui::PasskeySignal; use webauthn_rs::prelude::*; -/// Every passkey that signs in to an account, which its pages tell the -/// password manager: it forgets the account's passkeys this does not list, so -/// one missing would be lost there. Only [`AccountService::accepted_passkeys`] -/// makes one, from the very rows sign-in checks assertions against. -#[derive(Debug)] -pub(crate) struct AcceptedPasskeys { - user: UserId, - /// Their credential IDs, in unpadded base64url. - credentials: Vec, -} - -impl AcceptedPasskeys { - /// What the account's pages tell the password manager. - pub(crate) fn signal(&self) -> PasskeySignal<'_> { - PasskeySignal { - user: self.user, - credentials: &self.credentials, - } - } -} - /// Passkey settings any administrator may also change: listing, renaming and /// removing. Only the owner adds a passkey, since it is a way to sign in. impl AccountService { @@ -70,21 +48,19 @@ impl AccountService { Ok(passkeys.into_iter().map(Into::into).collect()) } - /// Every passkey that signs in to the account: all its unrevoked ones, the - /// rows sign-in checks an assertion against. + /// The credential ID, in unpadded base64url, of every passkey that signs in + /// to the owner's account: all its unrevoked ones, the rows sign-in checks + /// an assertion against. The account's pages tell the password manager, + /// which forgets the account's passkeys this does not list. pub(crate) async fn accepted_passkeys( &self, - viewer: &Viewer, - ) -> Result { - viewer.authorize(&self.database).await?; - let keys = self.database.passkeys().list_active(viewer.user()).await?; - Ok(AcceptedPasskeys { - user: viewer.user(), - credentials: keys - .iter() - .map(|key| URL_SAFE_NO_PAD.encode(&key.credential_id)) - .collect(), - }) + owner: &Owner, + ) -> Result, AccountError> { + let keys = self.database.passkeys().list_active(owner.user()).await?; + Ok(keys + .iter() + .map(|key| URL_SAFE_NO_PAD.encode(&key.credential_id)) + .collect()) } /// Changes a passkey's label. A name grants nothing, so the owner needs no diff --git a/apps/auth-service/src/web/account.rs b/apps/auth-service/src/web/account.rs index 8501427fc..95cc3fd28 100644 --- a/apps/auth-service/src/web/account.rs +++ b/apps/auth-service/src/web/account.rs @@ -22,8 +22,8 @@ use crate::{ use piquel_common::ErrorChain; use piquel_telemetry::HttpTelemetry; use piquel_ui::{ - AccountNav, Alert, Crumb, FieldError, LoginQuery, Messages, Notice, Query, Recovery, Section, - Tab, Who, + AccountNav, Alert, Crumb, FieldError, LoginQuery, Messages, Notice, PasskeySignal, Query, + Recovery, Section, Tab, Who, }; use serde::{Deserialize, de::DeserializeOwned}; use topcoat::{ @@ -433,7 +433,7 @@ impl WebApplication { Err(error) => return Err(error.into()), }; let administrator = self.account.is_administrator(&viewer).await?; - let accepted = self.account.accepted_passkeys(&viewer).await?; + let accepted = self.account.accepted_passkeys(reader.owner()).await?; let session = reader.owner().session_id(); let confirmed = reader.owner().was_passkey_confirmed(); // The preference forms come back here by GET, which a page answering a @@ -475,7 +475,10 @@ impl WebApplication { piquel_ui::account( nav: nav, who: who, - signal: accepted.signal(), + signal: PasskeySignal { + user: reader.owner().user(), + credentials: &accepted, + }, trail: trail, title: title, home: page::settings::HOME, diff --git a/crates/ui/src/layout/sections.rs b/crates/ui/src/layout/sections.rs index 60e72bd51..f6d5c98c4 100644 --- a/crates/ui/src/layout/sections.rs +++ b/crates/ui/src/layout/sections.rs @@ -66,8 +66,9 @@ pub struct AccountNav<'a> { } /// A signed-in page of `section`, in the account's shell: the sidebar of `nav` -/// for `who`, whose passkey script tells the password manager `signal`, signing out by posting to `sign_out`, the preference forms posting -/// to `preferences_action`, reversing `preferences`, and coming back to `here`, +/// for `who`, whose passkey script tells the password manager `signal`, signing +/// out by posting to `sign_out`, the preference forms posting to +/// `preferences_action`, reversing `preferences`, and coming back to `here`, /// the page named `title` in the crumb after `trail`, the pages it is under, /// and the status bar linking Piquel's `policies`; an administrator's sidebar /// also links the dashboard. Then what the account's `recovery` that can still