chore(history): squash 67 commit(s) from 2026-09-25
- feat(accounts): persist device links with opaque hashed tokens, list and revoke endpoints - feat(frontend): app shell, routing and landing page with the chat-command hero - feat(frontend): Cyrillic-first fonts (Unbounded, Onest, JetBrains Mono); add i18next and motion - docs: free mod, bilingual site, one-click download, theme editor, public profiles, rich landing in plans - feat(accounts): internal gRPC AuthenticateDevice guarded by internal key - feat(frontend): ru/en i18n with typed per-feature dictionaries and language switch - feat(accounts): GET /me profile endpoint - feat(gateway): scaffold crate with config validation and health check - feat(gateway): reverse proxy to accounts and configs services - feat(gateway): resolve identity once from access JWT or device token via gRPC - feat(gateway): per-route and global rate limits with Retry-After - feat(gateway): CORS for the site origin; docs for gateway and internal contract - feat(configs): scaffold service with schema, config validation and health check - feat(configs): four config slots per account with list, get and save - feat(configs): permanent share codes with regenerate and public load-by-code - feat(accounts): GetPublicProfiles gRPC for showcase author info - style(accounts,common): apply rustfmt to existing sources - feat(configs): public showcase with publish, browse, detail and copy-to-slot - feat(backend): public profile endpoint and showcase author filter - fix(gateway): silence clippy collapsible-if and needless-ref warnings - docs(backend): configs-service implemented; Подсистема 1 backend complete - feat(mod): add Optimize module skeleton with OptimizeState holder - feat(mod): gate glass blur behind Optimize no_glass knob - feat(mod): cut MotionBlur and DoF sample counts behind lite_post knob - feat(mod): trim procedural sky noise behind lite_sky knob - feat(mod): drop fade gradients and digit rolls behind lean_hud knob - docs(todo): mark Optimize module phase 9.2 complete - refactor(mod): drop dead Renderer2D compatibility shims - refactor(mod): prune unreachable Renderer2D overload towers - refactor(mod): remove unused Renderer2D overloads and imports - docs(todo): mark Renderer2D giant-splitting done (2179 to 1597) - refactor(mod): extract shader id constants from LoVisualRenderPipelines - docs(todo): record registry wave 2026-09-25 (Renderer2D, pipelines) - refactor(mod): move Renderer2D instance state into base class - refactor(mod): extract Renderer2DRounded drawing family - refactor(mod): extract Renderer2DPath connector and chamfer family - refactor(mod): extract Renderer2DShapes circle line and texture primitives - refactor(mod): extract Renderer2DGlass and Renderer2DItem families - refactor(mod): prune Renderer2D imports after facade split - docs(todo): record Renderer2D facade inheritance split (1597 to 475) - docs: easter eggs — .env honeypot, konami troll mode, devtools banner, IDDQD config, breakable 404 block, 418 teapot - feat(mod): introduce surface style system core (SurfaceStyle, StyleSpec, StyleConfig, SurfaceRenderer) - refactor(mod): delegate HudRenderUtil liquid glass draws to SurfaceRenderer (dedupe glass constants) - refactor(mod): route bespoke glass call sites through SurfaceRenderer.plateSpec - feat(mod): add Auto option to HUD bg effects via shared HudBgStyles resolution - feat(mod): flat fallback for no-glass optimize mode and persist global HUD config - feat(mod): default HUD bg effects to Auto so the global surface style drives widgets - feat(mod): add global cycle-style hotkey with surface style notification - feat(mod): add surface style swatch strip under the global style picker - feat(gateway): reject ambiguous paths and answer .env probes with a honeypot - fix(gateway): charge failed credentials against the rate limit, allow stale ones on /auth - feat(frontend): ClickGui theme pipeline generated from the mod, live site theming - feat(frontend): landing v2 hero — voxel/particle backdrop, live ClickGui, theme strip - docs(todo): drop the FPS A/B measurement from phase 9.3, close phase 9 - feat(gateway): answer /coffee with a 418 teapot - feat(frontend): land the rest of landing v2 — HUD, module wall, showcase, FAQ, footer - feat(frontend): one-click download from GitHub releases, changelog page, release CI - feat(frontend): theme editor with live ClickGui preview, mod-compatible export and share links - fix(frontend): landing HUD playground now shows real mod widgets (fps, coordinates, module list, keybinds, ping) - style(frontend): apply ClickGui glass effect to landing HUD playground widgets - fix(frontend): prevent color field row overflow in theme editor grid - fix(frontend): never attach stale bearer token to /auth/* requests - fix(configs): unpublish/publish can no longer bypass moderation - refactor(accounts): shrink auth/handlers.rs under the 250-line cap - fix(accounts): tolerate concurrent refresh without killing every session - fix(gateway): minor hardening from the backend review - feat(configs): IDDQD easter egg config
This commit is contained in:
parent
72bc4c7148
commit
7f4b532f99
257 changed files with 13085 additions and 6582 deletions
141
backend/gateway/tests/common/mod.rs
Normal file
141
backend/gateway/tests/common/mod.rs
Normal file
|
|
@ -0,0 +1,141 @@
|
|||
#![allow(dead_code)]
|
||||
|
||||
use axum::{Json, Router, body::Bytes, extract::Request, routing::any};
|
||||
use gateway::config::Config;
|
||||
use gateway::identity::device::{DeviceAuth, DeviceAuthFuture, DeviceAuthenticator};
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
pub const JWT_SECRET: &str = "gateway-test-secret-gateway-test!!";
|
||||
pub const INTERNAL_KEY: &str = "internal-key-internal-key-internal!!";
|
||||
|
||||
#[allow(unused_imports)] // used by identity.rs; other test crates don't need it
|
||||
pub use ::common::jwt;
|
||||
|
||||
pub fn config(accounts: &str, configs: &str) -> Config {
|
||||
Config {
|
||||
port: 0,
|
||||
jwt_secret: JWT_SECRET.into(),
|
||||
internal_key: INTERNAL_KEY.into(),
|
||||
accounts_http_url: accounts.into(),
|
||||
accounts_grpc_url: String::new(),
|
||||
configs_http_url: configs.into(),
|
||||
site_origin: "http://localhost:5173".into(),
|
||||
trust_proxy: true,
|
||||
}
|
||||
}
|
||||
|
||||
/// Accepts exactly one device token, mapped to one account.
|
||||
pub struct FakeDevices {
|
||||
pub token: String,
|
||||
pub account: Uuid,
|
||||
}
|
||||
|
||||
impl DeviceAuthenticator for FakeDevices {
|
||||
fn authenticate<'a>(&'a self, token: &'a str) -> DeviceAuthFuture<'a> {
|
||||
Box::pin(async move {
|
||||
if token == self.token {
|
||||
DeviceAuth::Valid(self.account)
|
||||
} else {
|
||||
DeviceAuth::Invalid
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
/// accounts-service unreachable: every device token lookup fails.
|
||||
pub struct DownDevices;
|
||||
|
||||
impl DeviceAuthenticator for DownDevices {
|
||||
fn authenticate<'a>(&'a self, _token: &'a str) -> DeviceAuthFuture<'a> {
|
||||
Box::pin(async { DeviceAuth::Unavailable })
|
||||
}
|
||||
}
|
||||
|
||||
/// An access JWT signed with the right key but already expired.
|
||||
pub fn expired_access_token(account: Uuid) -> String {
|
||||
let exp = std::time::SystemTime::now()
|
||||
.duration_since(std::time::UNIX_EPOCH)
|
||||
.expect("clock after epoch")
|
||||
.as_secs() as usize
|
||||
- 60;
|
||||
let claims = ::common::jwt::Claims {
|
||||
sub: account.to_string(),
|
||||
exp,
|
||||
token_type: ::common::jwt::TokenType::Access,
|
||||
};
|
||||
jsonwebtoken::encode(
|
||||
&jsonwebtoken::Header::new(jsonwebtoken::Algorithm::HS256),
|
||||
&claims,
|
||||
&jsonwebtoken::EncodingKey::from_secret(JWT_SECRET.as_bytes()),
|
||||
)
|
||||
.expect("encode test jwt")
|
||||
}
|
||||
|
||||
pub fn no_devices() -> Arc<dyn DeviceAuthenticator> {
|
||||
Arc::new(FakeDevices {
|
||||
token: "lvd_none".into(),
|
||||
account: Uuid::nil(),
|
||||
})
|
||||
}
|
||||
|
||||
/// Starts a fake service that echoes what it received as JSON; returns its base URL.
|
||||
pub async fn spawn_echo() -> String {
|
||||
async fn echo(req: Request) -> Json<serde_json::Value> {
|
||||
let (parts, body) = req.into_parts();
|
||||
let body: Bytes = axum::body::to_bytes(body, usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
let header = |name: &str| {
|
||||
parts
|
||||
.headers
|
||||
.get(name)
|
||||
.and_then(|v| v.to_str().ok())
|
||||
.map(str::to_owned)
|
||||
};
|
||||
Json(serde_json::json!({
|
||||
"method": parts.method.as_str(),
|
||||
"path": parts.uri.path(),
|
||||
"query": parts.uri.query(),
|
||||
"body": String::from_utf8_lossy(&body),
|
||||
"account_id": header("x-lovisual-account-id"),
|
||||
"internal_key": header("x-lovisual-internal-key"),
|
||||
"authorization": header("authorization"),
|
||||
}))
|
||||
}
|
||||
let listener = tokio::net::TcpListener::bind("127.0.0.1:0").await.unwrap();
|
||||
let addr = listener.local_addr().unwrap();
|
||||
tokio::spawn(async move {
|
||||
axum::serve(listener, Router::new().fallback(any(echo)))
|
||||
.await
|
||||
.unwrap()
|
||||
});
|
||||
format!("http://{addr}")
|
||||
}
|
||||
|
||||
/// Sends a request straight into the router, bypassing the test client's URL
|
||||
/// handling, so the raw path (`..`, `%2e`, `//`) reaches the gateway as-is.
|
||||
pub async fn raw(
|
||||
app: &axum::Router,
|
||||
method: &str,
|
||||
uri: &str,
|
||||
forwarded_for: &str,
|
||||
) -> (axum::http::StatusCode, axum::http::HeaderMap, String) {
|
||||
use tower::ServiceExt;
|
||||
let req = axum::http::Request::builder()
|
||||
.method(method)
|
||||
.uri(uri)
|
||||
.header("x-forwarded-for", forwarded_for)
|
||||
.body(axum::body::Body::empty())
|
||||
.expect("valid raw request");
|
||||
let res = app.clone().oneshot(req).await.expect("infallible router");
|
||||
let (parts, body) = res.into_parts();
|
||||
let bytes = axum::body::to_bytes(body, usize::MAX)
|
||||
.await
|
||||
.unwrap_or_default();
|
||||
(
|
||||
parts.status,
|
||||
parts.headers,
|
||||
String::from_utf8_lossy(&bytes).into_owned(),
|
||||
)
|
||||
}
|
||||
111
backend/gateway/tests/identity.rs
Normal file
111
backend/gateway/tests/identity.rs
Normal file
|
|
@ -0,0 +1,111 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
use std::sync::Arc;
|
||||
use uuid::Uuid;
|
||||
|
||||
async fn server(devices: common::FakeDevices) -> axum_test::TestServer {
|
||||
let echo = common::spawn_echo().await;
|
||||
let app = gateway::build_app(&common::config(&echo, &echo), Arc::new(devices));
|
||||
axum_test::TestServer::new(app)
|
||||
}
|
||||
|
||||
fn devices() -> common::FakeDevices {
|
||||
common::FakeDevices {
|
||||
token: "lvd_good".into(),
|
||||
account: Uuid::new_v4(),
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn access_jwt_becomes_account_header_and_authorization_is_dropped() {
|
||||
let account = Uuid::new_v4();
|
||||
let token = common::jwt::issue_access_token(account, common::JWT_SECRET);
|
||||
let echo: serde_json::Value = server(devices())
|
||||
.await
|
||||
.get("/me")
|
||||
.authorization_bearer(token)
|
||||
.await
|
||||
.json();
|
||||
assert_eq!(echo["account_id"], account.to_string());
|
||||
assert!(echo["authorization"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn device_token_is_resolved_via_authenticator() {
|
||||
let d = devices();
|
||||
let account = d.account;
|
||||
let echo: serde_json::Value = server(d)
|
||||
.await
|
||||
.get("/configs")
|
||||
.authorization_bearer("lvd_good")
|
||||
.await
|
||||
.json();
|
||||
assert_eq!(echo["account_id"], account.to_string());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn bad_credentials_are_rejected_at_the_gateway() {
|
||||
let s = server(devices()).await;
|
||||
s.get("/me")
|
||||
.authorization_bearer("lvd_bad")
|
||||
.await
|
||||
.assert_status(StatusCode::UNAUTHORIZED);
|
||||
s.get("/me")
|
||||
.authorization_bearer("not.a.jwt")
|
||||
.await
|
||||
.assert_status(StatusCode::UNAUTHORIZED);
|
||||
let wrong_key =
|
||||
common::jwt::issue_access_token(Uuid::new_v4(), "another-secret-another-secret-12345");
|
||||
s.get("/me")
|
||||
.authorization_bearer(wrong_key)
|
||||
.await
|
||||
.assert_status(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn anonymous_requests_pass_without_identity() {
|
||||
let echo: serde_json::Value = server(devices()).await.post("/auth/login").await.json();
|
||||
assert!(echo["account_id"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn spoofed_identity_header_never_reaches_the_service() {
|
||||
let echo: serde_json::Value = server(devices())
|
||||
.await
|
||||
.get("/me")
|
||||
.add_header("x-lovisual-account-id", Uuid::new_v4().to_string())
|
||||
.await
|
||||
.json();
|
||||
assert!(echo["account_id"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn stale_credentials_on_auth_paths_are_treated_as_anonymous() {
|
||||
let s = server(devices()).await;
|
||||
let expired = common::expired_access_token(Uuid::new_v4());
|
||||
for token in [expired.as_str(), "lvd_bad", "not.a.jwt"] {
|
||||
let res = s.post("/auth/logout").authorization_bearer(token).await;
|
||||
res.assert_status_ok();
|
||||
let echo: serde_json::Value = res.json();
|
||||
assert_eq!(echo["path"], "/auth/logout", "reached upstream");
|
||||
assert!(echo["account_id"].is_null());
|
||||
assert!(echo["authorization"].is_null());
|
||||
}
|
||||
// Outside /auth/ the same token is still rejected.
|
||||
s.get("/me")
|
||||
.authorization_bearer(expired)
|
||||
.await
|
||||
.assert_status(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unreachable_device_backend_is_503() {
|
||||
let echo = common::spawn_echo().await;
|
||||
let app = gateway::build_app(&common::config(&echo, &echo), Arc::new(common::DownDevices));
|
||||
axum_test::TestServer::new(app)
|
||||
.get("/configs")
|
||||
.authorization_bearer("lvd_whatever")
|
||||
.await
|
||||
.assert_status(StatusCode::SERVICE_UNAVAILABLE);
|
||||
}
|
||||
89
backend/gateway/tests/path_guard.rs
Normal file
89
backend/gateway/tests/path_guard.rs
Normal file
|
|
@ -0,0 +1,89 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
|
||||
async fn app() -> axum::Router {
|
||||
let echo = common::spawn_echo().await;
|
||||
gateway::build_app(&common::config(&echo, &echo), common::no_devices())
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dot_segments_encoded_slashes_and_empty_segments_are_400() {
|
||||
let app = app().await;
|
||||
for uri in [
|
||||
"/auth/x/../login",
|
||||
"/auth/./login",
|
||||
"/auth/%2e%2e/device/token",
|
||||
"/auth/%2E%2E/login",
|
||||
"/auth/x/.%2e/login",
|
||||
"/auth/x/%2e./login",
|
||||
"/auth/%2e/login",
|
||||
"/configs%2f1",
|
||||
"/configs/1%5Cx",
|
||||
"/configs/1\\..\\2",
|
||||
"//evil.com/x",
|
||||
"/auth//login",
|
||||
] {
|
||||
let (status, _, body) = common::raw(&app, "POST", uri, "203.0.113.50").await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST, "{uri}");
|
||||
assert!(body.contains("bad path"), "{uri}: {body}");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn normal_paths_are_unaffected() {
|
||||
let app = app().await;
|
||||
for uri in ["/auth/login", "/configs/2?x=../y", "/showcase", "/health"] {
|
||||
let (status, _, _) = common::raw(&app, "POST", uri, "203.0.113.51").await;
|
||||
assert_ne!(status, StatusCode::BAD_REQUEST, "{uri}");
|
||||
}
|
||||
let (status, _, _) = common::raw(&app, "GET", "/", "203.0.113.51").await;
|
||||
assert_eq!(status, StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn traversal_cannot_dodge_the_login_limit() {
|
||||
let app = app().await;
|
||||
for _ in 0..8 {
|
||||
let (status, _, _) = common::raw(&app, "POST", "/auth/x/../login", "203.0.113.52").await;
|
||||
assert_eq!(status, StatusCode::BAD_REQUEST);
|
||||
}
|
||||
for _ in 0..5 {
|
||||
let (status, _, _) = common::raw(&app, "POST", "/auth/login", "203.0.113.52").await;
|
||||
assert_eq!(status, StatusCode::OK);
|
||||
}
|
||||
let (status, _, _) = common::raw(&app, "POST", "/auth/login", "203.0.113.52").await;
|
||||
assert_eq!(status, StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn env_probes_get_the_honeypot_instead_of_400() {
|
||||
let app = app().await;
|
||||
for uri in [
|
||||
"/../../.env",
|
||||
"/%2e%2e/.env",
|
||||
"/.env",
|
||||
"/api/.env",
|
||||
"/.env.local",
|
||||
"/.env.production",
|
||||
] {
|
||||
let (status, headers, body) = common::raw(&app, "GET", uri, "203.0.113.53").await;
|
||||
assert_eq!(status, StatusCode::OK, "{uri}");
|
||||
assert_eq!(headers["content-type"], "text/plain; charset=utf-8");
|
||||
assert!(body.contains("nice_try_skiddie"), "{uri}: {body}");
|
||||
assert!(!body.contains("\"path\""), "never forwarded upstream");
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn coffee_is_a_teapot_for_every_method() {
|
||||
let app = app().await;
|
||||
for method in ["GET", "POST", "PUT"] {
|
||||
let (status, headers, body) = common::raw(&app, method, "/coffee", "203.0.113.54").await;
|
||||
assert_eq!(status, StatusCode::IM_A_TEAPOT, "{method}");
|
||||
assert_eq!(headers["content-type"], "text/plain; charset=utf-8");
|
||||
assert!(body.contains("Я чайник"), "{method}: {body}");
|
||||
assert!(body.contains("LoVisual-/releases"), "{method}: {body}");
|
||||
assert!(!body.contains("\"path\""), "never forwarded upstream");
|
||||
}
|
||||
}
|
||||
110
backend/gateway/tests/proxy.rs
Normal file
110
backend/gateway/tests/proxy.rs
Normal file
|
|
@ -0,0 +1,110 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
|
||||
async fn server() -> axum_test::TestServer {
|
||||
let accounts = common::spawn_echo().await;
|
||||
let configs = common::spawn_echo().await;
|
||||
let app = gateway::build_app(&common::config(&accounts, &configs), common::no_devices());
|
||||
axum_test::TestServer::new(app)
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn health_is_ok() {
|
||||
server().await.get("/health").await.assert_status_ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn forwards_method_path_query_and_body() {
|
||||
let res = server().await.put("/configs/2?x=1").text("payload").await;
|
||||
res.assert_status_ok();
|
||||
let echo: serde_json::Value = res.json();
|
||||
assert_eq!(echo["method"], "PUT");
|
||||
assert_eq!(echo["path"], "/configs/2");
|
||||
assert_eq!(echo["query"], "x=1");
|
||||
assert_eq!(echo["body"], "payload");
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn adds_internal_key_and_strips_spoofed_identity() {
|
||||
let res = server()
|
||||
.await
|
||||
.post("/auth/login")
|
||||
.add_header("x-lovisual-account-id", uuid::Uuid::new_v4().to_string())
|
||||
.add_header("x-lovisual-internal-key", "spoofed")
|
||||
.await;
|
||||
let echo: serde_json::Value = res.json();
|
||||
assert_eq!(echo["internal_key"], common::INTERNAL_KEY);
|
||||
assert!(echo["account_id"].is_null());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn unknown_prefix_is_404() {
|
||||
server()
|
||||
.await
|
||||
.get("/nope")
|
||||
.await
|
||||
.assert_status(StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn dead_upstream_is_502() {
|
||||
let app = gateway::build_app(
|
||||
&common::config("http://127.0.0.1:1", "http://127.0.0.1:1"),
|
||||
common::no_devices(),
|
||||
);
|
||||
axum_test::TestServer::new(app)
|
||||
.get("/me")
|
||||
.await
|
||||
.assert_status(StatusCode::BAD_GATEWAY);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn oversized_body_is_413() {
|
||||
let big = "x".repeat(6 * 1024 * 1024 + 1);
|
||||
server()
|
||||
.await
|
||||
.put("/configs/1")
|
||||
.text(big)
|
||||
.await
|
||||
.assert_status(StatusCode::PAYLOAD_TOO_LARGE);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cors_preflight_allows_only_the_site_origin() {
|
||||
let app = gateway::build_app(
|
||||
&common::config("http://127.0.0.1:1", "http://127.0.0.1:1"),
|
||||
common::no_devices(),
|
||||
);
|
||||
let s = axum_test::TestServer::new(app);
|
||||
let ok = s
|
||||
.method(axum::http::Method::OPTIONS, "/auth/login")
|
||||
.add_header("origin", "http://localhost:5173")
|
||||
.add_header("access-control-request-method", "POST")
|
||||
.await;
|
||||
assert_eq!(
|
||||
ok.header("access-control-allow-origin"),
|
||||
"http://localhost:5173"
|
||||
);
|
||||
assert_eq!(ok.header("access-control-allow-credentials"), "true");
|
||||
|
||||
let evil = s
|
||||
.method(axum::http::Method::OPTIONS, "/auth/login")
|
||||
.add_header("origin", "https://evil.example")
|
||||
.add_header("access-control-request-method", "POST")
|
||||
.await;
|
||||
assert!(evil.maybe_header("access-control-allow-origin").is_none());
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn cors_exposes_retry_after_so_js_can_read_it() {
|
||||
let s = server().await;
|
||||
let res = s
|
||||
.post("/auth/login")
|
||||
.add_header("origin", "http://localhost:5173")
|
||||
.await;
|
||||
assert_eq!(
|
||||
res.header("access-control-expose-headers"),
|
||||
"retry-after"
|
||||
);
|
||||
}
|
||||
78
backend/gateway/tests/rate_limit.rs
Normal file
78
backend/gateway/tests/rate_limit.rs
Normal file
|
|
@ -0,0 +1,78 @@
|
|||
mod common;
|
||||
|
||||
use axum::http::StatusCode;
|
||||
|
||||
async fn server() -> axum_test::TestServer {
|
||||
let echo = common::spawn_echo().await;
|
||||
axum_test::TestServer::new(gateway::build_app(
|
||||
&common::config(&echo, &echo),
|
||||
common::no_devices(),
|
||||
))
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn sixth_login_in_a_minute_from_one_ip_is_429_with_retry_after() {
|
||||
let s = server().await;
|
||||
for _ in 0..5 {
|
||||
s.post("/auth/login")
|
||||
.add_header("x-forwarded-for", "203.0.113.7")
|
||||
.await
|
||||
.assert_status_ok();
|
||||
}
|
||||
let res = s
|
||||
.post("/auth/login")
|
||||
.add_header("x-forwarded-for", "203.0.113.7")
|
||||
.await;
|
||||
res.assert_status(StatusCode::TOO_MANY_REQUESTS);
|
||||
let retry: u64 = res.header("retry-after").to_str().unwrap().parse().unwrap();
|
||||
assert!((1..=60).contains(&retry));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn limits_are_per_ip() {
|
||||
let s = server().await;
|
||||
for _ in 0..5 {
|
||||
s.post("/auth/login")
|
||||
.add_header("x-forwarded-for", "203.0.113.8")
|
||||
.await;
|
||||
}
|
||||
s.post("/auth/login")
|
||||
.add_header("x-forwarded-for", "203.0.113.9")
|
||||
.await
|
||||
.assert_status_ok();
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn rightmost_forwarded_for_entry_is_used() {
|
||||
// A client can prepend fake entries; only the one our proxy appended counts.
|
||||
let s = server().await;
|
||||
for i in 0..5 {
|
||||
s.post("/auth/login")
|
||||
.add_header("x-forwarded-for", format!("10.0.0.{i}, 203.0.113.10"))
|
||||
.await
|
||||
.assert_status_ok();
|
||||
}
|
||||
s.post("/auth/login")
|
||||
.add_header("x-forwarded-for", "1.1.1.1, 203.0.113.10")
|
||||
.await
|
||||
.assert_status(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn failed_credentials_count_against_the_ip_limit() {
|
||||
// Every bad device token costs accounts-service a gRPC call + DB query,
|
||||
// so the per-IP global limit must apply before identity rejects it.
|
||||
let s = server().await;
|
||||
for _ in 0..300 {
|
||||
s.get("/configs")
|
||||
.authorization_bearer("lvd_bad")
|
||||
.add_header("x-forwarded-for", "203.0.113.20")
|
||||
.await
|
||||
.assert_status(StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
s.get("/configs")
|
||||
.authorization_bearer("lvd_bad")
|
||||
.add_header("x-forwarded-for", "203.0.113.20")
|
||||
.await
|
||||
.assert_status(StatusCode::TOO_MANY_REQUESTS);
|
||||
}
|
||||
Loading…
Add table
Add a link
Reference in a new issue