Skip to main content

http_query/
server.rs

1//! Framework-agnostic helpers for serving the QUERY method.
2//!
3//! These helpers work with [`http::HeaderMap`] and a method string, so they
4//! plug into any server stack (axum, hyper, actix, …). See
5//! `examples/axum_server.rs` for a complete axum integration.
6
7use crate::accept_query::{format_accept_query, matches_media_range};
8use crate::consts::{HEADER_CONTENT_TYPE, METHOD_QUERY};
9use http::HeaderMap;
10
11/// The reason an incoming request is not a valid QUERY, with the HTTP status
12/// code a server should respond with (RFC 10008 §2).
13#[derive(Debug, Clone, Copy, PartialEq, Eq)]
14pub enum QueryRejection {
15    /// Not a QUERY request. Respond `405 Method Not Allowed` with `Allow`.
16    NotQuery,
17    /// The `Content-Type` field is missing. Respond `400 Bad Request`.
18    MissingContentType,
19    /// The `Content-Type` is not in `Accept-Query`. Respond `415`.
20    UnsupportedMediaType,
21}
22
23impl QueryRejection {
24    /// The HTTP status code to respond with for this rejection.
25    pub fn status(self) -> u16 {
26        match self {
27            QueryRejection::NotQuery => 405,
28            QueryRejection::MissingContentType => 400,
29            QueryRejection::UnsupportedMediaType => 415,
30        }
31    }
32}
33
34/// Validates an incoming request as a QUERY per RFC 10008.
35///
36/// `accept_query` is the list of supported query media ranges; when empty, any
37/// media type is accepted (only presence of `Content-Type` is required).
38///
39/// Returns `Ok(())` when the request should be handled as a QUERY, or a
40/// [`QueryRejection`] describing how to reject it.
41pub fn check_query_request(
42    method: &str,
43    headers: &HeaderMap,
44    accept_query: &[&str],
45) -> Result<(), QueryRejection> {
46    if !method.eq_ignore_ascii_case(METHOD_QUERY) {
47        return Err(QueryRejection::NotQuery);
48    }
49
50    let content_type = headers
51        .get(HEADER_CONTENT_TYPE)
52        .and_then(|value| value.to_str().ok())
53        .filter(|value| !value.is_empty());
54
55    let content_type = match content_type {
56        Some(value) => value,
57        None => return Err(QueryRejection::MissingContentType),
58    };
59
60    if !accept_query.is_empty() {
61        let media_type = content_type.split(';').next().unwrap_or("").trim();
62        let accepted = accept_query
63            .iter()
64            .any(|range| matches_media_range(range, media_type));
65        if !accepted {
66            return Err(QueryRejection::UnsupportedMediaType);
67        }
68    }
69
70    Ok(())
71}
72
73/// Builds an `Accept-Query` header value advertising the supported query media
74/// types as a Structured Fields List (RFC 10008 §3).
75pub fn accept_query_header(media_types: &[&str]) -> String {
76    format_accept_query(media_types.iter().copied())
77}
78
79#[cfg(test)]
80mod tests {
81    use super::*;
82    use http::HeaderValue;
83
84    fn ct(value: &str) -> HeaderMap {
85        let mut h = HeaderMap::new();
86        if !value.is_empty() {
87            h.insert(HEADER_CONTENT_TYPE, HeaderValue::from_str(value).unwrap());
88        }
89        h
90    }
91
92    #[test]
93    fn rejects_non_query() {
94        let err = check_query_request("GET", &ct("application/json"), &[]).unwrap_err();
95        assert_eq!(err, QueryRejection::NotQuery);
96        assert_eq!(err.status(), 405);
97    }
98
99    #[test]
100    fn rejects_missing_content_type() {
101        let err = check_query_request("QUERY", &ct(""), &[]).unwrap_err();
102        assert_eq!(err, QueryRejection::MissingContentType);
103        assert_eq!(err.status(), 400);
104    }
105
106    #[test]
107    fn rejects_unsupported_media_type() {
108        let err =
109            check_query_request("QUERY", &ct("text/plain"), &["application/json"]).unwrap_err();
110        assert_eq!(err, QueryRejection::UnsupportedMediaType);
111        assert_eq!(err.status(), 415);
112    }
113
114    #[test]
115    fn accepts_supported_query() {
116        assert!(check_query_request(
117            "query",
118            &ct("application/json; charset=utf-8"),
119            &["application/json"]
120        )
121        .is_ok());
122    }
123
124    #[test]
125    fn builds_accept_query_header() {
126        assert_eq!(
127            accept_query_header(&["application/json", "3d/model"]),
128            r#"application/json, "3d/model""#
129        );
130    }
131}