use axum::{
Json,
http::{HeaderMap, HeaderValue, StatusCode, header},
response::{IntoResponse, Response},
};
use crate::model::Problem;
use crate::schema::PayloadViolation;
use super::auth::{AuthError, Scope};
use super::store::StorageError;
#[derive(Debug, thiserror::Error)]
pub enum ApiError {
#[error("{0}")]
BadRequest(String),
#[error("{0}")]
UnsupportedMediaType(String),
#[error("{0}")]
PayloadTooLarge(String),
#[error("payload validation failed")]
InvalidPayload(Vec<PayloadViolation>),
#[error(transparent)]
Unauthorized(#[from] AuthError),
#[error("the {0} scope is required")]
MissingScope(Scope),
#[error("{0}")]
Forbidden(String),
#[error("{object_type} {id} not found")]
NotFound {
object_type: crate::model::ObjectType,
id: crate::model::ObjectId,
},
#[error("no such endpoint")]
NoSuchRoute,
#[error(transparent)]
Storage(#[from] StorageError),
#[error("{0}")]
NotImplemented(String),
#[error("{0}")]
Internal(String),
#[error("{0}")]
Unavailable(String),
}
impl ApiError {
pub fn status(&self) -> StatusCode {
match self {
ApiError::BadRequest(_) | ApiError::InvalidPayload(_) => StatusCode::BAD_REQUEST,
ApiError::UnsupportedMediaType(_) => StatusCode::UNSUPPORTED_MEDIA_TYPE,
ApiError::PayloadTooLarge(_) => StatusCode::PAYLOAD_TOO_LARGE,
ApiError::Unauthorized(_) => StatusCode::UNAUTHORIZED,
ApiError::MissingScope(_) | ApiError::Forbidden(_) => StatusCode::FORBIDDEN,
ApiError::NotFound { .. } | ApiError::NoSuchRoute => StatusCode::NOT_FOUND,
ApiError::NotImplemented(_) => StatusCode::NOT_IMPLEMENTED,
ApiError::Internal(_) => StatusCode::INTERNAL_SERVER_ERROR,
ApiError::Unavailable(_) => StatusCode::SERVICE_UNAVAILABLE,
ApiError::Storage(e) => match e {
StorageError::NotFound { .. } => StatusCode::NOT_FOUND,
StorageError::Conflict { .. } => StatusCode::CONFLICT,
StorageError::DanglingReference { .. } => StatusCode::BAD_REQUEST,
StorageError::Unavailable(_) => StatusCode::INTERNAL_SERVER_ERROR,
},
}
}
fn slug(&self) -> &'static str {
match self {
ApiError::BadRequest(_) => "bad-request",
ApiError::UnsupportedMediaType(_) => "unsupported-media-type",
ApiError::PayloadTooLarge(_) => "payload-too-large",
ApiError::InvalidPayload(_) => "invalid-payload",
ApiError::Unauthorized(_) => "unauthorized",
ApiError::MissingScope(_) => "missing-scope",
ApiError::Forbidden(_) => "forbidden",
ApiError::NotFound { .. } => "not-found",
ApiError::NoSuchRoute => "no-such-route",
ApiError::NotImplemented(_) => "not-implemented",
ApiError::Internal(_) => "internal-server-error",
ApiError::Unavailable(_) => "unavailable",
ApiError::Storage(e) => match e {
StorageError::NotFound { .. } => "not-found",
StorageError::Conflict { .. } => "conflict",
StorageError::DanglingReference { .. } => "dangling-reference",
StorageError::Unavailable(_) => "storage-unavailable",
},
}
}
pub fn problem(&self) -> Problem {
let status = self.status();
let title = status.canonical_reason().unwrap_or("Error");
let detail = match self {
ApiError::Internal(_) => "an unexpected internal error occurred".to_string(),
ApiError::InvalidPayload(violations) => violations
.iter()
.map(|v| v.to_string())
.collect::<Vec<_>>()
.join("; "),
other => other.to_string(),
};
Problem::new(status.as_u16(), self.slug(), title).with_detail(detail)
}
}
impl From<serde_json::Error> for ApiError {
fn from(e: serde_json::Error) -> Self {
ApiError::BadRequest(format!("malformed JSON: {e}"))
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let status = self.status();
if status.is_server_error() {
tracing::error!(error = %self, "request failed");
} else {
tracing::debug!(error = %self, status = %status, "request rejected");
}
let mut headers = HeaderMap::new();
if status == StatusCode::UNAUTHORIZED {
headers.insert(
header::WWW_AUTHENTICATE,
HeaderValue::from_static("Bearer realm=\"openadr\""),
);
}
headers.insert(
header::CONTENT_TYPE,
HeaderValue::from_static("application/problem+json"),
);
(status, headers, Json(self.problem())).into_response()
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::model::{ObjectId, ObjectType};
#[test]
fn storage_errors_map_to_the_documented_statuses() {
let not_found = ApiError::Storage(StorageError::NotFound {
object_type: ObjectType::Event,
id: ObjectId::new("e1").unwrap(),
});
assert_eq!(not_found.status(), StatusCode::NOT_FOUND);
let conflict = ApiError::Storage(StorageError::Conflict {
object_type: ObjectType::Program,
field: "programName",
value: "tou".into(),
});
assert_eq!(conflict.status(), StatusCode::CONFLICT);
let dangling = ApiError::Storage(StorageError::DanglingReference {
field: "programID",
value: "nope".into(),
});
assert_eq!(dangling.status(), StatusCode::BAD_REQUEST);
}
#[test]
fn internal_errors_do_not_leak_their_detail() {
let e = ApiError::Internal("connection string: postgres://user:hunter2@db".into());
let problem = e.problem();
assert_eq!(problem.status, Some(500));
assert!(!problem.detail.unwrap().contains("hunter2"));
}
#[test]
fn problems_carry_a_dereferenceable_type() {
let p = ApiError::MissingScope(Scope::WriteEvents).problem();
assert_eq!(
p.r#type.as_deref(),
Some("https://openadr.dev/problems/missing-scope")
);
assert!(p.detail.unwrap().contains("write_events"));
}
}