use std::future::Future;
use std::sync::Arc;
use std::sync::atomic::{AtomicBool, Ordering};
use std::time::Instant;
use http::{Method, StatusCode};
pub use crate::authorization::VerifyAuthorized;
pub use crate::cors::Cors;
use crate::context::Context;
use crate::handler::{BoxFuture, Handler};
use crate::response::Response;
pub trait Middleware: Send + Sync + 'static {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response>;
}
#[derive(Clone)]
pub struct Next {
stack: Arc<[Arc<dyn Middleware>]>,
endpoint: Arc<dyn Handler>,
index: usize,
}
impl Next {
pub(crate) fn new(stack: Arc<[Arc<dyn Middleware>]>, endpoint: Arc<dyn Handler>) -> Self {
Self {
stack,
endpoint,
index: 0,
}
}
pub async fn run(mut self, ctx: Context) -> Response {
match self.stack.get(self.index).cloned() {
Some(middleware) => {
self.index += 1;
middleware.handle(ctx, self).await
}
None => self.endpoint.call(ctx).await,
}
}
}
pub fn from_fn<F, Fut>(f: F) -> FromFn<F>
where
F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Response> + Send + 'static,
{
FromFn(f)
}
pub struct FromFn<F>(F);
impl<F, Fut> Middleware for FromFn<F>
where
F: Fn(Context, Next) -> Fut + Send + Sync + 'static,
Fut: Future<Output = Response> + Send + 'static,
{
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin((self.0)(ctx, next))
}
}
pub struct Logger;
impl Middleware for Logger {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin(async move {
let method = ctx.method().clone();
let path = ctx.path().to_owned();
let start = Instant::now();
let res = next.run(ctx).await;
let status = res.status().as_u16();
let elapsed = start.elapsed();
match LogFormat::current() {
LogFormat::Json => tracing::info!(
target: "glacier",
method = %method,
path,
status,
duration_ms = elapsed.as_micros() as f64 / 1000.0,
"request"
),
LogFormat::Text => tracing::info!(
target: "glacier",
"{method} {path} -> {status} in {elapsed:.1?}"
),
}
res
})
}
}
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum LogFormat {
Text,
Json,
}
static JSON_LOGS: AtomicBool = AtomicBool::new(false);
impl LogFormat {
pub fn choose(env: crate::Env, requested: Option<&str>) -> Self {
match requested {
Some("json") => LogFormat::Json,
Some("text") => LogFormat::Text,
_ if env.is_production() => LogFormat::Json,
_ => LogFormat::Text,
}
}
pub(crate) fn set(format: Self) {
JSON_LOGS.store(format == LogFormat::Json, Ordering::Relaxed);
}
fn current() -> Self {
if JSON_LOGS.load(Ordering::Relaxed) {
LogFormat::Json
} else {
LogFormat::Text
}
}
}
#[derive(Clone, Default)]
pub struct Pipeline {
pub(crate) stack: Vec<Arc<dyn Middleware>>,
}
impl Pipeline {
pub fn new() -> Self {
Self::default()
}
pub fn with(mut self, middleware: impl Middleware) -> Self {
self.stack.push(Arc::new(middleware));
self
}
pub fn browser() -> Self {
Self::new()
.with(ETag)
.with(SecureHeaders)
.with(crate::csrf::Csrf)
}
pub fn api() -> Self {
Self::new().with(ETag).with(JsonErrors)
}
}
pub struct ETag;
impl Middleware for ETag {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let conditional = matches!(*ctx.method(), Method::GET | Method::HEAD);
let if_none_match = ctx.header(http::header::IF_NONE_MATCH).map(str::to_owned);
Box::pin(async move {
let mut res = next.run(ctx).await;
let cache_control = res
.header(http::header::CACHE_CONTROL)
.unwrap_or("")
.to_owned();
let tagged = matches!(res.status().as_u16(), 200 | 201)
&& !res.headers().contains_key(http::header::ETAG)
&& !res.headers().contains_key(http::header::LAST_MODIFIED)
&& !cache_control.contains("no-cache")
&& !cache_control.contains("no-store")
&& !res.body().is_empty();
if !tagged {
if cache_control.is_empty() {
let validated = res.headers().contains_key(http::header::ETAG)
|| res.headers().contains_key(http::header::LAST_MODIFIED);
let value = if validated {
"max-age=0, private, must-revalidate"
} else {
"no-cache"
};
res.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static(value),
);
}
return res;
}
let mut hasher = std::hash::DefaultHasher::new();
std::hash::Hasher::write(&mut hasher, res.body());
let tag = format!(
"W/\"{:x}-{:016x}\"",
res.body().len(),
std::hash::Hasher::finish(&hasher)
);
if cache_control.is_empty() {
res.headers_mut().insert(
http::header::CACHE_CONTROL,
http::HeaderValue::from_static("max-age=0, private, must-revalidate"),
);
}
let matches = conditional
&& if_none_match.is_some_and(|sent| {
sent.split(',').any(|candidate| {
let candidate = candidate.trim();
candidate == "*"
|| candidate.trim_start_matches("W/") == tag.trim_start_matches("W/")
})
});
if matches {
let mut not_modified = Response::new(StatusCode::NOT_MODIFIED);
for (name, value) in res.headers() {
if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
not_modified
.headers_mut()
.insert(name.clone(), value.clone());
}
}
res = not_modified;
}
if let Ok(value) = http::HeaderValue::from_str(&tag) {
res.headers_mut().insert(http::header::ETAG, value);
}
res
})
}
}
#[derive(Clone, Default)]
pub struct DefaultHeaders(Vec<(http::HeaderName, http::HeaderValue)>);
impl DefaultHeaders {
pub fn new() -> Self {
Self::default()
}
#[must_use]
pub fn header(mut self, name: &str, value: &str) -> Self {
self.0.push((
http::HeaderName::try_from(name).expect("invalid header name"),
http::HeaderValue::try_from(value).expect("invalid header value"),
));
self
}
}
impl Middleware for DefaultHeaders {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let headers = self.0.clone();
Box::pin(async move {
let mut res = next.run(ctx).await;
for (name, value) in headers {
if !res.headers().contains_key(&name) {
res.headers_mut().insert(name, value);
}
}
res
})
}
}
pub struct JsonErrors;
impl JsonErrors {
pub fn body(body: fn(http::StatusCode) -> serde_json::Value) -> JsonErrorsWith {
JsonErrorsWith(body)
}
}
fn default_error_body(status: http::StatusCode) -> serde_json::Value {
serde_json::json!({
"status": status.as_u16(),
"error": status.canonical_reason().unwrap_or("Error"),
})
}
impl Middleware for JsonErrors {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
JsonErrorsWith(default_error_body).handle(ctx, next)
}
}
pub struct JsonErrorsWith(fn(http::StatusCode) -> serde_json::Value);
impl Middleware for JsonErrorsWith {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
let make_body = self.0;
Box::pin(async move {
let res = next.run(ctx).await;
let status = res.status();
let is_json = res
.header(http::header::CONTENT_TYPE)
.is_some_and(|ct| ct.starts_with("application/json"));
if !(status.is_client_error() || status.is_server_error()) || is_json || res.is_head() {
return res;
}
let body = make_body(status);
let mut json = Response::json(&body).with_status(status);
for (name, value) in res.headers() {
if name != http::header::CONTENT_TYPE && name != http::header::CONTENT_LENGTH {
json.headers_mut().insert(name.clone(), value.clone());
}
}
if let Some(report) = res.extensions().get::<crate::error::ErrorReport>() {
json.extensions_mut().insert(report.clone());
}
json
})
}
}
pub struct MethodOverride;
impl Middleware for MethodOverride {
fn handle(&self, mut ctx: Context, next: Next) -> BoxFuture<Response> {
if *ctx.method() == Method::POST {
let method =
ctx.form_field("_method")
.and_then(|m| match m.to_ascii_uppercase().as_str() {
"PATCH" => Some(Method::PATCH),
"PUT" => Some(Method::PUT),
"DELETE" => Some(Method::DELETE),
_ => None,
});
if let Some(method) = method {
ctx.set_method(method);
}
}
Box::pin(next.run(ctx))
}
}
pub struct SecureHeaders;
impl Middleware for SecureHeaders {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
Box::pin(async move {
let mut res = next.run(ctx).await;
let headers = res.headers_mut();
for (name, value) in [
("x-frame-options", "SAMEORIGIN"),
("x-content-type-options", "nosniff"),
("referrer-policy", "strict-origin-when-cross-origin"),
("cross-origin-opener-policy", "same-origin"),
] {
if !headers.contains_key(name) {
headers.insert(name, http::HeaderValue::from_static(value));
}
}
res
})
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::Env;
#[test]
fn json_logs_in_production_unless_asked_otherwise() {
assert_eq!(LogFormat::choose(Env::Production, None), LogFormat::Json);
assert_eq!(LogFormat::choose(Env::Development, None), LogFormat::Text);
assert_eq!(
LogFormat::choose(Env::Development, Some("json")),
LogFormat::Json
);
assert_eq!(
LogFormat::choose(Env::Production, Some("text")),
LogFormat::Text
);
assert_eq!(
LogFormat::choose(Env::Production, Some("xml")),
LogFormat::Json
);
}
}
pub struct Throttle {
name: &'static str,
limit: u32,
period: std::time::Duration,
key: fn(&Context) -> Option<String>,
counts: std::sync::Mutex<std::collections::HashMap<String, (u64, u32)>>,
}
impl Throttle {
pub fn new(
name: &'static str,
limit: u32,
period: std::time::Duration,
key: fn(&Context) -> Option<String>,
) -> Self {
assert!(
period.as_secs() > 0,
"a throttle's period is at least a second"
);
Self {
name,
limit,
period,
key,
counts: std::sync::Mutex::default(),
}
}
fn allow(&self, key: &str, now_secs: u64) -> bool {
let window = now_secs / self.period.as_secs();
let mut counts = self.counts.lock().unwrap_or_else(|e| e.into_inner());
if counts.len() > 10_000 {
counts.retain(|_, (w, _)| *w == window);
}
let entry = counts.entry(key.to_owned()).or_insert((window, 0));
if entry.0 != window {
*entry = (window, 0);
}
entry.1 += 1;
entry.1 <= self.limit
}
}
impl Middleware for Throttle {
fn handle(&self, ctx: Context, next: Next) -> BoxFuture<Response> {
if let Some(key) = (self.key)(&ctx) {
let now = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.map_or(0, |d| d.as_secs());
if !self.allow(&key, now) {
tracing::info!(throttle = self.name, "request throttled");
return Box::pin(async {
Response::text("Retry later\n").with_status(http::StatusCode::TOO_MANY_REQUESTS)
});
}
}
Box::pin(next.run(ctx))
}
}
#[cfg(test)]
mod throttle_tests {
use super::*;
#[test]
fn counts_each_key_in_fixed_windows() {
let throttle = Throttle::new("t", 2, std::time::Duration::from_secs(60), |_| None);
assert!(throttle.allow("a", 120));
assert!(throttle.allow("a", 130));
assert!(!throttle.allow("a", 179), "a third within the minute");
assert!(throttle.allow("b", 179), "keys are counted apart");
assert!(throttle.allow("a", 180), "a new window starts afresh");
}
}