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 document ownership and access control (GHSA-fv62-3hrm-gf83, GHSA-3h89-rqfj-5674), Paperless title XSS fix, remove known compose SECRET_KEY defaults

Omega (QA)0a91742e0f37
diff --git a/CHANGELOG.md b/CHANGELOG.md
index e7dd0d0..708ceb0 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -11,6 +11,12 @@
- _Files: `backend/oidc_handler.py`, `backend/admin_routes.py`, `frontend/login.html`, `frontend/settings-new.html`, `frontend/settings-new.js`, `locales/en/translation.json`, `Docker/.env.example`_
- **Dependency and runtime updates:** flask-cors 4.0.2 β†’ 6.0.5, fixing four published CORS policy-bypass vulnerabilities in the old version (CVE-2024-6221, CVE-2024-6866, CVE-2024-6839, CVE-2024-6844). Authlib 1.8.0 β†’ 1.9.1 and PyJWT 2.15.0 β†’ 2.15.1 bring the OIDC/JWT libraries to their current patch releases, and setuptools moves to 84.0.0. The Docker base image moves from Python 3.13 to Python 3.15.
- _Files: `backend/requirements.txt`, `Dockerfile`_
+- **Paperless-ngx document access control (security, GHSA-fv62-3hrm-gf83 / GHSA-3h89-rqfj-5674):** Warracker connects to Paperless-ngx with one shared API token, and any signed-in user could list every document in the instance, link another user's document to their own warranty or claim, and then download it β€” the link itself was treated as proof of ownership. Warracker now tracks which user owns each Paperless document (recorded when a document is uploaded through Warracker or first linked; existing links are backfilled by migration). Search results are scoped to the requesting user, linking a document owned by someone else is rejected in warranty create/update, search-and-link, and claim documents, downloads follow ownership plus the usual global-view rules for shared document types, and the Paperless debug endpoints are admin-only. Claim document metadata (filenames and linked document ids) is also no longer shown to global-view readers β€” claim documents are owner/admin-only, as their contents already were.
+ - _Files: `backend/migrations/054_create_paperless_document_ownership.sql`, `backend/paperless_access.py`, `backend/file_routes.py`, `backend/warranties_routes.py`_
+- **Stored XSS via Paperless document titles (security):** the Paperless document browser rendered document titles, correspondents, and tag names into the page without escaping, so a document titled with HTML/JavaScript executed in the browser of anyone who opened the browser view β€” admins included. These fields are now HTML-escaped before rendering.
+ - _Files: `frontend/js/components/paperless.js`_
+- **Known default JWT secret removed from the compose files (security):** both shipped docker-compose files defaulted `SECRET_KEY` to a fixed value printed in this public repository, so an install that never set its own key signed its login tokens with a secret anyone could read β€” enough to forge an admin session. The compose default is now empty, which activates the backend's existing behavior of generating a random key and persisting it to a file; setting `SECRET_KEY` explicitly still takes precedence.
+ - _Files: `docker-compose.yml`, `Docker/docker-compose.yml`, `Docker/.env.example`_
## 1.0.3 - 2026-10-02
diff --git a/Docker/.env.example b/Docker/.env.example
index 2cc244b..45a9ce4 100644
--- a/Docker/.env.example
+++ b/Docker/.env.example
@@ -23,8 +23,10 @@ POSTGRES_PASSWORD=warranty_password
### Security Configuration**
# Application secret key for JWT tokens and Flask sessions
-# IMPORTANT: Generate a strong, unique secret key for production!
-SECRET_KEY=your_very_secret_flask_key_change_me
+# IMPORTANT: Generate a strong, unique secret key for production
+# (e.g. `openssl rand -hex 32`). If left empty, the app generates a
+# random key on first start and persists it to a file.
+SECRET_KEY=
# JWT token expiration time (in hours)
JWT_EXPIRATION_HOURS=24
diff --git a/Docker/docker-compose.yml b/Docker/docker-compose.yml
index c9aab49..b2e2485 100644
--- a/Docker/docker-compose.yml
+++ b/Docker/docker-compose.yml
@@ -15,7 +15,7 @@ services:
- SMTP_PORT=465
- SMTP_PASSWORD=password
- - SECRET_KEY=${APP_SECRET_KEY:-your_strong_default_secret_key_here}
+ - SECRET_KEY=${APP_SECRET_KEY:-} # Leave unset to auto-generate and persist a random key (backend config); do NOT give this a known default
- MAX_UPLOAD_MB=32 # Example: Set max upload size to 32MB
- NGINX_MAX_BODY_SIZE_VALUE=32M # For Nginx, ensure this matches MAX_UPLOAD_MB in concept (e.g., 32M)
# OIDC SSO Configuration (User needs to set these based on their OIDC provider)
diff --git a/backend/file_routes.py b/backend/file_routes.py
index 9fed308..bf8121b 100644
--- a/backend/file_routes.py
+++ b/backend/file_routes.py
@@ -9,12 +9,24 @@ try:
from . import db_handler
from .auth_utils import token_required, admin_required
from .paperless_handler import get_paperless_handler, PaperlessHandler
+ from .paperless_access import (
+ check_paperless_document_access,
+ record_paperless_document_owner,
+ user_can_link_paperless_document,
+ visible_paperless_document_ids,
+ )
from .utils import allowed_file
from .db_handler import get_db_connection, release_db_connection
except ImportError:
import db_handler
from auth_utils import token_required, admin_required
from paperless_handler import get_paperless_handler, PaperlessHandler
+ from paperless_access import (
+ check_paperless_document_access,
+ record_paperless_document_owner,
+ user_can_link_paperless_document,
+ visible_paperless_document_ids,
+ )
from utils import allowed_file
from db_handler import get_db_connection, release_db_connection
@@ -282,64 +294,15 @@ def serve_paperless_document(paperless_id: int):
# Get database connection
conn = get_db_connection()
- # Find warranty that has this Paperless document ID
+ # Authorization is based on document ownership and references, not
+ # on the presence of a link alone: linking is gated separately (see
+ # paperless_access), so a reference here was created legitimately.
with conn.cursor() as cur:
- cur.execute("""
- SELECT w.id, w.user_id
- FROM warranties w
- WHERE w.paperless_invoice_id = %s OR w.paperless_manual_id = %s
- OR w.paperless_photo_id = %s OR w.paperless_other_id = %s
- """, (paperless_id, paperless_id, paperless_id, paperless_id))
-
- results = cur.fetchall()
-
- # Claim documents (issue #148) link Paperless documents too;
- # they resolve to the owning warranty's user and stay
- # owner/admin-only (no global-view sharing, like claims).
- if not results:
- cur.execute("""
- SELECT w.id, w.user_id
- FROM claim_documents d
- JOIN warranty_claims c ON d.claim_id = c.id
- JOIN warranties w ON c.warranty_id = w.id
- WHERE d.paperless_document_id = %s
- """, (paperless_id,))
- results = cur.fetchall()
-
- if not results:
- logger.warning(f"[PAPERLESS_FILE] No warranty found with Paperless document ID {paperless_id}")
+ access = check_paperless_document_access(cur, user_id, is_admin, paperless_id)
+ if access == "not_found":
+ logger.warning(f"[PAPERLESS_FILE] No Warracker record of Paperless document ID {paperless_id}")
return jsonify({"message": "Document not found"}), 404
-
- # Check authorization
- authorized = is_admin
- if not authorized:
- for warranty_id_db, warranty_user_id_db in results:
- if warranty_user_id_db == user_id:
- authorized = True
- break
-
- # Check global view for shared documents (photos, invoices, manuals)
- if not authorized:
- cur.execute("""
- SELECT w.id, w.user_id
- FROM warranties w
- WHERE w.paperless_photo_id = %s OR w.paperless_invoice_id = %s OR w.paperless_manual_id = %s
- """, (paperless_id, paperless_id, paperless_id))
- shared_doc_results = cur.fetchall()
-
- if shared_doc_results:
- # Get global view settings
- cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
- settings = {row[0]: row[1] for row in cur.fetchall()}
-
- global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
- admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
-
- if global_view_enabled and (not admin_only or is_admin):
- authorized = True
- logger.info(f"[PAPERLESS_FILE] Global view access granted for shared Paperless document: {paperless_id}")
-
- if not authorized:
+ if access != "ok":
logger.warning(f"[PAPERLESS_FILE] Unauthorized access to Paperless document {paperless_id} by user {user_id}")
return jsonify({"message": "You are not authorized to access this document"}), 403
@@ -471,6 +434,17 @@ def paperless_upload():
if success:
logger.info("Upload successful")
+ # Record the uploader as the document's owner in Warracker, so
+ # search/linking/serving can be scoped to them. Paperless may
+ # return a non-numeric (task) id instead of a document id; only
+ # numeric ids can be tracked.
+ try:
+ numeric_document_id = int(document_id)
+ with conn.cursor() as cur:
+ record_paperless_document_owner(cur, numeric_document_id, request.user['id'])
+ conn.commit()
+ except (TypeError, ValueError):
+ logger.info(f"Upload returned non-document id {document_id!r}; ownership not recorded")
return jsonify({
"success": True,
"document_id": document_id,
@@ -621,9 +595,20 @@ def paperless_search():
'message': f'Paperless-ngx search failed: {str(e)}'
}), 400
search_result = response.json()
-
+
logger.info(f"Paperless search returned {len(search_result.get('results', []))} documents")
-
+
+ # Scope results to the requesting user: the shared Paperless token
+ # can see every document in the instance, so non-admin users only
+ # receive documents they own or reference (GHSA-fv62-3hrm-gf83).
+ if not request.user.get('is_admin', False):
+ with conn.cursor() as cur:
+ visible_ids = visible_paperless_document_ids(cur, request.user['id'], False)
+ filtered = [d for d in search_result.get('results', []) if d.get('id') in visible_ids]
+ search_result['results'] = filtered
+ search_result['count'] = len(filtered)
+ search_result['next'] = None
+
return jsonify(search_result)
except Exception as e:
@@ -680,7 +665,7 @@ def paperless_tags():
release_db_connection(conn)
@file_bp.route('/paperless/debug', methods=['GET'])
-@token_required
+@admin_required
def paperless_debug():
"""
Debug endpoint to test Paperless-ngx configuration
@@ -736,7 +721,7 @@ def paperless_debug():
release_db_connection(conn)
@file_bp.route('/paperless/test-upload', methods=['POST'])
-@token_required
+@admin_required
def test_file_upload():
"""
Test file upload mechanism without Paperless-ngx
@@ -771,7 +756,7 @@ def test_file_upload():
return jsonify({"error": f"Test upload failed: {str(e)}"}), 500
@file_bp.route('/paperless/debug-document/<int:document_id>', methods=['GET'])
-@token_required
+@admin_required
def paperless_debug_document(document_id: int):
"""
Debug endpoint to check status of a specific Paperless-ngx document
@@ -973,6 +958,19 @@ def paperless_search_and_link():
db_field = valid_types[document_type]
with conn.cursor() as cursor:
+ # The found document must belong to the requesting user (or be
+ # unclaimed); linking another user's document is what used to
+ # unlock it in serve_paperless_document (GHSA-3h89-rqfj-5674).
+ if not user_can_link_paperless_document(
+ cursor, request.user["id"], request.user.get("is_admin", False), document_id
+ ):
+ logger.warning(
+ "User %s tried to link Paperless document %s owned by another user",
+ request.user["id"],
+ document_id,
+ )
+ return jsonify({"success": False, "message": "This document belongs to another user"}), 403
+
logger.info(
"Updating warranty %s field %s with document ID %s for user %s",
warranty_id,
@@ -995,6 +993,8 @@ def paperless_search_and_link():
conn.rollback()
return jsonify({"success": False, "message": "Warranty not found or access denied"}), 404
+ record_paperless_document_owner(cursor, document_id, request.user["id"])
+
conn.commit()
logger.info("Successfully linked document %s to warranty %s", document_id, warranty_id)
diff --git a/backend/migrations/054_create_paperless_document_ownership.sql b/backend/migrations/054_create_paperless_document_ownership.sql
new file mode 100644
index 0000000..e136d8e
--- /dev/null
+++ b/backend/migrations/054_create_paperless_document_ownership.sql
@@ -0,0 +1,35 @@
+-- Migration 054: paperless_document_ownership table (security fix)
+-- Warracker talks to Paperless-ngx with one shared API token, so Paperless
+-- itself cannot say which Warracker user a document belongs to. This table
+-- records which Warracker user first brought a Paperless document into
+-- Warracker β€” by uploading it through Warracker, or by linking it to one of
+-- their warranties or claims. Search, linking, and serving are gated on it
+-- so one user cannot enumerate, attach, or download another user's Paperless
+-- documents (GHSA-fv62-3hrm-gf83, GHSA-3h89-rqfj-5674).
+CREATE TABLE IF NOT EXISTS paperless_document_ownership (
+ paperless_document_id INTEGER PRIMARY KEY,
+ user_id INTEGER NOT NULL REFERENCES users(id) ON DELETE CASCADE,
+ created_at TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP
+);
+CREATE INDEX IF NOT EXISTS idx_paperless_doc_ownership_user ON paperless_document_ownership(user_id);
+
+-- Backfill: a document already linked from a warranty belongs to that
+-- warranty's owner; a claim document belongs to the claim's warranty owner.
+-- If two users somehow reference the same document, the lowest user id wins
+-- the backfill and the other reference is handled by the runtime checks.
+INSERT INTO paperless_document_ownership (paperless_document_id, user_id)
+SELECT doc_id, MIN(user_id)
+FROM (
+ SELECT paperless_invoice_id AS doc_id, user_id FROM warranties WHERE paperless_invoice_id IS NOT NULL
+ UNION ALL SELECT paperless_manual_id, user_id FROM warranties WHERE paperless_manual_id IS NOT NULL
+ UNION ALL SELECT paperless_photo_id, user_id FROM warranties WHERE paperless_photo_id IS NOT NULL
+ UNION ALL SELECT paperless_other_id, user_id FROM warranties WHERE paperless_other_id IS NOT NULL
+ UNION ALL SELECT d.paperless_document_id, w.user_id
+ FROM claim_documents d
+ JOIN warranty_claims c ON d.claim_id = c.id
+ JOIN warranties w ON c.warranty_id = w.id
+ WHERE d.paperless_document_id IS NOT NULL
+) s
+WHERE doc_id IS NOT NULL
+GROUP BY doc_id
+ON CONFLICT (paperless_document_id) DO NOTHING;
diff --git a/backend/paperless_access.py b/backend/paperless_access.py
new file mode 100644
index 0000000..2a61727
--- /dev/null
+++ b/backend/paperless_access.py
@@ -0,0 +1,168 @@
+# backend/paperless_access.py
+"""
+Authorization helpers for Paperless-ngx documents.
+
+Warracker connects to Paperless-ngx with a single shared API token, so
+Paperless cannot distinguish Warracker users. Document ownership is tracked
+in Warracker's own database (paperless_document_ownership, migration 054):
+the user who uploaded a document through Warracker, or first linked it to
+one of their warranties or claims, owns it here.
+
+Rules:
+ - Linking (warranty create/update, search-and-link, claim documents):
+ a user may link a document they own, a document already referenced by
+ one of their own warranties/claims, or a document nobody owns or
+ references yet (first linker claims it). A document owned or referenced
+ by another user can never be linked. Admins are unrestricted.
+ - Viewing (serving): the document's owner, the owner of a warranty or
+ claim referencing it, and admins may view. When global view is enabled,
+ invoice/manual/photo documents referenced by any warranty are viewable
+ by everyone global view covers β€” the same shared types as local files.
+ "Other" documents and claim documents never join global view.
+ - Search: non-admin users only see documents they own or reference.
+"""
+
+import logging
+
+logger = logging.getLogger(__name__)
+
+_WARRANTY_ID_CONDITION = (
+ "(paperless_invoice_id = %s OR paperless_manual_id = %s "
+ "OR paperless_photo_id = %s OR paperless_other_id = %s)"
+)
+
+_SHARED_ID_CONDITION = (
+ "(paperless_invoice_id = %s OR paperless_manual_id = %s "
+ "OR paperless_photo_id = %s)"
+)
+
+
+def get_paperless_document_owner(cur, document_id):
+ """Return the owning user id for a Paperless document, or None."""
+ cur.execute(
+ "SELECT user_id FROM paperless_document_ownership WHERE paperless_document_id = %s",
+ (document_id,),
+ )
+ row = cur.fetchone()
+ return row[0] if row else None
+
+
+def record_paperless_document_owner(cur, document_id, user_id):
+ """Record ownership of a Paperless document (first recorder wins)."""
+ 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
+ """,
+ (document_id, user_id),
+ )
+
+
+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)."""
+ op = "=" if own else "<>"
+ cur.execute(
+ f"SELECT 1 FROM warranties WHERE user_id {op} %s AND {_WARRANTY_ID_CONDITION} LIMIT 1",
+ (user_id, document_id, document_id, document_id, document_id),
+ )
+ if cur.fetchone():
+ return True
+ cur.execute(
+ f"""
+ SELECT 1
+ FROM claim_documents d
+ JOIN warranty_claims c ON d.claim_id = c.id
+ JOIN warranties w ON c.warranty_id = w.id
+ WHERE d.paperless_document_id = %s AND w.user_id {op} %s
+ LIMIT 1
+ """,
+ (document_id, user_id),
+ )
+ return cur.fetchone() is not None
+
+
+def user_can_link_paperless_document(cur, user_id, is_admin, document_id):
+ """True when the user may link this Paperless document to their own
+ warranty or claim. See the module docstring for the rules."""
+ if document_id is None:
+ return True
+ if is_admin:
+ return True
+ owner = get_paperless_document_owner(cur, document_id)
+ if owner is not None:
+ return owner == user_id
+ if _referenced_by(cur, document_id, user_id, own=True):
+ return True
+ if _referenced_by(cur, document_id, user_id, own=False):
+ return False
+ return True
+
+
+def check_paperless_document_access(cur, user_id, is_admin, document_id):
+ """Access verdict for serving a Paperless document:
+ 'ok' (serve it), 'forbidden' (it exists but is not the requester's),
+ or 'not_found' (no Warracker user owns or references it)."""
+ if is_admin:
+ return "ok"
+ owner = get_paperless_document_owner(cur, document_id)
+ if owner is not None and owner == user_id:
+ return "ok"
+ if _referenced_by(cur, document_id, user_id, own=True):
+ return "ok"
+
+ # Global view: shared document types (invoice, manual, photo) referenced
+ # by any warranty are viewable by everyone global view covers.
+ cur.execute(
+ f"SELECT 1 FROM warranties WHERE {_SHARED_ID_CONDITION} LIMIT 1",
+ (document_id, document_id, document_id),
+ )
+ if cur.fetchone():
+ cur.execute(
+ "SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')"
+ )
+ settings = {row[0]: row[1] for row in cur.fetchall()}
+ global_view_enabled = settings.get("global_view_enabled", "true").lower() == "true"
+ admin_only = settings.get("global_view_admin_only", "false").lower() == "true"
+ if global_view_enabled and not admin_only:
+ return "ok"
+
+ known = owner is not None or _referenced_by(cur, document_id, user_id, own=False)
+ return "forbidden" if known else "not_found"
+
+
+def visible_paperless_document_ids(cur, user_id, is_admin):
+ """The set of Paperless document ids a user may see in search results.
+ Returns None for admins, meaning unrestricted."""
+ if is_admin:
+ return None
+ ids = set()
+ cur.execute(
+ "SELECT paperless_document_id FROM paperless_document_ownership WHERE user_id = %s",
+ (user_id,),
+ )
+ ids.update(row[0] for row in cur.fetchall())
+ cur.execute(
+ """
+ SELECT paperless_invoice_id, paperless_manual_id, paperless_photo_id, paperless_other_id
+ FROM warranties WHERE user_id = %s
+ """,
+ (user_id,),
+ )
+ for row in cur.fetchall():
+ ids.update(value for value in row if value is not None)
+ cur.execute(
+ """
+ SELECT d.paperless_document_id
+ FROM claim_documents d
+ JOIN warranty_claims c ON d.claim_id = c.id
+ JOIN warranties w ON c.warranty_id = w.id
+ WHERE w.user_id = %s AND d.paperless_document_id IS NOT NULL
+ """,
+ (user_id,),
+ )
+ ids.update(row[0] for row in cur.fetchall())
+ return ids
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 0b5a2eb..2852544 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -22,12 +22,14 @@ try:
from .db_handler import get_db_connection, release_db_connection
from .auth_utils import token_required, admin_required
from .paperless_handler import get_paperless_handler
+ from .paperless_access import user_can_link_paperless_document, record_paperless_document_owner
from .utils import allowed_file
except ImportError:
# Fallback for development environment
from db_handler import get_db_connection, release_db_connection
from auth_utils import token_required, admin_required
from paperless_handler import get_paperless_handler
+ from paperless_access import user_can_link_paperless_document, record_paperless_document_owner
from utils import allowed_file
import logging
@@ -383,13 +385,31 @@ def add_warranty():
paperless_manual_id = request.form.get('paperless_manual_id')
paperless_photo_id = request.form.get('paperless_photo_id')
paperless_other_id = request.form.get('paperless_other_id')
-
+
# Convert empty strings to None for database insertion
paperless_invoice_id = int(paperless_invoice_id) if paperless_invoice_id and paperless_invoice_id.strip() else None
paperless_manual_id = int(paperless_manual_id) if paperless_manual_id and paperless_manual_id.strip() else None
paperless_photo_id = int(paperless_photo_id) if paperless_photo_id and paperless_photo_id.strip() else None
paperless_other_id = int(paperless_other_id) if paperless_other_id and paperless_other_id.strip() else None
+ # A Paperless document may only be linked by the user who owns it in
+ # Warracker; naming another user's document id used to be enough to
+ # download it afterwards (GHSA-fv62-3hrm-gf83). Unclaimed documents
+ # are claimed by the first user who links them.
+ _paperless_ids = [pid for pid in (paperless_invoice_id, paperless_manual_id,
+ paperless_photo_id, paperless_other_id) if pid is not None]
+ if _paperless_ids:
+ _vconn = get_db_connection()
+ try:
+ with _vconn.cursor() as _vcur:
+ for _pid in _paperless_ids:
+ if not user_can_link_paperless_document(
+ _vcur, user_id, request.user.get('is_admin', False), _pid):
+ return jsonify({"error": "You are not authorized to link one of the specified Paperless documents",
+ "code": "paperless_document_not_owned"}), 403
+ finally:
+ release_db_connection(_vconn)
+
# Handle invoice file upload (only if not stored in Paperless-ngx)
db_invoice_path = None
if not paperless_invoice_id and 'invoice' in request.files:
@@ -501,7 +521,13 @@ def add_warranty():
invoice_url, manual_url, other_document_url, model_number
))
warranty_id = cur.fetchone()[0]
-
+
+ # Claim ownership of any Paperless documents linked above
+ for _pid in (paperless_invoice_id, paperless_manual_id,
+ paperless_photo_id, paperless_other_id):
+ if _pid is not None:
+ record_paperless_document_owner(cur, _pid, user_id)
+
# Insert serial numbers
if serial_numbers:
for serial_number in serial_numbers:
@@ -900,6 +926,16 @@ def update_warranty(warranty_id):
paperless_other_id = int(paperless_other_id) if paperless_other_id and paperless_other_id.strip() else None
logger.info(f"[UPDATE] Converted Paperless IDs: invoice={paperless_invoice_id}, manual={paperless_manual_id}, photo={paperless_photo_id}, other={paperless_other_id}")
+
+ # Same linking rule as warranty creation: a Paperless document
+ # owned by another user cannot be linked (GHSA-fv62-3hrm-gf83).
+ # Ownership of newly linked documents is recorded just before
+ # the final commit below.
+ for _pid in (paperless_invoice_id, paperless_manual_id,
+ paperless_photo_id, paperless_other_id):
+ if _pid is not None and not user_can_link_paperless_document(cur, user_id, is_admin, _pid):
+ return jsonify({"error": "You are not authorized to link one of the specified Paperless documents",
+ "code": "paperless_document_not_owned"}), 403
# File handling for invoice
db_invoice_path = None
@@ -1228,9 +1264,15 @@ def update_warranty(warranty_id):
''', (warranty_id, tag_id))
else:
logger.warning(f"Skipping non-existent tag ID: {tag_id}")
-
+
+ # Claim ownership of any Paperless documents linked above
+ for _pid in (paperless_invoice_id, paperless_manual_id,
+ paperless_photo_id, paperless_other_id):
+ if _pid is not None:
+ record_paperless_document_owner(cur, _pid, user_id)
+
conn.commit()
-
+
return jsonify({"message": "Warranty updated successfully"}), 200
except RequestEntityTooLarge:
@@ -2477,28 +2519,34 @@ def get_claims(warranty_id):
}
claims.append(claim)
- # Embed each claim's documents (issue #148) in one extra query
+ # Embed each claim's documents (issue #148) in one extra query.
+ # Documents are owner/admin-only even under global view, so
+ # global-view readers get the claims without document metadata.
if claims:
- claim_ids = [c['id'] for c in claims]
- cur.execute("""
- SELECT id, claim_id, original_filename, file_path, paperless_document_id, created_at
- FROM claim_documents
- WHERE claim_id = ANY(%s)
- ORDER BY created_at, id
- """, (claim_ids,))
- docs_by_claim = {}
- for drow in cur.fetchall():
- doc = {
- 'id': drow[0],
- 'claim_id': drow[1],
- 'original_filename': drow[2],
- 'file_path': drow[3],
- 'paperless_document_id': drow[4],
- 'created_at': drow[5].isoformat() if drow[5] else None
- }
- docs_by_claim.setdefault(drow[1], []).append(doc)
- for claim in claims:
- claim['documents'] = docs_by_claim.get(claim['id'], [])
+ if warranty[2] == user_id or is_admin:
+ claim_ids = [c['id'] for c in claims]
+ cur.execute("""
+ SELECT id, claim_id, original_filename, file_path, paperless_document_id, created_at
+ FROM claim_documents
+ WHERE claim_id = ANY(%s)
+ ORDER BY created_at, id
+ """, (claim_ids,))
+ docs_by_claim = {}
+ for drow in cur.fetchall():
+ doc = {
+ 'id': drow[0],
+ 'claim_id': drow[1],
+ 'original_filename': drow[2],
+ 'file_path': drow[3],
+ 'paperless_document_id': drow[4],
+ 'created_at': drow[5].isoformat() if drow[5] else None
+ }
+ docs_by_claim.setdefault(drow[1], []).append(doc)
+ for claim in claims:
+ claim['documents'] = docs_by_claim.get(claim['id'], [])
+ else:
+ for claim in claims:
+ claim['documents'] = []
return jsonify(claims), 200
@@ -2756,6 +2804,14 @@ def add_claim_document(warranty_id, claim_id):
except (TypeError, ValueError):
return jsonify({'error': 'Invalid paperless_document_id'}), 400
+ # Claim documents follow the same Paperless linking rule as
+ # warranties: another user's document cannot be linked here either
+ # (GHSA-fv62-3hrm-gf83 / GHSA-3h89-rqfj-5674 via the claims path).
+ if paperless_document_id is not None and not user_can_link_paperless_document(
+ cur, user_id, request.user.get('is_admin', False), paperless_document_id):
+ return jsonify({'error': 'You are not authorized to link this Paperless document',
+ 'code': 'paperless_document_not_owned'}), 403
+
db_file_path = None
original_filename = None
@@ -2791,6 +2847,8 @@ def add_claim_document(warranty_id, claim_id):
""", (claim_id, original_filename, db_file_path, paperless_document_id))
document = _serialize_claim_document(cur.fetchone())
+ if paperless_document_id is not None:
+ record_paperless_document_owner(cur, paperless_document_id, user_id)
conn.commit()
logger.info(f"Added document {document['id']} to claim {claim_id} by user {user_id}")
@@ -2812,8 +2870,9 @@ def add_claim_document(warranty_id, claim_id):
@warranties_bp.route('/warranties/<int:warranty_id>/claims/<int:claim_id>/documents', methods=['GET'])
@token_required
def get_claim_documents(warranty_id, claim_id):
- """List a claim's documents. Read access follows the claims list:
- the warranty owner, admins, and global-view users may read."""
+ """List a claim's documents. Owner and admins only: claim documents are
+ private even under global view, and their metadata (filenames, linked
+ Paperless ids) stays private with them."""
conn = None
cur = None
@@ -2834,12 +2893,7 @@ def get_claim_documents(warranty_id, claim_id):
return jsonify({'error': 'Warranty or claim not found'}), 404
if owner_row[0] != user_id and not is_admin:
- cur.execute("SELECT key, value FROM site_settings WHERE key IN ('global_view_enabled', 'global_view_admin_only')")
- settings = {row[0]: row[1] for row in cur.fetchall()}
- global_view_enabled = settings.get('global_view_enabled', 'true').lower() == 'true'
- admin_only = settings.get('global_view_admin_only', 'false').lower() == 'true'
- if not global_view_enabled or admin_only:
- return jsonify({'error': 'Warranty or claim not found or access denied'}), 404
+ return jsonify({'error': 'Warranty or claim not found or access denied'}), 404
cur.execute("""
SELECT id, claim_id, original_filename, file_path, paperless_document_id, created_at
diff --git a/docker-compose.yml b/docker-compose.yml
index 214eed1..18aee47 100644
--- a/docker-compose.yml
+++ b/docker-compose.yml
@@ -22,7 +22,7 @@ services:
- SMTP_PASSWORD=${SMTP_PASSWORD:-}
# if SMTP_FROM_ADDRESS isn't defined, then SMTP_USERNAME will be used - but that may not always work
- SMTP_FROM_ADDRESS=${SMTP_FROM_ADDRESS:-}
- - SECRET_KEY=${SECRET_KEY:-your_very_secret_flask_key_change_me} # For Flask session and JWT
+ - SECRET_KEY=${SECRET_KEY:-} # Leave unset to auto-generate and persist a random key (backend config); do NOT give this a known default # For Flask session and JWT
# OIDC SSO Configuration (User needs to set these based on their OIDC provider)
- OIDC_PROVIDER_NAME=${OIDC_PROVIDER_NAME:-oidc}
- OIDC_CLIENT_ID=${OIDC_CLIENT_ID:-} # e.g., your_oidc_client_id
diff --git a/frontend/js/components/paperless.js b/frontend/js/components/paperless.js
index 960943c..5803aa6 100644
--- a/frontend/js/components/paperless.js
+++ b/frontend/js/components/paperless.js
@@ -28,6 +28,18 @@ function getAuthToken() {
return authService.getToken() || localStorage.getItem('auth_token');
}
+// Paperless document fields (title, correspondent, tag names) are
+// user-controlled text from the Paperless instance; they must be escaped
+// before being placed into innerHTML.
+function escapeHtml(value = '') {
+ return String(value)
+ .replace(/&/g, '&amp;')
+ .replace(/</g, '&lt;')
+ .replace(/>/g, '&gt;')
+ .replace(/"/g, '&quot;')
+ .replace(/'/g, '&#39;');
+}
+
function getSelectionInputId(documentType) {
if (documentType.startsWith('edit_')) {
const base = documentType.replace('edit_', '');
@@ -513,15 +525,15 @@ function renderPaperlessDocuments() {
item.className = 'paperless-document-item';
item.dataset.id = doc.id;
item.innerHTML = `
- <div class="document-title">${doc.title || ''}</div>
+ <div class="document-title">${escapeHtml(doc.title || '')}</div>
<div class="document-meta">
<span><i class="fas fa-calendar"></i> ${doc.created ? new Date(doc.created).toLocaleDateString() : ''}</span>
- <span><i class="fas fa-file"></i> ${doc.mime_type || 'Unknown'}</span>
- ${doc.correspondent ? `<span><i class="fas fa-user"></i> ${doc.correspondent}</span>` : ''}
+ <span><i class="fas fa-file"></i> ${escapeHtml(doc.mime_type || 'Unknown')}</span>
+ ${doc.correspondent ? `<span><i class="fas fa-user"></i> ${escapeHtml(doc.correspondent)}</span>` : ''}
</div>
${Array.isArray(doc.tags) && doc.tags.length ? `
<div class="document-tags">
- ${doc.tags.map((tag) => `<span class="document-tag">${tag}</span>`).join('')}
+ ${doc.tags.map((tag) => `<span class="document-tag">${escapeHtml(tag)}</span>`).join('')}
</div>` : ''}
`;
item.addEventListener('click', () => selectPaperlessDocument(doc.id));