Skip to content

Commit 641e354

Browse files
PiquelChipsclaude
andcommitted
fix(auth): routes ask for a confirmation before any other error
Checking the owner's confirmation only under the account lock changed which error a route answered first: without a recent confirmation, linking without pending evidence, adding an invalid or unsendable address, or naming a malformed passkey, address or provider answered something other than step_up_required, so the frontends would not ask for a passkey first. Those routes extract ConfirmedOwner or ConfirmedSubject again, which check before the path and body; the operations still check under the lock, for in-process callers too. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent b9dee36 commit 641e354

9 files changed

Lines changed: 169 additions & 35 deletions

File tree

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

Lines changed: 10 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -7,9 +7,11 @@
77
//!
88
//! The rule for sharing: administrators may view, edit and remove, but never add
99
//! a way to sign in or to receive the account's email, which would let them take
10-
//! the account over. Adding a passkey, linking an identity, adding or verifying
11-
//! an address, and reporting a history entry take an [`Owner`], which only the
12-
//! session cookie builds, so an administrator cannot call them. The owner's
10+
//! the account over. Adding a passkey, linking an identity, adding an address
11+
//! and reporting a history entry take an [`Owner`], which only the session cookie
12+
//! builds, so an administrator cannot call them. Verifying an address is
13+
//! authorized by its link's token instead, and takes the signed-in owner only if
14+
//! there is one, to refuse a browser signed in to another account. The owner's
1315
//! clients, which administrators manage through `AdminService`, are the owner's
1416
//! too.
1517
@@ -19,7 +21,7 @@ mod error;
1921
mod subject;
2022

2123
pub(crate) use error::AccountError;
22-
pub(crate) use subject::{Owner, Subject, Viewer};
24+
pub(crate) use subject::{ConfirmedOwner, ConfirmedSubject, Owner, Subject, Viewer};
2325

2426
use crate::{
2527
emails::EmailView,
@@ -170,7 +172,7 @@ impl AccountApplication {
170172
/// Removes a passkey, keeping at least one.
171173
async fn revoke_passkey(
172174
State(app): State<Self>,
173-
subject: Subject,
175+
subject: ConfirmedSubject,
174176
Path(id): Path<PasskeyId>,
175177
) -> Result<StatusCode, AccountError> {
176178
app.service.revoke_passkey(&subject, id).await?;
@@ -188,7 +190,7 @@ impl AccountApplication {
188190
/// Unlinks the provider the path names.
189191
async fn unlink_identity(
190192
State(app): State<Self>,
191-
subject: Subject,
193+
subject: ConfirmedSubject,
192194
Path(provider): Path<String>,
193195
) -> Result<StatusCode, AccountError> {
194196
let provider = provider
@@ -209,7 +211,7 @@ impl AccountApplication {
209211
/// Makes a verified address the primary one.
210212
async fn make_primary_email(
211213
State(app): State<Self>,
212-
subject: Subject,
214+
subject: ConfirmedSubject,
213215
Path(id): Path<EmailId>,
214216
) -> Result<StatusCode, AccountError> {
215217
app.service.make_primary_email(&subject, id).await?;
@@ -219,7 +221,7 @@ impl AccountApplication {
219221
/// Removes an address.
220222
async fn remove_email(
221223
State(app): State<Self>,
222-
subject: Subject,
224+
subject: ConfirmedSubject,
223225
Path(id): Path<EmailId>,
224226
) -> Result<StatusCode, AccountError> {
225227
app.service.remove_email(&subject, id).await?;

‎apps/auth-service/src/account/subject.rs‎

Lines changed: 55 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -14,6 +14,7 @@ use piquel_common::{
1414
events::{DomainEvent, EventContext, RevocationReason},
1515
};
1616
use piquel_repository::{Database, DatabaseTransaction, SessionScope, StoredSession};
17+
use std::ops::Deref;
1718

1819
/// The signed-in owner of an account, acting through their browser session. Its
1920
/// fields are private and only the extractors build one, from the session cookie,
@@ -63,6 +64,18 @@ pub(crate) struct Viewer {
6364
by: Reading,
6465
}
6566

67+
/// An [`Owner`] whose session the request's cookie showed confirmed with a passkey
68+
/// recently, for routes whose operation needs it. Checked when extracted, before
69+
/// the path and body, so such a route answers `step_up_required` before any other
70+
/// error and the browser confirms first. It only gates the request: the
71+
/// operation takes the [`Owner`] and checks the confirmation again under the
72+
/// account lock.
73+
pub(crate) struct ConfirmedOwner(Owner);
74+
75+
/// A [`Subject`] whose owner's session was confirmed when extracted, as
76+
/// [`ConfirmedOwner`]'s, for the routes of changes that need it.
77+
pub(crate) struct ConfirmedSubject(Subject);
78+
6679
/// Who reads a [`Viewer`]'s account.
6780
enum Reading {
6881
/// The account's own user, signed in with this session.
@@ -317,6 +330,48 @@ where
317330
}
318331
}
319332

333+
impl<S> FromRequestParts<S> for ConfirmedOwner
334+
where
335+
Database: FromRef<S>,
336+
S: Send + Sync,
337+
{
338+
type Rejection = ApiError;
339+
/// The owner of the request's browser session, confirmed recently.
340+
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
341+
let Confirmed(session) = <Confirmed>::from_request_parts(parts, state).await?;
342+
Owner::new(parts, state, session).await.map(Self)
343+
}
344+
}
345+
346+
impl<S> FromRequestParts<S> for ConfirmedSubject
347+
where
348+
Database: FromRef<S>,
349+
S: Send + Sync,
350+
{
351+
type Rejection = ApiError;
352+
/// The owner of the request's browser session, confirmed recently.
353+
async fn from_request_parts(parts: &mut Parts, state: &S) -> Result<Self, Self::Rejection> {
354+
let ConfirmedOwner(owner) = ConfirmedOwner::from_request_parts(parts, state).await?;
355+
Ok(Self(Subject::from(owner)))
356+
}
357+
}
358+
359+
impl Deref for ConfirmedOwner {
360+
type Target = Owner;
361+
/// The owner, whose session was confirmed when extracted.
362+
fn deref(&self) -> &Owner {
363+
&self.0
364+
}
365+
}
366+
367+
impl Deref for ConfirmedSubject {
368+
type Target = Subject;
369+
/// The subject, whose owner's session was confirmed when extracted.
370+
fn deref(&self) -> &Subject {
371+
&self.0
372+
}
373+
}
374+
320375
impl<S> FromRequestParts<S> for Subject
321376
where
322377
Database: FromRef<S>,

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

Lines changed: 42 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -7,10 +7,16 @@ use crate::{
77
AdminError, AdminService, Operator, Reason,
88
admin::tests::{Account, Harness, cli, operator},
99
passkey::PasskeyError,
10+
security::ApiError,
1011
security::CONFIRMATION_MAX_AGE,
1112
tests::{Browser, Replicas, sign_out, until_blocked},
1213
};
13-
use axum::http::Method;
14+
use axum::{
15+
Router,
16+
extract::{Path, State},
17+
http::Method,
18+
routing::delete,
19+
};
1420
use chrono::{Duration, Utc};
1521
use piquel_common::{
1622
AuthenticationMethod, EmailId, Provider, TokenId, UserId,
@@ -444,9 +450,9 @@ async fn the_last_passkey_stays_whoever_removes_it() {
444450
}
445451

446452
/// The shared changes that could cut the owner off need their recent passkey
447-
/// confirmation, checked under the account lock before anything is looked up: a
448-
/// session that never confirmed one is refused, whichever passkey, identity or
449-
/// address it names.
453+
/// confirmation, checked before anything else, and again under the account lock:
454+
/// a session that never confirmed one is refused, whichever passkey, identity or
455+
/// address it names, even a malformed one.
450456
#[tokio::test]
451457
#[ignore = "requires TEST_DATABASE_URL"]
452458
async fn owners_confirm_the_changes_that_need_it() {
@@ -455,15 +461,20 @@ async fn owners_confirm_the_changes_that_need_it() {
455461
let social =
456462
Browser::sign_in_with(&database, owner.user_id, AuthenticationMethod::Federation).await;
457463
let routes = AccountApplication::new(database).routes();
458-
let item = |template: &str| template.replace("{id}", &EmailId::new().to_string());
464+
let item = |template: &str, id: &str| template.replace("{id}", id);
465+
let id = EmailId::new().to_string();
466+
let identity = |provider| federation::IDENTITY.replace("{provider}", provider);
467+
// Before anything else: malformed IDs and unknown providers too, so the
468+
// browser confirms first.
459469
for (method, path) in [
460-
(Method::DELETE, item(passkey::ITEM)),
461-
(
462-
Method::DELETE,
463-
federation::IDENTITY.replace("{provider}", "github"),
464-
),
465-
(Method::POST, item(emails::PRIMARY)),
466-
(Method::DELETE, item(emails::ITEM)),
470+
(Method::DELETE, item(passkey::ITEM, &id)),
471+
(Method::DELETE, item(passkey::ITEM, "not-an-id")),
472+
(Method::DELETE, identity("github")),
473+
(Method::DELETE, identity("myspace")),
474+
(Method::POST, item(emails::PRIMARY, &id)),
475+
(Method::POST, item(emails::PRIMARY, "not-an-id")),
476+
(Method::DELETE, item(emails::ITEM, &id)),
477+
(Method::DELETE, item(emails::ITEM, "not-an-id")),
467478
] {
468479
let (status, body) = social.call(&routes, method.clone(), &path).await;
469480
assert_eq!(
@@ -474,18 +485,32 @@ async fn owners_confirm_the_changes_that_need_it() {
474485
}
475486
}
476487

477-
/// A change that needs the owner's confirmation checks it on the session as the
478-
/// request's cookie found it, too: a request whose session was confirmed only
479-
/// while it waited for the account lock is refused, so a cookie from before a
480-
/// confirmation never gains it.
488+
/// A change that needs the owner's confirmation checks it under the account lock
489+
/// on the session as the request's cookie found it, too: an owner whose session
490+
/// was confirmed only while the change waited for the lock is refused, so a
491+
/// cookie from before a confirmation never gains it. The account routes refuse
492+
/// such a request before it waits; this one calls the operation from a plain
493+
/// [`Owner`], as an in-process caller does.
481494
#[tokio::test]
482495
#[ignore = "requires TEST_DATABASE_URL"]
483496
async fn a_confirmation_while_waiting_does_not_count() {
484497
let database = Replicas::database().await;
485498
let owner = Browser::new_account(&database).await;
486499
let social =
487500
Browser::sign_in_with(&database, owner.user_id, AuthenticationMethod::Federation).await;
488-
let routes = AccountApplication::new(database.clone()).routes();
501+
let routes = Router::new()
502+
.route(
503+
passkey::ITEM,
504+
delete(
505+
|State(database): State<Database>, owner: Owner, Path(id): Path<PasskeyId>| async move {
506+
AccountService::new(database)
507+
.revoke_passkey(&Subject::from(owner), id)
508+
.await
509+
.map_err(ApiError::from)
510+
},
511+
),
512+
)
513+
.with_state(database.clone());
489514
let mut confirmation = database.begin().await.expect("transaction");
490515
confirmation
491516
.users()

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

Lines changed: 6 additions & 5 deletions
Original file line numberDiff line numberDiff line change
@@ -10,7 +10,7 @@
1010
//! derived from the address's ID with [`VerificationKey`], once here to store its
1111
//! digest, and again by the email sender. See `docs/architecture/delivery-queue.md`.
1212
use crate::{
13-
account::{AccountError, AccountService, Owner, Subject, Viewer},
13+
account::{AccountError, AccountService, ConfirmedOwner, Owner, Subject, Viewer},
1414
config::EmailConfig,
1515
routes,
1616
security::{ApiError, RequestContext},
@@ -151,7 +151,7 @@ impl EmailApplication {
151151
/// verification email.
152152
async fn add(
153153
State(app): State<Self>,
154-
owner: Owner,
154+
owner: ConfirmedOwner,
155155
Json(body): Json<AddEmail>,
156156
) -> Result<(StatusCode, Json<EmailView>), ApiError> {
157157
let added = AccountService::new(app.database.clone())
@@ -224,9 +224,10 @@ impl EmailApplication {
224224
}
225225
}
226226

227-
/// Address settings any administrator may also change: listing, choosing the
228-
/// primary address among verified ones, and removing. Each change queues the same
229-
/// notices, whoever makes it.
227+
/// The account's addresses. Any administrator may also list them, choose the
228+
/// primary one among verified ones, and remove one; each change queues the same
229+
/// notices, whoever makes it. Only the owner adds an address, since it receives
230+
/// the account's mail, and verifying one is authorized by its link's token.
230231
impl AccountService {
231232
/// Lists the account's addresses, primary first.
232233
pub(crate) async fn emails(&self, viewer: &Viewer) -> Result<Vec<EmailView>, AccountError> {

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

Lines changed: 24 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -189,6 +189,30 @@ impl Harness {
189189
}
190190
}
191191

192+
/// Adding an address asks an unconfirmed session to confirm before anything
193+
/// else, so the browser confirms first: even an invalid address, or one that
194+
/// email is off for, answers `step_up_required`.
195+
#[tokio::test]
196+
#[ignore = "requires TEST_DATABASE_URL"]
197+
async fn adding_asks_for_confirmation_first() {
198+
for enabled in [true, false] {
199+
let harness = Harness::new(enabled).await;
200+
let social = harness.account(AuthenticationMethod::Federation).await;
201+
let body = json!({ "email": "not an address" });
202+
assert_step_up_required(
203+
harness
204+
.send(
205+
Some(&social),
206+
Method::POST,
207+
routes::emails::LIST,
208+
Some(body),
209+
)
210+
.await,
211+
)
212+
.await;
213+
}
214+
}
215+
192216
/// Adding, changing the primary address and removing need a passkey
193217
/// confirmation; a link verifies its address once, without a session, and makes
194218
/// the first one primary. A new primary address notifies the previous one, which

‎apps/auth-service/src/federation/identities.rs‎

Lines changed: 2 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -1,7 +1,7 @@
11
//! Pending and linked social identities: signup, linking, listing and unlinking.
22
33
use super::{FederationApplication, FederationError, Provider};
4-
use crate::account::{AccountError, AccountService, Owner, Subject, Viewer};
4+
use crate::account::{AccountError, AccountService, ConfirmedOwner, Owner, Subject, Viewer};
55
use crate::security::{ApiError, BrowserCookie};
66
use axum::{
77
Json,
@@ -133,7 +133,7 @@ impl FederationApplication {
133133
/// account, then clears the evidence's cookie and says where to continue.
134134
pub(super) async fn confirm_link(
135135
State(app): State<Self>,
136-
owner: Owner,
136+
owner: ConfirmedOwner,
137137
headers: HeaderMap,
138138
) -> Result<Response, ApiError> {
139139
let browser = BrowserCookie::FederationPending

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

Lines changed: 22 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -597,6 +597,28 @@ async fn onboarding_commits_only_with_first_key_and_browser_and_never_claims_exi
597597
tx.rollback().await.expect("rollback");
598598
}
599599

600+
/// Linking asks an unconfirmed session to confirm before anything else, so the
601+
/// browser confirms first: even without this browser's pending evidence, the
602+
/// answer is `step_up_required`.
603+
#[tokio::test]
604+
#[ignore = "requires TEST_DATABASE_URL"]
605+
async fn linking_asks_for_confirmation_first() {
606+
let test = TestApp::new().await;
607+
let user = test.user(None, true).await;
608+
let (_, cookie) = test.session(user, false).await;
609+
let response = test
610+
.routes()
611+
.oneshot(TestApp::request(
612+
Method::POST,
613+
"/login/social/link",
614+
Some(&cookie),
615+
&serde_json::json!({}),
616+
))
617+
.await
618+
.expect("link");
619+
security::tests::assert_step_up_required(response).await;
620+
}
621+
600622
/// Linking and unlinking require the intended account’s recent passkey confirmation;
601623
/// unlink frees the subject and preserves email.
602624
#[expect(

‎docs/architecture/rust-conventions.md‎

Lines changed: 6 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -90,7 +90,9 @@ on it:
9090

9191
- an `Owner`, for what only the owner may do, such as adding a passkey or an
9292
address. Only the session cookie builds one, so these cannot be called for an
93-
administrator;
93+
administrator. Verifying an address is authorized by its link's token instead,
94+
and takes an optional `Owner` only to refuse a browser signed in to another
95+
account;
9496
- a `Subject`, for changes an administrator may also make: the owner, or an
9597
`Operator` with the reason it must give;
9698
- a `Viewer`, for reads, which need no reason. For an operator,
@@ -99,7 +101,9 @@ on it:
99101

100102
Only the extractors build an owner's `Owner`, `Subject` or `Viewer`, from the
101103
session cookie, and only the admin API's authenticator builds an
102-
`Operator::Admin`. Each operation says what it needs: it locks with `lock`, or
104+
`Operator::Admin`. Routes whose operation needs a recent confirmation extract
105+
`ConfirmedOwner` or `ConfirmedSubject` instead, which check it before the path and
106+
body, so the browser is asked to confirm before any other error. Each operation says what it needs: it locks with `lock`, or
103107
`lock_confirmed` when the owner must have confirmed with a passkey recently
104108
(operators confirm their own before committing), records events with `context`,
105109
and ends a `Subject`'s change with `Subject::commit`, which checks an

‎docs/architecture/surfaces.md‎

Lines changed: 2 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -83,7 +83,8 @@ The rule for what is shared: administrators may view, edit and remove, but never
8383
add a way to sign in or to receive the account's email, since that would let them
8484
take the account over. The operations only the owner may run take an `Owner`,
8585
which only the session cookie builds, so calling one for an administrator does not
86-
compile.
86+
compile. Verifying an address is the exception: its link's token authorizes it, so
87+
it works signed out.
8788

8889
| Area | Shared | Owner only |
8990
| --- | --- | --- |

0 commit comments

Comments
 (0)