1use crate::http::{HttpRequest, HttpResponse};
8use serde::Serialize;
9use serde::de::DeserializeOwned;
10
11pub const PROBLEM_JSON_CONTENT_TYPE: &str = "application/problem+json; charset=utf-8";
12pub const PROBLEM_BASE_URI: &str = "https://arks.build/problems/";
13
14#[derive(Debug, Clone, Serialize, PartialEq, Eq)]
16pub struct FieldError {
17 pub field: String,
18 pub code: String,
19 pub message: String,
20}
21
22#[derive(Debug, Clone, Serialize)]
24pub struct ProblemDetail {
25 #[serde(rename = "type")]
26 pub r#type: String,
27 pub title: String,
28 pub status: u16,
29 pub detail: String,
30 pub instance: String,
31 pub message: String,
33 pub documentation_url: String,
34 #[serde(skip_serializing_if = "Vec::is_empty")]
35 pub errors: Vec<FieldError>,
36 #[serde(skip_serializing_if = "Option::is_none")]
38 pub ok: Option<bool>,
39}
40
41pub fn problem_response(
43 status: u16,
44 slug: &str,
45 title: &str,
46 detail: impl Into<String>,
47 instance: &str,
48) -> HttpResponse {
49 problem_response_with_options(
50 status,
51 slug,
52 title,
53 detail,
54 instance,
55 Vec::new(),
56 None,
57 Vec::new(),
58 )
59}
60
61#[allow(clippy::too_many_arguments)]
64pub fn problem_response_with_options(
65 status: u16,
66 slug: &str,
67 title: &str,
68 detail: impl Into<String>,
69 instance: &str,
70 errors: Vec<FieldError>,
71 ok: Option<bool>,
72 extra: Vec<(String, String)>,
73) -> HttpResponse {
74 let detail = detail.into();
75 let type_uri = if slug.is_empty() {
76 "about:blank".to_string()
77 } else {
78 format!("{PROBLEM_BASE_URI}{slug}")
79 };
80 let payload = ProblemDetail {
81 r#type: type_uri.clone(),
82 title: title.to_string(),
83 status,
84 detail: detail.clone(),
85 instance: instance.to_string(),
86 message: detail,
87 documentation_url: type_uri,
88 errors,
89 ok,
90 };
91 let body = serde_json::to_vec(&payload)
92 .unwrap_or_else(|_| format!("{{\"status\":{status},\"title\":\"{title}\"}}").into_bytes());
93 let mut headers = vec![("X-Content-Type-Options".into(), "nosniff".into())];
94 headers.extend(extra);
95 HttpResponse {
96 status,
97 content_type: PROBLEM_JSON_CONTENT_TYPE.into(),
98 body,
99 www_authenticate: None,
100 extra_headers: headers,
101 }
102}
103
104pub fn bad_request(instance: &str, detail: impl Into<String>) -> HttpResponse {
105 problem_response(400, "bad-request", "Bad Request", detail, instance)
106}
107
108pub fn unauthorized(instance: &str, detail: impl Into<String>) -> HttpResponse {
109 problem_response(401, "unauthorized", "Unauthorized", detail, instance)
110}
111
112pub fn forbidden(instance: &str, detail: impl Into<String>) -> HttpResponse {
113 problem_response(403, "forbidden", "Forbidden", detail, instance)
114}
115
116pub fn not_found(instance: &str, detail: impl Into<String>) -> HttpResponse {
117 problem_response(404, "not-found", "Not Found", detail, instance)
118}
119
120pub fn method_not_allowed(instance: &str, allow: &str) -> HttpResponse {
121 problem_response_with_options(
122 405,
123 "method-not-allowed",
124 "Method Not Allowed",
125 format!("Method not allowed; allowed methods: {allow}"),
126 instance,
127 Vec::new(),
128 None,
129 vec![("Allow".into(), allow.to_string())],
130 )
131}
132
133pub fn conflict(instance: &str, detail: impl Into<String>) -> HttpResponse {
134 problem_response(409, "conflict", "Conflict", detail, instance)
135}
136
137pub fn unsupported_media_type(instance: &str, detail: impl Into<String>) -> HttpResponse {
138 problem_response(
139 415,
140 "unsupported-media-type",
141 "Unsupported Media Type",
142 detail,
143 instance,
144 )
145}
146
147pub fn unprocessable_entity(
148 instance: &str,
149 detail: impl Into<String>,
150 errors: Vec<FieldError>,
151) -> HttpResponse {
152 problem_response_with_options(
153 422,
154 "validation-failed",
155 "Unprocessable Entity",
156 detail,
157 instance,
158 errors,
159 None,
160 Vec::new(),
161 )
162}
163
164pub fn parse_json_body<T: DeserializeOwned>(req: &HttpRequest) -> Result<T, HttpResponse> {
168 if let Some(ct) = req.header("content-type") {
169 let mime = ct
170 .split(';')
171 .next()
172 .unwrap_or("")
173 .trim()
174 .to_ascii_lowercase();
175 if !mime.is_empty() && mime != "application/json" && !mime.ends_with("+json") {
176 return Err(unsupported_media_type(
177 &req.path,
178 format!("expected application/json request body, got {mime}"),
179 ));
180 }
181 }
182 if req.body.is_empty() {
183 return Err(bad_request(&req.path, "request body must be valid JSON"));
184 }
185 serde_json::from_slice(&req.body)
186 .map_err(|e| bad_request(&req.path, format!("invalid JSON request body: {e}")))
187}
188
189#[cfg(test)]
190mod tests {
191 use super::*;
192
193 #[test]
194 fn problem_response_emits_rfc9457_and_github_compat_fields() {
195 let resp = not_found("/api/v1/nope", "unknown endpoint");
196 assert_eq!(resp.status, 404);
197 assert_eq!(resp.content_type, PROBLEM_JSON_CONTENT_TYPE);
198 let v: serde_json::Value = serde_json::from_slice(&resp.body).unwrap();
199 assert_eq!(v["type"], "https://arks.build/problems/not-found");
200 assert_eq!(v["title"], "Not Found");
201 assert_eq!(v["status"], 404);
202 assert_eq!(v["detail"], "unknown endpoint");
203 assert_eq!(v["instance"], "/api/v1/nope");
204 assert_eq!(v["message"], "unknown endpoint");
205 assert_eq!(
206 v["documentation_url"],
207 "https://arks.build/problems/not-found"
208 );
209 assert!(v.get("ok").is_none());
210 }
211
212 #[test]
213 fn parse_json_body_rejects_malformed_json_with_400_and_non_json_with_415() {
214 let bad_ct = HttpRequest::new("POST", "/api/v1/issues", "", b"title=x".to_vec())
215 .with_header("Content-Type", "application/x-www-form-urlencoded");
216 let err_415 = parse_json_body::<serde_json::Value>(&bad_ct).unwrap_err();
217 assert_eq!(err_415.status, 415);
218 assert_eq!(err_415.content_type, PROBLEM_JSON_CONTENT_TYPE);
219
220 let malformed = HttpRequest::new("POST", "/api/v1/issues", "", b"{not json".to_vec())
221 .with_header("Content-Type", "application/json");
222 let err_400 = parse_json_body::<serde_json::Value>(&malformed).unwrap_err();
223 assert_eq!(err_400.status, 400);
224 assert_eq!(err_400.content_type, PROBLEM_JSON_CONTENT_TYPE);
225 }
226}