Skip to content

Commit be387a8

Browse files
PiquelChipsclaude
andcommitted
feat(auth): passkey sign-in on approved related origins
Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 85f1bc4 commit be387a8

41 files changed

Lines changed: 2243 additions & 191 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
@@ -50,6 +50,8 @@ opentelemetry_sdk = { version = "0.33", default-features = false, features = ["t
5050
opentelemetry-otlp = { version = "0.33", default-features = false, features = ["http-proto", "trace", "metrics", "logs", "internal-logs"] }
5151
opentelemetry-http = { version = "0.33", default-features = false }
5252
opentelemetry-appender-tracing = "0.33"
53+
# The public suffix list, compiled in, for the domains WebAuthn related origins count.
54+
psl = "2.1"
5355
serde = { version = "1.0", features = ["derive"] }
5456
serde_json = "1.0"
5557
sha2 = "0.10"

‎README.md‎

Lines changed: 32 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -212,6 +212,38 @@ with it. A pushed request is validated exactly like a browser one, but its error
212212
come back as JSON. Discovery advertises `pushed_authorization_request_endpoint`.
213213
Client-hosted request objects (`request` and `request_uri` from RFC 9101) are not
214214
supported.
215+
216+
#### Passkey sign-in on an application's own pages
217+
218+
A trusted client's pages can sign users in with their auth passkeys without
219+
leaving for auth's pages, through WebAuthn related origins (WebAuthn Level 3
220+
§5.11). An operator approves each origin:
221+
222+
```sh
223+
just auth client origin add piquel-web https://piquel.fr
224+
just auth client origin list
225+
just auth client origin remove piquel-web https://piquel.fr
226+
```
227+
228+
The client must be trusted, since this sign-in skips the consent page, and the
229+
origin must be the origin of one of its redirect URIs. Browsers honour only a few
230+
distinct domains in the list, so approved origins may span at most 5 registrable
231+
domains (`example` counts once for `app.example.co.uk` and `www.example.co.uk`);
232+
origins within auth's own domain count none. `/.well-known/webauthn` lists the
233+
approved origins, cacheable for five minutes, so a removed origin stops working
234+
within that time.
235+
236+
The page pushes an authorization request with PKCE, then posts its `request_uri`
237+
to `/webauthn/related/start` and the signed assertion to
238+
`/webauthn/related/finish`, which answers `{code, state, iss}` as JSON instead of
239+
redirecting. The page redeems the code with its verifier as usual. These calls send
240+
no cookies and get none: the sign-in creates a session that only the client's
241+
tokens use, recorded with the page's origin in the user's security history. A
242+
request with `prompt=consent` or `prompt=none` is refused with
243+
`interaction_required` and left unclaimed, for the redirect flow. `@piquel/auth-sdk`
244+
wraps this as `Passkeys.signInWithPasskey()`, given a function that pushes the
245+
request. It falls back to that redirect when the browser lacks related origins,
246+
auth refuses to start, or the browser refuses auth's passkeys on the page.
215247
The endpoints implement code exchange, RS256 ID/access tokens, userinfo, opt-in
216248
rotating refresh tokens, revocation and RP-initiated logout. Access tokens are
217249
intended for the configured client audience. Only requested claims are released;

‎apps/auth-service/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -18,6 +18,7 @@ base64.workspace = true
1818
chrono.workspace = true
1919
ipnet.workspace = true
2020
clap.workspace = true
21+
psl.workspace = true
2122
reqwest.workspace = true
2223
tower-http.workspace = true
2324
serde.workspace = true

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

Lines changed: 159 additions & 4 deletions
Original file line numberDiff line numberDiff line change
@@ -1,5 +1,5 @@
1-
//! The one place that changes OIDC client registrations. Each change commits with
2-
//! the event that records it. The `client` command uses it, as does the deployment
1+
//! The one place that changes OIDC client registrations and their approved
2+
//! related origins. Each change commits with the event that records it. The `client` command uses it, as does the deployment
33
//! job that registers the admin dashboard; the owner API (#43), dynamic
44
//! registration (#44) and the admin API (#38) will too.
55
//!
@@ -8,16 +8,24 @@
88
99
use piquel_common::{
1010
ClientId,
11-
clients::{ClientKind, ClientRegistration},
11+
clients::{ClientKind, ClientRegistration, RelatedOrigin},
1212
events::DomainEvent,
1313
};
1414
use piquel_crypto::{ClientSecret, CryptoError};
1515
use piquel_repository::{Database, DatabaseError, DatabaseTransaction, StoredOidcClient};
16+
use std::collections::BTreeSet;
1617
use thiserror::Error;
18+
use url::Url;
1719

1820
use crate::{GracePeriod, Operator};
1921

20-
/// Creates, updates, applies, enables, disables and rotates the secrets of clients.
22+
/// The most distinct domains related origins may span. Browsers must honour at
23+
/// least 5 (`WebAuthn` Level 3 §5.11.1) and ignore origins past their limit, so
24+
/// staying within 5 keeps every approved origin working in every browser.
25+
const MAX_RELATED_ORIGIN_DOMAINS: usize = 5;
26+
27+
/// Creates, updates, applies, enables, disables and rotates the secrets of
28+
/// clients, and approves their related origins.
2129
#[derive(Clone)]
2230
pub struct ClientRegistry {
2331
/// Where registrations and their events are stored.
@@ -50,6 +58,44 @@ pub enum ClientRegistryError {
5058
/// or secrets.
5159
#[error("client {0}'s ID and kind cannot change; register a new client instead")]
5260
Immutable(ClientId),
61+
/// Only trusted clients skip consent, which inline sign-in needs.
62+
#[error("client {0} is not trusted, so its pages cannot sign users in themselves")]
63+
Untrusted(ClientId),
64+
/// A client's pages are on the origins of its redirect URIs.
65+
#[error("{origin} is not the origin of any redirect URI of client {client}")]
66+
NotRedirectOrigin {
67+
/// The origin to approve.
68+
origin: RelatedOrigin,
69+
/// The client.
70+
client: ClientId,
71+
},
72+
/// Browsers ignore an origin whose host has no registrable domain.
73+
#[error("{0} is on a public suffix, so browsers would ignore it")]
74+
PublicSuffix(RelatedOrigin),
75+
/// Browsers would ignore some approved origins.
76+
#[error(
77+
"approved origins would span {} domains ({}); browsers honour {MAX_RELATED_ORIGIN_DOMAINS}",
78+
.0.len(),
79+
.0.join(", ")
80+
)]
81+
TooManyDomains(Vec<String>),
82+
/// The origin is already approved, for this client or another.
83+
#[error("{origin} is already approved")]
84+
OriginApproved {
85+
/// The origin.
86+
origin: RelatedOrigin,
87+
/// The uniqueness violation.
88+
#[source]
89+
source: DatabaseError,
90+
},
91+
/// The origin is not approved for this client.
92+
#[error("{origin} is not approved for client {client}")]
93+
OriginNotApproved {
94+
/// The origin.
95+
origin: RelatedOrigin,
96+
/// The client.
97+
client: ClientId,
98+
},
5399
/// A secret could not be generated.
54100
#[error("could not generate a client secret")]
55101
Crypto(#[from] CryptoError),
@@ -321,6 +367,115 @@ impl ClientRegistry {
321367
Ok(added || capped)
322368
}
323369

370+
/// Approves `origin` for client `id`'s pages to sign users in with passkeys
371+
/// for `rp_id`, auth's `WebAuthn` RP ID. The client must be trusted and have a
372+
/// redirect URI on the origin, and approved origins must stay within the
373+
/// domains every browser honours.
374+
///
375+
/// # Errors
376+
/// Fails if the client does not exist or breaks a rule above, the origin is
377+
/// already approved or the database fails.
378+
pub async fn approve_origin(
379+
&self,
380+
operator: &Operator,
381+
id: &ClientId,
382+
origin: &RelatedOrigin,
383+
rp_id: &str,
384+
) -> Result<(), ClientRegistryError> {
385+
let mut tx = self.database.begin().await?;
386+
let client = Self::locked(&mut tx, id).await?;
387+
if !client.trusted {
388+
return Err(ClientRegistryError::Untrusted(client.id));
389+
}
390+
let on_origin = |uri: &String| {
391+
Url::parse(uri).is_ok_and(|uri| uri.origin().ascii_serialization() == origin.as_str())
392+
};
393+
if !client.redirect_uris.iter().any(on_origin) {
394+
return Err(ClientRegistryError::NotRedirectOrigin {
395+
origin: origin.clone(),
396+
client: client.id,
397+
});
398+
}
399+
tx.oidc().lock_related_origins().await?;
400+
let mut domains = BTreeSet::new();
401+
for approved in tx.oidc().related_origins().await? {
402+
domains.extend(Self::domain(&approved.origin, rp_id)?);
403+
}
404+
domains.extend(Self::domain(origin, rp_id)?);
405+
if domains.len() > MAX_RELATED_ORIGIN_DOMAINS {
406+
return Err(ClientRegistryError::TooManyDomains(
407+
domains.into_iter().collect(),
408+
));
409+
}
410+
tx.oidc()
411+
.approve_related_origin(id, origin)
412+
.await
413+
.map_err(|error| match error {
414+
DatabaseError::Conflict(_) => ClientRegistryError::OriginApproved {
415+
origin: origin.clone(),
416+
source: error,
417+
},
418+
error => error.into(),
419+
})?;
420+
tx.record(
421+
&operator.context(),
422+
None,
423+
DomainEvent::RelatedOriginApproved {
424+
client_id: id.clone(),
425+
origin: origin.clone(),
426+
},
427+
)
428+
.await?;
429+
tx.commit().await?;
430+
Ok(())
431+
}
432+
433+
/// Removes `origin` from client `id`'s approved origins. Ceremonies its pages
434+
/// already started can no longer finish.
435+
///
436+
/// # Errors
437+
/// Fails if the origin is not approved for the client or the database fails.
438+
pub async fn remove_origin(
439+
&self,
440+
operator: &Operator,
441+
id: &ClientId,
442+
origin: &RelatedOrigin,
443+
) -> Result<(), ClientRegistryError> {
444+
let mut tx = self.database.begin().await?;
445+
if !tx.oidc().remove_related_origin(id, origin).await? {
446+
return Err(ClientRegistryError::OriginNotApproved {
447+
origin: origin.clone(),
448+
client: id.clone(),
449+
});
450+
}
451+
tx.record(
452+
&operator.context(),
453+
None,
454+
DomainEvent::RelatedOriginRemoved {
455+
client_id: id.clone(),
456+
origin: origin.clone(),
457+
},
458+
)
459+
.await?;
460+
tx.commit().await?;
461+
Ok(())
462+
}
463+
464+
/// The domain label browsers count for `origin` against their related-origins
465+
/// limit (`WebAuthn` Level 3 §5.11.1): its registrable domain's first label, e.g.
466+
/// `example` for `https://app.example.co.uk`. Browsers count every listed origin,
467+
/// those within `rp_id` included. They skip one without a registrable domain,
468+
/// such as `localhost`, so that works only within `rp_id`, which browsers allow
469+
/// without the list, and counts nothing.
470+
fn domain(origin: &RelatedOrigin, rp_id: &str) -> Result<Option<String>, ClientRegistryError> {
471+
let host = origin.host();
472+
match psl::domain_str(host).and_then(|domain| domain.split('.').next()) {
473+
Some(label) => Ok(Some(label.to_owned())),
474+
None if host == rp_id || host.ends_with(&format!(".{rp_id}")) => Ok(None),
475+
None => Err(ClientRegistryError::PublicSuffix(origin.clone())),
476+
}
477+
}
478+
324479
/// Locks client `id` for the rest of `tx`, then reads it.
325480
async fn locked(
326481
tx: &mut DatabaseTransaction<'_>,

0 commit comments

Comments
 (0)