use serde::{Deserialize, Serialize};
use uuid::Uuid;
use crate::AxiamError;
use crate::Sensitive;
use crate::client::{AxiamClient, OrgIdentifier, TenantIdentifier};
use crate::token::jwks::Claims;
use crate::token::refresh_guard::RefreshedTokens;
const LOGIN_PATH: &str = "/api/v1/auth/login";
const MFA_VERIFY_PATH: &str = "/api/v1/auth/mfa/verify";
const REFRESH_PATH: &str = "/api/v1/auth/refresh";
const LOGOUT_PATH: &str = "/api/v1/auth/logout";
const DEVICE_PATH: &str = "/api/v1/auth/device";
#[derive(Serialize)]
struct LoginRequestBody {
#[serde(skip_serializing_if = "Option::is_none")]
tenant_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
org_id: Option<Uuid>,
#[serde(skip_serializing_if = "Option::is_none")]
tenant_slug: Option<String>,
#[serde(skip_serializing_if = "Option::is_none")]
org_slug: Option<String>,
username_or_email: String,
password: String,
}
impl std::fmt::Debug for LoginRequestBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("LoginRequestBody")
.field("tenant_id", &self.tenant_id)
.field("org_id", &self.org_id)
.field("tenant_slug", &self.tenant_slug)
.field("org_slug", &self.org_slug)
.field("username_or_email", &self.username_or_email)
.field("password", &"[REDACTED]")
.finish()
}
}
#[derive(Serialize)]
struct MfaVerifyRequestBody {
challenge_token: String,
totp_code: String,
}
impl std::fmt::Debug for MfaVerifyRequestBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("MfaVerifyRequestBody")
.field("challenge_token", &"[REDACTED]")
.field("totp_code", &"[REDACTED]")
.finish()
}
}
#[derive(Deserialize)]
struct MfaSetupRequiredResponseWire {
#[serde(default)]
mfa_setup_required: bool,
setup_token: String,
}
#[derive(Debug, Serialize)]
struct RefreshRequestBody {
tenant_id: Uuid,
org_id: Uuid,
}
#[derive(Debug, Serialize)]
struct LogoutRequestBody {
session_id: Uuid,
}
#[derive(Debug, Deserialize)]
pub(crate) struct LoginUserInfoWire {
#[allow(dead_code)]
id: Uuid,
#[allow(dead_code)]
username: String,
#[allow(dead_code)]
email: String,
#[serde(default)]
organization_level: bool,
#[serde(default)]
tenant_id: Option<Uuid>,
#[serde(default)]
principal_tenant_id: Option<Uuid>,
#[serde(default)]
principal_tenant_slug: Option<String>,
#[serde(default)]
org_id: Option<Uuid>,
#[serde(default)]
reachable_tenant_ids: Option<Vec<Uuid>>,
}
impl LoginUserInfoWire {
pub(crate) fn principal_scope(&self) -> crate::client::PrincipalScope {
crate::client::PrincipalScope {
organization_level: self.organization_level,
reachable_tenant_ids: self.reachable_tenant_ids.clone(),
}
}
}
#[derive(Debug, Deserialize)]
struct LoginSuccessResponseWire {
user: LoginUserInfoWire,
session_id: Uuid,
expires_in: u64,
}
#[derive(Deserialize)]
struct MfaRequiredResponseWire {
challenge_token: String,
available_methods: Vec<String>,
}
#[derive(Debug, Deserialize)]
struct RefreshSuccessResponseWire {
expires_in: u64,
}
#[derive(Deserialize)]
struct DeviceAuthResponseWire {
access_token: String,
token_type: String,
expires_in: u64,
}
#[derive(Debug, Clone)]
#[non_exhaustive]
pub struct DeviceToken {
pub access_token: Sensitive<String>,
pub token_type: String,
pub expires_in: u64,
}
#[derive(Debug)]
pub struct LoginResult {
pub mfa_required: bool,
pub challenge_token: Option<Sensitive<String>>,
pub available_methods: Vec<String>,
pub session_id: Option<Uuid>,
pub expires_in: Option<u64>,
pub mfa_setup_required: bool,
pub setup_token: Option<Sensitive<String>>,
pub organization_level: bool,
pub tenant_id: Option<Uuid>,
pub principal_tenant_id: Option<Uuid>,
pub principal_tenant_slug: Option<String>,
pub org_id: Option<Uuid>,
pub reachable_tenant_ids: Option<Vec<Uuid>>,
}
impl LoginResult {
pub(crate) fn mfa_required(challenge_token: String, available_methods: Vec<String>) -> Self {
Self {
mfa_required: true,
challenge_token: Some(Sensitive::new(challenge_token)),
available_methods,
session_id: None,
expires_in: None,
mfa_setup_required: false,
setup_token: None,
organization_level: false,
tenant_id: None,
principal_tenant_id: None,
principal_tenant_slug: None,
org_id: None,
reachable_tenant_ids: None,
}
}
pub(crate) fn mfa_setup_required(setup_token: String) -> Self {
Self {
mfa_required: false,
challenge_token: None,
available_methods: Vec::new(),
session_id: None,
expires_in: None,
mfa_setup_required: true,
setup_token: Some(Sensitive::new(setup_token)),
organization_level: false,
tenant_id: None,
principal_tenant_id: None,
principal_tenant_slug: None,
org_id: None,
reachable_tenant_ids: None,
}
}
pub(crate) fn success(session_id: Uuid, expires_in: u64) -> Self {
Self {
mfa_required: false,
challenge_token: None,
available_methods: Vec::new(),
session_id: Some(session_id),
expires_in: Some(expires_in),
mfa_setup_required: false,
setup_token: None,
organization_level: false,
tenant_id: None,
principal_tenant_id: None,
principal_tenant_slug: None,
org_id: None,
reachable_tenant_ids: None,
}
}
pub(crate) fn success_with_user(
session_id: Uuid,
expires_in: u64,
user: &LoginUserInfoWire,
) -> Self {
Self {
mfa_required: false,
challenge_token: None,
available_methods: Vec::new(),
session_id: Some(session_id),
expires_in: Some(expires_in),
mfa_setup_required: false,
setup_token: None,
organization_level: user.organization_level,
tenant_id: user.tenant_id,
principal_tenant_id: user.principal_tenant_id.or(user.tenant_id),
principal_tenant_slug: user.principal_tenant_slug.clone(),
org_id: user.org_id,
reachable_tenant_ids: user.reachable_tenant_ids.clone(),
}
}
}
pub(crate) async fn absorb_session_cookies(client: &AxiamClient) -> Result<Claims, AxiamError> {
let access = client
.inner
.jar
.access_token(&client.inner.base_url)
.ok_or_else(|| AxiamError::Auth {
message: "server response did not set the axiam_access cookie".into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?;
let refresh = client.inner.jar.refresh_token(&client.url(REFRESH_PATH));
let claims = client
.jwks_verifier()
.verify_session_token(access.expose())
.await?;
let tenant_id = Uuid::parse_str(&claims.tenant_id).ok();
let org_id = claims
.org_id
.as_deref()
.and_then(|s| Uuid::parse_str(s).ok());
client
.token_manager()
.set_tokens(access, refresh, Some(claims.exp), tenant_id)
.await;
if let Some(org_id) = org_id {
client.set_resolved_org_id(org_id);
}
client.capture_csrf_from_jar();
client.set_principal_scope(None);
client.set_bearer_credential(false);
Ok(claims)
}
impl AxiamClient {
pub async fn login(&self, email: &str, password: &str) -> Result<LoginResult, AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let body = self.build_login_body(email, password);
let response = self
.http()
.post(self.url(LOGIN_PATH))
.tenant_headers_of(self)
.json(&body)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("login request failed: {e}"),
source: Some(Box::new(e)),
})?;
match response.status().as_u16() {
200 => {
let wire: LoginSuccessResponseWire = response.json().await.map_err(deser_err)?;
absorb_session_cookies(self).await?;
if let Some(pt) = wire.user.principal_tenant_id.or(wire.user.tenant_id) {
self.set_resolved_principal_tenant_id(pt);
}
self.set_principal_scope(Some(wire.user.principal_scope()));
Ok(LoginResult::success_with_user(
wire.session_id,
wire.expires_in,
&wire.user,
))
}
202 => {
let wire: MfaRequiredResponseWire = response.json().await.map_err(deser_err)?;
self.set_pending_mfa_challenge(Sensitive::new(wire.challenge_token.clone()));
Ok(LoginResult::mfa_required(
wire.challenge_token,
wire.available_methods,
))
}
403 => {
let body = response.text().await.unwrap_or_default();
if let Ok(wire) = serde_json::from_str::<MfaSetupRequiredResponseWire>(&body)
&& wire.mfa_setup_required
&& !wire.setup_token.is_empty()
{
return Ok(LoginResult::mfa_setup_required(wire.setup_token));
}
Err(AxiamError::from_http_status(403, body))
}
status => Err(map_error_response(status, response).await),
}
}
pub async fn verify_mfa(&self, code: &str) -> Result<LoginResult, AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let challenge = self
.take_pending_mfa_challenge()
.ok_or_else(|| AxiamError::Auth {
message: "verify_mfa called with no pending MFA challenge — call login() first"
.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?;
let body = MfaVerifyRequestBody {
challenge_token: challenge.expose().clone(),
totp_code: code.to_string(),
};
let response = self
.http()
.post(self.url(MFA_VERIFY_PATH))
.tenant_headers_of(self)
.json(&body)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("verify_mfa request failed: {e}"),
source: Some(Box::new(e)),
})?;
match response.status().as_u16() {
200 => {
let wire: LoginSuccessResponseWire = response.json().await.map_err(deser_err)?;
absorb_session_cookies(self).await?;
if let Some(pt) = wire.user.principal_tenant_id.or(wire.user.tenant_id) {
self.set_resolved_principal_tenant_id(pt);
}
self.set_principal_scope(Some(wire.user.principal_scope()));
Ok(LoginResult::success_with_user(
wire.session_id,
wire.expires_in,
&wire.user,
))
}
status => Err(map_error_response(status, response).await),
}
}
pub async fn refresh(&self) -> Result<(), AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let observed =
self.token_manager()
.cached_access_token()
.ok_or_else(|| AxiamError::Auth {
message: "no access token to refresh — call login() first".into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?;
let observed_value = observed.expose().clone();
let tenant_id = self
.resolved_tenant_id()
.await
.ok_or_else(|| AxiamError::Auth {
message: "tenant_id could not be resolved; login() must succeed before refresh()"
.into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?;
let org_id = self.resolved_org_id().ok_or_else(|| AxiamError::Auth {
message: "org_id could not be resolved; login() must succeed before refresh()".into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?;
let client = self.clone();
self.token_manager()
.refresh_if_needed(&observed_value, move |_refresh_token_unused| {
let client = client.clone();
async move {
let body = RefreshRequestBody { tenant_id, org_id };
let response = client
.http()
.post(client.url(REFRESH_PATH))
.tenant_headers_of(&client)
.maybe_csrf_header(&client)
.json(&body)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("refresh request failed: {e}"),
source: Some(Box::new(e)),
})?;
match response.status().as_u16() {
200 => {
let wire: RefreshSuccessResponseWire =
response.json().await.map_err(deser_err)?;
let access = client
.inner
.jar
.access_token(&client.inner.base_url)
.ok_or_else(|| AxiamError::Auth {
message: "refresh response did not set axiam_access".into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?;
let refresh_token =
client.inner.jar.refresh_token(&client.url(REFRESH_PATH));
let claims = client
.jwks_verifier()
.verify_session_token(access.expose())
.await?;
client.capture_csrf_from_jar();
let _ = wire.expires_in; Ok(RefreshedTokens {
access,
refresh: refresh_token,
exp: Some(claims.exp),
tenant_id: Uuid::parse_str(&claims.tenant_id).ok(),
})
}
status => Err(map_error_response(status, response).await),
}
}
})
.await?;
Ok(())
}
pub async fn logout(&self) -> Result<(), AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let session_id = {
let manager = self.token_manager();
let access = manager.cached_access_token();
match access {
Some(token) => {
let claims = self
.jwks_verifier()
.verify_session_token(token.expose())
.await?;
claims
.jti
.as_deref()
.and_then(|s| Uuid::parse_str(s).ok())
.ok_or_else(|| AxiamError::Auth {
message: "access token has no session id (jti) to log out".into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
})?
}
None => {
return Err(AxiamError::Auth {
message: "no active session to log out".into(),
oauth: None,
reason: None,
set_reason: None,
retry_after: None,
});
}
}
};
let body = LogoutRequestBody { session_id };
let response = self
.http()
.post(self.url(LOGOUT_PATH))
.tenant_headers_of(self)
.session_credential_of(self)
.maybe_csrf_header(self)
.json(&body)
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("logout request failed: {e}"),
source: Some(Box::new(e)),
})?;
if !response.status().is_success() {
return Err(map_error_response(response.status().as_u16(), response).await);
}
self.token_manager().clear().await;
self.set_principal_scope(None);
self.set_bearer_credential(false);
Ok(())
}
pub async fn authenticate_device(&self) -> Result<DeviceToken, AxiamError> {
self.ensure_open()?;
if !self.has_client_certificate() {
return Err(AxiamError::auth(
"authenticate_device: this client has no client certificate — configure one \
with AxiamClientBuilder::with_client_cert (CONTRACT.md §6.1 rule 7)",
));
}
self.decision_memo().clear();
let response = self
.http()
.post(self.url(DEVICE_PATH))
.header("X-Tenant-ID", self.tenant_header_value())
.header(reqwest::header::COOKIE, "")
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("authenticate_device request failed: {e}"),
source: Some(Box::new(e)),
})?;
let status = response.status().as_u16();
if status != 200 {
return Err(map_error_response(status, response).await);
}
let wire: DeviceAuthResponseWire = response.json().await.map_err(deser_err)?;
let access = Sensitive::new(wire.access_token);
let claims = self
.jwks_verifier()
.verify_session_token(access.expose())
.await?;
let tenant_id = Uuid::parse_str(&claims.tenant_id).ok();
if let Some(org_id) = claims
.org_id
.as_deref()
.and_then(|s| Uuid::parse_str(s).ok())
{
self.set_resolved_org_id(org_id);
}
let manager = self.token_manager();
manager.clear().await;
manager
.set_tokens(access.clone_inner(), None, Some(claims.exp), tenant_id)
.await;
self.set_bearer_credential(true);
self.set_principal_scope(None);
Ok(DeviceToken {
access_token: access,
token_type: wire.token_type,
expires_in: wire.expires_in,
})
}
fn build_login_body(&self, email: &str, password: &str) -> LoginRequestBody {
let (tenant_id, tenant_slug) = match &self.inner.tenant {
TenantIdentifier::Id(id) => (Some(*id), None),
TenantIdentifier::Slug(slug) => (None, Some(slug.clone())),
};
let (org_id, org_slug) = match self.org_identifier() {
Some(OrgIdentifier::Id(id)) => (Some(*id), None),
Some(OrgIdentifier::Slug(slug)) => (None, Some(slug.clone())),
None => (None, None),
};
LoginRequestBody {
tenant_id,
org_id,
tenant_slug,
org_slug,
username_or_email: email.to_string(),
password: password.to_string(),
}
}
pub(crate) fn url(&self, path: &str) -> url::Url {
self.inner
.base_url
.join(path)
.expect("path is a well-formed relative URL literal")
}
}
pub(crate) async fn map_error_response(status: u16, response: reqwest::Response) -> AxiamError {
let message = response
.text()
.await
.unwrap_or_else(|_| "no response body".to_string());
AxiamError::from_http_status(status, message)
}
pub(crate) fn deser_err(e: reqwest::Error) -> AxiamError {
AxiamError::Network {
message: format!("failed to parse response body: {e}"),
source: Some(Box::new(e)),
}
}
pub(crate) trait TenantHeadersExt {
fn tenant_headers_of(self, client: &AxiamClient) -> Self;
fn session_credential_of(self, client: &AxiamClient) -> Self;
}
impl TenantHeadersExt for reqwest::RequestBuilder {
fn tenant_headers_of(self, client: &AxiamClient) -> Self {
client.tenant_headers(self)
}
fn session_credential_of(self, client: &AxiamClient) -> Self {
client.session_credential(self)
}
}
pub(crate) trait CsrfHeaderExt {
fn maybe_csrf_header(self, client: &AxiamClient) -> Self;
}
impl CsrfHeaderExt for reqwest::RequestBuilder {
fn maybe_csrf_header(self, client: &AxiamClient) -> Self {
match client.csrf_token() {
Some(token) => self.header("X-CSRF-Token", token),
None => self,
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn login_body_debug_redacts_password() {
let body = LoginRequestBody {
tenant_id: None,
org_id: None,
tenant_slug: Some("acme".into()),
org_slug: None,
username_or_email: "user@example.com".into(),
password: "hunter2-super-secret".into(),
};
let rendered = format!("{body:?}");
assert!(
!rendered.contains("hunter2-super-secret"),
"password must never appear in Debug output: {rendered}"
);
assert!(rendered.contains("[REDACTED]"));
assert!(rendered.contains("user@example.com"));
assert!(rendered.contains("acme"));
}
#[test]
fn mfa_verify_body_debug_redacts_totp_and_challenge() {
let body = MfaVerifyRequestBody {
challenge_token: "challenge-abc-123".into(),
totp_code: "654321".into(),
};
let rendered = format!("{body:?}");
assert!(
!rendered.contains("654321"),
"totp_code must never appear in Debug output: {rendered}"
);
assert!(
!rendered.contains("challenge-abc-123"),
"challenge_token must never appear in Debug output: {rendered}"
);
assert!(rendered.contains("[REDACTED]"));
}
}
#[cfg(test)]
mod wire_redaction_tests {
#[test]
fn no_wire_struct_holding_a_secret_is_debug() {
assert!(
!crate::sensitive::implements_debug!(super::MfaRequiredResponseWire),
"MfaRequiredResponseWire is Debug"
);
}
}