Compare commits
1 Commits
feat/front
...
bugfix/log
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
4863219cf6 |
@@ -1,6 +1,6 @@
|
|||||||
[package]
|
[package]
|
||||||
name = "mangalord"
|
name = "mangalord"
|
||||||
version = "0.35.0"
|
version = "0.34.1"
|
||||||
edition = "2021"
|
edition = "2021"
|
||||||
default-run = "mangalord"
|
default-run = "mangalord"
|
||||||
|
|
||||||
|
|||||||
@@ -4,6 +4,8 @@
|
|||||||
//! expire naturally rather than being explicitly invalidated, so other
|
//! expire naturally rather than being explicitly invalidated, so other
|
||||||
//! devices keep their existing logins).
|
//! devices keep their existing logins).
|
||||||
|
|
||||||
|
use std::sync::OnceLock;
|
||||||
|
|
||||||
use axum::extract::{Path, State};
|
use axum::extract::{Path, State};
|
||||||
use axum::http::StatusCode;
|
use axum::http::StatusCode;
|
||||||
use axum::response::IntoResponse;
|
use axum::response::IntoResponse;
|
||||||
@@ -102,9 +104,15 @@ async fn login(
|
|||||||
));
|
));
|
||||||
}
|
}
|
||||||
|
|
||||||
let user = repo::user::find_by_username(&state.db, username)
|
let user = repo::user::find_by_username(&state.db, username).await?;
|
||||||
.await?
|
let Some(user) = user else {
|
||||||
.ok_or(AppError::Unauthenticated)?;
|
// 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);
|
||||||
|
};
|
||||||
if !verify_password(&input.password, &user.password_hash) {
|
if !verify_password(&input.password, &user.password_hash) {
|
||||||
return Err(AppError::Unauthenticated);
|
return Err(AppError::Unauthenticated);
|
||||||
}
|
}
|
||||||
@@ -113,6 +121,21 @@ async fn login(
|
|||||||
Ok((StatusCode::OK, jar, Json(AuthResponse { user })))
|
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(
|
async fn logout(
|
||||||
State(state): State<AppState>,
|
State(state): State<AppState>,
|
||||||
jar: CookieJar,
|
jar: CookieJar,
|
||||||
|
|||||||
@@ -567,6 +567,91 @@ async fn user_a_cannot_delete_user_b_token(pool: PgPool) {
|
|||||||
assert_eq!(resp.status(), StatusCode::NO_CONTENT);
|
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")]
|
#[sqlx::test(migrations = "./migrations")]
|
||||||
async fn delete_unknown_token_is_404(pool: PgPool) {
|
async fn delete_unknown_token_is_404(pool: PgPool) {
|
||||||
let h = common::harness(pool);
|
let h = common::harness(pool);
|
||||||
|
|||||||
@@ -1,6 +1,6 @@
|
|||||||
{
|
{
|
||||||
"name": "mangalord-frontend",
|
"name": "mangalord-frontend",
|
||||||
"version": "0.35.0",
|
"version": "0.34.1",
|
||||||
"private": true,
|
"private": true,
|
||||||
"type": "module",
|
"type": "module",
|
||||||
"scripts": {
|
"scripts": {
|
||||||
|
|||||||
@@ -1,5 +1,5 @@
|
|||||||
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
|
import { describe, it, expect, vi, beforeEach, afterEach, type MockInstance } from 'vitest';
|
||||||
import { ApiError, request, setOn401Hook } from './client';
|
import { ApiError, request } from './client';
|
||||||
import { getManga } from './mangas';
|
import { getManga } from './mangas';
|
||||||
|
|
||||||
describe('request error envelope parsing', () => {
|
describe('request error envelope parsing', () => {
|
||||||
@@ -73,88 +73,3 @@ describe('request error envelope parsing', () => {
|
|||||||
expect(err.code).toBe('http_error');
|
expect(err.code).toBe('http_error');
|
||||||
});
|
});
|
||||||
});
|
});
|
||||||
|
|
||||||
describe('on401 hook', () => {
|
|
||||||
let fetchSpy: MockInstance<typeof globalThis.fetch>;
|
|
||||||
|
|
||||||
beforeEach(() => {
|
|
||||||
fetchSpy = vi.spyOn(globalThis, 'fetch');
|
|
||||||
});
|
|
||||||
afterEach(() => {
|
|
||||||
vi.restoreAllMocks();
|
|
||||||
// Critical: reset the module-level hook between tests so a
|
|
||||||
// hook installed by one test doesn't leak into the next.
|
|
||||||
setOn401Hook(null);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('invokes the hook exactly once on a 401 response and re-throws', async () => {
|
|
||||||
const hook = vi.fn();
|
|
||||||
setOn401Hook(hook);
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({ error: { code: 'unauthenticated', message: 'no auth' } }),
|
|
||||||
{ status: 401, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await expect(getManga('x')).rejects.toMatchObject({
|
|
||||||
status: 401,
|
|
||||||
code: 'unauthenticated'
|
|
||||||
});
|
|
||||||
expect(hook).toHaveBeenCalledTimes(1);
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not invoke the hook on non-401 errors', async () => {
|
|
||||||
const hook = vi.fn();
|
|
||||||
setOn401Hook(hook);
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({ error: { code: 'not_found', message: 'no' } }),
|
|
||||||
{ status: 404, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await expect(getManga('x')).rejects.toMatchObject({ status: 404 });
|
|
||||||
expect(hook).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('does not invoke the hook on successful responses', async () => {
|
|
||||||
const hook = vi.fn();
|
|
||||||
setOn401Hook(hook);
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({
|
|
||||||
id: 'm1',
|
|
||||||
title: 't',
|
|
||||||
status: 'ongoing',
|
|
||||||
alt_titles: [],
|
|
||||||
description: null,
|
|
||||||
cover_image_path: null,
|
|
||||||
created_at: '2026-01-01T00:00:00Z',
|
|
||||||
updated_at: '2026-01-01T00:00:00Z',
|
|
||||||
authors: [],
|
|
||||||
genres: [],
|
|
||||||
tags: []
|
|
||||||
}),
|
|
||||||
{ status: 200, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await getManga('m1');
|
|
||||||
expect(hook).not.toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
|
|
||||||
it('swallows hook exceptions so the original ApiError still propagates', async () => {
|
|
||||||
const consoleSpy = vi.spyOn(console, 'error').mockImplementation(() => {});
|
|
||||||
setOn401Hook(() => {
|
|
||||||
throw new Error('hook boom');
|
|
||||||
});
|
|
||||||
fetchSpy.mockResolvedValueOnce(
|
|
||||||
new Response(
|
|
||||||
JSON.stringify({ error: { code: 'unauthenticated', message: 'x' } }),
|
|
||||||
{ status: 401, headers: { 'content-type': 'application/json' } }
|
|
||||||
)
|
|
||||||
);
|
|
||||||
await expect(getManga('x')).rejects.toMatchObject({ status: 401 });
|
|
||||||
// The original ApiError won — the hook's panic was logged but
|
|
||||||
// didn't replace the API error.
|
|
||||||
expect(consoleSpy).toHaveBeenCalled();
|
|
||||||
});
|
|
||||||
});
|
|
||||||
|
|||||||
@@ -25,21 +25,6 @@ export class ApiError extends Error {
|
|||||||
|
|
||||||
type ErrorEnvelope = { error?: { code?: unknown; message?: unknown } };
|
type ErrorEnvelope = { error?: { code?: unknown; message?: unknown } };
|
||||||
|
|
||||||
/**
|
|
||||||
* Optional hook fired the first moment `request()` observes a 401 on
|
|
||||||
* any endpoint. Used by the session store to clear the cached user
|
|
||||||
* when the server reports the session is no longer valid (expired
|
|
||||||
* cookie, rotated server-side, password changed on another device).
|
|
||||||
*
|
|
||||||
* Set to `null` (or `undefined`) to disable. Tests that don't want
|
|
||||||
* the side effect should leave it unset.
|
|
||||||
*/
|
|
||||||
let on401Hook: (() => void) | null = null;
|
|
||||||
|
|
||||||
export function setOn401Hook(handler: (() => void) | null): void {
|
|
||||||
on401Hook = handler;
|
|
||||||
}
|
|
||||||
|
|
||||||
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
||||||
// Forward credentials (session cookie) explicitly so cross-origin
|
// Forward credentials (session cookie) explicitly so cross-origin
|
||||||
// deployments — those configured via CORS_ALLOWED_ORIGINS — keep
|
// deployments — those configured via CORS_ALLOWED_ORIGINS — keep
|
||||||
@@ -69,16 +54,6 @@ export async function request<T>(path: string, init?: RequestInit): Promise<T> {
|
|||||||
} catch {
|
} catch {
|
||||||
// Body wasn't parseable; keep the http_error fallback.
|
// Body wasn't parseable; keep the http_error fallback.
|
||||||
}
|
}
|
||||||
if (res.status === 401 && on401Hook) {
|
|
||||||
// Fire before throwing so the session store updates even
|
|
||||||
// if the caller swallows the ApiError (e.g. the *OrEmpty
|
|
||||||
// wrappers used by guest-rendering pages).
|
|
||||||
try {
|
|
||||||
on401Hook();
|
|
||||||
} catch (e) {
|
|
||||||
console.error('on401 hook threw:', e);
|
|
||||||
}
|
|
||||||
}
|
|
||||||
throw new ApiError(res.status, code, message);
|
throw new ApiError(res.status, code, message);
|
||||||
}
|
}
|
||||||
// Any empty body (not just 204) returns undefined — the manga-add
|
// Any empty body (not just 204) returns undefined — the manga-add
|
||||||
|
|||||||
@@ -3,17 +3,7 @@
|
|||||||
// Only mutated client-side (onMount / form submits) so the module-level
|
// Only mutated client-side (onMount / form submits) so the module-level
|
||||||
// instance can't leak across SSR requests — SSR always renders the
|
// instance can't leak across SSR requests — SSR always renders the
|
||||||
// `loaded === false` state, and the client refreshes after hydration.
|
// `loaded === false` state, and the client refreshes after hydration.
|
||||||
//
|
|
||||||
// IMPORTANT: do not call any `api/*` helper from `+page.server.ts` /
|
|
||||||
// `+layout.server.ts`. The `setOn401Hook` below is registered at
|
|
||||||
// module load (gated on `browser`, so it only fires in the client
|
|
||||||
// bundle), so a 401 from a server-side fetch would mutate this
|
|
||||||
// module-level `session.user` across SvelteKit requests — a real
|
|
||||||
// cross-request state leak. The `if (browser)` guard makes that
|
|
||||||
// failure mode mechanical rather than convention-based.
|
|
||||||
|
|
||||||
import { browser } from '$app/environment';
|
|
||||||
import { setOn401Hook } from './api/client';
|
|
||||||
import { me, type User } from './api/auth';
|
import { me, type User } from './api/auth';
|
||||||
|
|
||||||
class SessionStore {
|
class SessionStore {
|
||||||
@@ -41,16 +31,3 @@ class SessionStore {
|
|||||||
}
|
}
|
||||||
|
|
||||||
export const session = new SessionStore();
|
export const session = new SessionStore();
|
||||||
|
|
||||||
// When any backend call returns 401, drop the cached user. Before this
|
|
||||||
// hook, the `*OrEmpty` wrappers silently returned empty pages on 401
|
|
||||||
// — so a mid-session expiry left the UI rendering as "logged in but
|
|
||||||
// no bookmarks/collections/etc." until the user manually reloaded.
|
|
||||||
// With the hook the session.user reactive store flips to null on the
|
|
||||||
// first 401, so the layout re-renders the login affordance.
|
|
||||||
//
|
|
||||||
// Gated on `browser` so it's only installed in the client bundle.
|
|
||||||
// See the module-level comment above for the SSR rationale.
|
|
||||||
if (browser) {
|
|
||||||
setOn401Hook(() => session.setUser(null));
|
|
||||||
}
|
|
||||||
|
|||||||
Reference in New Issue
Block a user