Skip to content

🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!

Security: Paperless upload reclaim, oracle removal, tag scoping, page_size cap (PPL-03, PPL-05, PPL-06, PPL-07)

Omega (QA)a5cd2e60be16
diff --git a/backend/file_routes.py b/backend/file_routes.py
index a97f421..9a287de 100644
--- a/backend/file_routes.py
+++ b/backend/file_routes.py
@@ -1,5 +1,6 @@
# backend/file_routes.py
from flask import Blueprint, request, jsonify, current_app, send_from_directory, Response
+from datetime import datetime, UTC
import os
import mimetypes
import logging
@@ -11,6 +12,7 @@ try:
from .paperless_handler import get_paperless_handler, PaperlessHandler
from .paperless_access import (
check_paperless_document_access,
+ claim_upload_ownership,
record_paperless_document_owner,
user_can_link_paperless_document,
visible_paperless_document_ids,
@@ -23,6 +25,7 @@ except ImportError:
from paperless_handler import get_paperless_handler, PaperlessHandler
from paperless_access import (
check_paperless_document_access,
+ claim_upload_ownership,
record_paperless_document_owner,
user_can_link_paperless_document,
visible_paperless_document_ids,
@@ -110,6 +113,19 @@ def _check_file_authorization(cur, db_search_path, user_id, is_admin):
return False
+def _paperless_next_path(next_url):
+ """Next-page path for paperless_handler.get, which takes a path.
+
+ Paperless returns absolute `next` URLs; convert them to path plus
+ query, and pass through relative values and None unchanged.
+ """
+ if next_url and next_url.startswith('http'):
+ from urllib.parse import urlparse
+ parts = urlparse(next_url)
+ return parts.path + (('?' + parts.query) if parts.query else '')
+ return next_url
+
+
# ============================
# Local File Serving Routes
# ============================
@@ -425,7 +441,10 @@ def paperless_upload():
logger.error(f"Error reading file content: {file_read_error}")
return jsonify({"error": f"Error reading file: {str(file_read_error)}"}), 400
- # Upload to Paperless-ngx
+ # Upload to Paperless-ngx. The start time bounds the PPL-03
+ # reclaim window: claims recorded after it cannot predate the
+ # document being uploaded.
+ upload_started_at = datetime.now(UTC)
logger.info("Starting upload to Paperless-ngx")
try:
success, document_id, message = paperless_handler.upload_document(
@@ -449,7 +468,7 @@ def paperless_upload():
try:
numeric_document_id = int(document_id)
with conn.cursor() as cur:
- record_paperless_document_owner(cur, numeric_document_id, request.user['id'])
+ claim_upload_ownership(cur, numeric_document_id, request.user['id'], upload_started_at)
conn.commit()
except (TypeError, ValueError):
logger.info(f"Upload returned non-document id {document_id!r}; ownership not recorded")
@@ -460,9 +479,20 @@ def paperless_upload():
}), 200
else:
logger.warning(f"Upload failed: {message}")
+ # PPL-05: a duplicate upload returns the existing document's
+ # id, which must not be revealed when another user owns it.
+ # Reveal it only when the requester could link it anyway.
+ revealed_id = document_id
+ if document_id is not None:
+ with conn.cursor() as cur:
+ if not user_can_link_paperless_document(
+ cur, request.user['id'],
+ request.user.get('is_admin', False), document_id
+ ):
+ revealed_id = None
return jsonify({
"success": False,
- "document_id": document_id,
+ "document_id": revealed_id,
"error": message
}), 200
@@ -553,6 +583,13 @@ def paperless_search():
except (ValueError, ZeroDivisionError):
page = '1'
limit = '25'
+
+ # PPL-07: never forward an unbounded page size to Paperless-ngx;
+ # page_size=100000 used to return every matching document at once.
+ try:
+ limit = str(max(1, min(int(limit), 100)))
+ except ValueError:
+ limit = '25'
# Build search URL using paperless handler's configuration
search_url = f"{paperless_handler.base_url.rstrip('/')}/api/documents/"
@@ -656,12 +693,29 @@ def paperless_tags():
response.raise_for_status()
page = response.json()
all_tags.extend(page.get('results', []))
- url = page.get('next')
- # paperless_handler.get takes a path; convert absolute next URLs
- if url and url.startswith('http'):
- from urllib.parse import urlparse
- parts = urlparse(url)
- url = parts.path + (('?' + parts.query) if parts.query else '')
+ url = _paperless_next_path(page.get('next'))
+
+ # PPL-06: non-admin users only receive tags attached to
+ # documents they may see. Without this, any signed-in user
+ # learned every instance tag, including tags used only on
+ # other users' documents.
+ if not request.user.get('is_admin', False):
+ with conn.cursor() as cur:
+ visible_ids = visible_paperless_document_ids(cur, request.user['id'], False)
+ if not visible_ids:
+ all_tags = []
+ else:
+ used_tag_ids = set()
+ url = '/api/documents/?page_size=100'
+ while url:
+ response = paperless_handler.get(url, timeout=30)
+ response.raise_for_status()
+ page = response.json()
+ for doc in page.get('results', []):
+ if doc.get('id') in visible_ids:
+ used_tag_ids.update(doc.get('tags') or [])
+ url = _paperless_next_path(page.get('next'))
+ all_tags = [t for t in all_tags if t.get('id') in used_tag_ids]
except Exception as e:
# See CFG-10 in paperless_search: exception text can carry
# the internal Paperless host and path, so log it and reply
@@ -1021,7 +1075,9 @@ def paperless_search_and_link():
request.user["id"],
document_id,
)
- return jsonify({"success": False, "message": "This document belongs to another user"}), 403
+ # PPL-05: answer exactly as for a missing document, so
+ # the status does not reveal that it exists or is owned.
+ return jsonify({"success": False, "message": "Document not found"}), 404
logger.info(
"Updating warranty %s field %s with document ID %s for user %s",
diff --git a/backend/paperless_access.py b/backend/paperless_access.py
index 2a61727..2a7f185 100644
--- a/backend/paperless_access.py
+++ b/backend/paperless_access.py
@@ -61,6 +61,39 @@ def record_paperless_document_owner(cur, document_id, user_id):
)
+def claim_upload_ownership(cur, document_id, user_id, upload_started_at):
+ """Record the uploader as owner, reclaiming mid-upload claims (PPL-03).
+
+ Ownership is recorded only after Paperless finishes processing an
+ upload, so a speculative link during the processing window could
+ claim the pending document id first, and ON CONFLICT DO NOTHING
+ then kept the speculator while the uploader's own link and download
+ were refused. A claim recorded after this upload started cannot
+ predate the document itself, so the uploader takes it over. Claims
+ predating the upload are left alone.
+ """
+ if document_id is None or user_id is None:
+ return
+ cur.execute(
+ """
+ INSERT INTO paperless_document_ownership (paperless_document_id, user_id)
+ VALUES (%s, %s)
+ ON CONFLICT (paperless_document_id) DO NOTHING
+ RETURNING paperless_document_id
+ """,
+ (document_id, user_id),
+ )
+ if cur.fetchone():
+ return
+ cur.execute(
+ """
+ UPDATE paperless_document_ownership SET user_id = %s
+ WHERE paperless_document_id = %s AND created_at >= %s
+ """,
+ (user_id, document_id, upload_started_at),
+ )
+
+
def _referenced_by(cur, document_id, user_id, own):
"""True when a warranty or claim-document reference to the document
exists for the given user (own=True) or for any other user (own=False)."""
diff --git a/tests/mock_paperless.py b/tests/mock_paperless.py
index 0aef543..7158395 100644
--- a/tests/mock_paperless.py
+++ b/tests/mock_paperless.py
@@ -19,12 +19,15 @@ PNG_BYTES = base64.b64decode(
DOCS = [
{"id": 1, "title": "Invoice - Laptop 2026", "created": "2026-01-20T10:00:00Z",
- "mime_type": "application/pdf", "archived_file_name": "invoice-laptop.pdf"},
+ "mime_type": "application/pdf", "archived_file_name": "invoice-laptop.pdf",
+ "tags": [1]},
{"id": 2, "title": "Manual - Headphones", "created": "2026-06-05T10:00:00Z",
- "mime_type": "application/pdf", "archived_file_name": "manual-headphones.pdf"},
+ "mime_type": "application/pdf", "archived_file_name": "manual-headphones.pdf",
+ "tags": [2]},
]
TASKS = {} # task_id -> doc_id
NEXT_ID = [3]
+LAST_DOCUMENT_QUERIES = [] # parsed query dicts of /api/documents/ GETs
class Handler(BaseHTTPRequestHandler):
@@ -51,6 +54,7 @@ class Handler(BaseHTTPRequestHandler):
path, qs = u.path, parse_qs(u.query)
if path == "/api/documents/":
+ LAST_DOCUMENT_QUERIES.append(qs)
docs = DOCS
# checksum dedup lookup: mock docs have no checksums -> no match
if "checksum__iexact" in qs:
@@ -95,9 +99,12 @@ class Handler(BaseHTTPRequestHandler):
return self._json([])
if path == "/api/tags/":
- return self._json({"count": 2, "next": None, "previous": None,
+ # Tag 3 is attached to no document: it must never reach a
+ # non-admin user (PPL-06).
+ return self._json({"count": 3, "next": None, "previous": None,
"results": [{"id": 1, "name": "invoice"},
- {"id": 2, "name": "manual"}]})
+ {"id": 2, "name": "manual"},
+ {"id": 3, "name": "secret"}]})
self._json({"detail": "not found"}, status=404)
diff --git a/tests/test_paperless_lows.py b/tests/test_paperless_lows.py
new file mode 100644
index 0000000..a011357
--- /dev/null
+++ b/tests/test_paperless_lows.py
@@ -0,0 +1,192 @@
+"""Paperless Low findings: upload race (PPL-03), oracles (PPL-05),
+tag scoping (PPL-06), and the page_size cap (PPL-07).
+"""
+import io
+import types
+from datetime import datetime, timedelta, UTC
+
+import mock_paperless
+import pytest
+
+import backend.file_routes as file_routes
+from backend.paperless_access import (
+ claim_upload_ownership,
+ get_paperless_document_owner,
+)
+
+
+def _user_id(db_connection, username):
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT id FROM users WHERE username = %s", (username,))
+ return cur.fetchone()[0]
+
+
+def _promote_to_admin(db_connection, username):
+ """Make a user an admin regardless of registration order.
+
+ token_required reads is_admin from the database on every request,
+ so this works with the token the user already holds.
+ """
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute("UPDATE users SET is_admin = TRUE WHERE username = %s",
+ (username,))
+
+
+# --- PPL-03: the uploader reclaims claims made during the upload window ---
+
+def test_upload_claim_inserts_when_unclaimed(client, user_factory, db_connection):
+ user = user_factory()
+ uid = _user_id(db_connection, user["username"])
+ with db_connection, db_connection.cursor() as cur:
+ claim_upload_ownership(cur, 9101, uid, datetime.now(UTC))
+ assert get_paperless_document_owner(cur, 9101) == uid
+
+
+def test_upload_claim_keeps_older_claim(client, user_factory, db_connection):
+ first = user_factory()
+ second = user_factory()
+ first_id = _user_id(db_connection, first["username"])
+ second_id = _user_id(db_connection, second["username"])
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO paperless_document_ownership "
+ "(paperless_document_id, user_id, created_at) VALUES (%s, %s, %s)",
+ (9102, first_id, datetime.now(UTC) - timedelta(hours=1)),
+ )
+ with db_connection, db_connection.cursor() as cur:
+ claim_upload_ownership(cur, 9102, second_id, datetime.now(UTC))
+ assert get_paperless_document_owner(cur, 9102) == first_id
+
+
+def test_upload_claim_reclaims_mid_window_claim(client, user_factory, db_connection):
+ speculator = user_factory()
+ uploader = user_factory()
+ speculator_id = _user_id(db_connection, speculator["username"])
+ uploader_id = _user_id(db_connection, uploader["username"])
+ started = datetime.now(UTC) - timedelta(seconds=30)
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO paperless_document_ownership "
+ "(paperless_document_id, user_id, created_at) VALUES (%s, %s, %s)",
+ (9103, speculator_id, datetime.now(UTC) - timedelta(seconds=10)),
+ )
+ with db_connection, db_connection.cursor() as cur:
+ claim_upload_ownership(cur, 9103, uploader_id, started)
+ assert get_paperless_document_owner(cur, 9103) == uploader_id
+
+
+# --- PPL-05: a duplicate upload must not reveal another user's document id ---
+
+def duplicate_handler(monkeypatch):
+ """A Paperless handler whose upload always reports a duplicate.
+
+ The duplicate id is arbitrary (9201): the handler is faked, so no
+ mock document is involved, and the id cannot collide with the
+ ownership rows other tests seed.
+ """
+ def _fake_get_paperless_handler(conn):
+ return types.SimpleNamespace(
+ upload_document=lambda **kwargs: (
+ False, 9201, "The file that is being uploaded to Paperless is a duplicate."),
+ )
+ monkeypatch.setattr(
+ file_routes, "get_paperless_handler", _fake_get_paperless_handler)
+
+
+def _upload_attempt(client, headers):
+ return client.post(
+ "/api/paperless/upload", headers=headers,
+ data={"title": "dup.pdf",
+ "file": (io.BytesIO(b"%PDF-1.4 test"), "dup.pdf")},
+ content_type="multipart/form-data")
+
+
+def test_duplicate_upload_hides_foreign_document_id(
+ client, user_factory, admin_user, db_connection, duplicate_handler):
+ owner = user_factory()
+ stranger = user_factory()
+ owner_id = _user_id(db_connection, owner["username"])
+ _promote_to_admin(db_connection, admin_user["username"])
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO paperless_document_ownership (paperless_document_id, user_id) "
+ "VALUES (9201, %s) ON CONFLICT (paperless_document_id) DO NOTHING",
+ (owner_id,),
+ )
+
+ r = _upload_attempt(client, stranger["headers"])
+ assert r.status_code == 200
+ assert r.get_json()["document_id"] is None
+
+ r = _upload_attempt(client, owner["headers"])
+ assert r.get_json()["document_id"] == 9201
+
+ r = _upload_attempt(client, admin_user["headers"])
+ assert r.get_json()["document_id"] == 9201
+
+
+def test_search_and_link_missing_title_matches_foreign_status(
+ client, user_factory, paperless_configured, warranty_factory):
+ # Both the missing-title and the foreign-document cases answer 404
+ # (the foreign case is covered in test_paperless_security.py).
+ user = user_factory()
+ r = warranty_factory(user["headers"])
+ wid = r.get_json()["id"]
+ r = client.post("/api/paperless-search-and-link", headers=user["headers"],
+ json={"warranty_id": wid, "document_type": "other",
+ "search_title": "no-such-title-anywhere"})
+ assert r.status_code == 404
+
+
+# --- PPL-06: tags are scoped to the requesting user's visible documents ---
+
+def test_tags_scoped_to_visible_documents(
+ client, user_factory, admin_user, db_connection, paperless_configured):
+ owner = user_factory()
+ stranger = user_factory()
+ owner_id = _user_id(db_connection, owner["username"])
+ _promote_to_admin(db_connection, admin_user["username"])
+ # Mock document 2 carries tag 2. (Document 1 is claimed by the
+ # security battery's scenario fixture; never seed ownership for it.)
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute(
+ "INSERT INTO paperless_document_ownership (paperless_document_id, user_id) "
+ "VALUES (2, %s) ON CONFLICT (paperless_document_id) DO NOTHING",
+ (owner_id,),
+ )
+
+ r = client.get("/api/paperless/tags", headers=stranger["headers"])
+ assert r.status_code == 200
+ assert r.get_json()["results"] == []
+
+ r = client.get("/api/paperless/tags", headers=owner["headers"])
+ assert [t["id"] for t in r.get_json()["results"]] == [2]
+
+ r = client.get("/api/paperless/tags", headers=admin_user["headers"])
+ assert {t["id"] for t in r.get_json()["results"]} == {1, 2, 3}
+
+
+# --- PPL-07: the forwarded page_size is capped ---
+
+def test_search_page_size_capped_at_100(
+ client, admin_user, paperless_configured, db_connection):
+ _promote_to_admin(db_connection, admin_user["username"])
+ mock_paperless.LAST_DOCUMENT_QUERIES.clear()
+ r = client.get("/api/paperless/search",
+ query_string={"page_size": "100000"},
+ headers=admin_user["headers"])
+ assert r.status_code == 200
+ assert mock_paperless.LAST_DOCUMENT_QUERIES[-1]["page_size"] == ["100"]
+
+ r = client.get("/api/paperless/search",
+ query_string={"page_size": "25"},
+ headers=admin_user["headers"])
+ assert r.status_code == 200
+ assert mock_paperless.LAST_DOCUMENT_QUERIES[-1]["page_size"] == ["25"]
+
+ r = client.get("/api/paperless/search",
+ query_string={"page_size": "not-a-number"},
+ headers=admin_user["headers"])
+ assert r.status_code == 200
+ assert mock_paperless.LAST_DOCUMENT_QUERIES[-1]["page_size"] == ["25"]
diff --git a/tests/test_paperless_security.py b/tests/test_paperless_security.py
index bb4506c..a75f7f9 100644
--- a/tests/test_paperless_security.py
+++ b/tests/test_paperless_security.py
@@ -104,11 +104,14 @@ def test_attacker_create_warranty_link_blocked(client, scenario,
def test_attacker_search_and_link_blocked(client, scenario):
+ # PPL-05: the block answers exactly as a missing document (404),
+ # so the status does not reveal that the title exists or is owned.
r = client.post("/api/paperless-search-and-link", headers=scenario.b,
json={"warranty_id": scenario.wid_b,
"document_type": "other",
"search_title": "ADMIN-SECRET-INVOICE"})
- assert r.status_code == 403
+ assert r.status_code == 404
+ assert r.get_json()["message"] == "Document not found"
def test_attacker_update_warranty_link_blocked(client, scenario):