Skip to main content

docsrs_cli/http/
content_type.rs

1//! Content-Type sniffing and fail-closed require helpers.
2
3use crate::error::{AppError, AppResult, ErrorKind};
4
5use super::constants::{
6    POOL_IDLE_TIMEOUT_SECS, POOL_MAX_IDLE_PER_HOST, TCP_KEEPALIVE_IDLE_SECS,
7    TCP_KEEPALIVE_INTERVAL_SECS, TCP_KEEPALIVE_RETRIES,
8};
9
10/// ASCII case-insensitive substring check without heap allocation.
11///
12/// Used on Content-Type sniffing (hot path after every successful GET) so we
13/// never build a lowercased temporary `String` for a few-byte header.
14pub(super) fn ascii_contains_ignore_case(haystack: &str, needle: &str) -> bool {
15    if needle.is_empty() {
16        return true;
17    }
18    let n = needle.as_bytes();
19    haystack
20        .as_bytes()
21        .windows(n.len())
22        .any(|w| w.eq_ignore_ascii_case(n))
23}
24
25/// True when Content-Type looks like JSON.
26pub fn content_type_looks_json(ct: Option<&str>) -> bool {
27    ct.is_some_and(|c| ascii_contains_ignore_case(c, "json"))
28}
29
30/// True when Content-Type looks like HTML/XHTML.
31pub fn content_type_looks_html(ct: Option<&str>) -> bool {
32    ct.is_some_and(|c| {
33        ascii_contains_ignore_case(c, "html") || ascii_contains_ignore_case(c, "xhtml")
34    })
35}
36
37/// Fail closed when a Content-Type is present but not JSON.
38///
39/// Missing Content-Type is allowed (some caches/mocks omit it); body parse still
40/// validates structure. Present-but-wrong types are rejected to reduce MIME confusion.
41///
42/// # Errors
43///
44/// Returns [`ErrorKind::Parse`] when `ct` is present and does not look like JSON.
45pub fn require_content_type_json(ct: Option<&str>) -> AppResult<()> {
46    match ct {
47        None => Ok(()),
48        Some(c) if content_type_looks_json(Some(c)) => Ok(()),
49        Some(c) => Err(AppError::new(
50            ErrorKind::Parse,
51            format!("unexpected Content-Type for JSON response: {c}"),
52        )),
53    }
54}
55
56/// Fail closed when a Content-Type is present but not HTML/XHTML.
57///
58/// # Errors
59///
60/// Returns [`ErrorKind::Parse`] when `ct` is present and does not look like HTML.
61pub fn require_content_type_html(ct: Option<&str>) -> AppResult<()> {
62    match ct {
63        None => Ok(()),
64        Some(c) if content_type_looks_html(Some(c)) => Ok(()),
65        Some(c) => Err(AppError::new(
66            ErrorKind::Parse,
67            format!("unexpected Content-Type for HTML response: {c}"),
68        )),
69    }
70}
71
72/// Floor for the direct `rustls` dependency pin (ADR 0007; RUSTSEC-2024-0399 era).
73pub const RUSTLS_VERSION_FLOOR: &str = "0.23.18";
74
75/// Crypto provider installed by the binary and selected by reqwest `rustls-tls`.
76pub const TLS_CRYPTO_PROVIDER: &str = "ring";
77
78/// Machine-readable summary of the compiled HTTP client posture (doctor / docs).
79///
80/// Single source for agent audits — README/SECURITY cite this string via `doctor`.
81pub fn client_posture_detail() -> String {
82    format!(
83        "rustls≥{RUSTLS_VERSION_FLOOR} provider={TLS_CRYPTO_PROVIDER} TLS≥1.2 webpki-roots http2 system-proxy tcp_nodelay keepalive={TCP_KEEPALIVE_IDLE_SECS}s/{TCP_KEEPALIVE_INTERVAL_SECS}s/r{TCP_KEEPALIVE_RETRIES} pool_idle={POOL_MAX_IDLE_PER_HOST}@{POOL_IDLE_TIMEOUT_SECS}s host-allowlist no-danger-tls"
84    )
85}