#![cfg_attr(not(feature = "rest"), allow(dead_code))]
use serde::Deserialize;
use crate::error::AuthzKind;
use crate::{AxiamError, Sensitive};
#[derive(Debug, Clone, thiserror::Error)]
#[error("{message}")]
pub struct ValidationError {
pub status: u16,
pub operation: &'static str,
pub message: String,
pub fields: Vec<FieldError>,
}
#[derive(Debug, Clone, PartialEq, Eq, Deserialize)]
pub struct FieldError {
pub field: String,
pub message: String,
}
#[derive(Deserialize)]
#[serde(untagged)]
enum FieldErrorBody {
Keyed {
errors: Vec<FieldError>,
},
Map {
errors: std::collections::BTreeMap<String, String>,
},
}
impl AxiamError {
pub fn validation(&self) -> Option<&ValidationError> {
match self {
AxiamError::Network {
source: Some(source),
..
} => source.downcast_ref::<ValidationError>(),
_ => None,
}
}
pub fn is_not_found(&self) -> bool {
matches!(
self,
AxiamError::Authz {
kind: AuthzKind::NotFound,
..
}
)
}
pub fn is_conflict(&self) -> bool {
matches!(
self,
AxiamError::Authz {
kind: AuthzKind::Conflict,
..
}
)
}
pub fn reason_code(&self) -> Option<&str> {
match self {
AxiamError::Authz {
kind: AuthzKind::Conflict,
reason_code,
..
} => reason_code.as_deref(),
_ => None,
}
}
}
pub(crate) fn from_management_status(
operation: &'static str,
status: u16,
body: String,
) -> AxiamError {
match status {
404 => AxiamError::authz_kind(
AuthzKind::NotFound,
format!("{operation}: not found (or not visible to this tenant): {body}"),
None,
None,
),
400 | 422 => {
let fields = parse_field_errors(&body);
AxiamError::network_with_source(
format!("{operation}: request rejected: {body}"),
Box::new(ValidationError {
status,
operation,
message: body,
fields,
}),
)
}
other => AxiamError::from_http_status(other, body),
}
}
fn parse_field_errors(body: &str) -> Vec<FieldError> {
match serde_json::from_str::<FieldErrorBody>(body) {
Ok(FieldErrorBody::Keyed { errors }) => errors,
Ok(FieldErrorBody::Map { errors }) => errors
.into_iter()
.map(|(field, message)| FieldError { field, message })
.collect(),
Err(_) => Vec::new(),
}
}
pub(crate) fn expose_for_wire(value: &Sensitive<String>) -> String {
value.expose().clone()
}
pub(crate) fn wrap_from_wire(value: String) -> Sensitive<String> {
Sensitive::new(value)
}
pub(crate) fn local_refusal(
operation: &'static str,
field: &str,
detail: impl std::fmt::Display,
) -> AxiamError {
let detail = detail.to_string();
let message = format!("{operation}: {field}: {detail}; no request was sent");
AxiamError::network_with_source(
message.clone(),
Box::new(ValidationError {
status: 400,
operation,
message,
fields: vec![FieldError {
field: field.to_string(),
message: detail,
}],
}),
)
}