use serde::{Deserialize, Serialize};
use serde_json::Value;
use uuid::Uuid;
use crate::AxiamError;
use crate::Sensitive;
use crate::client::{AxiamClient, OrgIdentifier, TenantIdentifier};
use crate::rest::LoginResult;
use crate::rest::auth::{
CsrfHeaderExt, LoginUserInfoWire, TenantHeadersExt, absorb_session_cookies, deser_err,
map_error_response,
};
const REGISTER_START_PATH: &str = "/api/v1/auth/webauthn/register/start";
const REGISTER_FINISH_PATH: &str = "/api/v1/auth/webauthn/register/finish";
const AUTH_START_PATH: &str = "/api/v1/auth/webauthn/authenticate/start";
const AUTH_FINISH_PATH: &str = "/api/v1/auth/webauthn/authenticate/finish";
const DISCOVERABLE_START_PATH: &str = "/api/v1/auth/webauthn/authenticate/discoverable/start";
const DISCOVERABLE_FINISH_PATH: &str = "/api/v1/auth/webauthn/authenticate/discoverable/finish";
const SETUP_REGISTER_START_PATH: &str = "/api/v1/auth/webauthn/setup/register/start";
const SETUP_REGISTER_FINISH_PATH: &str = "/api/v1/auth/webauthn/setup/register/finish";
#[derive(Debug, Clone)]
pub struct WebauthnChallenge {
pub challenge: Value,
pub state_token: Sensitive<String>,
}
impl WebauthnChallenge {
pub fn request_json(&self) -> String {
let options = self.challenge.get("publicKey").unwrap_or(&self.challenge);
options.to_string()
}
}
#[derive(Debug, Clone, Deserialize)]
pub struct WebauthnCredential {
pub id: Uuid,
pub credential_id: String,
pub name: String,
pub credential_type: String,
pub created_at: String,
#[serde(default)]
pub last_used_at: Option<String>,
}
#[derive(Debug, Clone)]
pub struct WebauthnLoginResult {
pub access_token: Sensitive<String>,
pub refresh_token: Sensitive<String>,
pub session_id: Uuid,
pub expires_in: u64,
}
#[derive(Debug, Clone, Default)]
pub struct WebauthnWorkspace {
pub org_id: Option<Uuid>,
pub org_slug: Option<String>,
pub tenant_id: Option<Uuid>,
pub tenant_slug: Option<String>,
}
#[derive(Deserialize)]
struct ChallengeWire {
challenge: Value,
state_token: String,
}
#[derive(Deserialize)]
struct LoginWire {
access_token: String,
refresh_token: String,
session_id: Uuid,
expires_in: u64,
}
#[derive(Deserialize)]
struct SetupLoginSuccessWire {
session_id: Uuid,
expires_in: u64,
#[serde(default)]
user: Option<LoginUserInfoWire>,
}
#[derive(Serialize)]
struct RegisterFinishBody {
state_token: String,
credential_name: String,
response: Value,
}
impl std::fmt::Debug for RegisterFinishBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("RegisterFinishBody")
.field("state_token", &"[REDACTED]")
.field("credential_name", &self.credential_name)
.field("response", &self.response)
.finish()
}
}
#[derive(Serialize)]
struct FinishBody {
state_token: String,
response: Value,
}
impl std::fmt::Debug for FinishBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("FinishBody")
.field("state_token", &"[REDACTED]")
.field("response", &self.response)
.finish()
}
}
#[derive(Debug, Serialize)]
struct AuthStartBody {
challenge_token: String,
}
#[derive(Serialize)]
struct SetupRegisterStartBody {
setup_token: String,
}
impl std::fmt::Debug for SetupRegisterStartBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SetupRegisterStartBody")
.field("setup_token", &"[REDACTED]")
.finish()
}
}
#[derive(Serialize)]
struct SetupRegisterFinishBody {
setup_token: String,
state_token: String,
credential_name: String,
response: Value,
}
impl std::fmt::Debug for SetupRegisterFinishBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SetupRegisterFinishBody")
.field("setup_token", &"[REDACTED]")
.field("state_token", &"[REDACTED]")
.field("credential_name", &self.credential_name)
.field("response", &self.response)
.finish()
}
}
#[derive(Debug, Default, Serialize)]
struct DiscoverableStartBody {
#[serde(skip_serializing_if = "Option::is_none")]
org_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
org_slug: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
tenant_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
tenant_slug: Option<String>,
}
impl AxiamClient {
pub async fn webauthn_register_start(&self) -> Result<WebauthnChallenge, AxiamError> {
self.ensure_open()?;
self.require_webauthn_session("webauthn_register_start")?;
self.webauthn_start(REGISTER_START_PATH, &serde_json::json!({}))
.await
}
pub async fn webauthn_register_finish(
&self,
state_token: &Sensitive<String>,
credential_name: &str,
response: Value,
) -> Result<WebauthnCredential, AxiamError> {
self.ensure_open()?;
self.require_webauthn_session("webauthn_register_finish")?;
let body = RegisterFinishBody {
state_token: state_token.expose().clone(),
credential_name: credential_name.to_string(),
response,
};
let http_response = self.webauthn_post(REGISTER_FINISH_PATH, &body).await?;
match http_response.status().as_u16() {
200 | 201 => http_response
.json::<WebauthnCredential>()
.await
.map_err(deser_err),
status => Err(map_error_response(status, http_response).await),
}
}
pub async fn webauthn_authenticate_start(
&self,
challenge_token: &Sensitive<String>,
) -> Result<WebauthnChallenge, AxiamError> {
self.ensure_open()?;
let body = AuthStartBody {
challenge_token: challenge_token.expose().clone(),
};
self.webauthn_start(AUTH_START_PATH, &body).await
}
pub async fn webauthn_authenticate_finish(
&self,
state_token: &Sensitive<String>,
response: Value,
) -> Result<WebauthnLoginResult, AxiamError> {
self.webauthn_finish(AUTH_FINISH_PATH, state_token, response)
.await
}
pub async fn webauthn_discoverable_start(
&self,
workspace: Option<&WebauthnWorkspace>,
) -> Result<WebauthnChallenge, AxiamError> {
self.ensure_open()?;
let body = self.webauthn_workspace_body(workspace)?;
self.webauthn_start(DISCOVERABLE_START_PATH, &body).await
}
pub async fn webauthn_discoverable_finish(
&self,
state_token: &Sensitive<String>,
response: Value,
) -> Result<WebauthnLoginResult, AxiamError> {
self.webauthn_finish(DISCOVERABLE_FINISH_PATH, state_token, response)
.await
}
pub async fn webauthn_setup_register_start(
&self,
setup_token: &Sensitive<String>,
) -> Result<WebauthnChallenge, AxiamError> {
self.ensure_open()?;
let body = SetupRegisterStartBody {
setup_token: setup_token.expose().clone(),
};
let response = self
.webauthn_post_no_session(SETUP_REGISTER_START_PATH, &body)
.await?;
match response.status().as_u16() {
200 => {
let wire: ChallengeWire = response.json().await.map_err(deser_err)?;
Ok(WebauthnChallenge {
challenge: wire.challenge,
state_token: Sensitive::new(wire.state_token),
})
}
status => Err(map_error_response(status, response).await),
}
}
pub async fn webauthn_setup_register_finish(
&self,
setup_token: &Sensitive<String>,
state_token: &Sensitive<String>,
credential_name: &str,
response: Value,
) -> Result<LoginResult, AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let body = SetupRegisterFinishBody {
setup_token: setup_token.expose().clone(),
state_token: state_token.expose().clone(),
credential_name: credential_name.to_string(),
response,
};
let http_response = self
.webauthn_post_no_session(SETUP_REGISTER_FINISH_PATH, &body)
.await?;
match http_response.status().as_u16() {
200 => {
let wire: SetupLoginSuccessWire = http_response.json().await.map_err(deser_err)?;
absorb_session_cookies(self).await?;
if let Some(user) = &wire.user {
self.set_principal_scope(Some(user.principal_scope()));
}
Ok(LoginResult::success(wire.session_id, wire.expires_in))
}
status => Err(map_error_response(status, http_response).await),
}
}
async fn webauthn_start<B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<WebauthnChallenge, AxiamError> {
let response = self.webauthn_post(path, body).await?;
match response.status().as_u16() {
200 => {
let wire: ChallengeWire = response.json().await.map_err(deser_err)?;
Ok(WebauthnChallenge {
challenge: wire.challenge,
state_token: Sensitive::new(wire.state_token),
})
}
status => Err(map_error_response(status, response).await),
}
}
async fn webauthn_finish(
&self,
path: &str,
state_token: &Sensitive<String>,
response: Value,
) -> Result<WebauthnLoginResult, AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let body = FinishBody {
state_token: state_token.expose().clone(),
response,
};
let http_response = self.webauthn_post(path, &body).await?;
match http_response.status().as_u16() {
200 => {
let wire: LoginWire = http_response.json().await.map_err(deser_err)?;
absorb_session_cookies(self).await?;
Ok(WebauthnLoginResult {
access_token: Sensitive::new(wire.access_token),
refresh_token: Sensitive::new(wire.refresh_token),
session_id: wire.session_id,
expires_in: wire.expires_in,
})
}
status => Err(map_error_response(status, http_response).await),
}
}
async fn webauthn_post<B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<reqwest::Response, AxiamError> {
self.http()
.post(self.url(path))
.maybe_csrf_header(self)
.session_credential_of(self)
.tenant_headers_of(self)
.json(body)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("webauthn request failed: {e}"),
source: Some(Box::new(e)),
})
}
async fn webauthn_post_no_session<B: Serialize>(
&self,
path: &str,
body: &B,
) -> Result<reqwest::Response, AxiamError> {
self.http()
.post(self.url(path))
.header("X-Tenant-ID", self.tenant_header_value())
.header(reqwest::header::COOKIE, "")
.json(body)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("webauthn request failed: {e}"),
source: Some(Box::new(e)),
})
}
fn require_webauthn_session(&self, operation: &str) -> Result<(), AxiamError> {
if self.inner.jar.access_token(&self.inner.base_url).is_none() {
return Err(AxiamError::Auth {
message: format!(
"{operation} requires an authenticated session: enrol a passkey while \
signed in (CONTRACT.md §24.1)"
),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
});
}
Ok(())
}
fn webauthn_workspace_body(
&self,
workspace: Option<&WebauthnWorkspace>,
) -> Result<DiscoverableStartBody, AxiamError> {
let mut body = DiscoverableStartBody {
org_id: workspace.and_then(|w| w.org_id),
org_slug: workspace.and_then(|w| w.org_slug.clone()),
tenant_id: workspace.and_then(|w| w.tenant_id),
tenant_slug: workspace.and_then(|w| w.tenant_slug.clone()),
};
if body.org_id.is_none() && body.org_slug.is_none() {
match self.org_identifier() {
Some(OrgIdentifier::Id(id)) => body.org_id = Some(*id),
Some(OrgIdentifier::Slug(slug)) => body.org_slug = Some(slug.clone()),
None => {
return Err(AxiamError::auth(
"webauthn_discoverable_start needs an organization: construct the \
client with one, or pass it in the workspace argument \
(CONTRACT.md §24.1)",
));
}
}
}
if body.tenant_id.is_none() && body.tenant_slug.is_none() {
match &self.inner.tenant {
TenantIdentifier::Id(id) => body.tenant_id = Some(*id),
TenantIdentifier::Slug(slug) => body.tenant_slug = Some(slug.clone()),
}
}
Ok(body)
}
}
pub fn webauthn_response_from_json(response: &str) -> Result<Value, AxiamError> {
let value: Value = serde_json::from_str(response).map_err(|e| {
AxiamError::auth(format!(
"the authenticator response string is not valid JSON ({e}). Pass the platform's \
response JSON verbatim (CONTRACT.md §24.6a)"
))
})?;
if !value.is_object() {
return Err(AxiamError::auth(
"the authenticator response must be a JSON object (CONTRACT.md §24.6a)",
));
}
Ok(value)
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum WebauthnFailure {
Cancelled,
AlreadyRegistered,
Timeout,
Unsupported,
Unknown,
}
impl WebauthnFailure {
pub fn classify(name: &str) -> Self {
match name.trim().to_ascii_lowercase().as_str() {
"notallowederror" | "canceled" | "cancelled" => Self::Cancelled,
"invalidstateerror" => Self::AlreadyRegistered,
"aborterror" | "timeout" => Self::Timeout,
"notsupportederror" | "securityerror" => Self::Unsupported,
_ => Self::Unknown,
}
}
pub fn message(self) -> &'static str {
match self {
Self::Cancelled => "The request was cancelled or timed out. You can try again.",
Self::AlreadyRegistered => {
"This device is already registered on your account. Try a different device, \
or remove the existing one first."
}
Self::Timeout => "The request timed out before it completed. Please try again.",
Self::Unsupported => {
"This browser or device cannot be used for passkeys. Try a different browser, \
or use another sign-in method."
}
Self::Unknown => "Something went wrong. Please try again.",
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn register_finish_body_debug_redacts_the_state_token() {
let rendered = format!(
"{:?}",
RegisterFinishBody {
state_token: "state-token-abc".into(),
credential_name: "Alice's laptop".into(),
response: serde_json::json!({ "id": "credential-id" }),
}
);
assert!(!rendered.contains("state-token-abc"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
assert!(rendered.contains("Alice's laptop"), "{rendered}");
assert!(rendered.contains("credential-id"), "{rendered}");
}
#[test]
fn finish_body_debug_redacts_the_state_token() {
let rendered = format!(
"{:?}",
FinishBody {
state_token: "state-token-abc".into(),
response: serde_json::json!({ "id": "credential-id" }),
}
);
assert!(!rendered.contains("state-token-abc"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
assert!(rendered.contains("credential-id"), "{rendered}");
}
}