Skip to content

Commit 41fc554

Browse files
PiquelChipsclaude
andcommitted
fix(auth): audit rejected passkey assertions
A signature counter regression, a credential mismatch or missing user verification on a signed assertion was only logged at debug, which the default filter drops, and the ceremony transaction rolled back with no security_audit_log row. These rejections now roll the ceremony back and append a `rejected` audit row on the pool (passkey.counter_regression, passkey.credential_mismatch, passkey.user_unverified). Counter regressions are caught both by webauthn-rs against the ceremony snapshot (CredentialPossibleCompromise) and by the locked recheck, and also log a warning with the stable event `auth.passkey_counter_regression`. Other browser-triggered rejections stay at debug so unauthenticated clients cannot flood the logs. Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
1 parent 20aa698 commit 41fc554

10 files changed

Lines changed: 264 additions & 83 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: 3 additions & 11 deletions
Original file line numberDiff line numberDiff line change
@@ -12,7 +12,7 @@ use axum::{
1212
use chrono::Utc;
1313
use piquel_auth_protocol::{SessionId, TokenId, UserId};
1414
use piquel_repository::{
15-
AppendAuditEvent, InsertRefreshFamily, InsertRefreshToken, RefreshRotationError, StoredSession,
15+
InsertRefreshFamily, InsertRefreshToken, RefreshRotationError, StoredSession,
1616
};
1717
use serde::{Deserialize, Serialize};
1818
use serde_json::{Value, json};
@@ -473,7 +473,7 @@ impl OidcApplication {
473473
mut tx: piquel_repository::DatabaseTransaction<'_>,
474474
error: RefreshRotationError,
475475
) -> OAuthError {
476-
use piquel_repository::{AuditAction, AuditMetadata, AuditOutcome};
476+
use piquel_repository::AuditAction;
477477
let (user_id, action) = match error {
478478
RefreshRotationError::Replay { user_id } => (user_id, AuditAction::RefreshReplay),
479479
RefreshRotationError::Policy { user_id } => {
@@ -485,15 +485,7 @@ impl OidcApplication {
485485
RefreshRotationError::Database(_) => return error.into(),
486486
};
487487
let audit = async {
488-
tx.audit_events()
489-
.append(&AppendAuditEvent {
490-
id: TokenId::new(),
491-
user_id: Some(user_id),
492-
action,
493-
outcome: AuditOutcome::Rejected,
494-
request_metadata: AuditMetadata::default(),
495-
})
496-
.await?;
488+
tx.audit_events().record_rejection(user_id, action).await?;
497489
tx.commit().await
498490
}
499491
.await;

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

Lines changed: 44 additions & 18 deletions
Original file line numberDiff line numberDiff line change
@@ -4,7 +4,7 @@ use super::ApiError;
44
use crate::security::SessionError;
55
use piquel_auth_protocol::InvalidValue;
66
use piquel_crypto::CryptoError;
7-
use piquel_repository::DatabaseError;
7+
use piquel_repository::{AuditAction, DatabaseError};
88
use std::borrow::Cow;
99
use webauthn_rs::prelude::WebauthnError;
1010

@@ -62,18 +62,12 @@ pub(super) enum PasskeyError {
6262
/// The account, or the credential it signed with, was disabled or removed.
6363
#[error("active account and credential required")]
6464
AccountInactive,
65-
/// The authenticator did not verify the person using it.
66-
#[error("passkey user verification required")]
67-
UserVerificationRequired,
65+
/// A signed assertion was rejected in a way that implicates its account.
66+
#[error(transparent)]
67+
Credential(#[from] CredentialRejection),
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.
72-
#[error("passkey signature counter did not increase")]
73-
CounterRegression,
74-
/// The verified credential does not match the stored passkey.
75-
#[error("verified passkey credential mismatch")]
76-
CredentialMismatch,
7771
/// The credential was revoked before its authentication update.
7872
#[error("passkey credential revoked")]
7973
CredentialRevoked,
@@ -170,13 +164,15 @@ impl From<PasskeyError> for ApiError {
170164
error @ PasskeyError::AccountUnavailable => {
171165
error.rejected("No passkey is available for this username.")
172166
}
173-
error @ PasskeyError::UserVerificationRequired => error
174-
.rejected("Your authenticator must verify you with a PIN, fingerprint or face."),
175-
error @ PasskeyError::CounterRegression => error.rejected(
176-
"This passkey's signature counter went backwards, which can mean it was copied. \
177-
Use another passkey.",
178-
),
179-
error @ PasskeyError::CredentialMismatch => {
167+
error @ PasskeyError::Credential(CredentialRejection::UserVerificationRequired) => {
168+
error.rejected("Your authenticator must verify you with a PIN, fingerprint or face.")
169+
}
170+
error @ PasskeyError::Credential(CredentialRejection::CounterRegression) => error
171+
.rejected(
172+
"This passkey's signature counter went backwards, which can mean it was copied. \
173+
Use another passkey.",
174+
),
175+
error @ PasskeyError::Credential(CredentialRejection::CredentialMismatch) => {
180176
error.rejected("This passkey does not match its stored credential.")
181177
}
182178
error @ PasskeyError::CredentialRevoked => {
@@ -194,9 +190,39 @@ impl From<PasskeyError> for ApiError {
194190
}
195191
}
196192

193+
/// Rejections of an assertion whose signature `WebAuthn` already verified against one
194+
/// of the account's credentials. Only a holder of that credential, or of a copy, can
195+
/// cause one, so each is attributable to the account and durably audited.
196+
#[derive(Clone, Copy, Debug, thiserror::Error)]
197+
pub(super) enum CredentialRejection {
198+
/// The authenticator did not verify the person using it.
199+
#[error("passkey user verification required")]
200+
UserVerificationRequired,
201+
/// A counter-capable authenticator reused or decreased its counter, compared with
202+
/// the ceremony's credential snapshot or the latest stored value.
203+
#[error("passkey signature counter did not increase")]
204+
CounterRegression,
205+
/// The verified credential does not match the stored passkey.
206+
#[error("verified passkey credential mismatch")]
207+
CredentialMismatch,
208+
}
209+
210+
impl CredentialRejection {
211+
/// Returns the audit action recording this rejection.
212+
pub(super) const fn audit_action(self) -> AuditAction {
213+
match self {
214+
Self::UserVerificationRequired => AuditAction::PasskeyUserUnverified,
215+
Self::CounterRegression => AuditAction::PasskeyCounterRegression,
216+
Self::CredentialMismatch => AuditAction::PasskeyCredentialMismatch,
217+
}
218+
}
219+
}
220+
197221
impl PasskeyError {
198222
/// Rejects a passkey ceremony with `message`. The reason is logged at debug level:
199-
/// browsers trigger these, and the Display holds no challenge or credential.
223+
/// any browser can trigger these up to the rate limit, so a higher level would let
224+
/// it flood the logs. Rejections that implicate an account are audited instead, see
225+
/// [`CredentialRejection`]. The Display holds no challenge or credential.
200226
fn rejected(&self, message: impl Into<Cow<'static, str>>) -> ApiError {
201227
tracing::debug!(error = %piquel_common::ErrorChain(self), "WebAuthn request rejected");
202228
ApiError::bad_request(message)

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

Lines changed: 61 additions & 17 deletions
Original file line numberDiff line numberDiff line change
@@ -32,7 +32,7 @@ use ceremonies::{
3232
ManagementCeremony, RegistrationCeremony,
3333
};
3434
pub use error::PasskeyConfigError;
35-
use error::PasskeyError;
35+
use error::{CredentialRejection, PasskeyError};
3636
use types::{
3737
AuthenticationFinish, DisplayName, EnrollmentStart, LoginStart, ManagementResponse,
3838
PasskeyKind, PasskeyName, PasskeyView, RegistrationFinish, RegistrationStart, Rename,
@@ -59,6 +59,8 @@ const RELYING_PARTY_NAME: &str = "Piquel";
5959
const ANDROID_USER_AGENT: &str = "Android";
6060
/// Signature counter location in webauthn-rs's serialized passkey representation.
6161
const CREDENTIAL_COUNTER_POINTER: &str = "/cred/counter";
62+
/// Stable telemetry event name for a signature counter regression, a sign of a copied passkey.
63+
const COUNTER_REGRESSION_EVENT: &str = "auth.passkey_counter_regression";
6264

6365
impl PasskeyApplication {
6466
/// Builds `WebAuthn` from the already validated origin and admission policy.
@@ -226,7 +228,7 @@ impl PasskeyApplication {
226228
result: &AuthenticationResult,
227229
) -> Result<(), PasskeyError> {
228230
if !result.user_verified() {
229-
return Err(PasskeyError::UserVerificationRequired);
231+
return Err(CredentialRejection::UserVerificationRequired.into());
230232
}
231233
tx.users()
232234
.find_active_by_id_for_update(user_id)
@@ -246,13 +248,13 @@ impl PasskeyApplication {
246248
.and_then(Value::as_u64)
247249
.ok_or(PasskeyError::MissingCounter)?;
248250
if (counter > 0 || result.counter() > 0) && u64::from(result.counter()) <= counter {
249-
return Err(PasskeyError::CounterRegression);
251+
return Err(CredentialRejection::CounterRegression.into());
250252
}
251253
let mut credential: Passkey =
252254
serde_json::from_value(stored.credential).map_err(PasskeyError::StoredCredential)?;
253255
credential
254256
.update_credential(result)
255-
.ok_or(PasskeyError::CredentialMismatch)?;
257+
.ok_or(CredentialRejection::CredentialMismatch)?;
256258
if !tx
257259
.passkeys()
258260
.update_after_authentication(
@@ -266,6 +268,50 @@ impl PasskeyApplication {
266268
Ok(())
267269
}
268270

271+
/// Takes `WebAuthn`'s verdict on an assertion for `user_id` and, once the latest
272+
/// credential state also accepts it, opens the transaction that completes the
273+
/// authentication. A [`CredentialRejection`] rolls the ceremony back, then commits
274+
/// its audit entry on the pool so the record outlives the rejection.
275+
async fn accept_credential(
276+
&self,
277+
user_id: UserId,
278+
verified: Result<AuthenticationResult, WebauthnError>,
279+
) -> Result<DatabaseTransaction<'_>, PasskeyError> {
280+
let rejection = match verified {
281+
Ok(result) => {
282+
let mut tx = self.database.begin().await?;
283+
match Self::update_credential(&mut tx, user_id, &result).await {
284+
Ok(()) => return Ok(tx),
285+
Err(PasskeyError::Credential(rejection)) => {
286+
tx.rollback().await?;
287+
rejection
288+
}
289+
Err(error) => return Err(error),
290+
}
291+
}
292+
// webauthn-rs compares the counter with the ceremony's credential snapshot
293+
// only after the signature verified, so this one implicates the account.
294+
// Its other errors, user verification included, can precede the signature.
295+
Err(WebauthnError::CredentialPossibleCompromise) => {
296+
CredentialRejection::CounterRegression
297+
}
298+
Err(error) => return Err(PasskeyError::Webauthn(error)),
299+
};
300+
// Logged before the audit insert so the signal survives a database failure.
301+
if matches!(rejection, CredentialRejection::CounterRegression) {
302+
tracing::warn!(
303+
event = COUNTER_REGRESSION_EVENT,
304+
%user_id,
305+
"passkey signature counter regression rejected"
306+
);
307+
}
308+
self.database
309+
.audit_events()
310+
.record_rejection(user_id, rejection.audit_action())
311+
.await?;
312+
Err(rejection.into())
313+
}
314+
269315
/// Locks account and session authorization in the same order as credential changes.
270316
async fn lock_management(
271317
tx: &mut DatabaseTransaction<'_>,
@@ -439,15 +485,14 @@ impl PasskeyApplication {
439485
headers: HeaderMap,
440486
Json(input): Json<AuthenticationFinish>,
441487
) -> Result<Response, ApiError> {
442-
let (user_id, result) = match app
488+
let (user_id, verified) = match app
443489
.consume::<AuthenticationCeremony>(&headers, input.ceremony_id)
444490
.await?
445491
{
446492
AuthenticationCeremony::Login(LoginCeremony { user_id, state }) => (
447493
user_id,
448494
app.webauthn
449-
.finish_passkey_authentication(&input.credential, &state)
450-
.map_err(PasskeyError::Webauthn)?,
495+
.finish_passkey_authentication(&input.credential, &state),
451496
),
452497
AuthenticationCeremony::Discover(DiscoverCeremony { state }) => {
453498
let (uuid, _) = app
@@ -463,14 +508,15 @@ impl PasskeyApplication {
463508
.collect();
464509
(
465510
user_id,
466-
app.webauthn
467-
.finish_discoverable_authentication(&input.credential, state, &keys)
468-
.map_err(PasskeyError::Webauthn)?,
511+
app.webauthn.finish_discoverable_authentication(
512+
&input.credential,
513+
state,
514+
&keys,
515+
),
469516
)
470517
}
471518
};
472-
let mut tx = app.database.begin().await?;
473-
Self::update_credential(&mut tx, user_id, &result).await?;
519+
let tx = app.accept_credential(user_id, verified).await?;
474520
Ok(Self::complete_sign_in(tx, user_id, AuditAction::PasskeyLogin).await?)
475521
}
476522

@@ -514,12 +560,10 @@ impl PasskeyApplication {
514560
if session.user_id != user_id || session.id != session_id {
515561
return Err(PasskeyError::SessionChanged.into());
516562
}
517-
let result = app
563+
let verified = app
518564
.webauthn
519-
.finish_passkey_authentication(&input.credential, &state)
520-
.map_err(PasskeyError::Webauthn)?;
521-
let mut tx = app.database.begin().await?;
522-
Self::update_credential(&mut tx, user_id, &result).await?;
565+
.finish_passkey_authentication(&input.credential, &state);
566+
let mut tx = app.accept_credential(user_id, verified).await?;
523567
let expires = tx.sessions().grant_management(session_id).await?;
524568
tx.audit_events()
525569
.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;
@@ -266,6 +266,15 @@ impl Fixture {
266266
assert_eq!(response.status(), StatusCode::NO_CONTENT);
267267
Self::cookie(&response)
268268
}
269+
/// Lists the seeded account's audit actions and outcomes, newest first.
270+
async fn audit(&self) -> Vec<(AuditAction, AuditOutcome)> {
271+
self.app
272+
.database
273+
.audit_events()
274+
.list_for_user(self.user_id)
275+
.await
276+
.expect("audit log")
277+
}
269278
/// Registers a new account with a fresh software credential; returns the finish response.
270279
async fn register(&self, cookies: &str, body: Value) -> Response {
271280
let (started, browser) = self.start("/webauthn/register/start", cookies, body).await;
@@ -348,7 +357,8 @@ async fn registration_attaches_a_pending_social_signup_only_when_it_names_it() {
348357
}
349358
}
350359

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

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

‎crates/database/Cargo.toml‎

Lines changed: 4 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -17,5 +17,9 @@ tokio.workspace = true
1717
url.workspace = true
1818
uuid.workspace = true
1919

20+
[features]
21+
# Read-only helpers that let other crates' tests observe stored state.
22+
test-support = []
23+
2024
[lints]
2125
workspace = true

0 commit comments

Comments
 (0)