Skip to content

Commit 4b28fa4

Browse files
PiquelChipsclaude
andcommitted
fix(auth): audit passkey signature counter regressions
A signature counter regression, a sign of a copied passkey, was only logged at debug, which the default filter drops, and the authentication transaction rolled back with no security_audit_log row. It now logs a warning with the stable event `auth.passkey_counter_regression` and the user_id, rolls back the authentication transaction, and appends a `passkey.counter_regression` `rejected` audit row on the pool. Regressions are caught both by webauthn-rs against the ceremony snapshot (CredentialPossibleCompromise, which now converts to PasskeyError::CounterRegression) and by the locked recheck. Other browser-triggered rejections stay at debug so unauthenticated clients cannot flood the logs or a victim's audit history. Refresh and authorization-code rejections commit their revocation and audit row through `commit_rejection`, now built on the new `record_rejection`, and both replay warnings are logged before that commit with the user_id. Tests read audit rows through `list_for_user` behind a `test-support` feature, and `just db prepare` builds with all features so its query is cached. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 94eea4d commit 4b28fa4

12 files changed

Lines changed: 282 additions & 87 deletions

File tree

‎apps/auth-service/Cargo.toml‎

Lines changed: 1 addition & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -31,6 +31,7 @@ webauthn-rs.workspace = true
3131
webauthn-rs-proto.workspace = true
3232

3333
[dev-dependencies]
34+
piquel-repository = { workspace = true, features = ["test-support"] }
3435
tower.workspace = true
3536
webauthn-authenticator-rs = { version = "0.5.5", features = ["softpasskey"] }
3637

‎apps/auth-service/src/oidc/token.rs‎

Lines changed: 21 additions & 25 deletions
Original file line numberDiff line numberDiff line change
@@ -12,9 +12,8 @@ use axum::{
1212
use chrono::Utc;
1313
use piquel_auth_protocol::{TokenId, UserId};
1414
use piquel_repository::{
15-
AppendAuditEvent, AuditAction, AuditMetadata, AuditOutcome, CodeRedemptionError,
16-
ConsumedAuthorizationCode, DatabaseError, DatabaseTransaction, InsertRefreshFamily,
17-
InsertRefreshToken, RefreshRotationError, StoredSession,
15+
AuditAction, CodeRedemptionError, ConsumedAuthorizationCode, DatabaseTransaction,
16+
InsertRefreshFamily, InsertRefreshToken, RefreshRotationError, StoredSession,
1817
};
1918
use serde::{Deserialize, Serialize};
2019
use serde_json::{Value, json};
@@ -469,16 +468,15 @@ impl OidcApplication {
469468
return error.into();
470469
}
471470
};
472-
if let Err(source) = Self::commit_rejection(tx, user_id, action).await {
473-
return source.into();
474-
}
471+
// Logged first so the signal survives a database failure.
475472
if action == AuditAction::RefreshReplay {
476473
tracing::warn!(
477474
event = REFRESH_REPLAY_EVENT,
475+
%user_id,
478476
"refresh token replay rejected"
479477
);
480478
}
481-
error.into()
479+
Self::commit_rejection(tx, user_id, action, error).await
482480
}
483481

484482
/// Persists the family revocation of a replayed code before returning the
@@ -495,35 +493,33 @@ impl OidcApplication {
495493
return error.into();
496494
}
497495
};
498-
if let Err(source) =
499-
Self::commit_rejection(tx, user_id, AuditAction::AuthorizationCodeReplay).await
500-
{
501-
return source.into();
502-
}
496+
// Logged first so the signal survives a database failure.
503497
tracing::warn!(
504498
event = CODE_REPLAY_EVENT,
499+
%user_id,
505500
"authorization code replay rejected"
506501
);
507-
error.into()
502+
Self::commit_rejection(tx, user_id, AuditAction::AuthorizationCodeReplay, error).await
508503
}
509504

510505
/// Commits the revocation a rejected grant already made in `tx`, together with
511-
/// its rejected audit event.
506+
/// its rejected audit event, then returns the grant's `error`, or the database
507+
/// failure that prevented the commit.
512508
async fn commit_rejection(
513509
mut tx: DatabaseTransaction<'_>,
514510
user_id: UserId,
515511
action: AuditAction,
516-
) -> Result<(), DatabaseError> {
517-
tx.audit_events()
518-
.append(&AppendAuditEvent {
519-
id: TokenId::new(),
520-
user_id: Some(user_id),
521-
action,
522-
outcome: AuditOutcome::Rejected,
523-
request_metadata: AuditMetadata::default(),
524-
})
525-
.await?;
526-
tx.commit().await
512+
error: impl Into<OAuthError>,
513+
) -> OAuthError {
514+
let committed = async {
515+
tx.audit_events().record_rejection(user_id, action).await?;
516+
tx.commit().await
517+
}
518+
.await;
519+
match committed {
520+
Ok(()) => error.into(),
521+
Err(source) => source.into(),
522+
}
527523
}
528524
}
529525

‎apps/auth-service/src/passkey/error.rs‎

Lines changed: 24 additions & 8 deletions
Original file line numberDiff line numberDiff line change
@@ -52,7 +52,7 @@ pub(super) enum PasskeyError {
5252
GooglePasswordManagerRequiresAndroid,
5353
/// `WebAuthn` rejected the challenge, credential or authenticator options.
5454
#[error("WebAuthn operation rejected")]
55-
Webauthn(#[from] WebauthnError),
55+
Webauthn(#[source] WebauthnError),
5656
/// A discoverable credential returned an invalid account handle.
5757
#[error("invalid discoverable account handle")]
5858
InvalidUserHandle(#[source] InvalidValue),
@@ -68,11 +68,14 @@ pub(super) enum PasskeyError {
6868
/// The latest stored signature counter is absent or malformed.
6969
#[error("stored passkey counter is missing")]
7070
MissingCounter,
71-
/// A counter-capable authenticator reused or decreased its counter.
71+
/// A counter-capable authenticator reused or decreased its counter, compared with
72+
/// the ceremony's credential snapshot or the latest stored value. Only a holder of
73+
/// the credential, or of a copy, can cause this, so it is audited against the account.
7274
#[error("passkey signature counter did not increase")]
7375
CounterRegression,
74-
/// The verified credential does not match the stored passkey.
75-
#[error("verified passkey credential mismatch")]
76+
/// The stored credential's ID differs from the row it was looked up by, so the
77+
/// stored passkey is corrupt.
78+
#[error("stored passkey credential does not match its ID")]
7679
CredentialMismatch,
7780
/// The credential was revoked before its authentication update.
7881
#[error("passkey credential revoked")]
@@ -173,15 +176,13 @@ impl From<PasskeyError> for ApiError {
173176
"This passkey's signature counter went backwards, which can mean it was copied. \
174177
Use another passkey.",
175178
),
176-
error @ PasskeyError::CredentialMismatch => {
177-
error.rejected("This passkey does not match its stored credential.")
178-
}
179179
error @ PasskeyError::CredentialRevoked => {
180180
error.rejected("This passkey was removed from your account.")
181181
}
182182
PasskeyError::Database(error) => error.into(),
183183
PasskeyError::Session(error) => error.into(),
184184
error @ (PasskeyError::MissingCounter
185+
| PasskeyError::CredentialMismatch
185186
| PasskeyError::StoredCredential(_)
186187
| PasskeyError::StoredCeremony(_)
187188
| PasskeyError::Serialization(_)
@@ -193,13 +194,28 @@ impl From<PasskeyError> for ApiError {
193194

194195
impl PasskeyError {
195196
/// Rejects a passkey ceremony with `message`. The reason is logged at debug level:
196-
/// browsers trigger these, and the Display holds no challenge or credential.
197+
/// any browser can trigger these up to the rate limit, so a higher level would let
198+
/// it flood the logs. A [`CounterRegression`](Self::CounterRegression) is also
199+
/// audited and logged as a warning. The Display holds no challenge or credential.
197200
fn rejected(&self, message: impl Into<Cow<'static, str>>) -> ApiError {
198201
tracing::debug!(error = %piquel_common::ErrorChain(self), "WebAuthn request rejected");
199202
ApiError::bad_request(message)
200203
}
201204
}
202205

206+
impl From<WebauthnError> for PasskeyError {
207+
/// webauthn-rs compares the counter with the ceremony's credential snapshot only
208+
/// after the signature verified, so its possible-compromise verdict is the same
209+
/// [`CounterRegression`](Self::CounterRegression) as the locked recheck. Its other
210+
/// errors, user verification included, can precede the signature check.
211+
fn from(error: WebauthnError) -> Self {
212+
match error {
213+
WebauthnError::CredentialPossibleCompromise => Self::CounterRegression,
214+
error => Self::Webauthn(error),
215+
}
216+
}
217+
}
218+
203219
/// Failure to initialize `WebAuthn` from validated configuration.
204220
#[derive(Debug, thiserror::Error)]
205221
pub enum PasskeyConfigError {

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

Lines changed: 52 additions & 13 deletions
Original file line numberDiff line numberDiff line change
@@ -65,6 +65,8 @@ const RELYING_PARTY_NAME: &str = "Piquel";
6565
const ANDROID_USER_AGENT: &str = "Android";
6666
/// Signature counter location in webauthn-rs's serialized passkey representation.
6767
const CREDENTIAL_COUNTER_POINTER: &str = "/cred/counter";
68+
/// Stable telemetry event name for a signature counter regression, a sign of a copied passkey.
69+
const COUNTER_REGRESSION_EVENT: &str = "auth.passkey_counter_regression";
6870

6971
impl PasskeyApplication {
7072
/// Builds `WebAuthn` from the already validated origin and admission policy.
@@ -274,6 +276,45 @@ impl PasskeyApplication {
274276
Ok(())
275277
}
276278

279+
/// Takes `WebAuthn`'s verdict on an assertion for `user_id` and, once the latest
280+
/// credential state also accepts it, opens the transaction that completes the
281+
/// authentication. The ceremony was already consumed. A
282+
/// [`PasskeyError::CounterRegression`] rolls this transaction back, then commits
283+
/// its audit entry on the pool so the record outlives the rejection.
284+
async fn accept_credential(
285+
&self,
286+
user_id: UserId,
287+
verified: Result<AuthenticationResult, WebauthnError>,
288+
) -> Result<DatabaseTransaction<'_>, PasskeyError> {
289+
let (error, tx) = match verified {
290+
Ok(result) => {
291+
let mut tx = self.database.begin().await?;
292+
match Self::update_credential(&mut tx, user_id, &result).await {
293+
Ok(()) => return Ok(tx),
294+
Err(error) => (error, Some(tx)),
295+
}
296+
}
297+
Err(error) => (error.into(), None),
298+
};
299+
let PasskeyError::CounterRegression = error else {
300+
return Err(error);
301+
};
302+
// Logged first so the signal survives a database failure.
303+
tracing::warn!(
304+
event = COUNTER_REGRESSION_EVENT,
305+
%user_id,
306+
"passkey signature counter regression rejected"
307+
);
308+
if let Some(tx) = tx {
309+
tx.rollback().await?;
310+
}
311+
self.database
312+
.audit_events()
313+
.record_rejection(user_id, AuditAction::PasskeyCounterRegression)
314+
.await?;
315+
Err(error)
316+
}
317+
277318
/// Locks account and session authorization in the same order as credential changes.
278319
async fn lock_management(
279320
tx: &mut DatabaseTransaction<'_>,
@@ -457,15 +498,14 @@ impl PasskeyApplication {
457498
headers: HeaderMap,
458499
Json(input): Json<AuthenticationFinish>,
459500
) -> Result<Response, ApiError> {
460-
let (user_id, result) = match app
501+
let (user_id, verified) = match app
461502
.consume::<AuthenticationCeremony>(&headers, input.ceremony_id)
462503
.await?
463504
{
464505
AuthenticationCeremony::Login(LoginCeremony { user_id, state }) => (
465506
user_id,
466507
app.webauthn
467-
.finish_passkey_authentication(&input.credential, &state)
468-
.map_err(PasskeyError::Webauthn)?,
508+
.finish_passkey_authentication(&input.credential, &state),
469509
),
470510
AuthenticationCeremony::Decoy => return Err(PasskeyError::AccountUnavailable.into()),
471511
AuthenticationCeremony::Discover(DiscoverCeremony { state }) => {
@@ -482,14 +522,15 @@ impl PasskeyApplication {
482522
.collect();
483523
(
484524
user_id,
485-
app.webauthn
486-
.finish_discoverable_authentication(&input.credential, state, &keys)
487-
.map_err(PasskeyError::Webauthn)?,
525+
app.webauthn.finish_discoverable_authentication(
526+
&input.credential,
527+
state,
528+
&keys,
529+
),
488530
)
489531
}
490532
};
491-
let mut tx = app.database.begin().await?;
492-
Self::update_credential(&mut tx, user_id, &result).await?;
533+
let tx = app.accept_credential(user_id, verified).await?;
493534
Ok(Self::complete_sign_in(tx, user_id, AuditAction::PasskeyLogin).await?)
494535
}
495536

@@ -533,12 +574,10 @@ impl PasskeyApplication {
533574
if session.user_id != user_id || session.id != session_id {
534575
return Err(PasskeyError::SessionChanged.into());
535576
}
536-
let result = app
577+
let verified = app
537578
.webauthn
538-
.finish_passkey_authentication(&input.credential, &state)
539-
.map_err(PasskeyError::Webauthn)?;
540-
let mut tx = app.database.begin().await?;
541-
Self::update_credential(&mut tx, user_id, &result).await?;
579+
.finish_passkey_authentication(&input.credential, &state);
580+
let mut tx = app.accept_credential(user_id, verified).await?;
542581
let expires = tx.sessions().grant_management(session_id).await?;
543582
tx.audit_events()
544583
.record(user_id, AuditAction::SettingsUnlock, None)

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

Lines changed: 72 additions & 2 deletions
Original file line numberDiff line numberDiff line change
@@ -7,7 +7,7 @@ use axum::{
77
};
88
use chrono::{Duration, Utc};
99
use piquel_crypto::Secret;
10-
use piquel_repository::{DatabaseConfig, PendingFederation};
10+
use piquel_repository::{AuditOutcome, DatabaseConfig, PendingFederation};
1111
use serde_json::json;
1212
use tower::ServiceExt;
1313
use url::Url;
@@ -270,6 +270,15 @@ impl Fixture {
270270
assert_eq!(response.status(), StatusCode::NO_CONTENT);
271271
Self::cookie(&response)
272272
}
273+
/// Lists the seeded account's audit actions and outcomes, newest first.
274+
async fn audit(&self) -> Vec<(AuditAction, AuditOutcome)> {
275+
self.app
276+
.database
277+
.audit_events()
278+
.list_for_user(self.user_id)
279+
.await
280+
.expect("audit log")
281+
}
273282
/// Registers a new account with a fresh software credential; returns the finish response.
274283
async fn register(&self, cookies: &str, body: Value) -> Response {
275284
let (started, browser) = self.start("/webauthn/register/start", cookies, body).await;
@@ -352,7 +361,8 @@ async fn registration_attaches_a_pending_social_signup_only_when_it_names_it() {
352361
}
353362
}
354363

355-
/// Checks counter ordering under concurrent ceremony snapshots and prevents replay.
364+
/// Checks counter ordering under concurrent ceremony snapshots, audits the regression
365+
/// and prevents replay.
356366
#[tokio::test]
357367
#[ignore = "requires TEST_DATABASE_URL"]
358368
async fn overlapping_assertions_reject_old_counter_after_new_counter_commits() {
@@ -417,6 +427,66 @@ async fn overlapping_assertions_reject_old_counter_after_new_counter_commits() {
417427
keys[0].credential.pointer(CREDENTIAL_COUNTER_POINTER),
418428
Some(&json!(2))
419429
);
430+
assert_eq!(
431+
fixture.audit().await,
432+
[
433+
(
434+
AuditAction::PasskeyCounterRegression,
435+
AuditOutcome::Rejected
436+
),
437+
(AuditAction::PasskeyLogin, AuditOutcome::Success),
438+
],
439+
"the regression outlives its rolled-back authentication transaction; the replay is not audited"
440+
);
441+
}
442+
443+
/// A copy of a passkey that signs behind the stored counter is rejected by `WebAuthn`'s
444+
/// snapshot check, and the rejection is audited like the locked check.
445+
#[tokio::test]
446+
#[ignore = "requires TEST_DATABASE_URL"]
447+
async fn lagging_counter_copy_is_rejected_and_audited() {
448+
let mut fixture = Fixture::new().await;
449+
// Simulate the original authenticator having signed far ahead of this copy.
450+
let mut passkeys = fixture.app.database.passkeys();
451+
let mut key = passkeys
452+
.list_active(fixture.user_id)
453+
.await
454+
.expect("keys")
455+
.remove(0);
456+
*key.credential
457+
.pointer_mut(CREDENTIAL_COUNTER_POINTER)
458+
.expect("counter") = json!(100);
459+
assert!(
460+
passkeys
461+
.update_after_authentication(&key.credential_id, &key.credential)
462+
.await
463+
.expect("advanced counter")
464+
);
465+
let (started, browser) = fixture
466+
.start(
467+
"/webauthn/authenticate/start",
468+
"",
469+
json!({"username":fixture.username}),
470+
)
471+
.await;
472+
let assertion = fixture.assertion(&started);
473+
let response = fixture
474+
.request(
475+
"/webauthn/authenticate/finish",
476+
Method::POST,
477+
&browser,
478+
json!({"ceremony_id":started["ceremony_id"],"credential":assertion}),
479+
)
480+
.await;
481+
assert_eq!(response.status(), StatusCode::BAD_REQUEST);
482+
assert!(response.headers().get(header::SET_COOKIE).is_none());
483+
assert_eq!(
484+
fixture.audit().await,
485+
[(
486+
AuditAction::PasskeyCounterRegression,
487+
AuditOutcome::Rejected
488+
)]
489+
);
420490
}
421491

422492
/// Checks browser/session binding, reusable authorization and last-passkey protection.

0 commit comments

Comments
 (0)