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 MFA_ENROLL_PATH: &str = "/api/v1/auth/mfa/enroll";
const MFA_CONFIRM_PATH: &str = "/api/v1/auth/mfa/confirm";
const MFA_SETUP_ENROLL_PATH: &str = "/api/v1/auth/mfa/setup/enroll";
const MFA_SETUP_CONFIRM_PATH: &str = "/api/v1/auth/mfa/setup/confirm";
const VERIFY_EMAIL_PATH: &str = "/api/v1/auth/verify-email";
const RESEND_VERIFICATION_PATH: &str = "/api/v1/auth/resend-verification";
const RESEND_OWN_VERIFICATION_PATH: &str = "/api/v1/users/me/resend-verification";
const RESET_PATH: &str = "/api/v1/auth/reset";
const RESET_CONFIRM_PATH: &str = "/api/v1/auth/reset/confirm";
const RESET_CONTEXT_PATH: &str = "/api/v1/auth/reset/context";
#[derive(Debug, Clone)]
pub struct MfaEnrollment {
pub secret_base32: Sensitive<String>,
pub totp_uri: Sensitive<String>,
}
#[derive(Debug, Clone, Default, Deserialize)]
pub struct PasswordResetContext {
#[serde(default)]
pub opaque: Option<Value>,
}
#[derive(Debug, Clone, Default)]
pub struct PasswordResetRequest {
pub email: String,
pub org_slug: Option<String>,
pub tenant_id: Option<Uuid>,
pub tenant_slug: Option<String>,
}
#[derive(Debug, Clone)]
pub struct PasswordResetConfirmation {
pub token: Sensitive<String>,
pub new_password: Sensitive<String>,
pub tenant_id: Uuid,
pub opaque: Option<Value>,
}
#[derive(Deserialize)]
struct MfaEnrollWire {
secret_base32: String,
totp_uri: String,
}
#[derive(Deserialize)]
struct MfaConfirmWire {
mfa_enabled: bool,
}
#[derive(Deserialize)]
struct LoginSuccessWire {
session_id: Uuid,
expires_in: u64,
#[serde(default)]
user: Option<LoginUserInfoWire>,
}
#[derive(Serialize)]
struct TotpCodeBody {
totp_code: String,
}
impl std::fmt::Debug for TotpCodeBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("TotpCodeBody")
.field("totp_code", &"[REDACTED]")
.finish()
}
}
#[derive(Serialize)]
struct SetupTokenBody {
setup_token: String,
}
impl std::fmt::Debug for SetupTokenBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SetupTokenBody")
.field("setup_token", &"[REDACTED]")
.finish()
}
}
#[derive(Serialize)]
struct SetupConfirmBody {
setup_token: String,
totp_code: String,
}
impl std::fmt::Debug for SetupConfirmBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("SetupConfirmBody")
.field("setup_token", &"[REDACTED]")
.field("totp_code", &"[REDACTED]")
.finish()
}
}
#[derive(Serialize)]
struct VerifyEmailBody {
token: String,
tenant_id: Uuid,
}
impl std::fmt::Debug for VerifyEmailBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("VerifyEmailBody")
.field("token", &"[REDACTED]")
.field("tenant_id", &self.tenant_id)
.finish()
}
}
#[derive(Debug, Serialize)]
struct ResendVerificationBody {
email: String,
tenant_id: Uuid,
}
#[derive(Debug, Default, Serialize)]
struct ResetBody {
email: String,
#[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>,
}
#[derive(Serialize)]
struct ResetConfirmBody {
token: String,
new_password: String,
tenant_id: Uuid,
#[serde(skip_serializing_if = "Option::is_none")]
opaque: Option<Value>,
}
impl std::fmt::Debug for ResetConfirmBody {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("ResetConfirmBody")
.field("token", &"[REDACTED]")
.field("new_password", &"[REDACTED]")
.field("tenant_id", &self.tenant_id)
.field("opaque", &self.opaque)
.finish()
}
}
impl AxiamClient {
pub async fn mfa_enroll(&self) -> Result<MfaEnrollment, AxiamError> {
self.ensure_open()?;
let response = self
.account_post(MFA_ENROLL_PATH, &serde_json::json!({}))
.await?;
Self::mfa_enrollment(response).await
}
pub async fn mfa_confirm(&self, totp_code: &str) -> Result<bool, AxiamError> {
self.ensure_open()?;
let body = TotpCodeBody {
totp_code: totp_code.to_string(),
};
let response = self.account_post(MFA_CONFIRM_PATH, &body).await?;
match response.status().as_u16() {
200 => Ok(response
.json::<MfaConfirmWire>()
.await
.map_err(deser_err)?
.mfa_enabled),
status => Err(map_error_response(status, response).await),
}
}
pub async fn mfa_setup_enroll(
&self,
setup_token: &Sensitive<String>,
) -> Result<MfaEnrollment, AxiamError> {
self.ensure_open()?;
let body = SetupTokenBody {
setup_token: setup_token.expose().clone(),
};
let response = self.account_post(MFA_SETUP_ENROLL_PATH, &body).await?;
Self::mfa_enrollment(response).await
}
pub async fn mfa_setup_confirm(
&self,
setup_token: &Sensitive<String>,
totp_code: &str,
) -> Result<LoginResult, AxiamError> {
self.ensure_open()?;
self.decision_memo().clear();
let body = SetupConfirmBody {
setup_token: setup_token.expose().clone(),
totp_code: totp_code.to_string(),
};
let response = self.account_post(MFA_SETUP_CONFIRM_PATH, &body).await?;
match response.status().as_u16() {
200 => {
let wire: LoginSuccessWire = 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, response).await),
}
}
pub async fn verify_email(
&self,
token: &Sensitive<String>,
tenant_id: Uuid,
) -> Result<(), AxiamError> {
self.ensure_open()?;
let body = VerifyEmailBody {
token: token.expose().clone(),
tenant_id,
};
let response = self.account_post(VERIFY_EMAIL_PATH, &body).await?;
Self::expect_success(response).await
}
pub async fn resend_verification(
&self,
email: &str,
tenant_id: Uuid,
) -> Result<(), AxiamError> {
self.ensure_open()?;
let body = ResendVerificationBody {
email: email.to_string(),
tenant_id,
};
let response = self.account_post(RESEND_VERIFICATION_PATH, &body).await?;
Self::expect_success(response).await
}
pub async fn resend_own_verification(&self) -> Result<(), AxiamError> {
self.ensure_open()?;
let response = self
.account_post(RESEND_OWN_VERIFICATION_PATH, &serde_json::json!({}))
.await?;
Self::expect_success(response).await
}
pub async fn request_password_reset(
&self,
request: &PasswordResetRequest,
) -> Result<(), AxiamError> {
self.ensure_open()?;
let mut body = ResetBody {
email: request.email.clone(),
org_slug: request.org_slug.clone(),
tenant_id: request.tenant_id,
tenant_slug: request.tenant_slug.clone(),
};
if body.org_slug.is_none()
&& let Some(OrgIdentifier::Slug(slug)) = self.org_identifier()
{
body.org_slug = Some(slug.clone());
}
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()),
}
}
let response = self.account_post(RESET_PATH, &body).await?;
Self::expect_success(response).await
}
pub async fn password_reset_context(
&self,
token: &Sensitive<String>,
) -> Result<PasswordResetContext, AxiamError> {
self.ensure_open()?;
let mut url = self.url(RESET_CONTEXT_PATH);
url.query_pairs_mut().append_pair("token", token.expose());
let response = self
.http()
.get(url)
.header("X-Tenant-ID", self.tenant_header_value())
.send()
.await
.map_err(|e| AxiamError::Network {
message: format!("password_reset_context request failed: {e}"),
source: Some(Box::new(e)),
})?;
match response.status().as_u16() {
200 => response
.json::<PasswordResetContext>()
.await
.map_err(deser_err),
status => Err(map_error_response(status, response).await),
}
}
pub async fn confirm_password_reset(
&self,
confirmation: &PasswordResetConfirmation,
) -> Result<(), AxiamError> {
self.ensure_open()?;
let body = ResetConfirmBody {
token: confirmation.token.expose().clone(),
new_password: confirmation.new_password.expose().clone(),
tenant_id: confirmation.tenant_id,
opaque: confirmation.opaque.clone(),
};
let response = self.account_post(RESET_CONFIRM_PATH, &body).await?;
Self::expect_success(response).await
}
async fn account_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!("request failed: {e}"),
source: Some(Box::new(e)),
})
}
async fn mfa_enrollment(response: reqwest::Response) -> Result<MfaEnrollment, AxiamError> {
match response.status().as_u16() {
200 => {
let wire: MfaEnrollWire = response.json().await.map_err(deser_err)?;
Ok(MfaEnrollment {
secret_base32: Sensitive::new(wire.secret_base32),
totp_uri: Sensitive::new(wire.totp_uri),
})
}
status => Err(map_error_response(status, response).await),
}
}
async fn expect_success(response: reqwest::Response) -> Result<(), AxiamError> {
match response.status().as_u16() {
200 | 202 | 204 => Ok(()),
status => Err(map_error_response(status, response).await),
}
}
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn totp_code_body_debug_redacts_the_code() {
let rendered = format!(
"{:?}",
TotpCodeBody {
totp_code: "654321".into()
}
);
assert!(!rendered.contains("654321"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
}
#[test]
fn setup_token_body_debug_redacts_the_token() {
let rendered = format!(
"{:?}",
SetupTokenBody {
setup_token: "setup-token-abc".into()
}
);
assert!(!rendered.contains("setup-token-abc"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
}
#[test]
fn setup_confirm_body_debug_redacts_both_secrets() {
let rendered = format!(
"{:?}",
SetupConfirmBody {
setup_token: "setup-token-abc".into(),
totp_code: "123456".into(),
}
);
assert!(!rendered.contains("setup-token-abc"), "{rendered}");
assert!(!rendered.contains("123456"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
}
#[test]
fn verify_email_body_debug_redacts_the_token_but_keeps_the_tenant() {
let tenant_id = Uuid::nil();
let rendered = format!(
"{:?}",
VerifyEmailBody {
token: "verify-token-xyz".into(),
tenant_id
}
);
assert!(!rendered.contains("verify-token-xyz"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
assert!(rendered.contains(&tenant_id.to_string()), "{rendered}");
}
#[test]
fn reset_confirm_body_debug_redacts_the_token_and_the_new_password() {
let tenant_id = Uuid::nil();
let rendered = format!(
"{:?}",
ResetConfirmBody {
token: "reset-token-xyz".into(),
new_password: "hunter2-super-secret".into(),
tenant_id,
opaque: None,
}
);
assert!(!rendered.contains("reset-token-xyz"), "{rendered}");
assert!(!rendered.contains("hunter2-super-secret"), "{rendered}");
assert!(rendered.contains("[REDACTED]"), "{rendered}");
assert!(rendered.contains(&tenant_id.to_string()), "{rendered}");
}
#[test]
fn reset_confirm_body_debug_keeps_the_opaque_envelope_visible() {
let rendered = format!(
"{:?}",
ResetConfirmBody {
token: "reset-token-xyz".into(),
new_password: String::new(),
tenant_id: Uuid::nil(),
opaque: Some(serde_json::json!({ "record": "opaque-record-b64" })),
}
);
assert!(rendered.contains("opaque-record-b64"), "{rendered}");
}
}