Repository Public
1// =============================================================================2// SP BOUCHER | SOFTWARE & RESEARCH3// ARTIFICIAL INTELLIGENCE • FINANCE • ENGINEERING4// =============================================================================5//6// PROJECT METADATA7// -----------------------------------------------------------------------------8// Project : SPSearch9// File : crates/protocol/src/http.rs10// Module : crates11// Repository : https://git.spboucher.ai/spweb12// Project Website : https://search.spboucher.ai13// Created : 2026-11-2714// Last Modified : 2026-12-0115//16// =============================================================================17// AUTHOR & PROFESSIONAL AFFILIATION18// =============================================================================19//20// Author : Simon-Pierre Boucher21// Position : Professor of Finance22// Institution : Université du Québec en Outaouais (UQO)23// Department : Département des sciences administratives24// Organization : SP Boucher25//26// Website : https://spboucher.ai27// Git : https://git.spboucher.ai28//29// =============================================================================30// OFFICIAL CONTACT DIRECTORY31// =============================================================================32//33// General : info@spboucher.ai34// Professional : contact@spboucher.ai35// Direct : simon@spboucher.ai36// Research : research@spboucher.ai37// Development : dev@spboucher.ai38// Support : support@spboucher.ai39// Security/Admin : admin@spboucher.ai40// Notifications : notifications@spboucher.ai41//42// Preferred Contact: contact@spboucher.ai43//44// =============================================================================45// COPYRIGHT & INTELLECTUAL PROPERTY46// =============================================================================47//48// Copyright (c) 202649// Simon-Pierre Boucher50//51// All rights reserved where applicable.52//53// This file is governed by the applicable project license,54// copyright notices, institutional agreements and relevant law.55//56// Unless expressly authorized by the applicable license or57// rights holder, copying, redistribution, sublicensing,58// publication and commercial exploitation are not permitted.59//60// Existing third-party rights and notices remain unaffected.61//62// =============================================================================63// CONFIDENTIALITY & SECURITY64// =============================================================================65//66// Classification : Public67// Distribution : Public repository; use is governed by the project license68// Security Contact : admin@spboucher.ai69//70// Access to this source does not independently grant permission71// to redistribute or disclose confidential materials.72//73// Do not embed credentials, private keys, access tokens,74// certificates or confidential personal information.75//76// =============================================================================77// LICENSE & MAINTENANCE78// =============================================================================79//80// License : None specified (no license file in this repository)81// Maintainer : Simon-Pierre Boucher82// Technical Contact: dev@spboucher.ai83//84// =============================================================================85// END OF SP BOUCHER SOURCE HEADER86// =============================================================================8788//! Outils HTTP communs aux services : authentification interne, IP cliente derrière le mandataire,89//! limitation de débit bornée, fichiers statiques avec CSP stricte, client interne authentifié.9091use axum::body::Body;92use axum::http::{header, HeaderMap, HeaderValue, Response, StatusCode};93use serde::de::DeserializeOwned;94use serde::Serialize;95use std::collections::HashMap;96use std::net::{IpAddr, SocketAddr};97use std::path::Path;98use std::sync::Mutex;99use std::time::Duration;100101pub const CSP: &str = "default-src 'self'; script-src 'self'; style-src 'self'; img-src 'self' data:; connect-src 'self'; font-src 'self'; object-src 'none'; base-uri 'none'; form-action 'self'; frame-ancestors 'none'";102103pub fn bearer(headers: &HeaderMap) -> Option<&str> {104 headers.get(header::AUTHORIZATION)?.to_str().ok()?.strip_prefix("Bearer ")105}106107/// Authentifie un appel interne : jeton partagé (comparaison en temps constant) et version de protocole.108pub fn internal_ok(headers: &HeaderMap, token: &str) -> bool {109 let tok_ok = bearer(headers).map(|t| spweb_common::ct_eq(t.as_bytes(), token.as_bytes())).unwrap_or(false);110 let ver_ok = headers.get(crate::HDR_PROTOCOL).and_then(|v| v.to_str().ok()).map(|v| v == crate::PROTOCOL_VERSION.to_string()).unwrap_or(false);111 tok_ok && ver_ok112}113114/// Adresse du client réel : on ne croit X-Forwarded-For que si la connexion vient d'un mandataire de confiance,115/// et on prend l'adresse la plus à droite qui n'est pas elle-même un mandataire de confiance.116pub fn client_ip(headers: &HeaderMap, peer: SocketAddr, trusted: &[String]) -> IpAddr {117 let is_trusted = |ip: &IpAddr| trusted.iter().any(|t| t.parse::<IpAddr>().map(|x| &x == ip).unwrap_or(false));118 let peer_ip = match peer.ip() {119 IpAddr::V6(v6) => v6.to_ipv4_mapped().map(IpAddr::V4).unwrap_or(IpAddr::V6(v6)),120 v4 => v4,121 };122 if !is_trusted(&peer_ip) {123 return peer_ip;124 }125 let mut chain: Vec<IpAddr> = Vec::new();126 for v in headers.get_all("x-forwarded-for") {127 if let Ok(s) = v.to_str() {128 for part in s.split(',') {129 if let Ok(ip) = part.trim().parse::<IpAddr>() {130 chain.push(ip);131 }132 }133 }134 }135 chain.into_iter().rev().find(|ip| !is_trusted(ip)).unwrap_or(peer_ip)136}137138/// Compteur à fenêtre fixe par clé, à mémoire bornée.139pub struct RateLimiter {140 window: Duration,141 max_keys: usize,142 state: Mutex<HashMap<String, (std::time::Instant, u32)>>,143}144145impl RateLimiter {146 pub fn new(window: Duration, max_keys: usize) -> Self {147 RateLimiter { window, max_keys, state: Mutex::new(HashMap::new()) }148 }149 /// État du quota d'une clé sans le consommer : (plafond, restant, secondes avant remise à zéro).150 pub fn peek(&self, key: &str, limit: u32) -> (u32, u32, u64) {151 let now = std::time::Instant::now();152 let m = self.state.lock().unwrap();153 match m.get(key) {154 Some(e) if now.duration_since(e.0) < self.window => (limit, limit.saturating_sub(e.1), self.window.saturating_sub(now.duration_since(e.0)).as_secs().max(1)),155 _ => (limit, limit, self.window.as_secs()),156 }157 }158 /// `Ok(())` si permis, sinon `Err(secondes avant réessai)`.159 pub fn check(&self, key: &str, limit: u32) -> Result<(), u64> {160 let now = std::time::Instant::now();161 let mut m = self.state.lock().unwrap();162 if m.len() >= self.max_keys {163 let w = self.window;164 m.retain(|_, v| now.duration_since(v.0) < w);165 if m.len() >= self.max_keys {166 m.clear(); // dernier recours : mémoire bornée avant tout167 }168 }169 let e = m.entry(key.to_string()).or_insert((now, 0));170 if now.duration_since(e.0) >= self.window {171 *e = (now, 0);172 }173 if e.1 >= limit {174 return Err((self.window.saturating_sub(now.duration_since(e.0))).as_secs().max(1));175 }176 e.1 += 1;177 Ok(())178 }179}180181pub fn security_headers(h: &mut HeaderMap) {182 h.insert("content-security-policy", HeaderValue::from_static(CSP));183 h.insert("x-content-type-options", HeaderValue::from_static("nosniff"));184 h.insert("x-frame-options", HeaderValue::from_static("DENY"));185 h.insert("referrer-policy", HeaderValue::from_static("no-referrer"));186 h.insert("permissions-policy", HeaderValue::from_static("geolocation=(), microphone=(self), camera=(), interest-cohort=()"));187 h.insert("strict-transport-security", HeaderValue::from_static("max-age=31536000"));188 h.insert("cross-origin-opener-policy", HeaderValue::from_static("same-origin"));189}190191pub fn json_response<T: Serialize>(status: StatusCode, value: &T) -> Response<Body> {192 let body = serde_json::to_vec(value).unwrap_or_else(|_| b"{}".to_vec());193 let mut r = Response::new(Body::from(body));194 *r.status_mut() = status;195 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static("application/json; charset=utf-8"));196 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static("no-store"));197 security_headers(r.headers_mut());198 r199}200201pub fn error_response(status: StatusCode, code: &str, message: &str, request_id: &str, retry_after: Option<u64>) -> Response<Body> {202 let mut r = json_response(status, &serde_json::json!({"error": {"code": code, "message": message}, "request_id": request_id}));203 if let Some(s) = retry_after {204 if let Ok(v) = HeaderValue::from_str(&s.to_string()) {205 r.headers_mut().insert(header::RETRY_AFTER, v);206 }207 }208 r209}210211fn mime(path: &str) -> &'static str {212 match path.rsplit('.').next().unwrap_or("") {213 "html" => "text/html; charset=utf-8",214 "js" | "mjs" => "text/javascript; charset=utf-8",215 "css" => "text/css; charset=utf-8",216 "svg" => "image/svg+xml",217 "json" | "map" => "application/json; charset=utf-8",218 "txt" => "text/plain; charset=utf-8",219 "png" => "image/png",220 "ico" => "image/x-icon",221 "webmanifest" => "application/manifest+json",222 "xml" => "application/xml; charset=utf-8",223 "woff2" => "font/woff2",224 _ => "application/octet-stream",225 }226}227228/// Sert un fichier de `dir`. Chemin inconnu sans extension -> `index.html` (application monopage).229/// Refuse toute traversée (`..`, octets hors liste blanche, fichiers cachés).230pub async fn serve_static(dir: &Path, uri_path: &str) -> Response<Body> {231 let clean = uri_path.trim_start_matches('/');232 let safe = clean.split('/').all(|seg| !seg.is_empty() && !seg.starts_with('.') && seg.chars().all(|c| c.is_ascii_alphanumeric() || matches!(c, '.' | '-' | '_')));233 let mut status = StatusCode::OK;234 let (rel, is_index) = if clean.is_empty() {235 ("index.html".to_string(), true)236 } else if safe && dir.join(clean).is_file() {237 (clean.to_string(), clean == "index.html")238 } else if safe && !clean.rsplit('/').next().unwrap_or("").contains('.') {239 ("index.html".to_string(), true)240 } else {241 status = StatusCode::NOT_FOUND;242 ("index.html".to_string(), true)243 };244 if status == StatusCode::NOT_FOUND && (clean.contains('.') || !safe) {245 let mut r = Response::new(Body::from("introuvable"));246 *r.status_mut() = StatusCode::NOT_FOUND;247 security_headers(r.headers_mut());248 return r;249 }250 match tokio::fs::read(dir.join(&rel)).await {251 Ok(bytes) => {252 let mut r = Response::new(Body::from(bytes));253 *r.status_mut() = status;254 r.headers_mut().insert(header::CONTENT_TYPE, HeaderValue::from_static(mime(&rel)));255 // Les fichiers à empreinte (assets/) sont immuables ; le reste est revalidé.256 let cc = if !is_index && rel.starts_with("assets/") { "public, max-age=31536000, immutable" } else { "no-cache" };257 r.headers_mut().insert(header::CACHE_CONTROL, HeaderValue::from_static(cc));258 security_headers(r.headers_mut());259 r260 }261 Err(_) => {262 let mut r = Response::new(Body::from("interface non installée"));263 *r.status_mut() = StatusCode::SERVICE_UNAVAILABLE;264 security_headers(r.headers_mut());265 r266 }267 }268}269270/// Client des appels internes (réseau privé) : jeton, version de protocole, délai strict, sans mandataire.271#[derive(Clone)]272pub struct InternalClient {273 http: reqwest::Client,274 token: String,275}276277impl InternalClient {278 pub fn new(token: &str, timeout: Duration) -> anyhow::Result<Self> {279 Ok(InternalClient { http: reqwest::Client::builder().no_proxy().timeout(timeout).connect_timeout(Duration::from_secs(3)).build()?, token: token.to_string() })280 }281 fn req(&self, m: reqwest::Method, url: &str) -> reqwest::RequestBuilder {282 self.http.request(m, url).bearer_auth(&self.token).header(crate::HDR_PROTOCOL, crate::PROTOCOL_VERSION.to_string())283 }284 pub async fn post<T: Serialize + ?Sized, R: DeserializeOwned>(&self, url: &str, body: &T) -> anyhow::Result<R> {285 let resp = self.req(reqwest::Method::POST, url).json(body).send().await?;286 let st = resp.status();287 anyhow::ensure!(st.is_success(), "{} -> {}", url.split('?').next().unwrap_or(""), st.as_u16());288 Ok(resp.json().await?)289 }290 pub async fn get<R: DeserializeOwned>(&self, url: &str) -> anyhow::Result<R> {291 let resp = self.req(reqwest::Method::GET, url).send().await?;292 let st = resp.status();293 anyhow::ensure!(st.is_success(), "{} -> {}", url.split('?').next().unwrap_or(""), st.as_u16());294 Ok(resp.json().await?)295 }296 pub async fn delete<R: DeserializeOwned>(&self, url: &str) -> anyhow::Result<R> {297 let resp = self.req(reqwest::Method::DELETE, url).send().await?;298 let st = resp.status();299 anyhow::ensure!(st.is_success(), "{} -> {}", url.split('?').next().unwrap_or(""), st.as_u16());300 Ok(resp.json().await?)301 }302 /// Variante qui rend aussi le code HTTP (pour relayer 4xx tels quels).303 pub async fn post_raw<T: Serialize + ?Sized>(&self, url: &str, body: &T) -> anyhow::Result<(u16, serde_json::Value)> {304 let resp = self.req(reqwest::Method::POST, url).json(body).send().await?;305 let st = resp.status().as_u16();306 Ok((st, resp.json().await.unwrap_or(serde_json::Value::Null)))307 }308 pub async fn get_raw(&self, url: &str) -> anyhow::Result<(u16, serde_json::Value)> {309 let resp = self.req(reqwest::Method::GET, url).send().await?;310 let st = resp.status().as_u16();311 Ok((st, resp.json().await.unwrap_or(serde_json::Value::Null)))312 }313}314315/// Attend SIGTERM ou SIGINT (arrêt propre).316pub async fn shutdown_signal() {317 #[cfg(unix)]318 {319 let mut term = tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()).expect("signal");320 tokio::select! {321 _ = term.recv() => {},322 _ = tokio::signal::ctrl_c() => {},323 }324 }325 #[cfg(not(unix))]326 {327 let _ = tokio::signal::ctrl_c().await;328 }329}330331#[cfg(test)]332mod tests {333 use super::*;334 #[test]335 fn xff_only_from_trusted_proxy() {336 let trusted = vec!["10.67.0.1".to_string(), "127.0.0.1".to_string()];337 let mut h = HeaderMap::new();338 h.insert("x-forwarded-for", HeaderValue::from_static("6.6.6.6, 203.0.113.9, 10.67.0.1"));339 // pair non fiable : l'en-tête est ignoré340 assert_eq!(client_ip(&h, "8.8.8.8:1".parse().unwrap(), &trusted).to_string(), "8.8.8.8");341 // pair fiable : adresse la plus à droite non fiable (un client ne peut pas forger sa propre entrée)342 assert_eq!(client_ip(&h, "10.67.0.1:1".parse().unwrap(), &trusted).to_string(), "203.0.113.9");343 assert_eq!(client_ip(&HeaderMap::new(), "127.0.0.1:1".parse().unwrap(), &trusted).to_string(), "127.0.0.1");344 }345 #[test]346 fn rate_limit_window_and_bound() {347 let r = RateLimiter::new(Duration::from_secs(60), 3);348 assert!(r.check("a", 2).is_ok() && r.check("a", 2).is_ok());349 assert!(r.check("a", 2).is_err());350 for k in ["b", "c", "d", "e", "f"] {351 let _ = r.check(k, 2);352 }353 assert!(r.state.lock().unwrap().len() <= 3);354 }355 #[test]356 fn internal_auth() {357 let mut h = HeaderMap::new();358 h.insert(header::AUTHORIZATION, HeaderValue::from_static("Bearer secret"));359 assert!(!internal_ok(&h, "secret"), "version de protocole requise");360 h.insert(crate::HDR_PROTOCOL, HeaderValue::from_static("1"));361 assert!(internal_ok(&h, "secret"));362 assert!(!internal_ok(&h, "autre"));363 }364 #[tokio::test]365 async fn static_traversal_refused() {366 let d = std::env::temp_dir().join(format!("spweb-static-{}", std::process::id()));367 std::fs::create_dir_all(d.join("assets")).unwrap();368 std::fs::write(d.join("index.html"), "<html>app</html>").unwrap();369 std::fs::write(d.join("assets/a.js"), "1").unwrap();370 std::fs::write(d.join(".secret"), "x").unwrap();371 assert_eq!(serve_static(&d, "/").await.status(), 200);372 assert_eq!(serve_static(&d, "/assets/a.js").await.status(), 200);373 assert_eq!(serve_static(&d, "/search").await.status(), 200); // repli monopage374 for bad in ["/../etc/passwd", "/.secret", "/assets/../../x.txt", "/%2e%2e/x.js", "/nope.js", "/a//b"] {375 let r = serve_static(&d, bad).await;376 assert_eq!(r.status(), 404, "{}", bad);377 }378 let r = serve_static(&d, "/").await;379 assert!(r.headers().get("content-security-policy").unwrap().to_str().unwrap().contains("frame-ancestors 'none'"));380 let _ = std::fs::remove_dir_all(d);381 }382}383