Skip to content

Commit d8ce058

Browse files
authored
feat(auth): apps sign users in with passkeys on their own pages (#163)
Closes #77 Apps on other domains must send users to auth.piquel.fr to sign in, which confuses people who have never heard of piquel.fr. Passkeys only worked on auth's own pages: the verifier accepted one origin, and every ceremony was bound to a host-only cookie another site cannot send. ## How WebAuthn Level 3 related origins (§5.11) let a page on `https://app.example` run a ceremony for RP ID `auth.piquel.fr` once `https://auth.piquel.fr/.well-known/webauthn` lists that origin. Existing passkeys keep working. - **Approved origins.** A new `client_webauthn_origins` table, managed from the admin dashboard's Clients page or with `auth-service client origin add|remove|list`. Both run the same `AdminService` operations and `ClientRegistry` rules, and record `RelatedOriginApproved`/`RelatedOriginRemoved`. Approval needs a trusted client (this sign-in skips consent), an origin that is one of its redirect origins, and at most 5 registrable-domain labels across all approved origins (`psl` crate), as browsers count them. Deleting a client removes its origins, by a trigger, so a replica on the previous release (including #152's account purge) does too. - **`GET /.well-known/webauthn`** lists them: discovery, public cache for 5 minutes. - **`POST /webauthn/related/start {request_uri}`** checks the page's `Origin` is approved for an enabled, trusted client, then claims that client's pushed request and stores the ceremony in one transaction, bound to the origin and the claim instead of a cookie. `prompt=consent` and `prompt=none` are refused with `interaction_required` and the request stays usable for the redirect flow. An `id_token_hint` limits the ceremony to that account's passkeys. - **`POST /webauthn/related/finish`** requires the same origin, still approved for the same client, and `clientDataJSON.origin` naming it. It creates a session with no browser secret, consumes the request, and answers `{code, state, iss}` as JSON. No cookie is set; the code needs the PKCE verifier. - **Security layer.** `Endpoint::RelatedLogin` gets its own credential-free CORS grant (`content-type, x-piquel-csrf`, `POST`) for approved origins, still requires the CSRF header, and uses the login rate bucket. The public-client grant is unchanged. - **History.** `SignedIn` gains an optional `inline: {client_id, origin}`; settings history shows "Signed in with a passkey on app.example". ### Since the first version of this PR Main moved every UI into server-rendered pages and deleted the TS SDK, so this is a port rather than a rebase: - There is no client-side helper. `passkey.js` serves only auth's own pages, and the related flow runs on the app's page, so README documents the protocol, including when to fall back to `/oauth/authorize`. A public SDK (#58, #59) can wrap it later; [#58 asks for that](#58 (comment)). - **Dashboard pages.** The dashboard now lives in auth, so its Clients page lists each client's approved origins, with Remove links and an "Approve an origin" form; untrusted and deleted clients show why they cannot have one. Approving and removing are change forms needing the dashboard's own confirmation, and a refused origin is explained beside the form. Listing origins is part of `ListClients`, the operation that page runs; `approve` and `remove` are their own. No admin JSON API. - Sessions take a `Credential`; inline sign-in passes on the one the assertion gave, #180's probation credential included. The code is issued only if the new session meets the request's requirements, checked as the redirect flow does, so a recovered passkey during its probation meets no `acr_values=phr`. That gets `interaction_required`, and auth's pages then answer the client `unmet_authentication_requirements`. Recovery enrolment stays on auth's own `/recover` page: related origins only sign in. - **Account deletion (#152).** An account scheduled for deletion gets `interaction_required` at finish rather than a session, since only auth's sign-in page offers to restore it. - Migration is `0023_related_origins`, right after #152's 0022. #163 merges before #159, which then takes 0024. - CodeRabbit's findings are fixed: the README's domain-count rule, and approved origins left behind by deleted clients. ## Tests - `related_pages_sign_in_for_pkce_bound_codes` and `related_sign_in_refuses_other_origins_requests_and_unverified_users` (passkey, across two replicas), `a_probation_passkey_meets_no_phr_on_related_pages`, `an_account_being_deleted_signs_in_on_auths_pages_only`, `origin_approval_needs_trust_a_redirect_origin_and_few_domains` (now also deleting the client) and `related_origins_count_registrable_domain_labels` (clients), plus the CLI/admin operation coverage tests. - `tests/browser/related-origins.spec.ts` signs in on a client page served through DevTools. In CI auth is on `localhost`, so the page is `https://localhost:4443`, where browsers need no list. On a piqueld preview it passed from `https://related-e2e.test`, a separate site, so Chromium read `/.well-known/webauthn` first; `oidc.spec.ts` and `sign-in.spec.ts` passed there too. - `related_origins_are_approved_and_removed_from_the_dashboard` drives the dashboard pages. - `just db test`: all 293 pass; `cargo clippy --all-targets --all-features` is clean. Reviewed with review-loop: 4 rounds with 3× GPT 6.1 Sol and Claude Opus 5.5 (Sol was over its usage limit in round 1; later rounds covered the rebases onto #180 and the dashboard). Verdict: approved. A GPT 6.1 Sol review of the rebase onto #152 found that older replicas left a deleted client's origins behind, which the trigger fixes. > [!NOTE] > Written by Claude Opus 5.5 in Claude Code and reviewed by GPT 6.1 Sol and Claude Opus 5.5 (via T3 Code)
1 parent 85d83cd commit d8ce058

53 files changed

Lines changed: 2603 additions & 227 deletions

Some content is hidden

Large Commits have some content hidden by default. Use the searchbox below for content that may be hidden.

‎Cargo.lock‎

Lines changed: 16 additions & 0 deletions
Some generated files are not rendered by default. Learn more about customizing how changed files appear on GitHub.

‎Cargo.toml‎

Lines changed: 2 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -49,6 +49,8 @@ opentelemetry_sdk = { version = "0.33", default-features = false, features = ["t
4949
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["http-proto", "trace", "metrics", "logs", "internal-logs"] }
5050
opentelemetry-http = { version = "0.33", default-features = false }
5151
opentelemetry-appender-tracing = "0.33"
52+
# The public suffix list, compiled in, for the domains WebAuthn related origins count.
53+
psl = "2.1"
5254
serde = { version = "1.0", features = ["derive"] }
5355
serde_json = "1.0"
5456
serde_urlencoded = "0.7"

‎README.md‎

Lines changed: 50 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -194,7 +194,8 @@ admin dashboard (`AdminService` in `apps/auth-service/src/admin`), and so does e
194194
setting administrators may change on another account (`AccountService` in
195195
`apps/auth-service/src/account`). Commands need only
196196
`AUTH_DATABASE_URL` (`invite create` also needs `AUTH_PUBLIC_BASE_URL`, to build its
197-
link, and `user recover` needs it and `AUTH_TOKEN_DIGEST_KEY`, to derive its link), so
197+
link, `user recover` needs it and `AUTH_TOKEN_DIGEST_KEY`, to derive its link, and
198+
`client origin add` needs it to tell auth's own domain apart), so
198199
they work while auth is down: they are the break-glass path when the
199200
dashboard or auth's frontends are unreachable. In deployed environments,
200201
run them with `piquelctl app exec piquel-fr auth --env ENV -- auth-service …` (see
@@ -268,9 +269,10 @@ just auth account alice emails remove <email-id> --reason "Asked by email"
268269
to recover one.
269270
- Failures print their causes and exit with 1; usage errors exit with 2.
270271

271-
Administrators manage accounts, sessions, invitations and other administrators
272-
from the admin dashboard, which auth serves on `AUTH_ADMIN_LISTENER` for the
273-
dashboard's origin, `AUTH_ADMIN_ORIGIN`, and which only a private route reaches.
272+
Administrators manage accounts, sessions, invitations, other administrators and
273+
the origins approved for clients' pages to sign users in from the admin dashboard,
274+
which auth serves on `AUTH_ADMIN_LISTENER` for the dashboard's origin,
275+
`AUTH_ADMIN_ORIGIN`, and which only a private route reaches.
274276
Its pages call `AdminService` in-process; there is no admin API.
275277

276278
An administrator signs in by a handoff from auth: the dashboard sends the browser
@@ -523,6 +525,50 @@ tokens it already holds expire within five minutes. An administrator removes one
523525
the same way from the account's Connected apps page on the dashboard, with a
524526
reason the owner sees in their history.
525527

528+
#### Passkey sign-in on an application's own pages
529+
530+
A trusted client's pages can sign users in with their auth passkeys without
531+
leaving for auth's pages, through WebAuthn related origins (WebAuthn Level 3
532+
§5.11). An administrator approves each origin on the dashboard's Clients page,
533+
which lists them, or with the CLI:
534+
535+
```sh
536+
just auth client origin add blog https://blog.example
537+
just auth client origin list # --output json for scripts
538+
just auth client origin remove blog https://blog.example
539+
```
540+
541+
The client must be trusted, since this sign-in skips the consent page, and the
542+
origin must be the origin of one of its redirect URIs. Browsers honour only a few
543+
distinct domains in the list, so approved origins may span at most 5 registrable
544+
domains (`example` counts once for `app.example.co.uk` and `www.example.co.uk`).
545+
Browsers count origins within auth's own domain too, as `piquel`; a host without a
546+
registrable domain, such as `localhost`, counts none and is accepted only within
547+
auth's domain. `/.well-known/webauthn` lists the approved origins, cacheable for
548+
five minutes and readable from any origin. Auth refuses a removed origin's
549+
sign-ins at once, and deleting a client removes its origins.
550+
551+
The page pushes an authorization request with PKCE, from its own origin, then posts
552+
its `request_uri` as `{"request_uri": …}` to `/webauthn/related/start`, with
553+
`content-type: application/json` and `x-piquel-csrf: 1`. It runs the WebAuthn
554+
assertion the answer describes, then posts `{"ceremony_id": …, "credential": …}`
555+
to `/webauthn/related/finish`, which answers `{code, state, iss}` as JSON instead
556+
of redirecting. The page checks `state` and `iss`, and redeems the code with its
557+
verifier as usual. These calls send no cookies and get none: the sign-in creates a
558+
session that only the client's tokens use, recorded with the page's origin in the
559+
user's security history. A request with `prompt=consent` or `prompt=none`, or an
560+
`id_token_hint` naming an account without passkeys, is refused at start with
561+
`interaction_required` and left unclaimed, so the page can send the browser to
562+
`/oauth/authorize?client_id=…&request_uri=…` with it instead. Finish answers
563+
`interaction_required` when the sign-in falls short of the request, such as a
564+
recovered passkey during its probation against `acr_values=phr`, or when the
565+
account is scheduled for deletion, which only auth's pages restore; the request was
566+
claimed at start, so the page pushes a fresh one before sending the browser to
567+
auth with it. The page should also redirect when the browser lacks related origins
568+
(`PublicKeyCredential.getClientCapabilities()` has no `relatedOrigins`), and push a
569+
fresh request first when a start or the passkey prompt failed, since auth may have
570+
claimed the first one.
571+
526572
### Authentication claims
527573

528574
ID and access tokens report how the browser session behind the grant

‎apps/auth-service/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -21,6 +21,7 @@ ipnet.workspace = true
2121
lettre.workspace = true
2222
percent-encoding.workspace = true
2323
clap.workspace = true
24+
psl.workspace = true
2425
reqwest.workspace = true
2526
tower-http.workspace = true
2627
serde.workspace = true

‎apps/auth-service/src/admin/operation.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -38,7 +38,8 @@ operations! {
3838
CreateInvitation,
3939
/// Revoke an unredeemed invitation.
4040
RevokeInvitation,
41-
/// List OIDC clients.
41+
/// List OIDC clients, and the origins approved for their pages to sign
42+
/// users in.
4243
ListClients,
4344
/// Show one OIDC client.
4445
ViewClient,
@@ -60,6 +61,10 @@ operations! {
6061
DeleteClient,
6162
/// Give a confidential client a new secret.
6263
RotateClientSecret,
64+
/// Approve an origin for a client's pages to sign users in.
65+
ApproveRelatedOrigin,
66+
/// Remove an approved origin.
67+
RemoveRelatedOrigin,
6368
/// Page through domain events.
6469
ListEvents,
6570
/// List administrators.

‎apps/auth-service/src/admin/service.rs‎

Lines changed: 40 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -15,10 +15,10 @@ use chrono::Utc;
1515
use piquel_common::{
1616
AccountStatus, ClientId, DeliveryId, Handle, Personal, RecoveryId, SessionId, TokenId, UserId,
1717
admin::{
18-
Administrator, Client, CreatedInvitation, Email, Event, EventPage, EventSearch, Invitation,
19-
UserDetail, UserPage,
18+
Administrator, ApprovedOrigin, Client, CreatedInvitation, Email, Event, EventPage,
19+
EventSearch, Invitation, UserDetail, UserPage,
2020
},
21-
clients::{ClientField, ClientOwner, ClientRegistration},
21+
clients::{ClientField, ClientOwner, ClientRegistration, RelatedOrigin},
2222
config::Origin,
2323
email::NormalizedEmail,
2424
events::{DomainEvent, EventContext, RecoveryRevocation, RevocationReason},
@@ -749,6 +749,43 @@ impl AdminService {
749749
.await
750750
}
751751

752+
/// Lists every origin approved for clients' pages to sign users in.
753+
pub(crate) async fn list_related_origins(
754+
&self,
755+
operator: &Operator,
756+
) -> Result<Vec<ApprovedOrigin>, AdminError> {
757+
operator.authorize_read(&self.database).await?;
758+
Ok(self.database.oidc().related_origins().await?)
759+
}
760+
761+
/// Approves `origin` for client `id`'s pages to sign users in with passkeys
762+
/// for `rp_id`, auth's `WebAuthn` RP ID.
763+
pub(crate) async fn approve_related_origin(
764+
&self,
765+
operator: &Operator,
766+
id: &ClientId,
767+
origin: &RelatedOrigin,
768+
rp_id: &str,
769+
) -> Result<(), AdminError> {
770+
self.change_clients(operator, async |clients| {
771+
Ok(clients.approve_origin(id, origin, rp_id).await?)
772+
})
773+
.await
774+
}
775+
776+
/// Removes `origin` from client `id`'s approved origins.
777+
pub(crate) async fn remove_related_origin(
778+
&self,
779+
operator: &Operator,
780+
id: &ClientId,
781+
origin: &RelatedOrigin,
782+
) -> Result<(), AdminError> {
783+
self.change_clients(operator, async |clients| {
784+
Ok(clients.remove_origin(id, origin).await?)
785+
})
786+
.await
787+
}
788+
752789
/// Returns a page of the events matching `search`, newest first.
753790
pub(crate) async fn events(
754791
&self,

‎apps/auth-service/src/admin/tests.rs‎

Lines changed: 6 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -702,7 +702,10 @@ impl AdminOperation {
702702
service.view_user(operator, user).await.map(drop),
703703
],
704704
Self::ListInvitations => vec![service.list_invitations(operator).await.map(drop)],
705-
Self::ListClients => vec![service.list_clients(operator).await.map(drop)],
705+
Self::ListClients => vec![
706+
service.list_clients(operator).await.map(drop),
707+
service.list_related_origins(operator).await.map(drop),
708+
],
706709
Self::ViewClient => vec![
707710
service
708711
.client_details(operator, &client.parse().expect("client ID"))
@@ -741,6 +744,8 @@ impl AdminOperation {
741744
| Self::UnsuspendClient
742745
| Self::DeleteClient
743746
| Self::RotateClientSecret
747+
| Self::ApproveRelatedOrigin
748+
| Self::RemoveRelatedOrigin
744749
| Self::GrantAdministrator
745750
| Self::RevokeAdministrator
746751
| Self::RenameHandle

‎apps/auth-service/src/cli/client.rs‎

Lines changed: 76 additions & 3 deletions
Original file line numberDiff line numberDiff line change
@@ -1,15 +1,15 @@
11
//! Registering, inspecting and changing OIDC clients.
22
33
use super::{CliError, Confirm, Console, Output};
4-
use crate::{Applied, DEFAULT_CLIENT_SCOPES, GracePeriod};
4+
use crate::{Applied, DEFAULT_CLIENT_SCOPES, GracePeriod, PUBLIC_BASE_URL};
55
use clap::{Args, Subcommand};
66
use piquel_common::{
77
ClientId,
88
clients::{
99
AllowedScopes, ClientKind, ClientRegistration, DisplayName, PostLogoutUris, RedirectUri,
10-
RedirectUris, ScopeName,
10+
RedirectUris, RelatedOrigin, ScopeName,
1111
},
12-
config::SecretReference,
12+
config::{Origin, SecretReference},
1313
};
1414
use piquel_crypto::ClientSecret;
1515
use piquel_repository::StoredOidcClient;
@@ -81,6 +81,75 @@ pub(super) enum ClientCommand {
8181
#[arg(long, default_value = "24h")]
8282
grace: GracePeriod,
8383
},
84+
/// Approve, remove or list the origins whose pages may sign users in with
85+
/// their passkeys, without sending them to auth's pages.
86+
#[command(subcommand)]
87+
Origin(OriginCommand),
88+
}
89+
90+
/// The origins approved for a client's pages to sign users in with passkeys,
91+
/// which `/.well-known/webauthn` lists as `WebAuthn` related origins.
92+
#[derive(Subcommand)]
93+
pub(super) enum OriginCommand {
94+
/// Approve an origin. The client must be trusted and have a redirect URI on it,
95+
/// and approved origins may span at most 5 domains, as browsers honour.
96+
Add {
97+
/// The client's ID.
98+
id: ClientId,
99+
/// The origin, as browsers send it, e.g. `https://notes.example`.
100+
origin: RelatedOrigin,
101+
},
102+
/// Remove an origin: its pages stop signing users in.
103+
Remove {
104+
/// The client's ID.
105+
id: ClientId,
106+
/// The origin, as approved.
107+
origin: RelatedOrigin,
108+
},
109+
/// List every approved origin.
110+
List {
111+
/// Output format.
112+
#[command(flatten)]
113+
output: Output,
114+
},
115+
}
116+
117+
impl OriginCommand {
118+
/// Runs this command as the operator at this terminal.
119+
async fn run(self, console: &Console) -> Result<(), CliError> {
120+
let Console {
121+
service, operator, ..
122+
} = console;
123+
match self {
124+
Self::Add { id, origin } => {
125+
// Tells hosts within auth's own domain, which browsers accept without the
126+
// list, from public suffixes.
127+
let auth: Origin = PUBLIC_BASE_URL.parse()?;
128+
service
129+
.approve_related_origin(operator, &id, &origin, auth.host())
130+
.await?;
131+
}
132+
Self::Remove { id, origin } => {
133+
service
134+
.remove_related_origin(operator, &id, &origin)
135+
.await?;
136+
}
137+
Self::List { output } => {
138+
output.print(&service.list_related_origins(operator).await?, |origins| {
139+
println!("ORIGIN\tCLIENT\tAPPROVED");
140+
for approved in origins {
141+
println!(
142+
"{}\t{}\t{}",
143+
approved.origin,
144+
approved.client_id,
145+
approved.approved_at.to_rfc3339()
146+
);
147+
}
148+
})?;
149+
}
150+
}
151+
Ok(())
152+
}
84153
}
85154

86155
impl ClientCommand {
@@ -168,6 +237,10 @@ impl ClientCommand {
168237
Self::RotateSecret { id, grace } => ClientChange::Secret(Some(
169238
service.rotate_client_secret(operator, &id, grace).await?,
170239
)),
240+
Self::Origin(command) => {
241+
command.run(console).await?;
242+
ClientChange::Silent
243+
}
171244
};
172245
done.print();
173246
Ok(())

‎apps/auth-service/src/cli/mod.rs‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -39,7 +39,7 @@ use account::AccountCommand;
3939
use admin::AdminCommand;
4040
use audit::AuditCommand;
4141
use clap::{Parser, Subcommand};
42-
use client::ClientCommand;
42+
use client::{ClientCommand, OriginCommand};
4343
use console::{Confirm, Console, Output};
4444
use deliveries::DeliveriesCommand;
4545
use error::CliError;
@@ -182,7 +182,9 @@ impl Administration {
182182
Self::Client(command) => match **command {
183183
ClientCommand::Create(_) => Op::CreateClient,
184184
ClientCommand::Apply(_) => Op::ApplyClient,
185-
ClientCommand::List { .. } => Op::ListClients,
185+
ClientCommand::List { .. } | ClientCommand::Origin(OriginCommand::List { .. }) => {
186+
Op::ListClients
187+
}
186188
ClientCommand::Show { .. } => Op::ViewClient,
187189
ClientCommand::Update(_) => Op::UpdateClient,
188190
ClientCommand::Disable { .. } => Op::DisableClient,
@@ -191,6 +193,8 @@ impl Administration {
191193
ClientCommand::Suspend { .. } => Op::SuspendClient,
192194
ClientCommand::Unsuspend { .. } => Op::UnsuspendClient,
193195
ClientCommand::RotateSecret { .. } => Op::RotateClientSecret,
196+
ClientCommand::Origin(OriginCommand::Add { .. }) => Op::ApproveRelatedOrigin,
197+
ClientCommand::Origin(OriginCommand::Remove { .. }) => Op::RemoveRelatedOrigin,
194198
},
195199
Self::Audit(_) => Op::ListEvents,
196200
Self::Admin(command) => match command {

‎apps/auth-service/src/cli/tests.rs‎

Lines changed: 10 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -66,6 +66,16 @@ impl AdminOperation {
6666
Self::UnsuspendClient => &["client", "unsuspend", "notes"],
6767
Self::DeleteClient => &["client", "delete", "notes"],
6868
Self::RotateClientSecret => &["client", "rotate-secret", "notes"],
69+
Self::ApproveRelatedOrigin => {
70+
&["client", "origin", "add", "notes", "https://notes.example"]
71+
}
72+
Self::RemoveRelatedOrigin => &[
73+
"client",
74+
"origin",
75+
"remove",
76+
"notes",
77+
"https://notes.example",
78+
],
6979
Self::ListEvents => &["audit"],
7080
Self::ListAdministrators => &["admin", "list"],
7181
Self::GrantAdministrator => &["admin", "grant", "alice"],

0 commit comments

Comments
 (0)