Skip to main content

snip_sync/
http.rs

1//! The snip-sync health and metrics HTTP control surface.
2//!
3//! Wire parity with the pre-migration Axum/Tower-HTTP server (proven by
4//! exercising parent commit `c1c77a8` over real sockets):
5//!
6//! - router fallback/method responses are empty with no application
7//!   content-type (`404`/`405`, `content-length: 0`); the metrics-disabled
8//!   `404` keeps its `"Not found"` text application payload;
9//! - known GET routes answer preflight/unsupported methods with
10//!   `Allow: GET, HEAD`; unknown-path preflight short-circuits to `200` with
11//!   no `Allow`;
12//! - preflight responses carry CORS metadata but never the ordinary security
13//!   headers; ordinary responses always carry the three security headers;
14//! - every non-allow-all response carries `Vary: origin` (the historical
15//!   Tower-HTTP `CorsLayer` recomputes its `Vary` from the configured rules at
16//!   layer-build time: the empty configuration varies on `Origin`, while the
17//!   configured and allow-all configurations use fixed origins and omit it).
18//!   The retained native policy keeps conditional `Access-Control-Allow-Origin`
19//!   emission, so `Vary: origin` is emitted for configured origins as well to
20//!   keep the cache key coherent.
21
22use crate::AppState;
23use eggserve_primitives::{HeaderBlock, RequestHead, Response, ResponseBody, StatusCode};
24use std::time::Duration;
25
26/// Window for the `/metrics` authentication failure budget. One minute matches
27/// the gRPC limiter's window so operators have one mental model.
28const METRICS_AUTH_WINDOW: Duration = Duration::from_secs(60);
29
30/// `Retry-After` value advertised with `429`. The budget window is one minute,
31/// so this is the maximum time a client must wait for a fresh window.
32const METRICS_AUTH_RETRY_AFTER_SECS: &str = "60";
33
34/// Historical CORS cache-key token: the only `Vary` value the pre-migration
35/// server ever emitted. Allow-all responses omit `Vary` entirely.
36const VARY_ORIGIN: &str = "origin";
37
38#[derive(Clone)]
39pub struct CorsPolicy {
40    pub allow_all: bool,
41    pub allowed_origins: Vec<String>,
42}
43
44/// Create the concrete two-endpoint service. EggServe rejects request bodies
45/// before this handler runs and normalizes HEAD framing at the wire boundary.
46pub fn service(state: AppState, cors: CorsPolicy) -> impl eggserve_server::Service {
47    eggserve_server::service_fn_head(move |head: RequestHead| {
48        let state = state.clone();
49        let cors = cors.clone();
50        async move { handle_request(state, cors, head).await }
51    })
52}
53
54async fn handle_request(
55    state: AppState,
56    cors: CorsPolicy,
57    head: RequestHead,
58) -> Result<Response, eggserve_server::ServiceError> {
59    let method = head.method().as_str();
60    let path = head.target().path();
61    let request_headers = head.headers();
62
63    if method == "OPTIONS" {
64        let mut response_headers = Vec::new();
65        if !cors.allow_all {
66            response_headers.push(("vary", VARY_ORIGIN.to_owned()));
67        }
68        if cors.allow_all {
69            response_headers.push(("access-control-allow-origin", "*".to_owned()));
70            response_headers.push(("access-control-allow-methods", "*".to_owned()));
71            response_headers.push(("access-control-allow-headers", "*".to_owned()));
72        } else if !cors.allowed_origins.is_empty() {
73            response_headers.push(("access-control-allow-methods", "GET".to_owned()));
74            response_headers.push((
75                "access-control-allow-headers",
76                "content-type,authorization".to_owned(),
77            ));
78            if let Some(origin) = get_header(request_headers, "origin")
79                && origin_allowed(&cors, &origin)
80            {
81                response_headers.push(("access-control-allow-origin", origin));
82            }
83        }
84        if path == "/health" || path == "/metrics" {
85            response_headers.push(("allow", "GET, HEAD".to_owned()));
86        }
87        return Ok(make_response(
88            200,
89            ResponseBody::Empty,
90            None,
91            response_headers,
92        ));
93    }
94
95    let (status, payload) = match (method, path) {
96        ("GET" | "HEAD", "/health") => {
97            let healthy = state.db.ping().await.is_ok();
98            let status = if healthy { 200 } else { 503 };
99            let health = if healthy { "healthy" } else { "unhealthy" };
100            let body = serde_json::to_vec(&serde_json::json!({
101                "version": env!("CARGO_PKG_VERSION"),
102                "status": health,
103            }))
104            .map_err(|error| eggserve_server::ServiceError::internal(error.to_string()))?;
105            (status, Some((body, "application/json")))
106        }
107        ("GET" | "HEAD", "/metrics") => {
108            let (status, body, content_type) = metrics_response(&state, request_headers).await;
109            (status, Some((body, content_type)))
110        }
111        (_, "/health" | "/metrics") => (405, None),
112        _ => (404, None),
113    };
114
115    let mut response_headers = vec![
116        ("x-content-type-options", "nosniff".to_owned()),
117        ("x-frame-options", "DENY".to_owned()),
118        ("cache-control", "no-store".to_owned()),
119    ];
120    if !cors.allow_all {
121        response_headers.push(("vary", VARY_ORIGIN.to_owned()));
122    }
123    if status == 405 {
124        response_headers.push(("allow", "GET, HEAD".to_owned()));
125    }
126    // RFC 9110 §11.1: a 401 response MUST carry a `WWW-Authenticate`
127    // challenge. Without it a client cannot learn the scheme, and browsers
128    // will not prompt for credentials — so a password-protected `/metrics`
129    // was unreachable through standard HTTP auth flows.
130    if status == 401 {
131        response_headers.push((
132            "www-authenticate",
133            "Basic realm=\"metrics\", charset=\"UTF-8\"".to_owned(),
134        ));
135    }
136    // RFC 9110 §15.5.30: a 429 MAY advertise how long to wait. Deliberately no
137    // `WWW-Authenticate` here — challenging a throttled caller would invite
138    // exactly the retry the budget exists to bound.
139    if status == 429 {
140        response_headers.push(("retry-after", METRICS_AUTH_RETRY_AFTER_SECS.to_owned()));
141    }
142    if let Some(origin) = get_header(request_headers, "origin")
143        && origin_allowed(&cors, &origin)
144    {
145        response_headers.push((
146            "access-control-allow-origin",
147            if cors.allow_all {
148                "*".to_owned()
149            } else {
150                origin
151            },
152        ));
153    }
154    let (body, content_type) = match payload {
155        Some((body, content_type)) => (ResponseBody::Bytes(body), Some(content_type)),
156        None => (ResponseBody::Empty, None),
157    };
158    Ok(make_response(status, body, content_type, response_headers))
159}
160
161async fn metrics_response(
162    state: &AppState,
163    request_headers: &HeaderBlock,
164) -> (u16, Vec<u8>, &'static str) {
165    let (username, password) = match (
166        &state.config.metrics_username,
167        &state.config.metrics_password,
168    ) {
169        (Some(username), Some(password)) => (username.as_str(), password.as_str()),
170        _ => return (404, b"Not found".to_vec(), "text/plain; charset=utf-8"),
171    };
172
173    let valid = get_header(request_headers, "authorization")
174        .and_then(|value| {
175            // RFC 9110 §11.1: the auth-scheme token is case-insensitive.
176            let (scheme, rest) = value.split_once(' ')?;
177            scheme
178                .eq_ignore_ascii_case("basic")
179                .then(|| rest.trim_start().to_owned())
180        })
181        .and_then(|encoded| {
182            base64::Engine::decode(&base64::engine::general_purpose::STANDARD, encoded).ok()
183        })
184        .is_some_and(|decoded| {
185            use subtle::ConstantTimeEq;
186            let expected = format!("{username}:{password}");
187            let mut padded = decoded.clone();
188            padded.resize(expected.len(), 0);
189            bool::from(padded.ct_eq(expected.as_bytes())) && decoded.len() == expected.len()
190        });
191    if !valid {
192        // Count the failure so a password-protected `/metrics` is covered by
193        // `snip_sync_auth_failures_total`, exactly like the gRPC path
194        // (`SnippetSyncService::record_auth_failure`). Without it the metric
195        // could never observe HTTP brute force.
196        state.metrics.auth_failures.inc();
197
198        // Bound password guessing. The budget is global and failure-only:
199        // correct credentials never reach this branch, so an attacker cannot
200        // lock the operator out of their own scrape by burning it. The leaf's
201        // `RequestHead` carries no peer address, so a per-caller budget is not
202        // available here; a global failure budget is the bounded design that
203        // the current handler shape supports.
204        let within_budget = state
205            .rate_limiter
206            .allow(
207                "metrics-auth",
208                state.config.metrics_auth_failures_per_minute as usize,
209                METRICS_AUTH_WINDOW,
210            )
211            .await;
212        if !within_budget {
213            state.metrics.rate_limit_hits.inc();
214            return (
215                429,
216                b"Too many failed authentication attempts".to_vec(),
217                "text/plain; charset=utf-8",
218            );
219        }
220        return (
221            401,
222            b"Authentication required".to_vec(),
223            "text/plain; charset=utf-8",
224        );
225    }
226
227    use prometheus::Encoder;
228    let mut buffer = Vec::new();
229    match prometheus::TextEncoder::new().encode(&state.metrics.registry.gather(), &mut buffer) {
230        Ok(()) => (200, buffer, "text/plain; charset=utf-8"),
231        Err(error) => (
232            500,
233            format!("Error gathering metrics: {error}").into_bytes(),
234            "text/plain; charset=utf-8",
235        ),
236    }
237}
238
239fn get_header(headers: &HeaderBlock, name: &str) -> Option<String> {
240    headers
241        .get_first(name)
242        .and_then(|value| value.to_str().ok())
243        .map(str::to_owned)
244}
245
246fn origin_allowed(cors: &CorsPolicy, origin: &str) -> bool {
247    cors.allow_all || cors.allowed_origins.iter().any(|allowed| allowed == origin)
248}
249
250fn make_response(
251    status: u16,
252    body: ResponseBody,
253    content_type: Option<&str>,
254    headers: Vec<(&str, String)>,
255) -> Response {
256    let mut builder = Response::builder().status(StatusCode::new(status).expect("valid status"));
257    if let Some(content_type) = content_type {
258        builder = builder
259            .header("content-type", content_type)
260            .expect("static content type is valid");
261    }
262    for (name, value) in headers {
263        builder = builder
264            .header(name, value)
265            .expect("HTTP response header is valid");
266    }
267    builder.body(body).expect("response body is valid")
268}