use super::*;
use crate::i18n::translate_error;
const EXTRA_SENSITIVE_KEYS: &[&str] = &[
"password",
"password_hash",
"secret",
"client_secret",
"token",
"access_token",
"refresh_token",
"id_token",
"old_token",
"new_token",
"old_key",
"new_key",
"authorization",
"credential",
"api_key",
"apikey",
];
const EXTRA_MAX_VALUE_LEN: usize = 256;
const EXTRA_MAX_ENTRIES: usize = 32;
pub(crate) fn sanitize_extras(extras: &HashMap<String, String>) -> HashMap<String, String> {
extras
.iter()
.take(EXTRA_MAX_ENTRIES)
.map(|(k, v)| {
let value = if EXTRA_SENSITIVE_KEYS.contains(&k.to_ascii_lowercase().as_str()) {
"***".to_string()
} else if v.len() > EXTRA_MAX_VALUE_LEN {
let mut end = EXTRA_MAX_VALUE_LEN;
while end > 0 && !v.is_char_boundary(end) {
end -= 1;
}
format!("{}\u{2026}", &v[..end])
} else {
v.clone()
};
(k.clone(), value)
})
.collect()
}
fn mask_preview(s: &str, keep: usize) -> String {
match s.get(..keep) {
Some(prefix) if s.len() > keep => format!("{prefix}***"),
_ => "***".to_string(),
}
}
impl NotLoginException {
pub fn new(message: impl Into<String>) -> Self {
Self {
message: message.into(),
login_type: String::new(),
}
}
pub fn with_login_type(mut self, login_type: impl Into<String>) -> Self {
self.login_type = login_type.into();
self
}
}
impl std::fmt::Display for NotLoginException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let err = GarrisonError::NotLogin(self.message.clone());
let base = translate_error(&err);
if self.login_type.is_empty() {
f.write_str(&base)
} else {
write!(f, "{base} (login_type={})", self.login_type)
}
}
}
impl std::error::Error for NotLoginException {}
impl GarrisonException {
pub fn new(code: i32, message: impl Into<String>) -> Self {
Self {
code,
message: message.into(),
login_type: 0,
token_value: None,
login_id: None,
extras: HashMap::new(),
}
}
pub fn with_token(mut self, token: impl Into<String>) -> Self {
self.token_value = Some(token.into());
self
}
pub fn with_login_id(mut self, login_id: impl Into<String>) -> Self {
self.login_id = Some(login_id.into());
self
}
pub fn with_login_type(mut self, login_type: i32) -> Self {
self.login_type = login_type;
self
}
pub fn with_extra(mut self, key: impl Into<String>, value: impl Into<String>) -> Self {
self.extras.insert(key.into(), value.into());
self
}
pub fn build(self) -> Self {
self
}
}
impl From<GarrisonException> for GarrisonError {
fn from(ex: GarrisonException) -> Self {
GarrisonError::Exception(Box::new(ex))
}
}
impl From<GarrisonError> for GarrisonException {
fn from(err: GarrisonError) -> Self {
match err {
GarrisonError::Exception(ex) => *ex,
GarrisonError::NotLogin(msg) => GarrisonException::new(-1, msg),
GarrisonError::InvalidToken(msg) => GarrisonException::new(-1, msg),
GarrisonError::ExpiredToken(msg) => GarrisonException::new(-1, msg),
GarrisonError::NotPermission(msg) => GarrisonException::new(-2, msg),
GarrisonError::NotRole(msg) => GarrisonException::new(-2, msg),
GarrisonError::FirewallBlocked(msg) => GarrisonException::new(-2, msg),
other => GarrisonException::new(500, other.to_string()),
}
}
}
impl std::fmt::Display for GarrisonException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let err = GarrisonError::Exception(Box::new(self.clone()));
f.write_str(&translate_error(&err))
}
}
impl std::fmt::Debug for GarrisonException {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
let masked_token = match &self.token_value {
Some(t) => format!("Some(\"{}\")", mask_preview(t, 8)),
None => "None".to_string(),
};
let masked_login_id = match &self.login_id {
Some(id) => format!("Some(\"{}\")", mask_preview(id, 4)),
None => "None".to_string(),
};
f.debug_struct("GarrisonException")
.field("code", &self.code)
.field("message", &self.message)
.field("login_type", &self.login_type)
.field("token_value", &masked_token)
.field("login_id", &masked_login_id)
.field("extras", &sanitize_extras(&self.extras))
.finish()
}
}
#[cfg(feature = "web-axum")]
impl axum::response::IntoResponse for GarrisonException {
fn into_response(self) -> axum::response::Response {
use axum::http::StatusCode;
tracing::error!(exception = ?self, "garrison exception");
let status = match self.code {
-1 => StatusCode::UNAUTHORIZED,
-2 => StatusCode::FORBIDDEN,
_ => StatusCode::INTERNAL_SERVER_ERROR,
};
let mut body = serde_json::json!({
"code": self.code,
"message": self.message,
"extras": sanitize_extras(&self.extras),
});
if let Some(id) = crate::context::request_id::current() {
body[crate::context::request_id::REQUEST_ID_BODY_FIELD] =
serde_json::Value::String(id.to_string());
}
let mut response = (status, axum::Json(body)).into_response();
if let Some(id) = crate::context::request_id::current() {
if let Ok(value) = axum::http::HeaderValue::from_str(id.as_ref()) {
response.headers_mut().insert(
axum::http::header::HeaderName::from_static("x-request-id"),
value,
);
}
}
response
}
}