spa hardening, offline logging, rate limit fixes
server: - backup exporter, auth extractors, error shapes, CONTEXT (prior work) - spa assets served outside the rate limit via route_layer - requests_per_second went to per_second(), which takes an interval not a rate: 50 meant one request per 50s once burst was spent. now converted properly. 15/s, burst 60 spa fixes: - account delete cleared snake_case token keys that were never written - refresh interceptor could retry forever - date ranges used local day boundaries stamped +00:00 - "all" period trend plotted one page; calendar days fabricated mood 3 - chart grid invisible: hsl(var(--border)) against rgba tokens - blob url leak, orphaned media on failed save, devtools in prod bundle - pt-safe/safe-area-pb classes never existed spa features: - offline outbox: entries queue to IndexedDB, replay with backoff, only server refusals count against an entry - drafts persist, quick-log sheet, diary infinite scroll + filters - route error boundary, stale-chunk recovery, no service worker in dev a11y + perf: - mood picker is a radiogroup, activity picker keyboard-operable, text alternatives for colour/emoji, locale week start - dark glass over the bright photo: worst case 1.4:1 -> 4.9-9.6:1 - initial payload 1095->769kB raw, 306->230kB gzip; 38 unused components and 5 deps dropped; fonts 218->133kB 53 tests added (43 spa, 10 server)
This commit is contained in:
129
crates/adapters/http-axum/tests/openapi_contract_test.rs
Normal file
129
crates/adapters/http-axum/tests/openapi_contract_test.rs
Normal file
@@ -0,0 +1,129 @@
|
||||
use utoipa::OpenApi;
|
||||
|
||||
fn spec() -> serde_json::Value {
|
||||
serde_json::to_value(http_axum::openapi::ApiDoc::openapi()).unwrap()
|
||||
}
|
||||
|
||||
fn operations(spec: &serde_json::Value) -> Vec<(String, String, serde_json::Value)> {
|
||||
spec["paths"]
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.flat_map(|(path, methods)| {
|
||||
methods
|
||||
.as_object()
|
||||
.unwrap()
|
||||
.iter()
|
||||
.map(move |(verb, op)| (verb.to_uppercase(), path.clone(), op.clone()))
|
||||
})
|
||||
.collect()
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_operation_that_can_succeed_with_a_body_declares_its_shape() {
|
||||
let spec = spec();
|
||||
let mut untyped = Vec::new();
|
||||
|
||||
for (verb, path, op) in operations(&spec) {
|
||||
let responses = op["responses"].as_object().unwrap();
|
||||
|
||||
let describes_a_success = responses
|
||||
.iter()
|
||||
.any(|(code, response)| code.starts_with('2') && response.get("content").is_some());
|
||||
let says_nothing_comes_back = responses.contains_key("204");
|
||||
let serves_bytes = path.starts_with("/api/v1/media/");
|
||||
|
||||
if !describes_a_success && !says_nothing_comes_back && !serves_bytes {
|
||||
untyped.push(format!("{verb} {path}"));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
untyped.is_empty(),
|
||||
"a generated client cannot type these responses: {untyped:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_operation_documents_the_refusals_a_client_must_handle() {
|
||||
let spec = spec();
|
||||
let mut silent = Vec::new();
|
||||
|
||||
for (verb, path, op) in operations(&spec) {
|
||||
let responses = op["responses"].as_object().unwrap();
|
||||
|
||||
if !responses.keys().any(|code| code.starts_with('4')) {
|
||||
silent.push(format!("{verb} {path}"));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
silent.is_empty(),
|
||||
"these operations can refuse a client but never say so: {silent:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_guarded_operation_says_what_a_wrong_credential_looks_like() {
|
||||
let spec = spec();
|
||||
let mut silent = Vec::new();
|
||||
|
||||
for (verb, path, op) in operations(&spec) {
|
||||
if op.get("security").is_none() {
|
||||
continue;
|
||||
}
|
||||
|
||||
let responses = op["responses"].as_object().unwrap();
|
||||
|
||||
if !responses.contains_key("401") || !responses.contains_key("403") {
|
||||
silent.push(format!("{verb} {path}"));
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
silent.is_empty(),
|
||||
"these need a credential but never describe refusing one: {silent:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn every_refusal_is_the_one_error_shape() {
|
||||
let spec = spec();
|
||||
let mut odd = Vec::new();
|
||||
|
||||
for (verb, path, op) in operations(&spec) {
|
||||
for (code, response) in op["responses"].as_object().unwrap() {
|
||||
if !code.starts_with('4') && !code.starts_with('5') {
|
||||
continue;
|
||||
}
|
||||
|
||||
let named = response["content"]["application/json"]["schema"]["$ref"]
|
||||
.as_str()
|
||||
.unwrap_or_default();
|
||||
|
||||
if named != "#/components/schemas/ErrorResponse" {
|
||||
odd.push(format!("{verb} {path} -> {code}"));
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
assert!(
|
||||
odd.is_empty(),
|
||||
"a client should parse one error shape, not several: {odd:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn the_server_tells_a_client_what_it_allows_without_a_credential() {
|
||||
let spec = spec();
|
||||
let info = &spec["paths"]["/api/v1/server"]["get"];
|
||||
|
||||
assert!(
|
||||
info.get("security").is_none(),
|
||||
"a client decides whether to offer registration before anyone has signed in"
|
||||
);
|
||||
assert_eq!(
|
||||
info["responses"]["200"]["content"]["application/json"]["schema"]["$ref"],
|
||||
"#/components/schemas/ServerInfoResponse"
|
||||
);
|
||||
}
|
||||
119
crates/adapters/http-axum/tests/rate_limit_test.rs
Normal file
119
crates/adapters/http-axum/tests/rate_limit_test.rs
Normal file
@@ -0,0 +1,119 @@
|
||||
//! The limit exists to protect the journal from being hammered. It must not
|
||||
//! also throttle the static files the browser needs to render the journal:
|
||||
//! one cold load of the client asks for a dozen or more hashed assets at once,
|
||||
//! and counting those against the same budget makes a hard refresh able to
|
||||
//! starve the app of its own code.
|
||||
|
||||
use std::net::SocketAddr;
|
||||
|
||||
use axum::Router;
|
||||
use axum::body::Body;
|
||||
use axum::extract::ConnectInfo;
|
||||
use axum::http::{Request, StatusCode};
|
||||
use axum::routing::get;
|
||||
use config::RateLimitConfig;
|
||||
use http_axum::router::rate_limited;
|
||||
use tower::util::ServiceExt;
|
||||
|
||||
const CALLER: SocketAddr =
|
||||
SocketAddr::new(std::net::IpAddr::V4(std::net::Ipv4Addr::LOCALHOST), 9000);
|
||||
|
||||
/// One request allowed, then nothing until it replenishes — so a second call
|
||||
/// is refused and the difference between guarded and exempt is unmistakable.
|
||||
fn strictest() -> RateLimitConfig {
|
||||
RateLimitConfig {
|
||||
enabled: true,
|
||||
requests_per_second: 1,
|
||||
burst: 1,
|
||||
trust_forwarded_for: false,
|
||||
}
|
||||
}
|
||||
|
||||
fn under_test(config: &RateLimitConfig) -> Router {
|
||||
rate_limited(
|
||||
Router::new().route("/api/v1/entries", get(|| async { "journal" })),
|
||||
config,
|
||||
)
|
||||
.fallback(|| async { "index.html" })
|
||||
}
|
||||
|
||||
async fn status_of(app: &Router, path: &str) -> StatusCode {
|
||||
let mut request = Request::builder().uri(path).body(Body::empty()).unwrap();
|
||||
request.extensions_mut().insert(ConnectInfo(CALLER));
|
||||
|
||||
app.clone().oneshot(request).await.unwrap().status()
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_guarded_route_is_refused_once_its_budget_is_spent() {
|
||||
let app = under_test(&strictest());
|
||||
|
||||
assert_eq!(status_of(&app, "/api/v1/entries").await, StatusCode::OK);
|
||||
assert_eq!(
|
||||
status_of(&app, "/api/v1/entries").await,
|
||||
StatusCode::TOO_MANY_REQUESTS
|
||||
);
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn client_assets_keep_being_served_after_the_budget_is_spent() {
|
||||
let app = under_test(&strictest());
|
||||
|
||||
// Spend the whole budget on the API.
|
||||
assert_eq!(status_of(&app, "/api/v1/entries").await, StatusCode::OK);
|
||||
assert_eq!(
|
||||
status_of(&app, "/api/v1/entries").await,
|
||||
StatusCode::TOO_MANY_REQUESTS
|
||||
);
|
||||
|
||||
// The files the client is made of are still served, as many as it asks for.
|
||||
for _ in 0..25 {
|
||||
assert_eq!(
|
||||
status_of(&app, "/assets/index-abc123.js").await,
|
||||
StatusCode::OK
|
||||
);
|
||||
}
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
async fn a_switched_off_limit_guards_nothing() {
|
||||
let off = RateLimitConfig {
|
||||
enabled: false,
|
||||
..strictest()
|
||||
};
|
||||
let app = under_test(&off);
|
||||
|
||||
for _ in 0..10 {
|
||||
assert_eq!(status_of(&app, "/api/v1/entries").await, StatusCode::OK);
|
||||
}
|
||||
}
|
||||
|
||||
/// `GovernorConfigBuilder::per_second` takes an interval, not a rate, so the
|
||||
/// configured figure has to be converted or it means its own opposite.
|
||||
mod replenishment {
|
||||
use http_axum::router::replenish_interval_millis;
|
||||
|
||||
#[test]
|
||||
fn a_rate_becomes_the_interval_between_replenishments() {
|
||||
assert_eq!(replenish_interval_millis(1), 1000);
|
||||
assert_eq!(replenish_interval_millis(10), 100);
|
||||
assert_eq!(replenish_interval_millis(15), 66);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_faster_rate_waits_a_shorter_time() {
|
||||
assert!(replenish_interval_millis(50) < replenish_interval_millis(5));
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn an_interval_is_never_zero_however_high_the_rate() {
|
||||
// The builder rejects a zero interval outright.
|
||||
assert_eq!(replenish_interval_millis(10_000), 1);
|
||||
assert_eq!(replenish_interval_millis(u64::MAX), 1);
|
||||
}
|
||||
|
||||
#[test]
|
||||
fn a_nonsensical_rate_of_zero_falls_back_to_one_a_second() {
|
||||
assert_eq!(replenish_interval_millis(0), 1000);
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user