1#[allow(
33 unused_imports,
34 clippy::wildcard_imports,
35 reason = "Standard workspace module prelude"
36)]
37use crate::utilities::*;
38
39use ::http::{HeaderMap, HeaderValue, StatusCode, header};
40use axum::middleware::Next;
41use axum::response::Response;
42use ctb_formats_html::markdown::html2md;
43
44const MAX_HTML_BODY_BYTES: usize = 10 * 1024 * 1024;
45
46fn parse_qvalue(params: &str) -> Option<f32> {
47 for param in params.split(';') {
48 let param = param.trim();
49 if let Some(val_str) = param.strip_prefix("q=") {
50 return val_str.trim().parse::<f32>().ok();
51 }
52 }
53 Some(1.0)
54}
55
56pub fn prefers_markdown(headers: &HeaderMap) -> bool {
59 let mut markdown_q: Option<f32> = None;
60 let mut html_q: Option<f32> = None;
61
62 for hval in headers.get_all(header::ACCEPT) {
63 let Ok(s) = hval.to_str() else {
64 continue;
65 };
66 for item in s.split(',') {
67 let item = item.trim();
68 if item.is_empty() {
69 continue;
70 }
71 let (mime, params) = match item.split_once(';') {
72 Some((m, p)) => (m.trim().to_ascii_lowercase(), p),
73 None => (item.trim().to_ascii_lowercase(), ""),
74 };
75 let q = parse_qvalue(params).unwrap_or(1.0);
77
78 if mime == "text/markdown" || mime == "text/x-markdown" {
79 markdown_q = Some(match markdown_q {
80 Some(curr) => curr.max(q),
81 None => q,
82 });
83 } else if mime == "text/html" {
84 html_q = Some(match html_q {
85 Some(curr) => curr.max(q),
86 None => q,
87 });
88 }
89 }
90 }
91
92 if let Some(mq) = markdown_q {
93 if mq > 0.0 {
94 return match html_q {
95 Some(hq) => mq >= hq,
96 None => true,
97 };
98 }
99 }
100
101 false
102}
103
104fn is_html_response(headers: &HeaderMap) -> bool {
105 if let Some(ct) = headers.get(header::CONTENT_TYPE) {
106 if let Ok(ct_str) = ct.to_str() {
107 return ct_str
108 .trim_start()
109 .to_ascii_lowercase()
110 .starts_with("text/html");
111 }
112 }
113 false
114}
115
116fn build_markdown_response(
117 status: StatusCode,
118 original_headers: &HeaderMap,
119 body: Vec<u8>,
120) -> Response {
121 let mut response = Response::builder()
123 .status(status)
124 .body(axum::body::Body::from(body))
125 .unwrap_or_else(|_| Response::default());
126
127 let headers = response.headers_mut();
128 for (key, value) in original_headers {
129 if key != header::CONTENT_TYPE && key != header::CONTENT_LENGTH {
130 headers.append(key.clone(), value.clone());
131 }
132 }
133 headers.insert(
134 header::CONTENT_TYPE,
135 HeaderValue::from_static("text/markdown; charset=utf-8"),
136 );
137
138 let mut vary_has_accept = false;
139 for vary_val in headers.get_all(header::VARY) {
140 if let Ok(v) = vary_val.to_str() {
141 if v.split(',')
142 .any(|p| p.trim().eq_ignore_ascii_case("accept"))
143 {
144 vary_has_accept = true;
145 break;
146 }
147 }
148 }
149 if !vary_has_accept {
150 headers.append(header::VARY, HeaderValue::from_static("Accept"));
151 }
152
153 response
154}
155
156pub async fn markdown_negotiation_middleware(
158 req: axum::http::Request<axum::body::Body>,
159 next: Next,
160) -> Response {
161 let markdown_requested = prefers_markdown(req.headers());
162 let resp = next.run(req).await;
163
164 if !markdown_requested || !is_html_response(resp.headers()) {
165 return resp;
166 }
167
168 if let Some(original_md) =
169 resp.extensions().get::<crate::OriginalMarkdown>()
170 {
171 return build_markdown_response(
172 resp.status(),
173 resp.headers(),
174 original_md.0.clone(),
175 );
176 }
177
178 let (parts, body) = resp.into_parts();
179 let body_bytes = match axum::body::to_bytes(body, MAX_HTML_BODY_BYTES).await
180 {
181 Ok(bytes) => bytes,
182 Err(e) => {
183 warn_fmt!(
184 "Failed reading HTML response body for Markdown negotiation: {e}"
185 );
186 return Response::builder()
188 .status(parts.status)
189 .body(axum::body::Body::empty())
190 .unwrap_or_default();
191 }
192 };
193
194 let md_bytes = match html2md(body_bytes.to_vec()) {
195 Ok(md) => md,
196 Err(e) => {
197 warn_fmt!(
198 "Failed converting HTML to Markdown in negotiation middleware: {e}"
199 );
200 body_bytes.to_vec()
201 }
202 };
203
204 build_markdown_response(parts.status, &parts.headers, md_bytes)
205}
206
207#[cfg(test)]
208#[allow(
209 clippy::panic,
210 clippy::expect_used,
211 clippy::unwrap_used,
212 clippy::unwrap_in_result,
213 clippy::panic_in_result_fn,
214 clippy::indexing_slicing,
215 clippy::arithmetic_side_effects,
216 reason = "Standard repository test boilerplate"
217)]
218mod tests {
219 use super::*;
220 use axum::body::Body;
221 use axum::http::Request;
222 use axum::response::Html;
223 use axum::response::IntoResponse;
224 use axum::routing::get;
225 use axum::{Router, middleware};
226 use tower::ServiceExt;
227
228 #[crate::ctb_test]
229 fn test_prefers_markdown_cases() {
230 let mut h = HeaderMap::new();
231 assert!(!prefers_markdown(&h));
232
233 h.insert(
234 header::ACCEPT,
235 HeaderValue::from_static("text/html,application/xhtml+xml"),
236 );
237 assert!(!prefers_markdown(&h));
238
239 h.insert(header::ACCEPT, HeaderValue::from_static("text/markdown"));
240 assert!(prefers_markdown(&h));
241
242 h.insert(header::ACCEPT, HeaderValue::from_static("text/x-markdown"));
243 assert!(prefers_markdown(&h));
244
245 h.insert(
246 header::ACCEPT,
247 HeaderValue::from_static("text/markdown;q=0.9, text/html;q=0.8"),
248 );
249 assert!(prefers_markdown(&h));
250
251 h.insert(
252 header::ACCEPT,
253 HeaderValue::from_static("text/html;q=1.0, text/markdown;q=0.5"),
254 );
255 assert!(!prefers_markdown(&h));
256
257 h.insert(
258 header::ACCEPT,
259 HeaderValue::from_static("text/markdown;q=0.0"),
260 );
261 assert!(!prefers_markdown(&h));
262 }
263
264 async fn html_endpoint() -> Html<&'static str> {
265 Html(
266 "<h1>Title</h1><p>Paragraph with <a href=\"https://example.com\">link</a>.</p>",
267 )
268 }
269
270 async fn md_origin_endpoint() -> Response {
271 let mut resp =
272 Html("<h1>Privacy Policy</h1><p>Rendered HTML</p>").into_response();
273 resp.extensions_mut().insert(crate::OriginalMarkdown(
274 b"# Privacy Policy\n\nOriginal MD".to_vec(),
275 ));
276 resp
277 }
278
279 async fn json_endpoint() -> Response {
280 (
281 StatusCode::OK,
282 [(header::CONTENT_TYPE, "application/json")],
283 r#"{"status":"ok"}"#,
284 )
285 .into_response()
286 }
287
288 fn test_app() -> Router {
289 Router::new()
290 .route("/page", get(html_endpoint))
291 .route("/privacy", get(md_origin_endpoint))
292 .route("/api", get(json_endpoint))
293 .layer(middleware::from_fn(markdown_negotiation_middleware))
294 }
295
296 #[crate::ctb_test("tokio")]
297 async fn test_html_request_returns_html() {
298 let app = test_app();
299 let req = Request::builder()
300 .uri("/page")
301 .header(header::ACCEPT, "text/html")
302 .body(Body::empty())
303 .unwrap();
304
305 let resp = app.oneshot(req).await.unwrap();
306 assert_eq!(resp.status(), StatusCode::OK);
307 assert_eq!(
308 resp.headers().get(header::CONTENT_TYPE).unwrap(),
309 "text/html; charset=utf-8"
310 );
311 let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
312 let text = String::from_utf8(body.to_vec()).unwrap();
313 assert!(text.contains("<h1>Title</h1>"));
314 }
315
316 #[crate::ctb_test("tokio")]
317 async fn test_markdown_request_converts_html() {
318 let app = test_app();
319 let req = Request::builder()
320 .uri("/page")
321 .header(header::ACCEPT, "text/markdown")
322 .body(Body::empty())
323 .unwrap();
324
325 let resp = app.oneshot(req).await.unwrap();
326 assert_eq!(resp.status(), StatusCode::OK);
327 assert_eq!(
328 resp.headers().get(header::CONTENT_TYPE).unwrap(),
329 "text/markdown; charset=utf-8"
330 );
331 assert!(
332 resp.headers()
333 .get(header::VARY)
334 .unwrap()
335 .to_str()
336 .unwrap()
337 .contains("Accept")
338 );
339 let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
340 let text = String::from_utf8(body.to_vec()).unwrap();
341 assert!(text.contains("# Title"));
342 assert!(text.contains("[link](https://example.com)"));
343 }
344
345 #[crate::ctb_test("tokio")]
346 async fn test_markdown_request_reuses_original_markdown() {
347 let app = test_app();
348 let req = Request::builder()
349 .uri("/privacy")
350 .header(header::ACCEPT, "text/markdown")
351 .body(Body::empty())
352 .unwrap();
353
354 let resp = app.oneshot(req).await.unwrap();
355 assert_eq!(resp.status(), StatusCode::OK);
356 assert_eq!(
357 resp.headers().get(header::CONTENT_TYPE).unwrap(),
358 "text/markdown; charset=utf-8"
359 );
360 let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
361 let text = String::from_utf8(body.to_vec()).unwrap();
362 assert_eq!(text, "# Privacy Policy\n\nOriginal MD");
363 }
364
365 #[crate::ctb_test("tokio")]
366 async fn test_non_html_response_not_modified() {
367 let app = test_app();
368 let req = Request::builder()
369 .uri("/api")
370 .header(header::ACCEPT, "text/markdown")
371 .body(Body::empty())
372 .unwrap();
373
374 let resp = app.oneshot(req).await.unwrap();
375 assert_eq!(resp.status(), StatusCode::OK);
376 assert_eq!(
377 resp.headers().get(header::CONTENT_TYPE).unwrap(),
378 "application/json"
379 );
380 let body = axum::body::to_bytes(resp.into_body(), 1024).await.unwrap();
381 let text = String::from_utf8(body.to_vec()).unwrap();
382 assert_eq!(text, r#"{"status":"ok"}"#);
383 }
384}