docsrs_cli/http/content_type.rs
1//! Content-Type sniffing and fail-closed require helpers.
2
3use crate::error::{AppError, AppResult, ContentKind, ErrorDetail};
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 [`crate::error::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::of(ErrorDetail::UnexpectedContentType {
50 expected: ContentKind::Json,
51 got: c.to_string(),
52 })),
53 }
54}
55
56/// Fail closed when a Content-Type is present but not HTML/XHTML.
57///
58/// # Errors
59///
60/// Returns [`crate::error::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::of(ErrorDetail::UnexpectedContentType {
66 expected: ContentKind::Html,
67 got: c.to_string(),
68 })),
69 }
70}
71
72/// Floor for the direct `rustls` dependency pin (ADR 0007; RUSTSEC-2024-0399 era).
73///
74/// A policy gate compares this against the pin in `Cargo.toml`. It used to be a
75/// bare literal sitting beside an equal literal in the manifest — equal by
76/// coincidence, with nothing keeping them equal — and a unit test asserted the
77/// constant against itself, which reads as coverage and verifies nothing.
78pub const RUSTLS_VERSION_FLOOR: &str = "0.23.18";
79
80/// Trust anchors the HTTP client validates against.
81///
82/// This is a constant rather than a word inside the posture string because the
83/// word was wrong for a month. reqwest 0.13 removed every webpki-roots feature,
84/// so upgrading from 0.12 moved the anchors to the operating system store while
85/// this string kept printing `webpki-roots` — the binary misreported its own
86/// trust anchors in the very line an operator reads to audit them
87/// (GAP-TLS-ROOTS-001). A policy gate now derives the truth from
88/// `src/http/tls.rs`, which is the module that builds the root store, and it can
89/// only reach this fact if the fact is a named constant.
90pub const TLS_TRUST_ANCHORS: &str = "webpki-roots";
91
92/// Crypto provider installed by the binary through `rustls-no-provider`.
93///
94/// Not selected by a reqwest feature: `Cargo.toml` uses `rustls-no-provider`
95/// precisely so no provider is chosen for us, and `src/main.rs` installs this one
96/// as the process default.
97///
98/// `ring` compiles C through `cc-rs`, which contradicts the self-contained,
99/// Rust-native product rule. Both pure-Rust replacements were evaluated in
100/// 2026-08 and both were rejected on measurement; see [`TLS_PROVIDER_POSTURE`]
101/// and ADR 0007. The non-conformance is tracked as GAP-TOOLCHAIN-001.
102pub const TLS_CRYPTO_PROVIDER: &str = "ring";
103
104/// Why the provider is not pure Rust, in one machine-readable token.
105///
106/// Surfaced through `doctor` rather than left to the source, because "this CLI
107/// builds C" is a fact an operator auditing a supposedly Rust-native binary is
108/// entitled to read from the binary itself. The two rejected candidates failed
109/// for opposite reasons: `graviola` needs x86_64 `adx` (Broadwell, 2015+) and
110/// aborts at the first handshake without it, while `rustls-rustcrypto` pins
111/// `rustls-webpki ^0.102`, which carries four certificate-validation advisories
112/// plus an unpatched `rsa` timing sidechannel.
113pub const TLS_PROVIDER_POSTURE: &str =
114 "c-build-dep(ring); pure-rust-blocked(graviola:needs-adx, rustcrypto:webpki-advisories)";
115
116/// Machine-readable summary of the compiled HTTP client posture (doctor / docs).
117///
118/// Single source for agent audits — README/SECURITY cite this string via `doctor`.
119pub fn client_posture_detail() -> String {
120 format!(
121 "rustls≥{RUSTLS_VERSION_FLOOR} provider={TLS_CRYPTO_PROVIDER} posture={TLS_PROVIDER_POSTURE} TLS≥1.2 {TLS_TRUST_ANCHORS} 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"
122 )
123}