use super::challenge::{ChallengePayload, ChallengeStore};
use super::credential::WebauthnCredential;
use super::{FactorPurpose, WebauthnCeremonyError, WebauthnConfig};
use crate::dao::repository::{WebauthnBindOutcome, WebauthnCredentialRepository};
use crate::error::{GarrisonError, GarrisonResult};
use std::sync::Arc;
use webauthn_rs::prelude::{
Base64UrlSafeData, Credential, CredentialID, PublicKeyCredential, RegisterPublicKeyCredential,
RequestChallengeResponse, Url, Uuid, Webauthn as WebauthnRs, WebauthnBuilder, WebauthnError,
};
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct RelyingParty {
pub rp_id: String,
pub origin: Url,
}
impl RelyingParty {
pub fn derive(issuer: &str) -> GarrisonResult<Self> {
let origin = Url::parse(issuer)
.map_err(|e| GarrisonError::Config(format!("webauthn-issuer-invalid::{e}")))?;
let host = origin.host_str().filter(|h| !h.is_empty()).ok_or_else(|| {
GarrisonError::Config(format!("webauthn-issuer-host-missing::{issuer}"))
})?;
Ok(Self {
rp_id: host.to_string(),
origin,
})
}
fn build_webauthn(&self) -> GarrisonResult<WebauthnRs> {
WebauthnBuilder::new(&self.rp_id, &self.origin)
.map_err(|e| GarrisonError::Config(format!("webauthn-rp-mismatch::{e}")))?
.build()
.map_err(|e| GarrisonError::Config(format!("webauthn-rp-build::{e}")))
}
}
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct WebauthnAuthentication {
pub tenant_id: i64,
pub user_id: String,
pub credential_id: String,
pub sign_count: u32,
pub backup_eligible: bool,
pub backup_state: bool,
pub user_verified: bool,
pub credential_updated: bool,
}
pub struct WebauthnService {
challenges: ChallengeStore,
credentials: Arc<dyn WebauthnCredentialRepository>,
config: WebauthnConfig,
}
fn extract_client_data_challenge(
client_data_json: &Base64UrlSafeData,
) -> Result<String, WebauthnCeremonyError> {
const MAX_CHALLENGE_KEY_CHARS: usize = 512;
let text = std::str::from_utf8(client_data_json.as_slice())
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("clientdata-utf8::{e}")))?;
let v: serde_json::Value = serde_json::from_str(text)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("clientdata-parse::{e}")))?;
let challenge = v.get("challenge").and_then(|c| c.as_str()).ok_or_else(|| {
WebauthnCeremonyError::CeremonyRejected("clientdata-challenge-missing".to_string())
})?;
if challenge.len() > MAX_CHALLENGE_KEY_CHARS
|| !challenge
.bytes()
.all(|b| b.is_ascii_alphanumeric() || b == b'-' || b == b'_')
{
return Err(WebauthnCeremonyError::CeremonyRejected(
"clientdata-challenge-malformed".to_string(),
));
}
Ok(challenge.to_string())
}
fn assertion_counter(authenticator_data: &Base64UrlSafeData) -> Option<u32> {
let bytes = authenticator_data.as_slice();
if bytes.len() < 37 {
return None;
}
Some(u32::from_be_bytes([
bytes[33], bytes[34], bytes[35], bytes[36],
]))
}
fn map_webauthn_error(e: &WebauthnError) -> WebauthnCeremonyError {
match e {
WebauthnError::CredentialPossibleCompromise => {
WebauthnCeremonyError::CeremonyRejected(format!("credential-possible-compromise::{e}"))
},
other => WebauthnCeremonyError::CeremonyRejected(format!("ceremony::{other}")),
}
}
impl WebauthnService {
pub fn new(
dao: Arc<dyn crate::dao::GarrisonDao>,
credentials: Arc<dyn WebauthnCredentialRepository>,
config: WebauthnConfig,
) -> Self {
Self {
challenges: ChallengeStore::new(dao, config.challenge_ttl_secs),
credentials,
config,
}
}
fn webauthn_for_current_issuer(&self) -> GarrisonResult<WebauthnRs> {
RelyingParty::derive(&self.config.issuer)?.build_webauthn()
}
fn challenge_key_of(challenge: &Base64UrlSafeData) -> GarrisonResult<String> {
serde_json::to_string(challenge)
.map(|s| s.trim_matches('"').to_string())
.map_err(|e| GarrisonError::Internal(format!("webauthn-challenge-encode::{e}")))
}
fn ensure_purpose_enabled(&self, purpose: FactorPurpose) -> Result<(), WebauthnCeremonyError> {
let enabled = match purpose {
FactorPurpose::Passwordless => self.config.passwordless.enabled,
FactorPurpose::SecondFactor => self.config.second_factor.enabled,
};
if enabled {
Ok(())
} else {
Err(WebauthnCeremonyError::PolicyDisabled(purpose))
}
}
pub async fn start_registration(
&self,
tenant_id: i64,
user_id: &str,
user_name: &str,
display_name: &str,
user_unique_id: Uuid,
purpose: FactorPurpose,
) -> Result<webauthn_rs::prelude::CreationChallengeResponse, WebauthnCeremonyError> {
self.ensure_purpose_enabled(purpose)?;
let wan = self
.webauthn_for_current_issuer()
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("rp::{e}")))?;
let existing = self
.credentials
.list_by_user(tenant_id, user_id)
.await
.map_err(|e| {
WebauthnCeremonyError::CeremonyRejected(format!("list-credentials::{e}"))
})?;
let mut exclude_ids = Vec::with_capacity(existing.len());
for row in &existing {
let id: CredentialID = serde_json::from_str(&format!("\"{}\"", row.credential_id))
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("cred-id::{e}")))?;
exclude_ids.push(id);
}
let exclude = if exclude_ids.is_empty() {
None
} else {
Some(exclude_ids)
};
let (ccr, state) = wan
.start_passkey_registration(user_unique_id, user_name, display_name, exclude)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("start-register::{e}")))?;
let challenge_b64 = Self::challenge_key_of(&ccr.public_key.challenge)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("challenge::{e}")))?;
self.challenges
.store(
&challenge_b64,
&ChallengePayload::Registration {
state,
tenant_id,
user_id: user_id.to_string(),
purpose,
},
)
.await
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("store::{e}")))?;
Ok(ccr)
}
pub async fn finish_registration(
&self,
reg: &RegisterPublicKeyCredential,
) -> Result<WebauthnCredential, WebauthnCeremonyError> {
let challenge_b64 = extract_client_data_challenge(®.response.client_data_json)?;
let payload = self.challenges.consume(&challenge_b64).await?;
let (state, tenant_id, user_id) = match payload {
ChallengePayload::Registration {
state,
tenant_id,
user_id,
..
} => (state, tenant_id, user_id),
ChallengePayload::Authentication { .. } => {
return Err(WebauthnCeremonyError::ChallengeKindMismatch);
},
};
let wan = self
.webauthn_for_current_issuer()
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("rp::{e}")))?;
let passkey = wan
.finish_passkey_registration(reg, &state)
.map_err(|e| map_webauthn_error(&e))?;
let credential =
WebauthnCredential::from_ceremony(tenant_id, &user_id, Credential::from(passkey));
let credential = credential
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("model::{e}")))?;
let row = credential
.to_row()
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("model::{e}")))?;
match self.credentials.create(&row).await {
Ok(WebauthnBindOutcome::Bound) => Ok(credential),
Ok(WebauthnBindOutcome::AlreadyBound { .. }) => {
Err(WebauthnCeremonyError::CredentialAlreadyBound)
},
Err(e) => Err(WebauthnCeremonyError::CeremonyRejected(format!(
"bind::{e}"
))),
}
}
pub async fn start_authentication(
&self,
tenant_id: i64,
user_id: &str,
) -> Result<RequestChallengeResponse, WebauthnCeremonyError> {
let rows = self
.credentials
.list_by_user(tenant_id, user_id)
.await
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("list::{e}")))?;
if rows.is_empty() {
return Err(WebauthnCeremonyError::NoCredentialBound);
}
let mut passkeys = Vec::with_capacity(rows.len());
for row in rows {
let cred = WebauthnCredential::from_row(row)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("row::{e}")))?;
passkeys.push(cred.to_passkey());
}
let wan = self
.webauthn_for_current_issuer()
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("rp::{e}")))?;
let (rcr, state) = wan
.start_passkey_authentication(&passkeys)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("start-auth::{e}")))?;
let challenge_b64 = Self::challenge_key_of(&rcr.public_key.challenge)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("challenge::{e}")))?;
self.challenges
.store(
&challenge_b64,
&ChallengePayload::Authentication {
state,
tenant_id,
user_id: user_id.to_string(),
},
)
.await
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("store::{e}")))?;
Ok(rcr)
}
pub async fn finish_authentication(
&self,
assertion: &PublicKeyCredential,
) -> Result<WebauthnAuthentication, WebauthnCeremonyError> {
let challenge_b64 = extract_client_data_challenge(&assertion.response.client_data_json)?;
let payload = self.challenges.consume(&challenge_b64).await?;
let (state, tenant_id, user_id) = match payload {
ChallengePayload::Authentication {
state,
tenant_id,
user_id,
} => (state, tenant_id, user_id),
ChallengePayload::Registration { .. } => {
return Err(WebauthnCeremonyError::ChallengeKindMismatch);
},
};
let wan = self
.webauthn_for_current_issuer()
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("rp::{e}")))?;
let result = match wan.finish_passkey_authentication(assertion, &state) {
Ok(r) => r,
Err(WebauthnError::CredentialPossibleCompromise) => {
let stored = self
.stored_counter_for(tenant_id, assertion)
.await
.unwrap_or(0);
let asserted =
assertion_counter(&assertion.response.authenticator_data).unwrap_or(0);
return Err(WebauthnCeremonyError::CloneSuspected { stored, asserted });
},
Err(other) => {
return Err(WebauthnCeremonyError::CeremonyRejected(format!(
"assertion::{other}"
)));
},
};
let asserted_id = base64url_string(result.cred_id())
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("cred-id::{e}")))?;
let matched = self
.credentials
.find_by_credential_id(tenant_id, &asserted_id)
.await
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("find::{e}")))?;
let mut credential = match matched {
Some(row) => WebauthnCredential::from_row(row)
.map_err(|e| WebauthnCeremonyError::CeremonyRejected(format!("row::{e}")))?,
None => {
return Err(WebauthnCeremonyError::CeremonyRejected(
"asserted-credential-not-found".to_string(),
));
},
};
let asserted_counter = result.counter();
if (asserted_counter > 0 || credential.sign_count > 0)
&& asserted_counter <= credential.sign_count
{
return Err(WebauthnCeremonyError::CloneSuspected {
stored: credential.sign_count,
asserted: asserted_counter,
});
}
let credential_updated = credential.apply_authentication_result(&result);
if credential_updated {
self.credentials
.update_authenticator_state(
tenant_id,
&credential.credential_id,
credential.sign_count,
credential.backup_eligible,
credential.backup_state,
)
.await
.map_err(|e| {
WebauthnCeremonyError::CeremonyRejected(format!("update-state::{e}"))
})?;
}
Ok(WebauthnAuthentication {
tenant_id,
user_id,
credential_id: credential.credential_id,
sign_count: credential.sign_count,
backup_eligible: credential.backup_eligible,
backup_state: credential.backup_state,
user_verified: result.user_verified(),
credential_updated,
})
}
async fn stored_counter_for(
&self,
tenant_id: i64,
assertion: &PublicKeyCredential,
) -> Option<u32> {
let asserted_id = base64url_string(&assertion.raw_id).ok()?;
self.credentials
.find_by_credential_id(tenant_id, &asserted_id)
.await
.ok()
.flatten()
.map(|row| row.sign_count)
}
}
fn base64url_string<T: serde::Serialize>(v: &T) -> GarrisonResult<String> {
serde_json::to_string(v)
.map(|s| s.trim_matches('"').to_string())
.map_err(|e| GarrisonError::Internal(format!("webauthn-cred-id-encode::{e}")))
}
impl std::fmt::Display for super::WebauthnCeremonyError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::ChallengeReplayed => write!(f, "webauthn challenge replayed or expired"),
Self::ChallengeKindMismatch => write!(f, "webauthn challenge kind mismatch"),
Self::CeremonyRejected(detail) => write!(f, "webauthn ceremony rejected: {detail}"),
Self::CredentialAlreadyBound => write!(f, "webauthn credential already bound"),
Self::CloneSuspected { stored, asserted } => write!(
f,
"webauthn sign_count regression (clone suspected): stored={stored}, asserted={asserted}"
),
Self::NoCredentialBound => write!(f, "no webauthn credential bound for user"),
Self::PolicyDisabled(purpose) => {
write!(f, "webauthn factor policy disabled: {purpose:?}")
},
}
}
}
impl std::error::Error for super::WebauthnCeremonyError {}
impl From<WebauthnCeremonyError> for GarrisonError {
fn from(e: WebauthnCeremonyError) -> Self {
GarrisonError::InvalidParam(format!("webauthn-ceremony::{e}"))
}
}