#[cfg(feature = "api")]
use crate::api::{self, Cors, TokenVerifier};
use crate::{
health::{self, BoxFuture, Check},
proxy::TrustedProxies,
security::{self, Hardening},
};
use axum::{Extension, Router};
use std::{future::Future, io, net::SocketAddr, sync::Arc, time::Duration};
pub struct Config {
pub app_env: String,
pub host: String,
pub port: u16,
pub database_url: String,
}
impl Config {
pub fn from_env() -> Self {
let _ = dotenvy::dotenv();
let var = |k: &str, d: &str| std::env::var(k).unwrap_or_else(|_| d.into());
Config {
app_env: var("APP_ENV", "local"),
host: var("HOST", "127.0.0.1"),
port: var("PORT", "3000").parse().unwrap_or_else(|_| {
panic!(
"PORT must be a number between 0 and 65535, got `{}`",
var("PORT", "3000")
)
}),
database_url: var("DATABASE_URL", "sqlite://db.sqlite?mode=rwc"),
}
}
pub fn validate(&self) -> Result<(), String> {
if self.host.is_empty() || self.host.contains(char::is_whitespace) {
return Err(format!(
"HOST `{}` is not a valid host name or IP",
self.host
));
}
match self.database_url.split_once(':') {
Some((scheme, rest))
if !scheme.is_empty()
&& !rest.is_empty()
&& scheme
.chars()
.all(|c| c.is_ascii_alphanumeric() || "+-.".contains(c)) =>
{
Ok(())
}
_ => Err(
"DATABASE_URL must look like `scheme://...` (e.g. sqlite://db.sqlite?mode=rwc)"
.into(),
),
}
}
}
pub struct App<S> {
state: S,
routes: Router<S>,
#[cfg(feature = "openapi")]
web: utoipa_axum::router::OpenApiRouter<S>,
#[cfg(feature = "api")]
api: ApiGroups<S>,
#[cfg(feature = "openapi")]
title: String,
#[cfg(feature = "openapi")]
version: String,
#[cfg(feature = "openapi")]
docs: Option<bool>,
#[cfg(feature = "sessions")]
sessions: Option<SessionApply<S>>,
#[cfg(feature = "sessions")]
session_opts: Option<crate::session::SessionOptions>,
#[cfg(feature = "csrf")]
csrf: Option<Vec<String>>,
proxies: Option<TrustedProxies>,
checks: Vec<(String, Check)>,
hard: Hardening,
drain: Duration,
}
#[cfg(all(feature = "api", feature = "openapi"))]
type Group<S> = utoipa_axum::router::OpenApiRouter<S>;
#[cfg(all(feature = "api", not(feature = "openapi")))]
type Group<S> = Router<S>;
#[cfg(feature = "api")]
struct ApiGroups<S> {
routes: Group<S>,
public: Group<S>,
used: bool,
prefix: String,
cors: Option<Cors>,
limit: (u32, Duration),
public_limit: (u32, Duration),
store: Option<Arc<dyn api::RateLimitStore>>,
fail_closed: bool,
gate: api::VersionGate,
verifiers: Vec<Arc<dyn TokenVerifier>>,
#[cfg(feature = "openapi")]
oauth2: Option<crate::openapi::OAuth2Cfg>,
#[cfg(feature = "openapi")]
document_web: bool,
}
#[cfg(all(feature = "api", feature = "openapi"))]
fn nest_group<S: Clone + Send + Sync + 'static>(
g: Group<S>,
prefix: &str,
) -> (Router<S>, utoipa::openapi::OpenApi) {
utoipa_axum::router::OpenApiRouter::new()
.nest(prefix, g)
.split_for_parts()
}
#[cfg(all(feature = "api", not(feature = "openapi")))]
fn nest_group<S: Clone + Send + Sync + 'static>(g: Group<S>, prefix: &str) -> Router<S> {
Router::new().nest(prefix, g)
}
#[cfg(feature = "sessions")]
type SessionApply<S> =
Box<dyn FnOnce(Router<S>, &crate::session::SessionOptions) -> Router<S> + Send>;
impl<S> App<S>
where
S: Clone + Send + Sync + 'static,
{
pub fn new(state: S) -> Self {
App {
state,
routes: Router::new(),
#[cfg(feature = "openapi")]
web: utoipa_axum::router::OpenApiRouter::new(),
#[cfg(feature = "api")]
api: ApiGroups {
routes: Group::new(),
public: Group::new(),
used: false,
prefix: "/api".into(),
cors: None,
limit: (120, Duration::from_secs(60)),
public_limit: (300, Duration::from_secs(60)),
store: None,
fail_closed: false,
gate: Default::default(),
verifiers: vec![],
#[cfg(feature = "openapi")]
oauth2: None,
#[cfg(feature = "openapi")]
document_web: false,
},
#[cfg(feature = "openapi")]
title: "ryuk".into(),
#[cfg(feature = "openapi")]
version: "0.1.0".into(),
#[cfg(feature = "openapi")]
docs: None,
#[cfg(feature = "sessions")]
sessions: None,
#[cfg(feature = "sessions")]
session_opts: None,
#[cfg(feature = "csrf")]
csrf: Some(Vec::new()),
proxies: None,
checks: vec![],
hard: Hardening::default(),
drain: Duration::from_secs(30),
}
}
pub fn trusted_proxies(mut self, p: TrustedProxies) -> Self {
self.proxies = Some(p);
self
}
pub fn health_check(
mut self,
name: &str,
check: impl Fn() -> BoxFuture<'static, Result<(), String>> + Send + Sync + 'static,
) -> Self {
self.checks.push((name.into(), Arc::new(check)));
self
}
#[cfg(feature = "db")]
pub fn database(self, db: &sea_orm::DatabaseConnection) -> Self {
let db = db.clone();
self.health_check("db", move || {
let db = db.clone();
Box::pin(async move { db.ping().await.map_err(|e| e.to_string()) })
})
}
pub fn hsts(mut self, on: bool) -> Self {
self.hard.hsts = on;
self
}
pub fn csp(mut self, policy: &str) -> Self {
self.hard.csp = Some(policy.parse().expect("CSP must be a valid header value"));
self
}
pub fn body_limit(mut self, bytes: usize) -> Self {
self.hard.body_limit = bytes;
self
}
pub fn timeout(mut self, d: Duration) -> Self {
self.hard.timeout = d;
self
}
pub fn shutdown_timeout(mut self, d: Duration) -> Self {
self.drain = d;
self
}
#[cfg(feature = "sessions")]
pub fn sessions(mut self, store: impl tower_sessions::SessionStore + Clone + 'static) -> Self {
self.sessions = Some(Box::new(move |r, o| {
r.layer(crate::session::layer_with(store, o))
}));
self
}
#[cfg(feature = "sessions")]
pub fn session_options(mut self, o: crate::session::SessionOptions) -> Self {
self.session_opts = Some(o);
self
}
#[cfg(feature = "csrf")]
pub fn csrf_except(mut self, patterns: &[&str]) -> Self {
if let Some(v) = &mut self.csrf {
v.extend(patterns.iter().map(|p| p.to_string()));
}
self
}
#[cfg(feature = "csrf")]
pub fn without_csrf(mut self) -> Self {
self.csrf = None;
self
}
pub fn routes(mut self, r: Router<S>) -> Self {
self.routes = self.routes.merge(r);
self
}
#[cfg(feature = "openapi")]
pub fn web(mut self, r: utoipa_axum::router::OpenApiRouter<S>) -> Self {
self.web = self.web.merge(r);
self
}
#[cfg(feature = "api")]
pub fn api(mut self, r: Group<S>) -> Self {
self.api.routes = self.api.routes.merge(r);
self.api.used = true;
self
}
#[cfg(feature = "api")]
pub fn public(mut self, r: Group<S>) -> Self {
self.api.public = self.api.public.merge(r);
self
}
#[cfg(feature = "api")]
pub fn api_prefix(mut self, prefix: &str) -> Self {
self.api.prefix = prefix.into();
self
}
#[cfg(feature = "api")]
pub fn cors(mut self, cors: Cors) -> Self {
self.api.cors = Some(cors);
self
}
#[cfg(feature = "api")]
pub fn api_rate_limit(mut self, max: u32, per: Duration) -> Self {
self.api.limit = (max, per);
self
}
#[cfg(feature = "api")]
pub fn public_rate_limit(mut self, max: u32, per: Duration) -> Self {
self.api.public_limit = (max, per);
self
}
#[cfg(feature = "api")]
pub fn api_rate_limit_store(mut self, store: impl api::RateLimitStore) -> Self {
self.api.store = Some(Arc::new(store));
self
}
#[cfg(feature = "api")]
pub fn api_rate_limit_fail_closed(mut self, yes: bool) -> Self {
self.api.fail_closed = yes;
self
}
#[cfg(feature = "api")]
pub fn min_app_version(mut self, platform: &str, min: &str) -> Self {
self.api.gate.set(platform, min);
self
}
#[cfg(feature = "api")]
pub fn require_app_headers(mut self, yes: bool) -> Self {
self.api.gate.require_headers = yes;
self
}
#[cfg(feature = "api")]
pub fn api_verifier(mut self, v: impl TokenVerifier) -> Self {
self.api.verifiers.push(Arc::new(v));
self
}
#[cfg(all(feature = "api", feature = "openapi"))]
pub fn oauth2_scheme(
mut self,
authorize_url: &str,
token_url: &str,
scopes: &[(&str, &str)],
) -> Self {
self.api.oauth2 = Some(crate::openapi::OAuth2Cfg {
authorize_url: authorize_url.into(),
token_url: token_url.into(),
scopes: scopes
.iter()
.map(|(a, b)| (a.to_string(), b.to_string()))
.collect(),
});
self
}
#[cfg(feature = "openapi")]
pub fn docs(mut self, on: bool) -> Self {
self.docs = Some(on);
self
}
#[cfg(all(feature = "api", feature = "openapi"))]
pub fn document_web(mut self, on: bool) -> Self {
self.api.document_web = on;
self
}
#[cfg(feature = "openapi")]
pub fn version(mut self, version: &str) -> Self {
self.version = version.into();
self
}
#[cfg(feature = "openapi")]
pub fn title(mut self, title: &str) -> Self {
self.title = title.into();
self
}
pub fn into_router(self) -> Router {
self.build(security::is_production())
}
fn build(self, production: bool) -> Router {
#[cfg(feature = "openapi")]
let docs_on = crate::openapi::docs_enabled(
self.docs,
std::env::var("OPENAPI_DOCS").ok().as_deref(),
production,
);
#[cfg(feature = "openapi")]
if production && !docs_on {
tracing::info!(
"OpenAPI docs (/docs, /openapi.json) are off in production; App::docs(true) or OPENAPI_DOCS=true turns them on"
);
}
let router = self.routes;
#[cfg(feature = "openapi")]
let (router, web_doc) = {
let (r, doc) = self.web.split_for_parts();
(router.merge(r), doc)
};
#[cfg(all(feature = "api", feature = "openapi"))]
let (pub_router, pub_doc) = self.api.public.split_for_parts();
#[cfg(all(feature = "api", not(feature = "openapi")))]
let pub_router = self.api.public;
#[cfg(feature = "openapi")]
let router = {
#[cfg(feature = "api")]
let (root, mount) = if !self.api.used || self.api.document_web {
let mut d = web_doc;
d.merge(pub_doc);
(d, true)
} else {
let any = !pub_doc.paths.paths.is_empty();
(pub_doc, any)
};
#[cfg(not(feature = "api"))]
let (root, mount) = (web_doc, true);
if mount {
router.merge(crate::openapi::docs(
root,
&self.title,
&self.version,
docs_on,
))
} else {
router
}
};
#[cfg(feature = "api")]
let prefix = format!("/{}", self.api.prefix.trim_matches('/'));
#[cfg(feature = "api")]
{
assert!(
prefix != "/",
"App::api_prefix must not be `/`: the api group needs its own prefix (e.g. `/api`)"
);
if self.api.used {
for p in api::paths(&router) {
assert!(
p != prefix && !p.starts_with(&format!("{prefix}/")),
"web route `{p}` is under the api prefix `{prefix}`: move it out or change App::api_prefix"
);
}
}
}
#[cfg(feature = "inertia")]
let router = router.nest_service(
"/assets",
tower_http::services::ServeDir::new("client/dist/assets"),
);
#[cfg(feature = "csrf")]
let router = match &self.csrf {
Some(except) => {
let except: Vec<&str> = except.iter().map(String::as_str).collect();
router.layer(axum::middleware::from_fn_with_state(
crate::csrf::Csrf::new(&except),
crate::csrf::middleware,
))
}
None => router,
};
#[cfg(feature = "sessions")]
let session_opts = self.session_opts.unwrap_or_else(|| {
crate::session::SessionOptions::from_env().unwrap_or_else(|e| panic!("{e}"))
});
#[cfg(feature = "sessions")]
let router = match self.sessions {
Some(apply) => apply(router, &session_opts),
None => {
if production {
tracing::warn!(
"using the in-memory session store in production: sessions are lost on restart and not shared between processes; call App::sessions(..) with a durable store"
);
}
router.layer(crate::session::layer_with(
tower_sessions::MemoryStore::default(),
&session_opts,
))
}
};
let proxies = self
.proxies
.unwrap_or_else(|| TrustedProxies::from_env().unwrap_or_else(|e| panic!("{e}")));
#[cfg(feature = "api")]
let state = self.state.clone();
let router = router
.with_state(self.state)
.merge(health::router(self.checks))
.layer(Extension(proxies.clone()));
#[cfg(not(feature = "api"))]
let out = security::harden(router, &self.hard, production);
#[cfg(feature = "api")]
let out = {
let (hard, used) = (self.hard, self.api.used);
let harden = |r: Router| {
security::harden(r.layer(Extension(proxies.clone())), &hard, production)
};
#[cfg(feature = "openapi")]
let api_router = {
let (r, mut doc) = nest_group(self.api.routes, &prefix);
crate::openapi::add_security(&mut doc, self.api.oauth2.as_ref());
let docs = crate::openapi::docs(
doc,
&format!("{} API", self.title),
&self.version,
docs_on,
);
r.merge(Router::new().nest(&prefix, docs))
};
#[cfg(not(feature = "openapi"))]
let api_router = nest_group(self.api.routes, &prefix);
let api_router = api_router
.merge(Router::new().nest(&prefix, Router::new().fallback(api_not_found)))
.with_state(state.clone());
let (max, per) = self.api.limit;
let cors = self.api.cors.as_ref();
let store = self
.api
.store
.unwrap_or_else(|| Arc::new(api::MemoryRateLimit::default()));
let (pmax, pper) = self.api.public_limit;
let pub_limit = api::RateCfg {
store: store.clone(),
max: pmax,
per: pper,
fail_closed: self.api.fail_closed,
};
let api_router = api::wrap_api(
api_router,
Arc::new(self.api.verifiers),
api::RateCfg {
store,
max,
per,
fail_closed: self.api.fail_closed,
},
self.api.gate,
cors,
harden,
);
let pub_router =
api::wrap_public(pub_router.with_state(state), pub_limit, cors, harden);
let web = harden(router.fallback(|| async { axum::http::StatusCode::NOT_FOUND }))
.merge(pub_router);
if used { web.merge(api_router) } else { web }
};
out
}
pub async fn serve(self, cfg: &Config) -> io::Result<()> {
init_tracing();
let bad = |e: String| io::Error::new(io::ErrorKind::InvalidInput, e);
cfg.validate().map_err(bad)?;
let proxies = match &self.proxies {
Some(p) => p.clone(),
None => TrustedProxies::from_env().map_err(bad)?,
};
let production = cfg.app_env == "production";
if production {
if !self.hard.hsts {
tracing::warn!(
"HSTS is disabled in production; terminate TLS in front and leave App::hsts(true)"
);
}
if proxies.is_empty() {
tracing::warn!(
"TRUSTED_PROXIES is empty: behind a reverse proxy every client appears as the proxy's address"
);
}
}
let drain = self.drain;
let router = self.trusted_proxies(proxies).build(production);
let l = tokio::net::TcpListener::bind((cfg.host.as_str(), cfg.port))
.await
.map_err(|e| {
io::Error::new(
e.kind(),
format!("cannot bind {}:{}: {e}", cfg.host, cfg.port),
)
})?;
tracing::info!("listening on http://{}", l.local_addr()?);
run(l, router, shutdown_signal(), drain).await
}
}
#[cfg(feature = "api")]
async fn api_not_found() -> api::ApiError {
api::ApiError::not_found()
}
pub fn init_tracing() {
let filter = tracing_subscriber::EnvFilter::try_from_default_env()
.unwrap_or_else(|_| "info,sqlx=warn".into());
let b = tracing_subscriber::fmt().with_env_filter(filter);
let _ = if std::env::var("LOG_FORMAT").is_ok_and(|v| v.eq_ignore_ascii_case("json")) {
b.json().try_init()
} else {
b.try_init()
};
}
async fn shutdown_signal() {
let ctrl_c = async {
let _ = tokio::signal::ctrl_c().await;
};
#[cfg(unix)]
let term = async {
match tokio::signal::unix::signal(tokio::signal::unix::SignalKind::terminate()) {
Ok(mut s) => {
s.recv().await;
}
Err(_) => std::future::pending().await,
}
};
#[cfg(not(unix))]
let term = std::future::pending::<()>();
tokio::select! { _ = ctrl_c => {}, _ = term => {} }
tracing::info!("shutdown signal received, draining requests");
}
async fn run(
l: tokio::net::TcpListener,
router: Router,
stop: impl Future<Output = ()> + Send + 'static,
drain: Duration,
) -> io::Result<()> {
let (tx, rx) = tokio::sync::oneshot::channel();
let server = axum::serve(
l,
router.into_make_service_with_connect_info::<SocketAddr>(),
)
.with_graceful_shutdown(async move {
stop.await;
let _ = tx.send(());
});
let server = std::future::IntoFuture::into_future(server);
tokio::pin!(server);
tokio::select! {
r = &mut server => r,
_ = async { if rx.await.is_ok() { tokio::time::sleep(drain).await } else { std::future::pending().await } } => {
tracing::warn!("drain timeout of {drain:?} reached, closing remaining connections");
Ok(())
}
}
}
#[cfg(all(test, feature = "csrf"))]
mod tests {
use super::*;
use axum::{
body::Body,
http::{Request, header},
routing::{get, post},
};
use tower::ServiceExt;
async fn count(r: &Router, cookie: Option<&str>) -> (String, Option<String>) {
let mut q = Request::get("/n");
if let Some(c) = cookie {
q = q.header(header::COOKIE, c);
}
let res = r
.clone()
.oneshot(q.body(Body::empty()).unwrap())
.await
.unwrap();
let sess = res
.headers()
.get_all(header::SET_COOKIE)
.iter()
.filter_map(|v| v.to_str().ok())
.find(|c| !c.starts_with("XSRF"))
.map(|c| c.split(';').next().unwrap().to_owned());
let b = axum::body::to_bytes(res.into_body(), 64).await.unwrap();
(String::from_utf8(b.to_vec()).unwrap(), sess)
}
fn routes() -> Router<()> {
use tower_sessions::Session;
Router::new()
.route(
"/n",
get(|s: Session| async move {
let n: u32 = s.get("n").await.unwrap().unwrap_or(0) + 1;
s.insert("n", n).await.unwrap();
n.to_string()
}),
)
.route("/w/h", post(|| async { "ok" }))
}
async fn persists(app: App<()>) {
let r = app.routes(routes()).into_router();
let (one, sess) = count(&r, None).await;
assert_eq!(one, "1");
assert_eq!(count(&r, sess.as_deref()).await.0, "2");
}
#[tokio::test]
async fn default_memory_sessions() {
persists(App::new(())).await;
}
#[tokio::test]
async fn csrf_default_on_except_and_off() {
let post_h = |r: Router| async move {
r.oneshot(Request::post("/w/h").body(Body::empty()).unwrap())
.await
.unwrap()
.status()
};
assert_eq!(
post_h(App::new(()).routes(routes()).into_router()).await,
419
);
assert_eq!(
post_h(
App::new(())
.routes(routes())
.csrf_except(&["/w/*"])
.into_router()
)
.await,
200
);
assert_eq!(
post_h(App::new(()).routes(routes()).without_csrf().into_router()).await,
200
);
}
#[cfg(feature = "session-file")]
#[tokio::test]
async fn file_store() {
let dir = std::env::temp_dir().join(format!("ryuk-sess-{}", std::process::id()));
persists(
App::new(()).sessions(crate::session::file::FileSessionStorage::new_in_folder(
dir.clone(),
)),
)
.await;
assert!(std::fs::read_dir(&dir).unwrap().count() >= 1);
let _ = std::fs::remove_dir_all(&dir);
}
#[cfg(feature = "session-db")]
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn db_store() {
let db = sea_orm::Database::connect("sqlite::memory:").await.unwrap();
let s = crate::session::DbStore::new(db);
s.ensure_table().await.unwrap();
persists(App::new(()).sessions(s)).await;
}
#[cfg(feature = "session-redis")]
#[tokio::test]
async fn redis_store() {
use crate::session::redis::{
RedisStore,
fred::prelude::{ClientLike, Pool},
};
let Ok(url) = std::env::var("TEST_REDIS_URL") else {
return eprintln!("skipped: TEST_REDIS_URL not set");
};
let pool = Pool::new(
crate::session::redis::fred::prelude::Config::from_url(&url).unwrap(),
None,
None,
None,
2,
)
.unwrap();
let _connection = pool.connect(); pool.wait_for_connect().await.unwrap();
persists(App::new(()).sessions(RedisStore::new(pool))).await;
}
#[cfg(feature = "session-moka")]
#[tokio::test]
async fn moka_store() {
persists(App::new(()).sessions(crate::session::moka::MokaStore::new(Some(100)))).await;
}
#[tokio::test]
async fn custom_store() {
use std::{
collections::HashMap,
sync::{Arc, Mutex},
};
use tower_sessions::{
SessionStore,
session::{Id, Record},
session_store::Result,
};
#[derive(Clone, Debug, Default)]
struct Mine(Arc<Mutex<HashMap<Id, Record>>>);
#[async_trait::async_trait]
impl SessionStore for Mine {
async fn save(&self, r: &Record) -> Result<()> {
self.0.lock().unwrap().insert(r.id, r.clone());
Ok(())
}
async fn load(&self, id: &Id) -> Result<Option<Record>> {
Ok(self.0.lock().unwrap().get(id).cloned())
}
async fn delete(&self, id: &Id) -> Result<()> {
self.0.lock().unwrap().remove(id);
Ok(())
}
}
let s = Mine::default();
persists(App::new(()).sessions(s.clone())).await;
assert_eq!(s.0.lock().unwrap().len(), 1);
}
}
#[cfg(test)]
mod hardening_tests {
use super::*;
use axum::{
body::Body,
extract::ConnectInfo,
http::{Request, StatusCode},
routing::{get, post},
};
use tower::ServiceExt;
fn app() -> App<()> {
let a = App::new(());
#[cfg(feature = "csrf")]
let a = a.without_csrf();
a.routes(
Router::new()
.route("/ok", get(|| async { "hi" }))
.route(
"/panic",
get(|| async {
if true {
panic!("secret detail")
}
"x"
}),
)
.route(
"/slow",
get(|| async { tokio::time::sleep(Duration::from_secs(5)).await }),
)
.route(
"/echo",
post(|b: String| async move { b.len().to_string() }),
)
.route(
"/ip",
get(|ip: crate::proxy::ClientIp| async move { ip.0.unwrap().to_string() }),
),
)
}
async fn call(r: Router, req: Request<Body>) -> axum::response::Response {
r.oneshot(req).await.unwrap()
}
fn get_(uri: &str) -> Request<Body> {
Request::get(uri).body(Body::empty()).unwrap()
}
#[tokio::test]
async fn health_and_ready() {
let r = app()
.health_check("good", || Box::pin(async { Ok(()) }))
.build(false);
assert_eq!(call(r.clone(), get_("/healthz")).await.status(), 200);
assert_eq!(call(r, get_("/readyz")).await.status(), 200);
let r = app()
.health_check("good", || Box::pin(async { Ok(()) }))
.health_check("db", || Box::pin(async { Err("down".into()) }))
.build(false);
let res = call(r.clone(), get_("/readyz")).await;
assert_eq!(res.status(), StatusCode::SERVICE_UNAVAILABLE);
let b = axum::body::to_bytes(res.into_body(), 1024).await.unwrap();
assert_eq!(
serde_json::from_slice::<serde_json::Value>(&b).unwrap(),
serde_json::json!({"status":"unavailable","failed":["db"]})
);
let live = call(r, get_("/healthz")).await;
assert_eq!(live.status(), 200);
assert!(live.headers().get("set-cookie").is_none());
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn database_check() {
let db = sea_orm::Database::connect("sqlite::memory:").await.unwrap();
let r = app().database(&db).build(false);
assert_eq!(call(r, get_("/readyz")).await.status(), 200);
let db2 = sea_orm::Database::connect("sqlite::memory:").await.unwrap();
let r = app().database(&db2).build(false);
db2.close().await.unwrap();
assert_eq!(call(r, get_("/readyz")).await.status(), 503);
}
#[tokio::test]
async fn security_headers_and_hsts_only_in_production() {
let h = |res: &axum::response::Response, k: &str| {
res.headers().get(k).map(|v| v.to_str().unwrap().to_owned())
};
let dev = call(app().build(false), get_("/ok")).await;
assert_eq!(
h(&dev, "x-content-type-options").as_deref(),
Some("nosniff")
);
assert_eq!(h(&dev, "x-frame-options").as_deref(), Some("DENY"));
assert_eq!(
h(&dev, "referrer-policy").as_deref(),
Some("strict-origin-when-cross-origin")
);
assert_eq!(
h(&dev, "permissions-policy").as_deref(),
Some("camera=(), microphone=(), geolocation=()")
);
assert_eq!(
h(&dev, "cross-origin-opener-policy").as_deref(),
Some("same-origin")
);
assert!(
h(&dev, "strict-transport-security").is_none()
&& h(&dev, "content-security-policy").is_none()
);
let prod = call(app().build(true), get_("/ok")).await;
assert_eq!(
h(&prod, "strict-transport-security").as_deref(),
Some("max-age=31536000; includeSubDomains")
);
assert!(
h(
&call(app().hsts(false).build(true), get_("/ok")).await,
"strict-transport-security"
)
.is_none()
);
assert_eq!(
h(
&call(app().csp("default-src 'self'").build(false), get_("/ok")).await,
"content-security-policy"
)
.as_deref(),
Some("default-src 'self'")
);
}
#[tokio::test]
async fn body_limit_413() {
let r = app().body_limit(8).build(false);
let post_ = |n: usize| {
Request::post("/echo")
.body(Body::from("x".repeat(n)))
.unwrap()
};
assert_eq!(call(r.clone(), post_(8)).await.status(), 200);
assert_eq!(
call(r, post_(9)).await.status(),
StatusCode::PAYLOAD_TOO_LARGE
);
}
#[cfg(feature = "sessions")]
#[tokio::test]
async fn session_options_set_cookie_name_and_max_age() {
use crate::session::{Session, SessionOptions};
let routes = || {
Router::new().route(
"/s",
get(|s: Session| async move {
s.insert("k", 1).await.unwrap();
"ok"
}),
)
};
let cookie = |app: App<()>| async move {
let r = call(app.build(false), get_("/s")).await;
r.headers()
.get("set-cookie")
.unwrap()
.to_str()
.unwrap()
.to_string()
};
let base = || {
let a = App::new(());
#[cfg(feature = "csrf")]
let a = a.without_csrf();
a.routes(routes())
};
let custom = cookie(
base().session_options(
SessionOptions::default()
.lifetime(Duration::from_secs(3600))
.cookie_name("shop_session"),
),
)
.await;
assert!(custom.starts_with("shop_session="), "{custom}");
assert!(custom.contains("Max-Age=3600"), "{custom}");
assert!(
custom.contains("HttpOnly") && custom.contains("SameSite=Lax"),
"{custom}"
);
let plain = cookie(base()).await;
assert!(plain.starts_with("id="), "{plain}");
assert!(!plain.contains("Max-Age"), "{plain}");
}
#[cfg(feature = "openapi")]
#[tokio::test]
async fn docs_routes_are_404_in_production_by_default() {
use utoipa_axum::{router::OpenApiRouter, routes};
#[utoipa::path(get, path = "/ping", responses((status = 200, body = String)))]
async fn ping() -> &'static str {
"pong"
}
let mk = || {
let a = App::new(());
#[cfg(feature = "csrf")]
let a = a.without_csrf();
a.web(OpenApiRouter::new().routes(routes!(ping)))
};
for path in ["/docs", "/openapi.json"] {
assert_eq!(
call(mk().build(true), get_(path)).await.status(),
404,
"production {path}"
);
assert_eq!(
call(mk().build(false), get_(path)).await.status(),
200,
"local {path}"
);
assert_eq!(
call(mk().docs(true).build(true), get_(path)).await.status(),
200,
"opted in {path}"
);
assert_eq!(
call(mk().docs(false).build(false), get_(path))
.await
.status(),
404,
"opted out {path}"
);
}
assert_eq!(call(mk().build(true), get_("/ping")).await.status(), 200);
}
#[tokio::test]
async fn body_limit_above_axum_default_is_honored_by_extractors() {
let mib = 1024 * 1024;
let r = app().body_limit(3 * mib).build(false);
let post_ = |n: usize| {
Request::post("/echo")
.body(Body::from("x".repeat(n)))
.unwrap()
};
assert_eq!(
call(r.clone(), post_(2 * mib + mib / 2)).await.status(),
200
);
assert_eq!(
call(r, post_(3 * mib + 1)).await.status(),
StatusCode::PAYLOAD_TOO_LARGE
);
}
#[tokio::test]
async fn timeout_408() {
let r = app().timeout(Duration::from_millis(50)).build(false);
assert_eq!(
call(r, get_("/slow")).await.status(),
StatusCode::REQUEST_TIMEOUT
);
}
#[tokio::test]
async fn panic_is_500_without_details() {
let res = call(app().build(false), get_("/panic")).await;
assert_eq!(res.status(), 500);
assert!(res.headers().contains_key("x-frame-options"));
let b = String::from_utf8(
axum::body::to_bytes(res.into_body(), 1024)
.await
.unwrap()
.to_vec(),
)
.unwrap();
assert!(!b.contains("secret"), "{b}");
}
#[tokio::test]
async fn request_id_generated_and_propagated() {
let r = app().build(false);
let a = call(r.clone(), get_("/ok")).await.headers()["x-request-id"]
.to_str()
.unwrap()
.to_owned();
let b = call(r.clone(), get_("/ok")).await.headers()["x-request-id"]
.to_str()
.unwrap()
.to_owned();
assert!(a.len() >= 32 && a != b);
let res = call(
r,
Request::get("/ok")
.header("x-request-id", "abc-123")
.body(Body::empty())
.unwrap(),
)
.await;
assert_eq!(res.headers()["x-request-id"], "abc-123");
}
#[tokio::test]
async fn client_ip_wired_through_app() {
let req = |xff: &str| {
let mut r = Request::get("/ip")
.header("x-forwarded-for", xff)
.body(Body::empty())
.unwrap();
r.extensions_mut()
.insert(ConnectInfo(SocketAddr::from(([10, 0, 0, 1], 1))));
r
};
let body = |r: axum::response::Response| async move {
String::from_utf8(
axum::body::to_bytes(r.into_body(), 64)
.await
.unwrap()
.to_vec(),
)
.unwrap()
};
let trusting = || {
app()
.trusted_proxies(TrustedProxies::parse("10.0.0.0/8").unwrap())
.build(false)
};
assert_eq!(
body(call(trusting(), req("1.2.3.4")).await).await,
"1.2.3.4"
);
let default = app()
.trusted_proxies(TrustedProxies::default())
.build(false);
assert_eq!(body(call(default, req("1.2.3.4")).await).await, "10.0.0.1");
}
#[test]
fn config_validation() {
let c = |host: &str, url: &str| Config {
app_env: "local".into(),
host: host.into(),
port: 1,
database_url: url.into(),
};
assert!(
c("127.0.0.1", "sqlite://db.sqlite?mode=rwc")
.validate()
.is_ok()
);
assert!(c("127.0.0.1", "postgres://u@h/db").validate().is_ok());
assert!(
c("bad host", "sqlite://x")
.validate()
.unwrap_err()
.contains("HOST")
);
assert!(
c("h", "not a url")
.validate()
.unwrap_err()
.contains("DATABASE_URL")
);
}
#[tokio::test]
async fn graceful_shutdown_serves_then_stops_and_drain_times_out() {
let l = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
let addr = l.local_addr().unwrap();
let (tx, rx) = tokio::sync::oneshot::channel::<()>();
let r = app().timeout(Duration::from_secs(10)).build(false);
let h = tokio::spawn(run(
l,
r,
async {
let _ = rx.await;
},
Duration::from_millis(200),
));
let fetch = |path: &'static str| async move {
use tokio::io::{AsyncReadExt, AsyncWriteExt};
let mut s = tokio::net::TcpStream::connect(addr).await.unwrap();
s.write_all(
format!("GET {path} HTTP/1.1\r\nhost: x\r\nconnection: close\r\n\r\n").as_bytes(),
)
.await
.unwrap();
let mut out = String::new();
let _ = s.read_to_string(&mut out).await;
out
};
assert!(fetch("/healthz").await.starts_with("HTTP/1.1 200"));
let slow = tokio::spawn(fetch("/slow"));
tokio::time::sleep(Duration::from_millis(100)).await;
tx.send(()).unwrap();
let t = std::time::Instant::now();
h.await.unwrap().unwrap();
assert!(t.elapsed() < Duration::from_secs(3), "{:?}", t.elapsed());
slow.abort();
}
}
#[cfg(all(test, feature = "api"))]
mod api_tests {
use super::*;
use crate::api::{ApiAuth, ApiError, Cors, OptionalApiAuth, Principal, PrincipalKind};
use axum::{
Json,
body::Body,
extract::ConnectInfo,
http::{Request, StatusCode, header},
response::Response,
routing::{get, post},
};
use tower::ServiceExt;
struct Token(&'static str, &'static str, &'static [&'static str]);
impl TokenVerifier for Token {
fn verify<'a>(&'a self, b: &'a str) -> BoxFuture<'a, Option<Principal>> {
Box::pin(async move {
(b == self.0).then(|| Principal {
kind: PrincipalKind::ApiKey,
id: self.1.into(),
user_id: Some(7),
client_id: None,
scopes: self.2.iter().map(|s| s.to_string()).collect(),
name: None,
})
})
}
}
fn grp(r: Router<()>) -> Group<()> {
#[cfg(feature = "openapi")]
return utoipa_axum::router::OpenApiRouter::from(r);
#[cfg(not(feature = "openapi"))]
return r;
}
fn group() -> Router<()> {
Router::new()
.route("/me", get(|ApiAuth(p): ApiAuth| async move { p.id }))
.route(
"/opt",
get(|OptionalApiAuth(p): OptionalApiAuth| async move {
format!("{:?}", p.map(|p| p.id))
}),
)
.route(
"/admin",
get(|ApiAuth(p): ApiAuth| async move {
p.require("admin:write")?;
Ok::<_, ApiError>("ok")
}),
)
.route(
"/echo",
post(|b: String| async move { b.len().to_string() }),
)
.route(
"/json",
post(|Json(v): Json<serde_json::Value>| async move { Json(v) }),
)
.route(
"/panic",
get(|| async {
if true {
panic!("secret detail")
}
"x"
}),
)
.route(
"/err",
get(|| async {
Err::<&str, ApiError>(std::io::Error::other("db password is hunter2").into())
}),
)
.route(
"/slow",
get(|| async { tokio::time::sleep(Duration::from_secs(5)).await }),
)
.route("/ip", get(|| async { "ok" }))
}
fn web() -> Router<()> {
let r = Router::new()
.route("/w", post(|| async { "posted" }))
.route(
"/w/opt",
get(|OptionalApiAuth(_): OptionalApiAuth| async { "x" }),
);
#[cfg(feature = "auth")]
let r = r.route(
"/w/me",
get(|crate::auth::Auth(id): crate::auth::Auth| async move { id.to_string() }),
);
#[cfg(feature = "sessions")]
let r = r.route(
"/w/n",
get(|s: tower_sessions::Session| async move {
s.insert("n", 1).await.unwrap();
"n"
}),
);
r
}
fn app() -> App<()> {
App::new(())
.routes(web())
.api_verifier(Token("tok", "k1", &["posts:*"]))
.api_verifier(Token("tok2", "k2", &["*"]))
.api(grp(group()))
}
async fn send(r: &Router, req: Request<Body>) -> Response {
r.clone().oneshot(req).await.unwrap()
}
fn req(method: &str, uri: &str, headers: &[(&str, &str)], body: &str) -> Request<Body> {
let mut r = Request::builder().method(method).uri(uri);
for (k, v) in headers {
r = r.header(*k, *v);
}
r.body(Body::from(body.to_owned())).unwrap()
}
async fn text(res: Response) -> String {
let b = axum::body::to_bytes(res.into_body(), usize::MAX).await;
String::from_utf8(b.unwrap().to_vec()).unwrap()
}
async fn json(res: Response) -> (StatusCode, serde_json::Value, header::HeaderMap) {
let (p, b) = res.into_parts();
let b = axum::body::to_bytes(b, usize::MAX).await.unwrap();
let v = serde_json::from_slice(&b)
.unwrap_or_else(|_| panic!("not JSON: {}", String::from_utf8_lossy(&b)));
(p.status, v, p.headers)
}
async fn expect(res: Response, status: u16, code: &str) -> header::HeaderMap {
let (st, v, h) = json(res).await;
assert_eq!(
(st.as_u16(), v["error"]["code"].as_str()),
(status, Some(code)),
"{v}"
);
assert!(v["error"]["message"].is_string());
assert!(h[header::CONTENT_TYPE].to_str().unwrap().contains("json"));
h
}
#[cfg(feature = "csrf")]
#[tokio::test]
async fn groups_are_isolated() {
let r = app().into_router();
assert_eq!(send(&r, req("POST", "/w", &[], "")).await.status(), 419);
let auth = [("authorization", "Bearer tok")];
let res = send(&r, req("POST", "/api/echo", &auth, "abc")).await;
assert_eq!(res.status(), 200);
assert!(
res.headers().get(header::SET_COOKIE).is_none(),
"no cookie on api routes"
);
let res = send(&r, req("GET", "/w/n", &[], "")).await;
assert!(res.headers().get(header::SET_COOKIE).is_some());
let res = send(&r, req("GET", "/api/nope", &[], "")).await;
assert!(res.headers().get(header::SET_COOKIE).is_none());
}
#[cfg(feature = "auth")]
#[tokio::test]
async fn bearer_ignored_on_web_and_session_auth_unavailable_on_api() {
let r = app().without_csrf().into_router();
let bearer = [("authorization", "Bearer tok")];
let res = send(&r, req("GET", "/w/me", &bearer, "")).await;
assert_eq!(
res.status(),
303,
"a Bearer token must not log a web request in"
);
let res = send(&r, req("GET", "/w/opt", &bearer, "")).await;
assert_eq!(res.status(), 500);
let s = Router::new().route(
"/s",
get(|crate::auth::Auth(id): crate::auth::Auth| async move { id.to_string() }),
);
let r = App::new(()).api(grp(s)).into_router();
let (st, v, _) = json(send(&r, req("GET", "/api/s", &[], "")).await).await;
assert_eq!(st, 401);
assert_eq!(
v["error"]["message"],
"session auth is not available on api routes"
);
}
#[tokio::test]
async fn authentication_and_scopes() {
let r = app().into_router();
let h = expect(
send(&r, req("GET", "/api/me", &[], "")).await,
401,
"unauthorized",
)
.await;
assert_eq!(h[header::WWW_AUTHENTICATE], "Bearer");
let bad = req("GET", "/api/me", &[("authorization", "Bearer bad")], "");
expect(send(&r, bad).await, 401, "unauthorized").await;
let me = |h: &str, v: &str| req("GET", "/api/me", &[(h, v)], "");
assert_eq!(
text(send(&r, me("authorization", "Bearer tok")).await).await,
"k1"
);
assert_eq!(text(send(&r, me("x-api-key", "tok")).await).await, "k1");
let opt = |k: &[(&str, &str)]| req("GET", "/api/opt", k, "");
assert_eq!(text(send(&r, opt(&[])).await).await, "None");
assert_eq!(
text(send(&r, opt(&[("x-api-key", "tok")])).await).await,
"Some(\"k1\")"
);
let admin = |k: &'static str| req("GET", "/api/admin", &[("x-api-key", k)], "");
expect(send(&r, admin("tok")).await, 403, "insufficient_scope").await;
assert_eq!(send(&r, admin("tok2")).await.status(), 200);
}
#[tokio::test]
async fn verifier_chain_order_first_some_wins() {
let who = |first: Token, second: Token| async move {
let r = App::new(())
.api_verifier(first)
.api_verifier(second)
.api(grp(group()))
.into_router();
text(send(&r, req("GET", "/api/me", &[("x-api-key", "shared")], "")).await).await
};
let t = |tok, id| Token(tok, id, &[]);
assert_eq!(
who(t("shared", "first"), t("shared", "second")).await,
"first"
);
assert_eq!(
who(t("other", "first"), t("shared", "second")).await,
"second"
);
}
#[tokio::test]
async fn every_error_class_is_json() {
let a = app().body_limit(8).timeout(Duration::from_millis(100));
#[cfg(feature = "csrf")]
let a = a.without_csrf();
let r = a.into_router();
let auth = [("authorization", "Bearer tok")];
let go = |m: &str, u: &str, h: &[(&str, &str)], b: &str| send(&r, req(m, u, h, b));
expect(go("GET", "/api/nope", &[], "").await, 404, "not_found").await;
expect(
go("DELETE", "/api/me", &auth, "").await,
405,
"method_not_allowed",
)
.await;
expect(
go("POST", "/api/echo", &auth, "123456789").await,
413,
"payload_too_large",
)
.await;
expect(
go("GET", "/api/slow", &auth, "").await,
408,
"request_timeout",
)
.await;
let h = expect(
go("GET", "/api/panic", &auth, "").await,
500,
"internal_error",
)
.await;
assert!(h.contains_key("x-request-id"), "hardening headers survive");
let c = [("content-type", "application/json")];
let (st, v, _) = json(go("POST", "/api/json", &c, "{no").await).await;
assert!(st == 400 || st == 422, "{st}");
assert!(v["error"]["code"].is_string());
let t = [("content-type", "text/plain")];
expect(
go("POST", "/api/json", &t, "x").await,
415,
"unsupported_media_type",
)
.await;
let (st, v, _) = json(go("GET", "/api/err", &auth, "").await).await;
assert_eq!(st, 500);
assert!(
!v.to_string().contains("hunter2") && !v.to_string().contains("secret"),
"{v}"
);
let res = go("GET", "/nope", &[], "").await;
assert_eq!(res.status(), 404);
assert!(res.headers().get(header::CONTENT_TYPE).is_none());
}
#[tokio::test]
async fn public_group_is_json_and_unauthenticated() {
let p = App::new(()).body_limit(8).public(grp(group()));
#[cfg(feature = "csrf")]
let p = p.without_csrf();
let p = p.into_router();
expect(
send(&p, req("GET", "/panic", &[], "")).await,
500,
"internal_error",
)
.await;
expect(
send(&p, req("PUT", "/echo", &[], "")).await,
405,
"method_not_allowed",
)
.await;
expect(
send(&p, req("POST", "/echo", &[], "123456789")).await,
413,
"payload_too_large",
)
.await;
let res = send(&p, req("POST", "/echo", &[], "abc")).await;
assert_eq!(res.status(), 200);
assert!(res.headers().get(header::SET_COOKIE).is_none());
let res = send(&p, req("GET", "/me", &[("x-api-key", "tok")], "")).await;
assert_eq!(res.status(), 500);
}
#[tokio::test]
async fn rate_limit_per_principal_then_ip() {
let r = app()
.api_rate_limit(2, Duration::from_secs(60))
.into_router();
let ip = |mut q: Request<Body>, ip: [u8; 4]| {
q.extensions_mut()
.insert(ConnectInfo(SocketAddr::from((ip, 9))));
send(&r, q)
};
let call = |tok: &'static str| {
ip(
req("GET", "/api/ip", &[("x-api-key", tok)], ""),
[1, 2, 3, 4],
)
};
let h = call("tok").await;
assert_eq!(h.headers()["x-ratelimit-limit"], "2");
assert_eq!(h.headers()["x-ratelimit-remaining"], "1");
let reset: u64 = h.headers()["x-ratelimit-reset"]
.to_str()
.unwrap()
.parse()
.unwrap();
assert!((1..=60).contains(&reset));
assert_eq!(call("tok").await.headers()["x-ratelimit-remaining"], "0");
let h = expect(call("tok").await, 429, "rate_limited").await;
assert!(h.contains_key("retry-after") && h["x-ratelimit-remaining"] == "0");
assert_eq!(call("tok2").await.status(), 200);
let anon = |a: [u8; 4]| ip(req("GET", "/api/opt", &[], ""), a);
assert_eq!(anon([9, 9, 9, 9]).await.status(), 200);
assert_eq!(anon([9, 9, 9, 9]).await.status(), 200);
assert_eq!(anon([9, 9, 9, 9]).await.status(), 429);
assert_eq!(anon([8, 8, 8, 8]).await.status(), 200);
}
#[tokio::test]
async fn public_group_is_rate_limited_per_ip_bucket() {
let p = App::new(())
.public(grp(group()))
.public_rate_limit(2, Duration::from_secs(60));
#[cfg(feature = "csrf")]
let p = p.without_csrf();
let r = p.into_router();
let from = |ip: &str| {
let mut q = req("POST", "/echo", &[], "x");
q.extensions_mut()
.insert(ConnectInfo(SocketAddr::new(ip.parse().unwrap(), 9)));
send(&r, q)
};
assert_eq!(from("1.2.3.4").await.status(), 200);
assert_eq!(from("1.2.3.4").await.status(), 200);
let h = expect(from("1.2.3.4").await, 429, "rate_limited").await;
assert!(h.contains_key("retry-after"));
assert_eq!(from("5.6.7.8").await.status(), 200);
assert_eq!(from("2001:db8:1:2::1").await.status(), 200);
assert_eq!(from("2001:db8:1:2::2").await.status(), 200);
assert_eq!(from("2001:db8:1:2::3").await.status(), 429);
assert_eq!(from("2001:db8:1:3::1").await.status(), 200);
for _ in 0..4 {
assert_eq!(
send(&r, req("GET", "/healthz", &[], "")).await.status(),
200
);
}
}
#[tokio::test]
async fn version_gate_rules() {
let r = app()
.min_app_version("ios", "1.10.0")
.min_app_version("android", "2")
.into_router();
let call = |path: &'static str, p: &'static str, v: &'static str| {
let h = [("x-app-platform", p), ("x-app-version", v)];
send(&r, req("GET", path, &h, ""))
};
let (st, v, h) = json(call("/api/ip", "ios", "1.9.3").await).await;
assert_eq!(st.as_u16(), 426);
assert_eq!(v["error"]["code"], "upgrade_required");
assert_eq!(v["error"]["min_version"], "1.10.0");
assert_eq!(v["error"]["platform"], "ios");
assert_eq!(h["x-min-app-version"], "1.10.0");
assert!(
h.contains_key("x-request-id"),
"request id runs before the gate"
);
assert_eq!(call("/api/ip", "ios", "1.10.0").await.status(), 200);
assert_eq!(call("/api/ip", "IOS", "1.10.1-beta+7").await.status(), 200);
assert_eq!(call("/api/ip", "android", "1.99").await.status(), 426);
assert_eq!(call("/api/ip", "android", "2.0.0").await.status(), 200);
assert_eq!(call("/api/ip", "ios", "banana").await.status(), 200);
assert_eq!(call("/api/ip", "windows", "0.0.1").await.status(), 200);
assert_eq!(send(&r, req("GET", "/api/ip", &[], "")).await.status(), 200);
let res = send(
&r,
req(
"GET",
"/api/me",
&[("x-app-platform", "ios"), ("x-app-version", "1.0")],
"",
),
)
.await;
assert_eq!(res.status().as_u16(), 426);
assert!(!res.headers().contains_key("x-ratelimit-limit"));
let res = send(
&r,
req(
"POST",
"/w",
&[("x-app-platform", "ios"), ("x-app-version", "1.0")],
"",
),
)
.await;
assert_ne!(res.status(), 426, "web routes are not gated");
let r = app().require_app_headers(true).into_router();
expect(
send(&r, req("GET", "/api/ip", &[], "")).await,
400,
"bad_request",
)
.await;
let bad = [("x-app-platform", "ios"), ("x-app-version", "x.y")];
expect(
send(&r, req("GET", "/api/ip", &bad, "")).await,
400,
"bad_request",
)
.await;
let ok = [("x-app-platform", "ios"), ("x-app-version", "1.0")];
assert_eq!(send(&r, req("GET", "/api/ip", &ok, "")).await.status(), 200);
assert_ne!(send(&r, req("POST", "/w", &[], "")).await.status(), 400);
}
#[test]
#[should_panic(expected = "not a dotted version")]
fn min_version_must_parse() {
let _ = app().min_app_version("ios", "one.two");
}
struct FakeStore(std::sync::atomic::AtomicU32, bool);
impl api::RateLimitStore for FakeStore {
fn hit<'a>(
&'a self,
key: &'a str,
limit: u32,
_: Duration,
) -> BoxFuture<'a, Result<api::RateStatus, api::RateError>> {
let n = self.0.fetch_add(1, std::sync::atomic::Ordering::SeqCst) + 1;
Box::pin(async move {
assert!(key.starts_with("principal:ApiKey:") || key.starts_with("ip:"));
if self.1 {
return Err(api::RateError("down".into()));
}
Ok(api::RateStatus {
limited: n > 1,
remaining: limit,
reset_in: Duration::from_secs(7),
})
})
}
}
#[tokio::test]
async fn custom_store_is_used_and_fail_modes() {
let r = app()
.api_rate_limit(5, Duration::from_secs(60))
.api_rate_limit_store(FakeStore(Default::default(), false))
.into_router();
let h = send(&r, req("GET", "/api/ip", &[], ""))
.await
.headers()
.clone();
assert_eq!(h["x-ratelimit-limit"], "5");
assert_eq!(h["x-ratelimit-reset"], "7");
let h = expect(
send(&r, req("GET", "/api/ip", &[], "")).await,
429,
"rate_limited",
)
.await;
assert_eq!(h["retry-after"], "7");
let broken = || FakeStore(Default::default(), true);
let r = app().api_rate_limit_store(broken()).into_router();
let res = send(&r, req("GET", "/api/ip", &[], "")).await;
assert_eq!(res.status(), 200);
assert!(!res.headers().contains_key("x-ratelimit-limit"));
let r = app()
.api_rate_limit_store(broken())
.api_rate_limit_fail_closed(true)
.into_router();
expect(
send(&r, req("GET", "/api/ip", &[], "")).await,
503,
"rate_limit_unavailable",
)
.await;
}
#[tokio::test]
async fn cors_preflight() {
let preflight = |origin: &'static str| {
let h = [
("origin", origin),
("access-control-request-method", "GET"),
("access-control-request-headers", "authorization,x-trace"),
];
req("OPTIONS", "/api/me", &h, "")
};
let cors = Cors::allow_origins(&["https://app.example.com"])
.allow_headers(&["x-trace"])
.max_age(Duration::from_secs(600));
let r = app().cors(cors).into_router();
let res = send(&r, preflight("https://app.example.com")).await;
assert!(res.status().is_success(), "{}", res.status());
let h = res.headers();
assert_eq!(h["access-control-allow-origin"], "https://app.example.com");
assert_eq!(h["access-control-max-age"], "600");
assert!(
h["access-control-allow-headers"]
.to_str()
.unwrap()
.contains("x-trace")
);
assert!(!h.contains_key("access-control-allow-credentials"));
let evil = send(&r, preflight("https://evil.example")).await;
assert!(!evil.headers().contains_key("access-control-allow-origin"));
let o = [("origin", "https://app.example.com")];
let res = send(&r, req("GET", "/api/me", &o, "")).await;
assert_eq!(res.status(), 401);
assert_eq!(
res.headers()["access-control-allow-origin"],
"https://app.example.com"
);
let r = app().into_router();
let res = send(&r, req("GET", "/api/me", &o, "")).await;
assert!(!res.headers().contains_key("access-control-allow-origin"));
}
#[test]
#[should_panic(expected = "must not be `/`")]
fn prefix_slash_panics() {
let _ = app().api_prefix("/").into_router();
}
#[test]
#[should_panic(expected = "under the api prefix")]
fn web_route_under_api_prefix_panics() {
let _ = App::new(())
.routes(Router::new().route("/api/users", get(|| async { "x" })))
.api(grp(group()))
.into_router();
}
#[test]
#[should_panic(expected = "under the api prefix")]
fn custom_prefix_is_checked_too() {
let _ = app()
.api_prefix("v1/")
.routes(Router::new().route("/v1/x", get(|| async { "x" })))
.into_router();
}
#[test]
fn unused_prefix_does_not_block_web_routes() {
let _ = App::new(())
.routes(Router::new().route("/api/users", get(|| async { "x" })))
.into_router();
}
#[tokio::test]
async fn custom_prefix_serves_group() {
let r = app().api_prefix("/v1/").into_router();
let key = [("x-api-key", "tok")];
assert_eq!(send(&r, req("GET", "/v1/me", &key, "")).await.status(), 200);
expect(
send(&r, req("GET", "/v1/nope", &key, "")).await,
404,
"not_found",
)
.await;
assert_eq!(
send(&r, req("GET", "/api/me", &key, "")).await.status(),
404
);
}
#[cfg(feature = "openapi")]
mod spec {
use super::*;
use utoipa_axum::{router::OpenApiRouter, routes};
#[utoipa::path(get, path = "/things", security(("api_key" = [])), responses((status = 200, body = String)))]
async fn things() -> &'static str {
"t"
}
#[utoipa::path(get, path = "/page", responses((status = 200, body = String)))]
async fn page() -> &'static str {
"p"
}
#[utoipa::path(get, path = "/api/clash", responses((status = 200, body = String)))]
async fn clash() -> &'static str {
"c"
}
#[utoipa::path(post, path = "/hook", responses((status = 200, body = String)))]
async fn hook() -> &'static str {
"h"
}
async fn spec(r: &Router, uri: &str) -> serde_json::Value {
json(send(r, req("GET", uri, &[], "")).await).await.1
}
#[tokio::test]
async fn per_group_docs_and_security_schemes() {
let r = App::new(())
.title("Shop")
.web(OpenApiRouter::new().routes(routes!(page)))
.api(OpenApiRouter::new().routes(routes!(things)))
.public(OpenApiRouter::new().routes(routes!(hook)))
.oauth2_scheme(
"https://x/authorize",
"https://x/token",
&[("posts:read", "Read posts")],
)
.into_router();
let api = spec(&r, "/api/openapi.json").await;
assert!(api["paths"]["/api/things"].is_object());
assert!(api["paths"]["/page"].is_null() && api["paths"]["/hook"].is_null());
assert_eq!(api["info"]["title"], "Shop API");
let s = &api["components"]["securitySchemes"];
assert_eq!(s["api_key"]["type"], "http");
assert_eq!(s["api_key"]["scheme"], "bearer");
assert_eq!(s["api_key"]["bearerFormat"], "API key");
assert_eq!(s["oauth2"]["type"], "oauth2");
let flow = &s["oauth2"]["flows"]["authorizationCode"];
assert_eq!(flow["tokenUrl"], "https://x/token");
assert_eq!(flow["authorizationUrl"], "https://x/authorize");
assert_eq!(flow["scopes"]["posts:read"], "Read posts");
let sec = &api["paths"]["/api/things"]["get"]["security"][0]["api_key"];
assert_eq!(*sec, serde_json::json!([]));
assert_eq!(
send(&r, req("GET", "/api/docs", &[], "")).await.status(),
200
);
let root = spec(&r, "/openapi.json").await;
assert!(root["paths"]["/hook"].is_object());
assert!(root["paths"]["/page"].is_null() && root["paths"]["/api/things"].is_null());
let r2 = App::new(())
.api(OpenApiRouter::new().routes(routes!(things)))
.document_web(true)
.web(OpenApiRouter::new().routes(routes!(page)))
.into_router();
let api2 = spec(&r2, "/api/openapi.json").await;
assert!(api2["components"]["securitySchemes"]["oauth2"].is_null());
let root2 = spec(&r2, "/openapi.json").await;
assert!(root2["paths"]["/page"].is_object() && root2["paths"]["/api/things"].is_null());
}
#[tokio::test]
async fn without_api_group_root_documents_everything() {
let r = App::new(())
.web(OpenApiRouter::new().routes(routes!(page)))
.public(OpenApiRouter::new().routes(routes!(hook)))
.into_router();
let root = spec(&r, "/openapi.json").await;
assert!(root["paths"]["/page"].is_object() && root["paths"]["/hook"].is_object());
assert_eq!(send(&r, req("GET", "/docs", &[], "")).await.status(), 200);
assert_eq!(
send(&r, req("GET", "/api/openapi.json", &[], ""))
.await
.status(),
404
);
}
#[test]
#[should_panic(expected = "under the api prefix")]
fn documented_web_route_under_prefix_panics() {
let _ = App::new(())
.web(OpenApiRouter::new().routes(routes!(clash)))
.api(OpenApiRouter::new().routes(routes!(things)))
.into_router();
}
}
}