use super::WebauthnCeremonyError;
use crate::error::{GarrisonError, GarrisonResult};
use std::sync::Arc;
pub(crate) fn challenge_key(challenge_b64: &str) -> String {
format!("garrison:webauthn:challenge:{challenge_b64}")
}
#[derive(Debug, Clone, serde::Serialize, serde::Deserialize)]
#[serde(tag = "kind", rename_all = "snake_case")]
pub enum ChallengePayload {
Registration {
state: webauthn_rs::prelude::PasskeyRegistration,
tenant_id: i64,
user_id: String,
purpose: super::FactorPurpose,
},
Authentication {
state: webauthn_rs::prelude::PasskeyAuthentication,
tenant_id: i64,
user_id: String,
},
}
pub struct ChallengeStore {
dao: Arc<dyn crate::dao::GarrisonDao>,
ttl_secs: u64,
}
impl ChallengeStore {
pub fn new(dao: Arc<dyn crate::dao::GarrisonDao>, ttl_secs: u64) -> Self {
Self { dao, ttl_secs }
}
pub async fn store(
&self,
challenge_b64: &str,
payload: &ChallengePayload,
) -> GarrisonResult<()> {
let value = serde_json::to_string(payload)
.map_err(|e| GarrisonError::Internal(format!("webauthn-challenge-serialize::{e}")))?;
let claimed = self
.dao
.set_if_absent(&challenge_key(challenge_b64), &value, self.ttl_secs)
.await
.map_err(|e| GarrisonError::Dao(format!("webauthn-challenge-setifabsent::{e}")))?;
if !claimed {
return Err(GarrisonError::InvalidParam(format!(
"webauthn-challenge-conflict::{challenge_b64}"
)));
}
Ok(())
}
pub async fn consume(
&self,
challenge_b64: &str,
) -> Result<ChallengePayload, WebauthnCeremonyError> {
let raw = self
.dao
.get_and_delete(&challenge_key(challenge_b64))
.await
.map_err(|e| {
WebauthnCeremonyError::CeremonyRejected(format!("webauthn-challenge-getdel::{e}"))
})?;
let raw = raw.ok_or(WebauthnCeremonyError::ChallengeReplayed)?;
serde_json::from_str(&raw).map_err(|e| {
WebauthnCeremonyError::CeremonyRejected(format!("webauthn-challenge-deserialize::{e}"))
})
}
}