1use crate::AppState;
23use eggserve_primitives::{HeaderBlock, RequestHead, Response, ResponseBody, StatusCode};
24use std::time::Duration;
25
26const METRICS_AUTH_WINDOW: Duration = Duration::from_secs(60);
29
30const METRICS_AUTH_RETRY_AFTER_SECS: &str = "60";
33
34const VARY_ORIGIN: &str = "origin";
37
38#[derive(Clone)]
39pub struct CorsPolicy {
40 pub allow_all: bool,
41 pub allowed_origins: Vec<String>,
42}
43
44pub 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 if status == 401 {
131 response_headers.push((
132 "www-authenticate",
133 "Basic realm=\"metrics\", charset=\"UTF-8\"".to_owned(),
134 ));
135 }
136 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 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 state.metrics.auth_failures.inc();
197
198 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}