use crate::http::{HttpRequest, HttpResponse};
use serde::Serialize;
use serde::de::DeserializeOwned;
pub const PROBLEM_JSON_CONTENT_TYPE: &str = "application/problem+json; charset=utf-8";
pub const PROBLEM_BASE_URI: &str = "https://arks.build/problems/";
#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
pub struct FieldError {
pub field: String,
pub code: String,
pub message: String,
}
#[derive(Debug, Clone, Serialize)]
pub struct ProblemDetail {
#[serde(rename = "type")]
pub r#type: String,
pub title: String,
pub status: u16,
pub detail: String,
pub instance: String,
pub message: String,
pub documentation_url: String,
#[serde(skip_serializing_if = "Vec::is_empty")]
pub errors: Vec<FieldError>,
#[serde(skip_serializing_if = "Option::is_none")]
pub ok: Option<bool>,
}
pub fn problem_response(
status: u16,
slug: &str,
title: &str,
detail: impl Into<String>,
instance: &str,
) -> HttpResponse {
problem_response_with_options(
status,
slug,
title,
detail,
instance,
Vec::new(),
None,
Vec::new(),
)
}
#[allow(clippy::too_many_arguments)]
pub fn problem_response_with_options(
status: u16,
slug: &str,
title: &str,
detail: impl Into<String>,
instance: &str,
errors: Vec<FieldError>,
ok: Option<bool>,
extra: Vec<(String, String)>,
) -> HttpResponse {
let detail = detail.into();
let type_uri = if slug.is_empty() {
"about:blank".to_string()
} else {
format!("{PROBLEM_BASE_URI}{slug}")
};
let payload = ProblemDetail {
r#type: type_uri.clone(),
title: title.to_string(),
status,
detail: detail.clone(),
instance: instance.to_string(),
message: detail,
documentation_url: type_uri,
errors,
ok,
};
let body = serde_json::to_vec(&payload)
.unwrap_or_else(|_| format!("{{\"status\":{status},\"title\":\"{title}\"}}").into_bytes());
let mut headers = vec![("X-Content-Type-Options".into(), "nosniff".into())];
headers.extend(extra);
HttpResponse {
status,
content_type: PROBLEM_JSON_CONTENT_TYPE.into(),
body,
www_authenticate: None,
extra_headers: headers,
}
}
pub fn bad_request(instance: &str, detail: impl Into<String>) -> HttpResponse {
problem_response(400, "bad-request", "Bad Request", detail, instance)
}
pub fn unauthorized(instance: &str, detail: impl Into<String>) -> HttpResponse {
problem_response(401, "unauthorized", "Unauthorized", detail, instance)
}
pub fn forbidden(instance: &str, detail: impl Into<String>) -> HttpResponse {
problem_response(403, "forbidden", "Forbidden", detail, instance)
}
pub fn not_found(instance: &str, detail: impl Into<String>) -> HttpResponse {
problem_response(404, "not-found", "Not Found", detail, instance)
}
pub fn method_not_allowed(instance: &str, allow: &str) -> HttpResponse {
problem_response_with_options(
405,
"method-not-allowed",
"Method Not Allowed",
format!("Method not allowed; allowed methods: {allow}"),
instance,
Vec::new(),
None,
vec![("Allow".into(), allow.to_string())],
)
}
pub fn conflict(instance: &str, detail: impl Into<String>) -> HttpResponse {
problem_response(409, "conflict", "Conflict", detail, instance)
}
pub fn unsupported_media_type(instance: &str, detail: impl Into<String>) -> HttpResponse {
problem_response(
415,
"unsupported-media-type",
"Unsupported Media Type",
detail,
instance,
)
}
pub fn unprocessable_entity(
instance: &str,
detail: impl Into<String>,
errors: Vec<FieldError>,
) -> HttpResponse {
problem_response_with_options(
422,
"validation-failed",
"Unprocessable Entity",
detail,
instance,
errors,
None,
Vec::new(),
)
}
pub fn parse_json_body<T: DeserializeOwned>(req: &HttpRequest) -> Result<T, HttpResponse> {
if let Some(ct) = req.header("content-type") {
let mime = ct
.split(';')
.next()
.unwrap_or("")
.trim()
.to_ascii_lowercase();
if !mime.is_empty() && mime != "application/json" && !mime.ends_with("+json") {
return Err(unsupported_media_type(
&req.path,
format!("expected application/json request body, got {mime}"),
));
}
}
if req.body.is_empty() {
return Err(bad_request(&req.path, "request body must be valid JSON"));
}
serde_json::from_slice(&req.body)
.map_err(|e| bad_request(&req.path, format!("invalid JSON request body: {e}")))
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn problem_response_emits_rfc9457_and_github_compat_fields() {
let resp = not_found("/api/v1/nope", "unknown endpoint");
assert_eq!(resp.status, 404);
assert_eq!(resp.content_type, PROBLEM_JSON_CONTENT_TYPE);
let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
assert_eq!(v["type"], "https://arks.build/problems/not-found");
assert_eq!(v["title"], "Not Found");
assert_eq!(v["status"], 404);
assert_eq!(v["detail"], "unknown endpoint");
assert_eq!(v["instance"], "/api/v1/nope");
assert_eq!(v["message"], "unknown endpoint");
assert_eq!(
v["documentation_url"],
"https://arks.build/problems/not-found"
);
assert!(v.get("ok").is_none());
}
#[test]
fn parse_json_body_rejects_malformed_json_with_400_and_non_json_with_415() {
let bad_ct = HttpRequest::new("POST", "/api/v1/issues", "", b"title=x".to_vec())
.with_header("Content-Type", "application/x-www-form-urlencoded");
let err_415 = parse_json_body::<serde_json::Value>(&bad_ct).unwrap_err();
assert_eq!(err_415.status, 415);
assert_eq!(err_415.content_type, PROBLEM_JSON_CONTENT_TYPE);
let malformed = HttpRequest::new("POST", "/api/v1/issues", "", b"{not json".to_vec())
.with_header("Content-Type", "application/json");
let err_400 = parse_json_body::<serde_json::Value>(&malformed).unwrap_err();
assert_eq!(err_400.status, 400);
assert_eq!(err_400.content_type, PROBLEM_JSON_CONTENT_TYPE);
}
}