1use std::fmt;
2
3use serde::Deserialize;
4
5#[derive(Debug, Clone, PartialEq, Eq)]
7pub struct OwlAuthError {
8 pub code: String,
9 pub status: Option<u16>,
10 pub message: String,
11 pub request_id: Option<String>,
12 pub retryable: bool,
13}
14
15impl OwlAuthError {
16 #[must_use]
17 pub fn new(code: &str, message: &str, status: Option<u16>) -> Self {
18 Self {
19 code: code.into(),
20 status,
21 message: message.into(),
22 request_id: None,
23 retryable: matches!(code, "timeout" | "network_error")
24 || matches!(status, Some(408 | 429 | 500..=599)),
25 }
26 }
27
28 pub(crate) fn http(status: u16, body: &[u8], secrets: &[&str]) -> Self {
29 let Ok(reply) = serde_json::from_slice::<ErrorEnvelope>(body) else {
30 return Self::new("http_error", "Runtime request failed", Some(status));
31 };
32 if reply.code.is_empty() || reply.message.is_empty() || reply.request_id.is_empty() {
33 return Self::new("http_error", "Runtime request failed", Some(status));
34 }
35 let code = sanitize(&reply.code, secrets);
36 let mut error = Self::new(&code, &sanitize(&reply.message, secrets), Some(status));
37 error.request_id = Some(sanitize(&reply.request_id, secrets));
38 error
39 }
40}
41
42impl fmt::Display for OwlAuthError {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 f.write_str(&self.message)
45 }
46}
47
48impl std::error::Error for OwlAuthError {}
49
50#[derive(Deserialize)]
51struct ErrorEnvelope {
52 code: String,
53 message: String,
54 request_id: String,
55}
56
57fn sanitize(value: &str, secrets: &[&str]) -> String {
58 if secrets
59 .iter()
60 .any(|secret| !secret.is_empty() && value.contains(secret))
61 {
62 return "[redacted]".into();
63 }
64 value
65 .chars()
66 .take(256)
67 .map(|c| if c.is_ascii_control() { ' ' } else { c })
68 .collect()
69}