Compare commits
1 Commits
bugfix/api
...
bugfix/man
| Author | SHA1 | Date | |
|---|---|---|---|
|
|
3495190854 |
@@ -230,24 +230,8 @@ async fn create_token(
|
||||
Json(input): Json<CreateTokenInput>,
|
||||
) -> AppResult<impl IntoResponse> {
|
||||
let name = input.name.trim();
|
||||
// Both arms use `ValidationFailed` (422 with field details) to
|
||||
// match the structured-error shape `attach_tag` returns for the
|
||||
// same kind of free-form-identifier validation. The other
|
||||
// /auth/* handlers in this file use `InvalidInput` (400); the
|
||||
// divergence is pre-existing and would warrant a project-wide
|
||||
// pass to flip them all if the client side wants uniform per-
|
||||
// field error rendering.
|
||||
if name.is_empty() {
|
||||
return Err(AppError::ValidationFailed {
|
||||
message: "token name is required".into(),
|
||||
details: serde_json::json!({ "name": "required" }),
|
||||
});
|
||||
}
|
||||
if name.chars().count() > 64 {
|
||||
return Err(AppError::ValidationFailed {
|
||||
message: "token name too long".into(),
|
||||
details: serde_json::json!({ "name": "max 64 characters" }),
|
||||
});
|
||||
return Err(AppError::InvalidInput("token name is required".into()));
|
||||
}
|
||||
let (raw, hash) = generate_token();
|
||||
let token = repo::api_token::create(&state.db, user.id, name, &hash).await?;
|
||||
|
||||
@@ -196,16 +196,14 @@ async fn create(
|
||||
|
||||
async fn update(
|
||||
State(state): State<AppState>,
|
||||
CurrentUser(_user): CurrentUser,
|
||||
CurrentUser(user): CurrentUser,
|
||||
Path(id): Path<Uuid>,
|
||||
Json(patch): Json<MangaPatch>,
|
||||
) -> AppResult<Json<MangaDetail>> {
|
||||
// TODO(auth): until uploaders are tracked (Phase 5), any signed-in
|
||||
// user can edit any manga. Restrict to uploader + admin once that
|
||||
// column lands.
|
||||
if !repo::manga::exists(&state.db, id).await? {
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
require_can_edit(&state, id, user.id).await?;
|
||||
|
||||
if let Some(ref status) = patch.status {
|
||||
let trimmed = status.trim();
|
||||
@@ -269,16 +267,14 @@ async fn update(
|
||||
/// `MangaDetail`.
|
||||
async fn put_cover(
|
||||
State(state): State<AppState>,
|
||||
CurrentUser(_user): CurrentUser,
|
||||
CurrentUser(user): CurrentUser,
|
||||
Path(id): Path<Uuid>,
|
||||
mut multipart: Multipart,
|
||||
) -> AppResult<Json<MangaDetail>> {
|
||||
// TODO(auth): until uploaders are tracked (Phase 5), any signed-in
|
||||
// user can edit any manga's cover. Restrict to uploader + admin
|
||||
// once that column lands.
|
||||
if !repo::manga::exists(&state.db, id).await? {
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
require_can_edit(&state, id, user.id).await?;
|
||||
|
||||
let mut cover: Option<UploadedImage> = None;
|
||||
while let Some(field) = next_field(&mut multipart).await? {
|
||||
@@ -320,13 +316,13 @@ async fn put_cover(
|
||||
/// with the unchanged detail.
|
||||
async fn delete_cover(
|
||||
State(state): State<AppState>,
|
||||
CurrentUser(_user): CurrentUser,
|
||||
CurrentUser(user): CurrentUser,
|
||||
Path(id): Path<Uuid>,
|
||||
) -> AppResult<Json<MangaDetail>> {
|
||||
// TODO(auth): same caveat as put_cover.
|
||||
if !repo::manga::exists(&state.db, id).await? {
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
require_can_edit(&state, id, user.id).await?;
|
||||
if let Some(key) = repo::manga::get(&state.db, id).await?.cover_image_path {
|
||||
match state.storage.delete(&key).await {
|
||||
Ok(()) | Err(StorageError::NotFound) => {}
|
||||
@@ -348,7 +344,6 @@ async fn attach_tag(
|
||||
Path(id): Path<Uuid>,
|
||||
Json(body): Json<AttachTagBody>,
|
||||
) -> AppResult<(StatusCode, Json<TagRef>)> {
|
||||
validate_tag_name(&body.name)?;
|
||||
if !repo::manga::exists(&state.db, id).await? {
|
||||
return Err(AppError::NotFound);
|
||||
}
|
||||
@@ -395,27 +390,6 @@ async fn detach_tag(
|
||||
}
|
||||
}
|
||||
|
||||
/// Request-side validation for `POST /mangas/:id/tags` body. Mirrors
|
||||
/// the repo-level cap in `repo::tag::upsert_by_name` (max 64 chars
|
||||
/// after trim) but surfaces the failure at the handler boundary with
|
||||
/// the same envelope shape other validations use.
|
||||
fn validate_tag_name(name: &str) -> AppResult<()> {
|
||||
let trimmed = name.trim();
|
||||
if trimmed.is_empty() {
|
||||
return Err(AppError::ValidationFailed {
|
||||
message: "tag name cannot be empty".into(),
|
||||
details: json!({ "name": "required" }),
|
||||
});
|
||||
}
|
||||
if trimmed.chars().count() > 64 {
|
||||
return Err(AppError::ValidationFailed {
|
||||
message: "tag name too long".into(),
|
||||
details: json!({ "name": "max 64 characters" }),
|
||||
});
|
||||
}
|
||||
Ok(())
|
||||
}
|
||||
|
||||
fn validate_new_manga(input: &NewManga) -> AppResult<()> {
|
||||
if input.title.trim().is_empty() {
|
||||
return Err(AppError::ValidationFailed {
|
||||
@@ -435,6 +409,30 @@ fn validate_new_manga(input: &NewManga) -> AppResult<()> {
|
||||
Ok(())
|
||||
}
|
||||
|
||||
/// Authorisation gate for manga mutations. The manga is assumed to
|
||||
/// exist (the caller runs [`repo::manga::exists`] first so a missing id
|
||||
/// surfaces as `NotFound`, not `Forbidden`).
|
||||
///
|
||||
/// Rule: a non-NULL `uploaded_by` must match the current user. Legacy
|
||||
/// rows with `uploaded_by IS NULL` (pre-migration-0011) are still
|
||||
/// editable by any signed-in user — there's nobody to gate on yet, and
|
||||
/// the historical-data note in 0011 acknowledges the gap. Once an
|
||||
/// admin role lands the NULL case can flip to admin-only.
|
||||
///
|
||||
/// Returns `Forbidden` (not `NotFound`) on owner mismatch — mangas
|
||||
/// are listable via `GET /mangas`, so existence isn't a secret and
|
||||
/// the more accurate 403 is fine. This deliberately differs from
|
||||
/// `repo::collection::require_owner`, which collapses both states to
|
||||
/// `NotFound` because collections are private to a user and existence
|
||||
/// itself is information worth hiding from non-owners.
|
||||
async fn require_can_edit(state: &AppState, manga_id: Uuid, user_id: Uuid) -> AppResult<()> {
|
||||
match repo::manga::uploaded_by(&state.db, manga_id).await? {
|
||||
Some(owner) if owner != user_id => Err(AppError::Forbidden),
|
||||
// Some(owner) == user_id (good) or None (legacy row, no owner).
|
||||
_ => Ok(()),
|
||||
}
|
||||
}
|
||||
|
||||
async fn validate_genre_ids(state: &AppState, ids: &[Uuid]) -> AppResult<()> {
|
||||
if ids.is_empty() {
|
||||
return Ok(());
|
||||
|
||||
@@ -281,3 +281,17 @@ pub async fn exists(pool: &PgPool, id: Uuid) -> AppResult<bool> {
|
||||
.await?;
|
||||
Ok(exists)
|
||||
}
|
||||
|
||||
/// Returns the uploader's user id for a manga. `None` either when the
|
||||
/// manga doesn't exist or when the row predates the `uploaded_by`
|
||||
/// column (historical NULL — see migration 0011). Callers must
|
||||
/// distinguish "manga missing" via [`exists`] before relying on this
|
||||
/// to make an authz decision.
|
||||
pub async fn uploaded_by(pool: &PgPool, id: Uuid) -> AppResult<Option<Uuid>> {
|
||||
let row: Option<(Option<Uuid>,)> =
|
||||
sqlx::query_as("SELECT uploaded_by FROM mangas WHERE id = $1")
|
||||
.bind(id)
|
||||
.fetch_optional(pool)
|
||||
.await?;
|
||||
Ok(row.and_then(|(u,)| u))
|
||||
}
|
||||
|
||||
@@ -16,13 +16,6 @@ impl LocalStorage {
|
||||
}
|
||||
|
||||
fn resolve(&self, key: &str) -> Result<PathBuf, StorageError> {
|
||||
// NUL bytes are rejected by the Linux syscall layer, but the
|
||||
// error surfaces as an opaque IO failure rather than the
|
||||
// explicit `BadKey` the rest of the contract uses. Catch it
|
||||
// here so the error path is consistent.
|
||||
if key.contains('\0') {
|
||||
return Err(StorageError::BadKey);
|
||||
}
|
||||
let key = key.trim_start_matches('/');
|
||||
if key.is_empty() {
|
||||
return Err(StorageError::BadKey);
|
||||
@@ -121,9 +114,6 @@ mod tests {
|
||||
assert!(matches!(s.get(".").await, Err(StorageError::BadKey)));
|
||||
// Empty segment via doubled slash.
|
||||
assert!(matches!(s.get("a//b").await, Err(StorageError::BadKey)));
|
||||
// NUL byte (rejected explicitly so callers see BadKey rather
|
||||
// than an opaque IO error from the kernel).
|
||||
assert!(matches!(s.put("a\0b", b"x").await, Err(StorageError::BadKey)));
|
||||
}
|
||||
|
||||
#[tokio::test]
|
||||
|
||||
@@ -581,27 +581,3 @@ async fn delete_unknown_token_is_404(pool: PgPool) {
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
/// Bot token names are user-supplied free-form strings; a 10 MB name
|
||||
/// was accepted before. Cap at 64 chars to match the other free-form
|
||||
/// identifier caps (tags, collection names). The response uses
|
||||
/// `ValidationFailed` (422 with per-field details) so clients can
|
||||
/// render the same shape they already handle for `attach_tag`.
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn create_token_rejects_name_over_64_chars(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
"/api/v1/auth/tokens",
|
||||
json!({ "name": "x".repeat(65) }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "validation_failed");
|
||||
assert!(body["error"]["details"]["name"].is_string());
|
||||
}
|
||||
|
||||
@@ -410,3 +410,53 @@ async fn delete_cover_404_on_unknown_id(pool: PgPool) {
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::NOT_FOUND);
|
||||
}
|
||||
|
||||
/// Authz: PUT /mangas/:id/cover must be uploader-only.
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn put_cover_forbidden_for_non_uploader(pool: PgPool) {
|
||||
let h = harness(pool);
|
||||
let (_, owner_cookie) = register_user(&h.app).await;
|
||||
let (_, intruder_cookie) = register_user(&h.app).await;
|
||||
|
||||
let manga =
|
||||
create_manga_with_cover(&h.app, &owner_cookie, "Mine", None).await;
|
||||
let id = id_of(&manga);
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(put_multipart_with_cookie(
|
||||
&format!("/api/v1/mangas/{id}/cover"),
|
||||
cover_form(&fake_png_bytes()),
|
||||
&intruder_cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
/// Authz: DELETE /mangas/:id/cover must be uploader-only.
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn delete_cover_forbidden_for_non_uploader(pool: PgPool) {
|
||||
let h = harness(pool);
|
||||
let (_, owner_cookie) = register_user(&h.app).await;
|
||||
let (_, intruder_cookie) = register_user(&h.app).await;
|
||||
|
||||
let manga = create_manga_with_cover(
|
||||
&h.app,
|
||||
&owner_cookie,
|
||||
"Mine",
|
||||
Some(("image/jpeg", &fake_jpeg_bytes())),
|
||||
)
|
||||
.await;
|
||||
let id = id_of(&manga);
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(delete_with_cookie(
|
||||
&format!("/api/v1/mangas/{id}/cover"),
|
||||
&intruder_cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
@@ -566,3 +566,78 @@ async fn patch_requires_authentication(pool: PgPool) {
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNAUTHORIZED);
|
||||
}
|
||||
|
||||
/// A signed-in user who didn't upload the manga must not be able to
|
||||
/// PATCH it. Without the uploader-gate this returned 200 — see
|
||||
/// REVIEW.md "manga PATCH / cover endpoints don't check ownership".
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn patch_forbidden_for_non_uploader(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, owner_cookie) = common::register_user(&h.app).await;
|
||||
let (_, intruder_cookie) = common::register_user(&h.app).await;
|
||||
|
||||
let created = create_manga(&h.app, &owner_cookie, json!({ "title": "Mine" })).await;
|
||||
let id = id_of(&created);
|
||||
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::patch_json_with_cookie(
|
||||
&format!("/api/v1/mangas/{id}"),
|
||||
json!({ "status": "completed" }),
|
||||
&intruder_cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::FORBIDDEN);
|
||||
}
|
||||
|
||||
/// Owner can still edit their own manga (regression guard for the
|
||||
/// authz fix).
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn patch_allowed_for_uploader(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
let created = create_manga(&h.app, &cookie, json!({ "title": "Owned" })).await;
|
||||
let id = id_of(&created);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::patch_json_with_cookie(
|
||||
&format!("/api/v1/mangas/{id}"),
|
||||
json!({ "status": "completed" }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
/// Legacy rows with `uploaded_by IS NULL` (created before migration
|
||||
/// 0011) remain editable by any signed-in user. Without this carve-out
|
||||
/// the historical-data note in 0011 would be broken.
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn patch_allowed_on_legacy_null_uploader(pool: PgPool) {
|
||||
let h = common::harness(pool.clone());
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
let created = create_manga(&h.app, &cookie, json!({ "title": "Legacy" })).await;
|
||||
let id = id_of(&created);
|
||||
|
||||
// Simulate a row uploaded before the column existed: clear
|
||||
// uploaded_by directly via SQL.
|
||||
sqlx::query("UPDATE mangas SET uploaded_by = NULL WHERE id = $1")
|
||||
.bind(id)
|
||||
.execute(&pool)
|
||||
.await
|
||||
.unwrap();
|
||||
|
||||
let (_, other_cookie) = common::register_user(&h.app).await;
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::patch_json_with_cookie(
|
||||
&format!("/api/v1/mangas/{id}"),
|
||||
json!({ "status": "completed" }),
|
||||
&other_cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
@@ -59,31 +59,6 @@ async fn reattach_same_tag_is_idempotent_and_returns_200(pool: PgPool) {
|
||||
assert_eq!(second.status(), StatusCode::OK);
|
||||
}
|
||||
|
||||
/// Tag names over 64 chars are rejected at the handler boundary. The
|
||||
/// repo enforces the same cap, but doing it at the handler keeps the
|
||||
/// envelope consistent with the other validation paths
|
||||
/// (username, collection name, etc.).
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn attach_rejects_tag_name_over_64_chars(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
let (_, cookie) = common::register_user(&h.app).await;
|
||||
let manga_id = common::seed_manga_via_api(&h.app, &cookie, "Berserk").await;
|
||||
|
||||
let long_name: String = "x".repeat(65);
|
||||
let resp = h
|
||||
.app
|
||||
.oneshot(common::post_json_with_cookie(
|
||||
&format!("/api/v1/mangas/{manga_id}/tags"),
|
||||
json!({ "name": long_name }),
|
||||
&cookie,
|
||||
))
|
||||
.await
|
||||
.unwrap();
|
||||
assert_eq!(resp.status(), StatusCode::UNPROCESSABLE_ENTITY);
|
||||
let body = common::body_json(resp).await;
|
||||
assert_eq!(body["error"]["code"], "validation_failed");
|
||||
}
|
||||
|
||||
#[sqlx::test(migrations = "./migrations")]
|
||||
async fn tag_names_dedup_case_insensitively(pool: PgPool) {
|
||||
let h = common::harness(pool);
|
||||
|
||||
@@ -94,11 +94,6 @@ describe('auth api client', () => {
|
||||
expect(url).toMatch(/\/v1\/auth\/logout$/);
|
||||
const init = fetchSpy.mock.calls[0][1] as RequestInit;
|
||||
expect(init.method).toBe('POST');
|
||||
// Consistent content-type for all mutation requests, matching
|
||||
// the rest of the module — axum doesn't require it but the
|
||||
// header keeps the request style uniform.
|
||||
const headers = new Headers(init.headers);
|
||||
expect(headers.get('content-type')).toBe('application/json');
|
||||
});
|
||||
|
||||
it('me returns the user on 200', async () => {
|
||||
|
||||
@@ -32,14 +32,7 @@ export async function login(creds: Credentials): Promise<User> {
|
||||
}
|
||||
|
||||
export async function logout(): Promise<void> {
|
||||
await request<void>('/v1/auth/logout', {
|
||||
method: 'POST',
|
||||
// Consistent with the other POST/PATCH helpers in this module.
|
||||
// axum doesn't require it (no body), but keeping the header
|
||||
// on every mutation request avoids the false-flag in logs and
|
||||
// matches the project's style.
|
||||
headers: { 'content-type': 'application/json' }
|
||||
});
|
||||
await request<void>('/v1/auth/logout', { method: 'POST' });
|
||||
}
|
||||
|
||||
export type ChangePassword = {
|
||||
|
||||
@@ -350,24 +350,30 @@
|
||||
});
|
||||
|
||||
/**
|
||||
* Flush read-progress as the tab is closing. A plain `fetch()`
|
||||
* during `pagehide` / `beforeunload` is cancelled by every
|
||||
* browser; `fetch(..., { keepalive: true })` is the supported
|
||||
* escape hatch and survives the close.
|
||||
*
|
||||
* `sendBeacon` would be the textbook alternative, but it's
|
||||
* POST-only and `/me/read-progress` takes PUT — so a beacon
|
||||
* always 405s, adds server-log noise, then falls through to this
|
||||
* same keepalive path anyway. The beacon was dropped; the
|
||||
* keepalive fetch is the only path.
|
||||
* `fetch()` initiated during `pagehide` / `beforeunload` is
|
||||
* cancelled by every browser by default. `sendBeacon` is the
|
||||
* supported way to ship a small payload during unload — it's
|
||||
* guaranteed to survive even if the tab is closing. Failure here
|
||||
* is silent because the API is fire-and-forget.
|
||||
*/
|
||||
function flushFinalProgress() {
|
||||
function beaconFinalProgress() {
|
||||
if (!session.user) return;
|
||||
const body = JSON.stringify({
|
||||
manga_id: manga.id,
|
||||
chapter_id: chapter.id,
|
||||
page: progressPage
|
||||
});
|
||||
const blob = new Blob([body], { type: 'application/json' });
|
||||
// sendBeacon only supports POST — the server's PUT route is
|
||||
// strict on method. The dedicated POST alias is omitted; in
|
||||
// practice the in-app navigation path (back-link, chapter
|
||||
// links) already covers the common-case unmount via the
|
||||
// onDestroy fetch. Fall through to fetch+keepalive for browser
|
||||
// implementations that don't honor sendBeacon for this endpoint.
|
||||
try {
|
||||
const ok = navigator.sendBeacon('/api/v1/me/read-progress', blob);
|
||||
if (!ok) throw new Error('sendBeacon rejected');
|
||||
} catch {
|
||||
try {
|
||||
void fetch('/api/v1/me/read-progress', {
|
||||
method: 'PUT',
|
||||
@@ -377,21 +383,21 @@
|
||||
credentials: 'include'
|
||||
});
|
||||
} catch {
|
||||
// keepalive fetch was rejected (very old Firefox etc.);
|
||||
// the in-app onDestroy flush below catches the SPA-
|
||||
// navigation case, which is the common one anyway.
|
||||
// Final fallback failed; the in-app onDestroy flush
|
||||
// below catches the SPA-navigation case.
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
onMount(() => {
|
||||
window.addEventListener('pagehide', flushFinalProgress);
|
||||
window.addEventListener('pagehide', beaconFinalProgress);
|
||||
});
|
||||
|
||||
onDestroy(() => {
|
||||
observer?.disconnect();
|
||||
if (progressTimer) clearTimeout(progressTimer);
|
||||
if (typeof window !== 'undefined') {
|
||||
window.removeEventListener('pagehide', flushFinalProgress);
|
||||
window.removeEventListener('pagehide', beaconFinalProgress);
|
||||
}
|
||||
// Don't let the fullscreen flag leak to non-reader pages —
|
||||
// otherwise the layout header would stay slid-off on /upload
|
||||
|
||||
Reference in New Issue
Block a user