use std::fmt;
use serde::Deserialize;
#[derive(Debug, Clone, PartialEq, Eq)]
pub struct OwlAuthError {
pub code: String,
pub status: Option<u16>,
pub message: String,
pub request_id: Option<String>,
pub retryable: bool,
}
impl OwlAuthError {
#[must_use]
pub fn new(code: &str, message: &str, status: Option<u16>) -> Self {
Self {
code: code.into(),
status,
message: message.into(),
request_id: None,
retryable: matches!(code, "timeout" | "network_error")
|| matches!(status, Some(408 | 429 | 500..=599)),
}
}
pub(crate) fn http(status: u16, body: &[u8], secrets: &[&str]) -> Self {
let Ok(reply) = serde_json::from_slice::<ErrorEnvelope>(body) else {
return Self::new("http_error", "Runtime request failed", Some(status));
};
if reply.code.is_empty() || reply.message.is_empty() || reply.request_id.is_empty() {
return Self::new("http_error", "Runtime request failed", Some(status));
}
let code = sanitize(&reply.code, secrets);
let mut error = Self::new(&code, &sanitize(&reply.message, secrets), Some(status));
error.request_id = Some(sanitize(&reply.request_id, secrets));
error
}
}
impl fmt::Display for OwlAuthError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.message)
}
}
impl std::error::Error for OwlAuthError {}
#[derive(Deserialize)]
struct ErrorEnvelope {
code: String,
message: String,
request_id: String,
}
fn sanitize(value: &str, secrets: &[&str]) -> String {
if secrets
.iter()
.any(|secret| !secret.is_empty() && value.contains(secret))
{
return "[redacted]".into();
}
value
.chars()
.take(256)
.map(|c| if c.is_ascii_control() { ' ' } else { c })
.collect()
}