fraiseql_auth/
error_sanitizer.rs1use std::fmt;
10
11#[derive(Debug, Clone)]
13pub struct SanitizedError {
14 user_message: String,
16 internal_message: String,
18}
19
20impl SanitizedError {
21 pub fn new(user_message: impl Into<String>, internal_message: impl Into<String>) -> Self {
23 Self {
24 user_message: user_message.into(),
25 internal_message: internal_message.into(),
26 }
27 }
28
29 #[must_use]
31 pub fn user_facing(&self) -> &str {
32 &self.user_message
33 }
34
35 #[must_use]
37 pub fn internal(&self) -> &str {
38 &self.internal_message
39 }
40}
41
42impl fmt::Display for SanitizedError {
43 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
44 write!(f, "{}", self.user_message)
46 }
47}
48
49impl std::error::Error for SanitizedError {}
50
51pub trait Sanitize {
57 fn sanitized(self, user_message: &str) -> SanitizedError;
59}
60
61impl<E: fmt::Display> Sanitize for E {
62 fn sanitized(self, user_message: &str) -> SanitizedError {
63 SanitizedError::new(user_message, self.to_string())
64 }
65}
66
67pub mod messages {
69 pub const AUTH_FAILED: &str = "Authentication failed";
71
72 pub const PERMISSION_DENIED: &str = "Permission denied";
74
75 pub const SERVICE_UNAVAILABLE: &str = "Service temporarily unavailable";
77
78 pub const REQUEST_FAILED: &str = "Request failed";
80
81 pub const INVALID_STATE: &str = "Authentication failed";
83
84 pub const TOKEN_EXPIRED: &str = "Authentication failed";
86
87 pub const INVALID_SIGNATURE: &str = "Authentication failed";
89
90 pub const SESSION_EXPIRED: &str = "Authentication failed";
92
93 pub const SESSION_REVOKED: &str = "Authentication failed";
95}
96
97pub struct AuthErrorSanitizer;
99
100impl AuthErrorSanitizer {
101 #[must_use]
103 pub fn jwt_validation_error(internal_error: &str) -> SanitizedError {
104 SanitizedError::new(messages::AUTH_FAILED, internal_error)
105 }
106
107 #[must_use]
109 pub fn oidc_provider_error(internal_error: &str) -> SanitizedError {
110 SanitizedError::new(messages::AUTH_FAILED, internal_error)
111 }
112
113 #[must_use]
115 pub fn session_token_error(internal_error: &str) -> SanitizedError {
116 SanitizedError::new(messages::AUTH_FAILED, internal_error)
117 }
118
119 #[must_use]
121 pub fn csrf_state_error(internal_error: &str) -> SanitizedError {
122 SanitizedError::new(messages::INVALID_STATE, internal_error)
123 }
124
125 #[must_use]
127 pub fn permission_error(internal_error: &str) -> SanitizedError {
128 SanitizedError::new(messages::PERMISSION_DENIED, internal_error)
129 }
130
131 #[must_use]
133 pub fn database_error(internal_error: &str) -> SanitizedError {
134 SanitizedError::new(messages::SERVICE_UNAVAILABLE, internal_error)
135 }
136}