Compare commits
1 Commits
bugfix/log
...
chore/reve
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
0a3877be51 |
@@ -51,3 +51,8 @@ MAX_FILE_BYTES=20971520
|
||||
# internal docker network. Override only if you're running the
|
||||
# frontend container against a backend somewhere else.
|
||||
BACKEND_URL=http://backend:8080
|
||||
# Per-request wall-clock cap for the /api/* reverse proxy (milliseconds).
|
||||
# Default 300000 (5 min) covers a typical 200 MiB chapter upload over
|
||||
# 25 Mbps; raise for users on slower upstream links or lower if a
|
||||
# tighter front proxy already bounds the request lifetime.
|
||||
BACKEND_PROXY_TIMEOUT_MS=300000
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
[package]
|
||||
name = "mangalord"
|
||||
version = "0.34.1"
|
||||
version = "0.34.0"
|
||||
edition = "2021"
|
||||
default-run = "mangalord"
|
||||
|
||||
|
||||
@@ -4,8 +4,6 @@
|
||||
//! expire naturally rather than being explicitly invalidated, so other
|
||||
//! devices keep their existing logins).
|
||||
|
||||
use std::sync::OnceLock;
|
||||
|
||||
use axum::extract::{Path, State};
|
||||
use axum::http::StatusCode;
|
||||
use axum::response::IntoResponse;
|
||||
@@ -104,15 +102,9 @@ async fn login(
|
||||
));
|
||||
}
|
||||
|
||||
let user = repo::user::find_by_username(&state.db, username).await?;
|
||||
let Some(user) = user else {
|
||||
// No such user. Run argon2 against a stable dummy hash so the
|
||||
// response time matches the wrong-password branch — otherwise
|
||||
// an attacker can enumerate usernames by timing the no-user
|
||||
// 401 against the wrong-password 401.
|
||||
let _ = verify_password(&input.password, dummy_password_hash());
|
||||
return Err(AppError::Unauthenticated);
|
||||
};
|
||||
let user = repo::user::find_by_username(&state.db, username)
|
||||
.await?
|
||||
.ok_or(AppError::Unauthenticated)?;
|
||||
if !verify_password(&input.password, &user.password_hash) {
|
||||
return Err(AppError::Unauthenticated);
|
||||
}
|
||||
@@ -121,21 +113,6 @@ async fn login(
|
||||
Ok((StatusCode::OK, jar, Json(AuthResponse { user })))
|
||||
}
|
||||
|
||||
/// Lazily-computed argon2 hash used to equalise login response time
|
||||
/// across the "no such user" and "wrong password" branches. Computing
|
||||
/// it once (on the first login of the process) is enough — the hash is
|
||||
/// never compared against a real password, only used to force argon2
|
||||
/// to do the same amount of work it would for a real verify.
|
||||
fn dummy_password_hash() -> &'static str {
|
||||
static DUMMY: OnceLock<String> = OnceLock::new();
|
||||
DUMMY
|
||||
.get_or_init(|| {
|
||||
crate::auth::password::hash_password("login-timing-equaliser")
|
||||
.expect("hash_password on a fixed input cannot fail")
|
||||
})
|
||||
.as_str()
|
||||
}
|
||||
|
||||
async fn logout(
|
||||
State(state): State<AppState>,
|
||||
jar: CookieJar,
|
||||
|
||||
@@ -567,91 +567,6 @@ async fn user_a_cannot_delete_user_b_token(pool: PgPool) {
|
||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
||||
}
|
||||
|
||||
/// Username enumeration via login response time: an attacker probes
|
||||
/// for valid usernames by measuring how long /auth/login takes. Before
|
||||
/// the equalisation fix, the no-user branch returned 401 in <1 ms
|
||||
/// while the wrong-password branch took ~50-100 ms (the argon2 verify
|
||||
/// cost). This test asserts the no-user branch now spends at least
|
||||
/// some meaningful fraction of the wrong-password branch's time.
|
||||
///
|
||||
/// Tolerance is intentionally loose so CI variance doesn't flap the
|
||||
/// test. The unequalised gap is large enough (~50x) that even a noisy
|
||||
/// CI run with a 5x slack still catches it.
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn login_no_user_branch_runs_argon2_for_timing_equalisation(pool: PgPool) {
|
||||
use std::time::Instant;
|
||||
|
||||
let h = common::harness(pool);
|
||||
|
||||
// Register the victim user so the wrong-password branch has a real
|
||||
// argon2 hash to verify against.
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/auth/register",
|
||||
json!({ "username": "victim", "password": "hunter2hunter2" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Warm-up: first login of the process initialises the dummy hash
|
||||
// lazily. Skip that cost when measuring.
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/auth/login",
|
||||
json!({ "username": "victim", "password": "wrong" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
let _ = h
|
||||
.app
|
||||
.clone()
|
||||
.oneshot(common::post_json(
|
||||
"/api/v1/auth/login",
|
||||
json!({ "username": "ghost", "password": "wrong" }),
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
// Median-of-N is more stable than a single sample.
|
||||
async fn sample_min(
|
||||
app: &axum::Router,
|
||||
username: &str,
|
||||
n: u32,
|
||||
) -> std::time::Duration {
|
||||
let mut samples = Vec::with_capacity(n as usize);
|
||||
for _ in 0..n {
|
||||
let req = common::post_json(
|
||||
"/api/v1/auth/login",
|
||||
json!({ "username": username, "password": "wrong-guess" }),
|
||||
);
|
||||
let t = Instant::now();
|
||||
let resp = app.clone().oneshot(req).await.unwrap();
|
||||
let d = t.elapsed();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
samples.push(d);
|
||||
}
|
||||
// Use the minimum: it's the floor that argon2 takes, robust
|
||||
// against unrelated stalls (DB connection acquisition, etc.).
|
||||
*samples.iter().min().unwrap()
|
||||
}
|
||||
|
||||
let wrong_pwd = sample_min(&h.app, "victim", 3).await;
|
||||
let no_user = sample_min(&h.app, "ghost", 3).await;
|
||||
|
||||
// 5x slack: argon2 dominates both branches, so they should be
|
||||
// within an order of magnitude. Unequalised, no_user would be
|
||||
// ~50-100x faster. Asserting "no_user >= wrong_pwd / 5" catches
|
||||
// the bug without being flaky in CI.
|
||||
assert!(
|
||||
no_user * 5 >= wrong_pwd,
|
||||
"login timing leaks user existence: no_user={no_user:?}, wrong_pwd={wrong_pwd:?}"
|
||||
);
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_unknown_token_is_404(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
|
||||
@@ -1,6 +1,6 @@
|
||||
{
|
||||
"name": "mangalord-frontend",
|
||||
"version": "0.34.1",
|
||||
"version": "0.34.0",
|
||||
"private": true,
|
||||
"type": "module",
|
||||
"scripts": {
|
||||
|
||||
@@ -118,4 +118,77 @@ describe('hooks.server proxy', () => {
|
||||
expect(body.error.code).toBe('upstream_unavailable');
|
||||
expect(errSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('strips every hop-by-hop header listed in RFC 7230 §6.1', async () => {
|
||||
// Defence in depth: axum doesn't emit these, but a future
|
||||
// middleware that did would otherwise leak per-connection
|
||||
// state across the proxy boundary.
|
||||
fetchSpy.mockResolvedValueOnce(new Response('[]', { status: 200 }));
|
||||
const resolve = vi.fn();
|
||||
await handle({
|
||||
event: makeEvent('/api/v1/health', {
|
||||
headers: {
|
||||
host: 'app.example.com',
|
||||
'content-length': '0',
|
||||
connection: 'keep-alive',
|
||||
'keep-alive': 'timeout=5',
|
||||
'proxy-authenticate': 'Basic realm=x',
|
||||
'proxy-authorization': 'Basic xyz',
|
||||
te: 'trailers',
|
||||
trailer: 'Expires',
|
||||
'transfer-encoding': 'chunked',
|
||||
upgrade: 'websocket',
|
||||
// A non-hop-by-hop header to ensure non-targets
|
||||
// aren't accidentally stripped.
|
||||
'x-custom': 'pass-through'
|
||||
}
|
||||
}),
|
||||
resolve
|
||||
});
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
const headers = init.headers as Headers;
|
||||
for (const h of [
|
||||
'host',
|
||||
'content-length',
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailer',
|
||||
'transfer-encoding',
|
||||
'upgrade'
|
||||
]) {
|
||||
expect(headers.get(h), `${h} should be stripped`).toBeNull();
|
||||
}
|
||||
expect(headers.get('x-custom')).toBe('pass-through');
|
||||
});
|
||||
|
||||
it('aborts and returns 502 when the upstream stalls past the timeout', async () => {
|
||||
const errSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
||||
// Simulate an aborted fetch (AbortController.abort() raises a
|
||||
// DOMException with name 'AbortError' on Node's fetch). The
|
||||
// handler should treat it as the same upstream_unavailable
|
||||
// 502 it uses for any other network failure.
|
||||
const abortErr = new DOMException('aborted', 'AbortError');
|
||||
fetchSpy.mockRejectedValueOnce(abortErr);
|
||||
|
||||
const resolve = vi.fn();
|
||||
const resp = await handle({ event: makeEvent('/api/v1/slow'), resolve });
|
||||
expect(resp.status).toBe(502);
|
||||
const body = await resp.json();
|
||||
expect(body.error.code).toBe('upstream_unavailable');
|
||||
expect(errSpy).toHaveBeenCalled();
|
||||
});
|
||||
|
||||
it('attaches an AbortSignal to the upstream fetch so it can time out', async () => {
|
||||
fetchSpy.mockResolvedValueOnce(new Response('[]', { status: 200 }));
|
||||
const resolve = vi.fn();
|
||||
await handle({ event: makeEvent('/api/v1/health'), resolve });
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.signal).toBeInstanceOf(AbortSignal);
|
||||
// The signal hasn't fired (handler returned in time), but its
|
||||
// presence is the contract this test is pinning.
|
||||
expect(init.signal?.aborted).toBe(false);
|
||||
});
|
||||
});
|
||||
|
||||
@@ -12,20 +12,66 @@ import type { Handle } from '@sveltejs/kit';
|
||||
|
||||
const BACKEND_URL = process.env.BACKEND_URL ?? 'http://localhost:8080';
|
||||
|
||||
/**
|
||||
* Hop-by-hop headers per RFC 7230 §6.1. These are scoped to a single
|
||||
* transport-level connection and must not be forwarded by a proxy.
|
||||
* Plus `host` and `content-length`: `host` would mislead the backend
|
||||
* about its origin, and `content-length` is recomputed by the upstream
|
||||
* fetch from the body stream.
|
||||
*/
|
||||
const HOP_BY_HOP_HEADERS = [
|
||||
'host',
|
||||
'content-length',
|
||||
'connection',
|
||||
'keep-alive',
|
||||
'proxy-authenticate',
|
||||
'proxy-authorization',
|
||||
'te',
|
||||
'trailer',
|
||||
'transfer-encoding',
|
||||
'upgrade'
|
||||
];
|
||||
|
||||
/**
|
||||
* Cap each proxied request at 5 minutes. The bound exists to surface
|
||||
* a wedged backend (stuck on a slow DB query, deadlocked, etc.) as a
|
||||
* 502 rather than letting the browser request hang indefinitely.
|
||||
*
|
||||
* The default leans toward the slow-upload end of the spectrum: at a
|
||||
* 1 Mbps upstream, a 200 MiB chapter upload (the default
|
||||
* `MAX_REQUEST_BYTES` cap) needs ~27 minutes; 300 s covers the more
|
||||
* realistic 25 Mbps urban-broadband case (~64 s for the same upload)
|
||||
* with comfortable headroom. Operators serving very slow clients
|
||||
* should raise `BACKEND_PROXY_TIMEOUT_MS`; operators behind a
|
||||
* tighter upstream proxy may want to lower it. A future improvement
|
||||
* is an idle-based timeout (reset per chunk) instead of this
|
||||
* wall-clock budget — that's a fair bit more code, deferred.
|
||||
*/
|
||||
const PROXY_TIMEOUT_MS = (() => {
|
||||
const raw = process.env.BACKEND_PROXY_TIMEOUT_MS;
|
||||
const n = raw ? Number(raw) : 300_000;
|
||||
return Number.isFinite(n) && n > 0 ? n : 300_000;
|
||||
})();
|
||||
|
||||
export const handle: Handle = async ({ event, resolve }) => {
|
||||
if (event.url.pathname.startsWith('/api/')) {
|
||||
const target = `${BACKEND_URL}${event.url.pathname}${event.url.search}`;
|
||||
|
||||
// Strip hop-by-hop headers — `host` would mislead the backend
|
||||
// about the origin, and `content-length` will be recomputed.
|
||||
const headers = new Headers(event.request.headers);
|
||||
headers.delete('host');
|
||||
headers.delete('content-length');
|
||||
for (const h of HOP_BY_HOP_HEADERS) headers.delete(h);
|
||||
|
||||
// AbortController times the upstream fetch out so a backend
|
||||
// wedged on a slow DB query doesn't keep the browser request
|
||||
// hanging forever. The `signal` is also wired into the
|
||||
// RequestInit so the body stream is cancelled cleanly.
|
||||
const ctrl = new AbortController();
|
||||
const timeoutHandle = setTimeout(() => ctrl.abort(), PROXY_TIMEOUT_MS);
|
||||
|
||||
const init: RequestInit & { duplex?: 'half' } = {
|
||||
method: event.request.method,
|
||||
headers,
|
||||
redirect: 'manual'
|
||||
redirect: 'manual',
|
||||
signal: ctrl.signal
|
||||
};
|
||||
if (event.request.method !== 'GET' && event.request.method !== 'HEAD') {
|
||||
init.body = event.request.body;
|
||||
@@ -39,11 +85,13 @@ export const handle: Handle = async ({ event, resolve }) => {
|
||||
upstream = await fetch(target, init);
|
||||
} catch (e) {
|
||||
// Network-layer failure (DNS / connection refused / TLS
|
||||
// handshake) — most commonly "backend container restarting".
|
||||
// SvelteKit's default 500 would be an HTML page that
|
||||
// client.ts can't .json(), which masks the real cause. Emit
|
||||
// the standard envelope with a dedicated code instead.
|
||||
// handshake / abort by timeout) — most commonly "backend
|
||||
// container restarting". SvelteKit's default 500 would be
|
||||
// an HTML page that client.ts can't .json(), which masks
|
||||
// the real cause. Emit the standard envelope with a
|
||||
// dedicated code instead.
|
||||
console.error('Proxy to backend failed:', e);
|
||||
clearTimeout(timeoutHandle);
|
||||
return new Response(
|
||||
JSON.stringify({
|
||||
error: {
|
||||
@@ -58,6 +106,7 @@ export const handle: Handle = async ({ event, resolve }) => {
|
||||
);
|
||||
}
|
||||
|
||||
clearTimeout(timeoutHandle);
|
||||
return new Response(upstream.body, {
|
||||
status: upstream.status,
|
||||
statusText: upstream.statusText,
|
||||
|
||||
Reference in New Issue
Block a user