Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
6 changes: 6 additions & 0 deletions README.md
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
58 changes: 34 additions & 24 deletions apps/auth-service/assets/passkey.js
Original file line number Diff line number Diff line change
Expand Up @@ -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<void>} SignalCurrentUserDetails
* @typedef {{
* signalCurrentUserDetails?: (details: {
* rpId: string;
* userId: string;
* name: string;
* displayName: string;
* }) => Promise<void>;
* signalAllAcceptedCredentials?: (credentials: {
* rpId: string;
* userId: string;
* allAcceptedCredentialIds: string[];
* }) => Promise<void>;
* }} 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.
Expand Down Expand Up @@ -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.
Expand Down Expand Up @@ -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<HTMLFormElement>} */ (
Expand Down
16 changes: 16 additions & 0 deletions apps/auth-service/src/passkey/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,7 @@

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,
events::{DomainEvent, RevocationReason},
Expand Down Expand Up @@ -47,6 +48,21 @@ impl AccountService {
Ok(passkeys.into_iter().map(Into::into).collect())
}

/// 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,
owner: &Owner,
) -> Result<Vec<String>, 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
/// passkey confirmation.
pub(crate) async fn rename_passkey(
Expand Down
10 changes: 7 additions & 3 deletions apps/auth-service/src/web/account.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -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(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
Expand All @@ -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(),
Expand All @@ -475,6 +475,10 @@ impl WebApplication {
piquel_ui::account(
nav: nav,
who: who,
signal: PasskeySignal {
user: reader.owner().user(),
credentials: &accepted,
},
trail: trail,
title: title,
home: page::settings::HOME,
Expand Down
1 change: 0 additions & 1 deletion apps/auth-service/src/web/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
1 change: 0 additions & 1 deletion apps/auth-service/src/web/admin/settings.rs
Original file line number Diff line number Diff line change
Expand Up @@ -170,7 +170,6 @@ pub(super) async fn profile(cx: &Cx, body: Body) -> Result<Response> {
.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(),
Expand Down
1 change: 0 additions & 1 deletion apps/auth-service/src/web/settings/profile.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down
97 changes: 95 additions & 2 deletions apps/auth-service/src/web/tests.rs
Original file line number Diff line number Diff line change
Expand Up @@ -14,18 +14,20 @@ 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::{
body::Body,
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;
Expand Down Expand Up @@ -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::<String>::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]
Expand Down
1 change: 0 additions & 1 deletion crates/ui/src/admin/lists.rs
Original file line number Diff line number Diff line change
Expand Up @@ -70,7 +70,6 @@ pub async fn administrator_list<'a>(
<ul class="list">
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(),
Expand Down
2 changes: 2 additions & 0 deletions crates/ui/src/admin/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
2 changes: 0 additions & 2 deletions crates/ui/src/admin/users.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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(),
Expand Down Expand Up @@ -162,7 +161,6 @@ pub async fn user_page<'a>(
) -> Result<impl View> {
let user = &detail.user;
let who = Who {
user: None,
name: &user.display_name,
handle: user.handle.as_str(),
picture,
Expand Down
2 changes: 1 addition & 1 deletion crates/ui/src/layout/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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,
Expand Down
12 changes: 9 additions & 3 deletions crates/ui/src/layout/sections.rs
Original file line number Diff line number Diff line change
Expand Up @@ -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::{
Expand Down Expand Up @@ -63,8 +66,9 @@ 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
/// 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
Expand All @@ -74,6 +78,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,
Expand Down Expand Up @@ -148,6 +153,7 @@ pub async fn account<'a>(
},
groups: &groups,
who: Some(who),
signal: Some(signal),
me: Some(home),
trail,
page: title,
Expand Down
Loading
Loading