http-query 0.2.0

A client and server SDK for the HTTP QUERY method (RFC 10008).
Documentation
//! Framework-agnostic helpers for serving the QUERY method.
//!
//! These helpers work with [`http::HeaderMap`] and a method string, so they
//! plug into any server stack (axum, hyper, actix, …). See
//! `examples/axum_server.rs` for a complete axum integration.

use crate::accept_query::{format_accept_query, matches_media_range};
use crate::consts::{HEADER_CONTENT_TYPE, METHOD_QUERY};
use http::HeaderMap;

/// The reason an incoming request is not a valid QUERY, with the HTTP status
/// code a server should respond with (RFC 10008 §2).
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum QueryRejection {
    /// Not a QUERY request. Respond `405 Method Not Allowed` with `Allow`.
    NotQuery,
    /// The `Content-Type` field is missing. Respond `400 Bad Request`.
    MissingContentType,
    /// The `Content-Type` is not in `Accept-Query`. Respond `415`.
    UnsupportedMediaType,
}

impl QueryRejection {
    /// The HTTP status code to respond with for this rejection.
    pub fn status(self) -> u16 {
        match self {
            QueryRejection::NotQuery => 405,
            QueryRejection::MissingContentType => 400,
            QueryRejection::UnsupportedMediaType => 415,
        }
    }
}

/// Validates an incoming request as a QUERY per RFC 10008.
///
/// `accept_query` is the list of supported query media ranges; when empty, any
/// media type is accepted (only presence of `Content-Type` is required).
///
/// Returns `Ok(())` when the request should be handled as a QUERY, or a
/// [`QueryRejection`] describing how to reject it.
pub fn check_query_request(
    method: &str,
    headers: &HeaderMap,
    accept_query: &[&str],
) -> Result<(), QueryRejection> {
    if !method.eq_ignore_ascii_case(METHOD_QUERY) {
        return Err(QueryRejection::NotQuery);
    }

    let content_type = headers
        .get(HEADER_CONTENT_TYPE)
        .and_then(|value| value.to_str().ok())
        .filter(|value| !value.is_empty());

    let content_type = match content_type {
        Some(value) => value,
        None => return Err(QueryRejection::MissingContentType),
    };

    if !accept_query.is_empty() {
        let media_type = content_type.split(';').next().unwrap_or("").trim();
        let accepted = accept_query
            .iter()
            .any(|range| matches_media_range(range, media_type));
        if !accepted {
            return Err(QueryRejection::UnsupportedMediaType);
        }
    }

    Ok(())
}

/// Builds an `Accept-Query` header value advertising the supported query media
/// types as a Structured Fields List (RFC 10008 §3).
pub fn accept_query_header(media_types: &[&str]) -> String {
    format_accept_query(media_types.iter().copied())
}

#[cfg(test)]
mod tests {
    use super::*;
    use http::HeaderValue;

    fn ct(value: &str) -> HeaderMap {
        let mut h = HeaderMap::new();
        if !value.is_empty() {
            h.insert(HEADER_CONTENT_TYPE, HeaderValue::from_str(value).unwrap());
        }
        h
    }

    #[test]
    fn rejects_non_query() {
        let err = check_query_request("GET", &ct("application/json"), &[]).unwrap_err();
        assert_eq!(err, QueryRejection::NotQuery);
        assert_eq!(err.status(), 405);
    }

    #[test]
    fn rejects_missing_content_type() {
        let err = check_query_request("QUERY", &ct(""), &[]).unwrap_err();
        assert_eq!(err, QueryRejection::MissingContentType);
        assert_eq!(err.status(), 400);
    }

    #[test]
    fn rejects_unsupported_media_type() {
        let err =
            check_query_request("QUERY", &ct("text/plain"), &["application/json"]).unwrap_err();
        assert_eq!(err, QueryRejection::UnsupportedMediaType);
        assert_eq!(err.status(), 415);
    }

    #[test]
    fn accepts_supported_query() {
        assert!(check_query_request(
            "query",
            &ct("application/json; charset=utf-8"),
            &["application/json"]
        )
        .is_ok());
    }

    #[test]
    fn builds_accept_query_header() {
        assert_eq!(
            accept_query_header(&["application/json", "3d/model"]),
            r#"application/json, "3d/model""#
        );
    }
}