1use std::future::Future;
7use std::sync::Arc;
8use std::sync::atomic::{AtomicBool, Ordering};
9use std::time::Instant;
10
11use http::{Method, StatusCode};
12
13pub use crate::authorization::VerifyAuthorized;
14pub use crate::basic_auth::BasicAuth;
15pub use crate::cors::Cors;
16
17use crate::context::Context;
18use crate::handler::{BoxFuture, Handler};
19use crate::response::Response;
20
21pub trait Middleware: Send + Sync + 'static {
22 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response>;
23}
24
25#[derive(Clone)]
27pub struct Next {
28 stack: Arc<[Arc<dyn Middleware>]>,
29 endpoint: Arc<dyn Handler>,
30 index: usize,
31}
32
33impl Next {
34 pub(crate) fn new(stack: Arc<[Arc<dyn Middleware>]>, endpoint: Arc<dyn Handler>) -> Self {
35 Self {
36 stack,
37 endpoint,
38 index: 0,
39 }
40 }
41
42 pub async fn run(mut self, ctx: Context) -> Response {
43 match self.stack.get(self.index).cloned() {
44 Some(middleware) => {
45 self.index += 1;
46 middleware.handle(ctx, self).await
47 }
48 None => self.endpoint.call(ctx).await,
49 }
50 }
51}
52
53pub fn from_fn<F, Fut>(f: F) -> FromFn<F>
63where
64 F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
65 Fut: Future<Output = Response> + Send + 'static,
66{
67 FromFn(f)
68}
69
70pub struct FromFn<F>(F);
71
72impl<F, Fut> Middleware for FromFn<F>
73where
74 F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
75 Fut: Future<Output = Response> + Send + 'static,
76{
77 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
78 Box::pin((self.0)(ctx, next))
79 }
80}
81
82pub struct Logger;
84
85impl Middleware for Logger {
86 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
87 Box::pin(async move {
88 let method = ctx.method().clone();
89 let path = ctx.path().to_owned();
90 let start = Instant::now();
91 let res = next.run(ctx).await;
92 let status = res.status().as_u16();
93 let elapsed = start.elapsed();
94 match LogFormat::current() {
95 LogFormat::Json => tracing::info!(
97 target: "glacier",
98 method = %method,
99 path,
100 status,
101 request_id = crate::request::id().unwrap_or_default(),
102 duration_ms = elapsed.as_micros() as f64 / 1000.0,
103 "request"
104 ),
105 LogFormat::Text => tracing::info!(
106 target: "glacier",
107 "{method} {path} -> {status} in {elapsed:.1?}"
108 ),
109 }
110 res
111 })
112 }
113}
114
115#[derive(Debug, Clone, Copy, PartialEq, Eq)]
117pub enum LogFormat {
118 Text,
120 Json,
122}
123
124static JSON_LOGS: AtomicBool = AtomicBool::new(false);
125
126impl LogFormat {
127 pub fn choose(env: crate::Env, requested: Option<&str>) -> Self {
130 match requested {
131 Some("json") => LogFormat::Json,
132 Some("text") => LogFormat::Text,
133 _ if env.is_production() => LogFormat::Json,
134 _ => LogFormat::Text,
135 }
136 }
137
138 pub(crate) fn set(format: Self) {
139 JSON_LOGS.store(format == LogFormat::Json, Ordering::Relaxed);
140 }
141
142 fn current() -> Self {
143 if JSON_LOGS.load(Ordering::Relaxed) {
144 LogFormat::Json
145 } else {
146 LogFormat::Text
147 }
148 }
149}
150
151#[derive(Clone, Default)]
161pub struct Pipeline {
162 pub(crate) stack: Vec<Arc<dyn Middleware>>,
163}
164
165impl Pipeline {
166 pub fn new() -> Self {
167 Self::default()
168 }
169
170 pub fn with(mut self, middleware: impl Middleware) -> Self {
171 self.stack.push(Arc::new(middleware));
172 self
173 }
174
175 pub fn browser() -> Self {
177 Self::new()
178 .with(ETag)
179 .with(SecureHeaders)
180 .with(crate::csrf::Csrf)
181 }
182
183 pub fn api() -> Self {
186 Self::new().with(ETag).with(JsonErrors)
187 }
188}
189
190pub struct ETag;
199
200impl Middleware for ETag {
201 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
202 let conditional = matches!(*ctx.method(), Method::GET | Method::HEAD);
203 let if_none_match = ctx.header(http::header::IF_NONE_MATCH).map(str::to_owned);
204 Box::pin(async move {
205 let mut res = next.run(ctx).await;
206 let cache_control = res
207 .header(http::header::CACHE_CONTROL)
208 .unwrap_or("")
209 .to_owned();
210 let tagged = matches!(res.status().as_u16(), 200 | 201)
213 && !res.headers().contains_key(http::header::ETAG)
214 && !res.headers().contains_key(http::header::LAST_MODIFIED)
215 && !cache_control.contains("no-cache")
216 && !cache_control.contains("no-store")
217 && !res.body().is_empty();
218 if !tagged {
219 if cache_control.is_empty() {
220 let validated = res.headers().contains_key(http::header::ETAG)
223 || res.headers().contains_key(http::header::LAST_MODIFIED);
224 let value = if validated {
225 "max-age=0, private, must-revalidate"
226 } else {
227 "no-cache"
228 };
229 res.headers_mut().insert(
230 http::header::CACHE_CONTROL,
231 http::HeaderValue::from_static(value),
232 );
233 }
234 return res;
235 }
236 let mut hasher = std::hash::DefaultHasher::new();
239 std::hash::Hasher::write(&mut hasher, res.body());
240 let tag = format!(
241 "W/\"{:x}-{:016x}\"",
242 res.body().len(),
243 std::hash::Hasher::finish(&hasher)
244 );
245 if cache_control.is_empty() {
246 res.headers_mut().insert(
247 http::header::CACHE_CONTROL,
248 http::HeaderValue::from_static("max-age=0, private, must-revalidate"),
249 );
250 }
251 let matches = conditional
252 && if_none_match.is_some_and(|sent| {
253 sent.split(',').any(|candidate| {
254 let candidate = candidate.trim();
255 candidate == "*"
256 || candidate.trim_start_matches("W/") == tag.trim_start_matches("W/")
257 })
258 });
259 if matches {
260 let mut not_modified = Response::new(StatusCode::NOT_MODIFIED);
261 for (name, value) in res.headers() {
262 if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
263 not_modified
264 .headers_mut()
265 .insert(name.clone(), value.clone());
266 }
267 }
268 res = not_modified;
269 }
270 if let Ok(value) = http::HeaderValue::from_str(&tag) {
271 res.headers_mut().insert(http::header::ETAG, value);
272 }
273 res
274 })
275 }
276}
277
278#[derive(Clone, Default)]
282pub struct DefaultHeaders(Vec<(http::HeaderName, http::HeaderValue)>);
283
284impl DefaultHeaders {
285 pub fn new() -> Self {
286 Self::default()
287 }
288
289 #[must_use]
293 pub fn header(mut self, name: &str, value: &str) -> Self {
294 self.0.push((
295 http::HeaderName::try_from(name).expect("invalid header name"),
296 http::HeaderValue::try_from(value).expect("invalid header value"),
297 ));
298 self
299 }
300}
301
302impl Middleware for DefaultHeaders {
303 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
304 let headers = self.0.clone();
305 Box::pin(async move {
306 let mut res = next.run(ctx).await;
307 for (name, value) in headers {
308 if !res.headers().contains_key(&name) {
309 res.headers_mut().insert(name, value);
310 }
311 }
312 res
313 })
314 }
315}
316
317pub struct JsonErrors;
321
322impl JsonErrors {
323 pub fn body(body: fn(http::StatusCode) -> serde_json::Value) -> JsonErrorsWith {
327 JsonErrorsWith(body)
328 }
329}
330
331fn default_error_body(status: http::StatusCode) -> serde_json::Value {
332 serde_json::json!({
333 "status": status.as_u16(),
334 "error": status.canonical_reason().unwrap_or("Error"),
335 })
336}
337
338impl Middleware for JsonErrors {
339 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
340 JsonErrorsWith(default_error_body).handle(ctx, next)
341 }
342}
343
344pub struct JsonErrorsWith(fn(http::StatusCode) -> serde_json::Value);
347
348impl Middleware for JsonErrorsWith {
349 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
350 let make_body = self.0;
351 Box::pin(async move {
352 let res = next.run(ctx).await;
353 let status = res.status();
354 let is_json = res
355 .header(http::header::CONTENT_TYPE)
356 .is_some_and(|ct| ct.starts_with("application/json"));
357 if !(status.is_client_error() || status.is_server_error()) || is_json || res.is_head() {
358 return res;
359 }
360 let body = make_body(status);
361 let mut json = Response::json(&body).with_status(status);
362 for (name, value) in res.headers() {
364 if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
365 json.headers_mut().insert(name.clone(), value.clone());
366 }
367 }
368 if let Some(report) = res.extensions().get::<crate::error::ErrorReport>() {
369 json.extensions_mut().insert(report.clone());
370 }
371 json
372 })
373 }
374}
375
376pub struct MethodOverride;
380
381impl Middleware for MethodOverride {
382 fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
383 if *ctx.method() == Method::POST {
384 let method =
385 ctx.form_field("_method")
386 .and_then(|m| match m.to_ascii_uppercase().as_str() {
387 "PATCH" => Some(Method::PATCH),
388 "PUT" => Some(Method::PUT),
389 "DELETE" => Some(Method::DELETE),
390 _ => None,
391 });
392 if let Some(method) = method {
393 ctx.set_method(method);
394 }
395 }
396 Box::pin(next.run(ctx))
397 }
398}
399
400pub struct IdPrefix;
406
407impl Middleware for IdPrefix {
408 fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
409 let path = ctx.path().to_owned();
410 let mut segments = path.splitn(3, '/');
411 let (Some(""), Some(id)) = (segments.next(), segments.next()) else {
412 return Box::pin(next.run(ctx));
413 };
414 if id.is_empty() || !id.bytes().all(|b| b.is_ascii_digit()) {
415 return Box::pin(next.run(ctx));
416 }
417 let id = id.to_owned();
418 let rest = format!("/{}", segments.next().unwrap_or(""));
419 ctx.set_path(&rest);
420 ctx.set_path_prefix(id.clone());
421 Box::pin(crate::router::with_path_prefix(
422 format!("/{id}"),
423 next.run(ctx),
424 ))
425 }
426}
427
428pub struct SecureHeaders;
431
432impl Middleware for SecureHeaders {
433 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
434 Box::pin(async move {
435 let mut res = next.run(ctx).await;
436 let headers = res.headers_mut();
437 for (name, value) in [
438 ("x-frame-options", "SAMEORIGIN"),
439 ("x-content-type-options", "nosniff"),
440 ("referrer-policy", "strict-origin-when-cross-origin"),
441 ("cross-origin-opener-policy", "same-origin"),
442 ] {
443 if !headers.contains_key(name) {
444 headers.insert(name, http::HeaderValue::from_static(value));
445 }
446 }
447 res
448 })
449 }
450}
451
452pub struct Throttle {
471 name: &'static str,
472 limit: u32,
473 period: std::time::Duration,
474 key: fn(&Context) -> Option<String>,
475}
476
477impl Throttle {
478 pub fn new(
482 name: &'static str,
483 limit: u32,
484 period: std::time::Duration,
485 key: fn(&Context) -> Option<String>,
486 ) -> Self {
487 assert!(
488 period.as_secs() > 0,
489 "a throttle's period is at least a second"
490 );
491 Self {
492 name,
493 limit,
494 period,
495 key,
496 }
497 }
498}
499
500impl Middleware for Throttle {
501 fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
502 let Some(key) = (self.key)(&ctx) else {
503 return Box::pin(next.run(ctx));
504 };
505 let (name, limit, period) = (self.name, self.limit, self.period);
506 Box::pin(async move {
507 let key = format!("throttle:{name}:{key}");
508 use crate::rate_limit::RateLimit;
509 match RateLimit::attempt(&key, limit, period).await {
510 Ok(true) => {}
511 Ok(false) => {
512 tracing::info!(throttle = name, "request throttled");
513 let wait = RateLimit::available_in(&key, period).num_seconds().max(1);
514 return Response::text("Retry later\n")
515 .with_status(http::StatusCode::TOO_MANY_REQUESTS)
516 .with_header(http::header::RETRY_AFTER, wait.to_string());
517 }
518 Err(error) => {
519 tracing::error!(throttle = name, %error, "throttle couldn't count; letting the request through");
520 }
521 }
522 next.run(ctx).await
523 })
524 }
525}
526
527#[cfg(test)]
528mod tests {
529 use super::*;
530 use crate::Env;
531
532 #[test]
533 fn json_logs_in_production_unless_asked_otherwise() {
534 assert_eq!(LogFormat::choose(Env::Production, None), LogFormat::Json);
535 assert_eq!(LogFormat::choose(Env::Development, None), LogFormat::Text);
536 assert_eq!(
537 LogFormat::choose(Env::Development, Some("json")),
538 LogFormat::Json
539 );
540 assert_eq!(
541 LogFormat::choose(Env::Production, Some("text")),
542 LogFormat::Text
543 );
544 assert_eq!(
545 LogFormat::choose(Env::Production, Some("xml")),
546 LogFormat::Json
547 );
548 }
549}