use crate::{health::BoxFuture, proxy::ClientIp};
use axum::{
Json, Router,
extract::{FromRequestParts, Request, State},
http::{HeaderMap, HeaderName, HeaderValue, Method, StatusCode, header, request::Parts},
middleware::{Next, from_fn, from_fn_with_state},
response::{IntoResponse, Response},
};
use serde_json::json;
use std::{
collections::{BTreeMap, HashMap},
sync::{Arc, Mutex},
time::{Duration, Instant},
};
use tower_http::cors::{AllowOrigin, CorsLayer};
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum PrincipalKind {
ApiKey,
OAuthToken,
OAuthClient,
}
#[derive(Clone, Debug, PartialEq, Eq)]
pub struct Principal {
pub kind: PrincipalKind,
pub id: String,
pub user_id: Option<i64>,
pub client_id: Option<String>,
pub scopes: Vec<String>,
pub name: Option<String>,
}
impl Principal {
pub fn has(&self, scope: &str) -> bool {
self.scopes.iter().any(|g| {
g == scope
|| g == "*"
|| g.strip_suffix('*')
.is_some_and(|area| area.ends_with(':') && scope.starts_with(area))
})
}
pub fn require(&self, scope: &str) -> Result<(), ApiError> {
if self.has(scope) {
Ok(())
} else {
Err(ApiError::forbidden(scope))
}
}
}
#[derive(Clone, Debug)]
pub struct ApiError {
pub status: StatusCode,
pub code: &'static str,
pub message: String,
}
impl ApiError {
fn new(status: StatusCode, code: &'static str, message: impl Into<String>) -> Self {
ApiError {
status,
code,
message: message.into(),
}
}
pub fn unauthorized() -> Self {
Self::new(
StatusCode::UNAUTHORIZED,
"unauthorized",
"Authentication required",
)
}
pub fn forbidden(scope: &str) -> Self {
Self::new(
StatusCode::FORBIDDEN,
"insufficient_scope",
format!("Missing scope: {scope}"),
)
}
pub fn not_found() -> Self {
Self::new(StatusCode::NOT_FOUND, "not_found", "Not found")
}
pub fn bad_request(msg: impl Into<String>) -> Self {
Self::new(StatusCode::BAD_REQUEST, "bad_request", msg)
}
pub fn validation(errors: BTreeMap<String, Vec<String>>) -> Self {
let list: Vec<_> = errors
.iter()
.flat_map(|(f, m)| m.iter().map(move |m| format!("{f}: {m}")))
.collect();
Self::new(
StatusCode::UNPROCESSABLE_ENTITY,
"validation_failed",
list.join("; "),
)
}
pub fn internal() -> Self {
Self::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"Internal server error",
)
}
}
impl<E: std::error::Error> From<E> for ApiError {
fn from(e: E) -> Self {
tracing::error!("api handler error: {e}");
ApiError::internal()
}
}
impl IntoResponse for ApiError {
fn into_response(self) -> Response {
let mut res = (
self.status,
Json(json!({"error": {"code": self.code, "message": self.message}})),
)
.into_response();
if self.status == StatusCode::UNAUTHORIZED {
res.headers_mut()
.insert(header::WWW_AUTHENTICATE, HeaderValue::from_static("Bearer"));
}
res
}
}
pub trait TokenVerifier: Send + Sync + 'static {
fn verify<'a>(&'a self, bearer: &'a str) -> BoxFuture<'a, Option<Principal>>;
}
#[derive(Clone)]
struct ApiCtx(Option<Principal>);
fn ctx(parts: &Parts) -> Result<Option<Principal>, ApiError> {
match parts.extensions.get::<ApiCtx>() {
Some(c) => Ok(c.0.clone()),
None => {
tracing::error!("ApiAuth used outside the api group (mount the route with App::api)");
Err(ApiError::new(
StatusCode::INTERNAL_SERVER_ERROR,
"internal_error",
"ApiAuth used outside the api group",
))
}
}
}
pub struct ApiAuth(pub Principal);
pub struct OptionalApiAuth(pub Option<Principal>);
impl<S: Send + Sync> FromRequestParts<S> for ApiAuth {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
ctx(parts)?.map(ApiAuth).ok_or_else(ApiError::unauthorized)
}
}
impl<S: Send + Sync> FromRequestParts<S> for OptionalApiAuth {
type Rejection = ApiError;
async fn from_request_parts(parts: &mut Parts, _: &S) -> Result<Self, ApiError> {
ctx(parts).map(OptionalApiAuth)
}
}
fn bearer(h: &HeaderMap) -> Option<&str> {
let auth = h.get(header::AUTHORIZATION).and_then(|v| v.to_str().ok());
let tok = match auth.and_then(|a| a.split_once(' ')) {
Some((s, t)) if s.eq_ignore_ascii_case("bearer") => Some(t.trim()),
_ => h.get("x-api-key").and_then(|v| v.to_str().ok()),
};
tok.filter(|t| !t.is_empty())
}
#[derive(Clone, Default)]
pub struct Cors {
origins: Vec<String>,
headers: Vec<String>,
max_age: Option<Duration>,
}
impl Cors {
pub fn allow_origins(origins: &[&str]) -> Self {
Cors {
origins: origins.iter().map(|o| o.to_string()).collect(),
..Default::default()
}
}
pub fn allow_headers(mut self, headers: &[&str]) -> Self {
self.headers.extend(headers.iter().map(|h| h.to_string()));
self
}
pub fn max_age(mut self, d: Duration) -> Self {
self.max_age = Some(d);
self
}
fn layer(&self) -> CorsLayer {
let origin = if self.origins.iter().any(|o| o == "*") {
AllowOrigin::any()
} else {
AllowOrigin::list(self.origins.iter().map(|o| {
o.parse::<HeaderValue>()
.unwrap_or_else(|_| panic!("Cors: `{o}` is not a valid origin"))
}))
};
let name = |s: &str| {
s.parse::<HeaderName>()
.unwrap_or_else(|_| panic!("Cors: `{s}` is not a valid header name"))
};
let headers = ["authorization", "content-type", "x-api-key"]
.into_iter()
.map(name)
.chain(self.headers.iter().map(|h| name(h)))
.collect::<Vec<_>>();
let expose = [
"x-ratelimit-limit",
"x-ratelimit-remaining",
"x-ratelimit-reset",
"retry-after",
"x-request-id",
]
.map(name);
let l = CorsLayer::new()
.allow_origin(origin)
.allow_methods([
Method::GET,
Method::POST,
Method::PUT,
Method::PATCH,
Method::DELETE,
Method::HEAD,
Method::OPTIONS,
])
.allow_headers(headers)
.expose_headers(expose);
match self.max_age {
Some(d) => l.max_age(d),
None => l,
}
}
}
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct RateStatus {
pub limited: bool,
pub remaining: u32,
pub reset_in: Duration,
}
#[derive(Debug, thiserror::Error)]
#[error("rate limit store: {0}")]
pub struct RateError(pub String);
pub trait RateLimitStore: Send + Sync + 'static {
fn hit<'a>(
&'a self,
key: &'a str,
limit: u32,
window: Duration,
) -> BoxFuture<'a, Result<RateStatus, RateError>>;
}
#[derive(Default)]
pub struct MemoryRateLimit {
hits: Mutex<HashMap<String, (Instant, u32)>>,
}
impl RateLimitStore for MemoryRateLimit {
fn hit<'a>(
&'a self,
key: &'a str,
limit: u32,
window: Duration,
) -> BoxFuture<'a, Result<RateStatus, RateError>> {
let now = Instant::now();
let mut m = self.hits.lock().unwrap_or_else(|e| e.into_inner());
if m.len() > 10_000 {
m.retain(|_, (start, _)| now.duration_since(*start) < window);
}
let e = m.entry(key.to_owned()).or_insert((now, 0));
if now.duration_since(e.0) >= window {
*e = (now, 0);
}
let reset_in = window.saturating_sub(now.duration_since(e.0));
let limited = e.1 >= limit;
if !limited {
e.1 += 1;
}
let remaining = if limited { 0 } else { limit - e.1 };
Box::pin(std::future::ready(Ok(RateStatus {
limited,
remaining,
reset_in,
})))
}
}
#[cfg(feature = "db")]
pub mod api_rate_limits {
use sea_orm::entity::prelude::*;
#[derive(Clone, Debug, PartialEq, DeriveEntityModel)]
#[sea_orm(table_name = "api_rate_limits")]
pub struct Model {
#[sea_orm(
primary_key,
auto_increment = false,
column_type = "String(StringLen::N(255))"
)]
pub key: String,
pub hits: i64,
pub reset_at: i64,
}
#[derive(Copy, Clone, Debug, EnumIter, DeriveRelation)]
pub enum Relation {}
impl ActiveModelBehavior for ActiveModel {}
}
#[cfg(feature = "db")]
#[derive(Clone)]
pub struct DbRateLimit {
db: sea_orm::DatabaseConnection,
}
#[cfg(feature = "db")]
impl DbRateLimit {
pub fn new(db: sea_orm::DatabaseConnection) -> Self {
Self { db }
}
pub async fn ensure_tables(&self) -> Result<(), sea_orm::DbErr> {
use sea_orm::{ConnectionTrait, Schema};
let mut t = Schema::new(self.db.get_database_backend())
.create_table_from_entity(api_rate_limits::Entity);
self.db.execute(t.if_not_exists()).await?;
Ok(())
}
pub async fn prune(&self) -> Result<u64, sea_orm::DbErr> {
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter};
let r = api_rate_limits::Entity::delete_many()
.filter(api_rate_limits::Column::ResetAt.lte(chrono::Utc::now().timestamp()))
.exec(&self.db)
.await?;
Ok(r.rows_affected)
}
async fn hit_db(
&self,
key: &str,
limit: u32,
window: Duration,
) -> Result<RateStatus, sea_orm::DbErr> {
use api_rate_limits::{ActiveModel, Column, Entity};
use sea_orm::sea_query::Expr;
use sea_orm::{ActiveValue::Set, ColumnTrait, EntityTrait, ExprTrait, QueryFilter};
if key.len() > 255 {
return Err(sea_orm::DbErr::Custom(
"rate limit key over 255 bytes".into(),
));
}
let now = chrono::Utc::now().timestamp();
let win = std::cmp::max(window.as_secs(), 1) as i64;
Entity::insert(ActiveModel {
key: Set(key.into()),
hits: Set(0),
reset_at: Set(now + win),
})
.on_conflict_do_nothing()
.exec_without_returning(&self.db)
.await?;
Entity::update_many()
.col_expr(Column::Hits, Expr::value(0i64))
.col_expr(Column::ResetAt, Expr::value(now + win))
.filter(Column::Key.eq(key))
.filter(Column::ResetAt.lte(now))
.exec(&self.db)
.await?;
Entity::update_many()
.col_expr(Column::Hits, Expr::col(Column::Hits).add(1))
.filter(Column::Key.eq(key))
.exec(&self.db)
.await?;
let (hits, reset_at) = match Entity::find_by_id(key).one(&self.db).await? {
Some(r) => (r.hits, r.reset_at),
None => (1, now + win),
};
Ok(RateStatus {
limited: hits > limit as i64,
remaining: std::cmp::max(limit as i64 - hits, 0) as u32,
reset_in: Duration::from_secs(std::cmp::max(reset_at - now, 1) as u64),
})
}
}
#[cfg(feature = "db")]
impl RateLimitStore for DbRateLimit {
fn hit<'a>(
&'a self,
key: &'a str,
limit: u32,
window: Duration,
) -> BoxFuture<'a, Result<RateStatus, RateError>> {
Box::pin(async move {
self.hit_db(key, limit, window)
.await
.map_err(|e| RateError(e.to_string()))
})
}
}
#[derive(Clone)]
pub(crate) struct RateCfg {
pub store: Arc<dyn RateLimitStore>,
pub max: u32,
pub per: Duration,
pub fail_closed: bool,
}
fn parse_version(s: &str) -> Option<Vec<u64>> {
let core = s.trim().split(['-', '+']).next()?;
let parts: Vec<u64> = core
.split('.')
.map(|p| {
if p.is_empty() || !p.bytes().all(|b| b.is_ascii_digit()) {
return None;
}
p.parse().ok()
})
.collect::<Option<_>>()?;
(parts.len() <= 8).then_some(parts)
}
fn version_lt(a: &[u64], b: &[u64]) -> bool {
let at = |v: &[u64], i| v.get(i).copied().unwrap_or(0);
(0..a.len().max(b.len()))
.map(|i| (at(a, i), at(b, i)))
.find(|(x, y)| x != y)
.is_some_and(|(x, y)| x < y)
}
#[derive(Clone, Default)]
pub(crate) struct VersionGate {
pub min: Vec<(String, String, Vec<u64>)>,
pub require_headers: bool,
}
impl VersionGate {
pub(crate) fn set(&mut self, platform: &str, min: &str) {
let parsed = parse_version(min)
.unwrap_or_else(|| panic!("App::min_app_version: `{min}` is not a dotted version"));
let p = platform.trim().to_ascii_lowercase();
self.min.retain(|(q, ..)| *q != p);
self.min.push((p, min.to_owned(), parsed));
}
fn active(&self) -> bool {
!self.min.is_empty() || self.require_headers
}
}
async fn version_gate(State(g): State<Arc<VersionGate>>, req: Request, next: Next) -> Response {
match upgrade_error(&g, req.headers()) {
Some(res) => res,
None => next.run(req).await,
}
}
fn upgrade_error(g: &VersionGate, h: &HeaderMap) -> Option<Response> {
let hv = |n: &str| h.get(n).and_then(|v| v.to_str().ok());
let (platform, ver) = (
hv("x-app-platform"),
hv("x-app-version").and_then(parse_version),
);
if g.require_headers && (platform.is_none() || ver.is_none()) {
return Some(
ApiError::bad_request("X-App-Platform and X-App-Version headers are required")
.into_response(),
);
}
let (p, v) = (platform?.trim().to_ascii_lowercase(), ver?);
let (_, min, minv) = g.min.iter().find(|(q, ..)| *q == p)?;
if !version_lt(&v, minv) {
return None;
}
let mut r = (
StatusCode::UPGRADE_REQUIRED,
Json(json!({"error": {
"code": "upgrade_required",
"message": format!("Update the app to {min} or newer"),
"min_version": min, "platform": p,
}})),
)
.into_response();
if let Ok(h) = HeaderValue::from_str(min) {
r.headers_mut().insert("x-min-app-version", h);
}
Some(r)
}
type Verifiers = Arc<Vec<Arc<dyn TokenVerifier>>>;
#[derive(Clone)]
struct Guard {
verifiers: Verifiers,
limit: RateCfg,
public: bool,
}
fn limit_key(p: Option<&Principal>, ip: Option<std::net::IpAddr>, public: bool) -> String {
let pre = if public { "public:" } else { "" };
match (p, ip) {
(Some(p), _) => format!("principal:{:?}:{}", p.kind, p.id),
(None, Some(ip)) => format!("{pre}ip:{}", crate::proxy::ip_bucket(ip)),
(None, None) => format!("{pre}ip:unknown"),
}
}
async fn guard(State(g): State<Guard>, ip: ClientIp, mut req: Request, next: Next) -> Response {
let mut principal = None;
if let Some(tok) = bearer(req.headers()).filter(|_| !g.public) {
for v in g.verifiers.iter() {
if let Some(p) = v.verify(tok).await {
principal = Some(p);
break;
}
}
}
let key = limit_key(principal.as_ref(), ip.0, g.public);
if !g.public {
req.extensions_mut().insert(ApiCtx(principal));
}
let st = match g.limit.store.hit(&key, g.limit.max, g.limit.per).await {
Ok(st) => st,
Err(e) if g.limit.fail_closed => {
tracing::error!("{e}: rejecting the request (fail closed)");
return ApiError::new(
StatusCode::SERVICE_UNAVAILABLE,
"rate_limit_unavailable",
"Service temporarily unavailable",
)
.into_response();
}
Err(e) => {
tracing::error!("{e}: letting the request through (fail open)");
return next.run(req).await;
}
};
let reset = st.reset_in.as_secs_f64().ceil() as u64;
let mut res = if !st.limited {
next.run(req).await
} else {
let mut r = (
StatusCode::TOO_MANY_REQUESTS,
Json(json!({"error": {"code": "rate_limited", "message": "Too many requests"}})),
)
.into_response();
r.headers_mut().insert(header::RETRY_AFTER, reset.into());
r
};
let h = res.headers_mut();
h.entry(header::CACHE_CONTROL)
.or_insert(header::HeaderValue::from_static("no-store"));
h.append(
header::VARY,
header::HeaderValue::from_static("Authorization"),
);
h.insert("x-ratelimit-limit", g.limit.max.into());
h.insert("x-ratelimit-remaining", st.remaining.into());
h.insert("x-ratelimit-reset", reset.into());
res
}
fn is_json(h: &HeaderMap) -> bool {
h.get(header::CONTENT_TYPE)
.and_then(|v| v.to_str().ok())
.is_some_and(|v| v.contains("json"))
}
async fn json_errors(req: Request, next: Next) -> Response {
let res = next.run(req).await;
let st = res.status();
if !(st.is_client_error() || st.is_server_error()) || is_json(res.headers()) {
return res;
}
let (parts, body) = res.into_parts();
let text = axum::body::to_bytes(body, 1024)
.await
.ok()
.and_then(|b| String::from_utf8(b.to_vec()).ok())
.unwrap_or_default();
let reason = st.canonical_reason().unwrap_or("Error");
let err = match st.as_u16() {
500 if text.contains("SessionManagerLayer") => ApiError::new(
StatusCode::UNAUTHORIZED,
"unauthorized",
"session auth is not available on api routes",
),
c if c >= 500 => ApiError::new(st, "internal_error", reason),
c => {
let code = match c {
400 => "bad_request",
401 => "unauthorized",
403 => "forbidden",
404 => "not_found",
405 => "method_not_allowed",
408 => "request_timeout",
413 => "payload_too_large",
415 => "unsupported_media_type",
422 => "unprocessable_entity",
429 => "rate_limited",
_ => "error",
};
ApiError::new(st, code, if text.is_empty() { reason.into() } else { text })
}
};
let mut out = err.into_response();
for (k, v) in &parts.headers {
if k != header::CONTENT_TYPE && k != header::CONTENT_LENGTH {
out.headers_mut().entry(k).or_insert_with(|| v.clone());
}
}
out
}
pub(crate) fn wrap_api(
r: Router,
verifiers: Verifiers,
limit: RateCfg,
gate: VersionGate,
cors: Option<&Cors>,
harden: impl FnOnce(Router) -> Router,
) -> Router {
let mut r = r.layer(from_fn_with_state(
Guard {
verifiers,
limit,
public: false,
},
guard,
));
if gate.active() {
r = r.layer(from_fn_with_state(Arc::new(gate), version_gate));
}
wrap(harden(r), cors)
}
pub(crate) fn wrap_public(
r: Router,
limit: RateCfg,
cors: Option<&Cors>,
harden: impl FnOnce(Router) -> Router,
) -> Router {
let g = Guard {
verifiers: Arc::new(vec![]),
limit,
public: true,
};
wrap(harden(r.layer(from_fn_with_state(g, guard))), cors)
}
fn wrap(r: Router, cors: Option<&Cors>) -> Router {
let r = r.layer(from_fn(json_errors));
match cors {
Some(c) => r.layer(c.layer()),
None => r,
}
}
pub(crate) fn paths<S>(r: &Router<S>) -> Vec<String> {
let dbg = format!("{r:?}");
let dbg = dbg.split("fallback_router").next().unwrap_or("");
let mut out = vec![];
let mut rest = dbg;
while let Some(i) = rest.find("): \"") {
rest = &rest[i + 4..];
if let Some(end) = rest.find('"') {
out.push(rest[..end].to_owned());
rest = &rest[end..];
}
}
out
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn limit_key_uses_ip_bucket() {
let k = |s: &str, public| limit_key(None, Some(s.parse().unwrap()), public);
assert_eq!(k("2001:db8:1:2::1", false), k("2001:db8:1:2::9", false));
assert_ne!(k("2001:db8:1:2::1", false), k("2001:db8:1:3::1", false));
assert_eq!(k("::ffff:1.2.3.4", false), "ip:1.2.3.4");
assert_eq!(k("1.2.3.4", true), "public:ip:1.2.3.4");
}
fn p(scopes: &[&str]) -> Principal {
Principal {
kind: PrincipalKind::ApiKey,
id: "k1".into(),
user_id: Some(1),
client_id: None,
scopes: scopes.iter().map(|s| s.to_string()).collect(),
name: None,
}
}
#[test]
fn scope_wildcards() {
assert!(p(&["posts:read"]).has("posts:read"));
assert!(!p(&["posts:read"]).has("posts:write"));
assert!(p(&["*"]).has("anything:at:all"));
assert!(p(&["posts:*"]).has("posts:write") && p(&["posts:*"]).has("posts:a:b"));
assert!(!p(&["posts:*"]).has("postsx:write") && !p(&["posts:*"]).has("users:read"));
assert!(
!p(&["pos*"]).has("posts:read"),
"wildcard must end at a colon"
);
assert!(!p(&[]).has("x"));
let e = p(&["a:b"]).require("a:c").unwrap_err();
assert_eq!(
(e.status, e.code),
(StatusCode::FORBIDDEN, "insufficient_scope")
);
assert!(p(&["a:*"]).require("a:c").is_ok());
}
#[test]
fn bearer_forms() {
let h = |k: &str, v: &str| {
let mut m = HeaderMap::new();
m.insert(
HeaderName::from_bytes(k.as_bytes()).unwrap(),
v.parse().unwrap(),
);
m
};
assert_eq!(bearer(&h("authorization", "Bearer abc")), Some("abc"));
assert_eq!(bearer(&h("authorization", "bearer abc")), Some("abc"));
assert_eq!(bearer(&h("x-api-key", "abc")), Some("abc"));
assert_eq!(bearer(&h("authorization", "Basic abc")), None);
assert_eq!(bearer(&h("authorization", "Bearer ")), None);
}
#[tokio::test]
async fn fixed_window() {
let rl = MemoryRateLimit::default();
let w = Duration::from_millis(80);
assert!(!rl.hit("a", 2, w).await.unwrap().limited);
let s = rl.hit("a", 2, w).await.unwrap();
assert!(!s.limited && s.remaining == 0);
assert!(rl.hit("a", 2, w).await.unwrap().limited);
assert!(
!rl.hit("b", 2, w).await.unwrap().limited,
"keys are independent"
);
tokio::time::sleep(Duration::from_millis(100)).await;
assert!(!rl.hit("a", 2, w).await.unwrap().limited, "window reset");
}
#[test]
fn versions() {
let lt =
|a: &str, b: &str| version_lt(&parse_version(a).unwrap(), &parse_version(b).unwrap());
assert!(lt("1.9.3", "1.10.0") && !lt("1.10.0", "1.9.3"));
assert!(!lt("1.4", "1.4.0") && !lt("1.4.0", "1.4") && lt("1.4", "1.4.1"));
assert!(!lt("2.0.0-beta.1", "2.0") && !lt("2.0+build7", "2.0.0") && lt("1", "2"));
for bad in [
"",
".",
"1..2",
"a.b",
"-1",
"1.-2",
"1.2.3.4.5.6.7.8.9",
"99999999999999999999999",
"\u{0}",
"\u{ff11}.\u{ff12}",
"v1.2",
" ",
] {
assert_eq!(parse_version(bad), None, "{bad:?}");
}
let mut x = 0x2545F491u32;
for _ in 0..2000 {
let n = x % 12;
let s: String = (0..n)
.map(|_| {
x = x.wrapping_mul(1664525).wrapping_add(1013904223);
char::from_u32((x >> 16) % 0x300).unwrap_or('?')
})
.collect();
let _ = parse_version(&s);
}
}
#[cfg(feature = "sqlite")]
async fn dbs() -> Vec<(&'static str, sea_orm::DatabaseConnection)> {
let path = std::env::temp_dir().join(format!(
"ryuk-rate-{}.db",
std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos()
));
let url = format!("sqlite://{}?mode=rwc", path.display());
#[allow(unused_mut)]
let mut v = vec![("sqlite", sea_orm::Database::connect(url).await.unwrap())];
#[cfg(feature = "postgres")]
if let Ok(url) = std::env::var("TEST_POSTGRES_URL") {
v.push(("postgres", sea_orm::Database::connect(url).await.unwrap()));
}
#[cfg(feature = "mysql")]
if let Ok(url) = std::env::var("TEST_MYSQL_URL") {
v.push(("mysql", sea_orm::Database::connect(url).await.unwrap()));
}
v
}
#[cfg(feature = "sqlite")]
#[tokio::test]
async fn db_store_limits_resets_and_counts_concurrent_hits() {
use sea_orm::{ColumnTrait, EntityTrait, QueryFilter, sea_query::Expr};
let uniq = std::time::SystemTime::now()
.duration_since(std::time::UNIX_EPOCH)
.unwrap()
.as_nanos();
for (name, db) in dbs().await {
let s = DbRateLimit::new(db.clone());
s.ensure_tables().await.unwrap();
s.ensure_tables().await.unwrap();
let w = Duration::from_secs(60);
let k = format!("seq-{name}-{uniq}");
for i in (0..3).rev() {
let st = s.hit(&k, 3, w).await.unwrap();
assert!(!st.limited && st.remaining == i, "{name}");
assert!((1..=60).contains(&st.reset_in.as_secs()), "{name}");
}
let st = s.hit(&k, 3, w).await.unwrap();
assert!(st.limited && st.remaining == 0, "{name}");
api_rate_limits::Entity::update_many()
.col_expr(api_rate_limits::Column::ResetAt, Expr::value(1i64))
.filter(api_rate_limits::Column::Key.eq(&k))
.exec(&db)
.await
.unwrap();
let st = s.hit(&k, 3, w).await.unwrap();
assert!(!st.limited && st.remaining == 2, "{name} window reset");
let k = format!("conc-{name}-{uniq}");
let hs: Vec<_> = (0..50)
.map(|_| {
let (s, k) = (s.clone(), k.clone());
tokio::spawn(async move { s.hit(&k, 1000, w).await })
})
.collect();
for h in hs {
assert!(!h.await.unwrap().unwrap().limited);
}
let row = api_rate_limits::Entity::find_by_id(&k)
.one(&db)
.await
.unwrap()
.unwrap();
assert_eq!(row.hits, 50, "{name}");
api_rate_limits::Entity::update_many()
.col_expr(api_rate_limits::Column::ResetAt, Expr::value(1i64))
.filter(api_rate_limits::Column::Key.eq(format!("seq-{name}-{uniq}")))
.exec(&db)
.await
.unwrap();
assert!(s.prune().await.unwrap() >= 1);
assert!(
api_rate_limits::Entity::find_by_id(&k)
.one(&db)
.await
.unwrap()
.is_some(),
"{name}"
);
assert!(s.hit(&"x".repeat(256), 1, w).await.is_err());
}
}
}