use axum::response::{IntoResponse, Response};
use http::StatusCode;
use parse_rust_core::{ErrorCode, ParseError};
#[derive(Debug, Clone)]
pub struct HttpError {
pub status: StatusCode,
pub message: String,
}
impl HttpError {
pub fn master_key_required(sanitized: bool) -> Self {
Self {
status: StatusCode::FORBIDDEN,
message: if sanitized {
"Permission denied".to_string()
} else {
"unauthorized: master key is required".to_string()
},
}
}
pub fn unauthorized() -> Self {
Self {
status: StatusCode::FORBIDDEN,
message: "unauthorized".to_string(),
}
}
}
impl IntoResponse for HttpError {
fn into_response(self) -> Response {
let body = format!("{{\"error\":{}}}", json_string(&self.message));
(
self.status,
[(
http::header::CONTENT_TYPE,
"application/json; charset=utf-8",
)],
body,
)
.into_response()
}
}
pub struct ParseErrorResponse(pub ParseError);
impl IntoResponse for ParseErrorResponse {
fn into_response(self) -> Response {
let status = match self.0.code {
ErrorCode::InternalServerError => StatusCode::INTERNAL_SERVER_ERROR,
ErrorCode::ObjectNotFound => StatusCode::NOT_FOUND,
_ => StatusCode::BAD_REQUEST,
};
let body = format!(
"{{\"code\":{},\"error\":{}}}",
self.0.code.as_i32(),
json_string(&self.0.message)
);
(
status,
[(
http::header::CONTENT_TYPE,
"application/json; charset=utf-8",
)],
body,
)
.into_response()
}
}
fn json_string(s: &str) -> String {
let mut out = String::with_capacity(s.len() + 2);
out.push('"');
for c in s.chars() {
match c {
'"' => out.push_str("\\\""),
'\\' => out.push_str("\\\\"),
'\n' => out.push_str("\\n"),
c if (c as u32) < 0x20 => out.push_str(&format!("\\u{:04x}", c as u32)),
c => out.push(c),
}
}
out.push('"');
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn the_two_envelopes_are_distinguishable() {
let http = HttpError::master_key_required(true);
assert_eq!(http.message, "Permission denied");
assert_eq!(http.status, StatusCode::FORBIDDEN);
assert_eq!(HttpError::unauthorized().message, "unauthorized");
}
#[test]
fn sanitization_toggles_only_the_master_key_message() {
assert_eq!(
HttpError::master_key_required(false).message,
"unauthorized: master key is required"
);
assert_eq!(HttpError::unauthorized().message, "unauthorized");
}
#[test]
fn escaping_is_applied_to_messages() {
assert_eq!(json_string(r#"a"b"#), r#""a\"b""#);
assert_eq!(json_string("a\nb"), r#""a\nb""#);
}
}