Skip to content

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

Harden proxy headers, Nginx/CSP, Paperless strict mode, JWT transport, and account cleanup

sassanixadce57a4b256
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 4055bee..5e1cadd 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -2,6 +2,22 @@
## 1.0.8 - Unreleased
+- **Security hardening — proxy headers, Nginx/CSP, Paperless strict ownership, JWT transport, and account cleanup:**
+ - Bundled Nginx now trusts `X-Forwarded-Proto` only from loopback/LAN/Docker proxy ranges (or all peers when `TRUST_PROXY_HEADERS=true`, and none when `TRUST_PROXY_HEADERS=false`), strips `X-Forwarded-Host` and `X-Forwarded-Prefix`, removes duplicate `Access-Control-*` headers (leaving Flask-CORS as the single source of truth), removes the `/test-uploads` debug route and `X-Debug-Message` header, and emits `X-Content-Type-Options: nosniff` globally alongside Flask. Gunicorn's `forwarded_allow_ips` is scoped to loopback by default (`127.0.0.1,::1`), private proxy CIDRs when `DISABLE_NGINX=true`, and configurable via `GUNICORN_FORWARDED_ALLOW_IPS` / `TRUST_PROXY_HEADERS`. OIDC login derives `redirect_uri` from `APP_BASE_URL` / `FRONTEND_URL` when explicitly configured.
+ - Replaced the remote Buy Me a Coffee script on the About page with a static styled link and removed `buymeacoffee.com` from the Content-Security-Policy.
+ - Added an opt-in **Restrict Pre-Existing Documents to Admins** (`paperless_strict_ownership`, off by default) toggle in Paperless-ngx settings so shared Paperless instances can prevent standard users from claiming pre-existing unowned documents.
+ - Backend JWT authentication now accepts tokens strictly via the `Authorization: Bearer` header (rejecting `?token=` query-string and form fallbacks), and the Service Worker skips `/api/` routes and `Cache-Control: no-store` responses.
+ - Local accounts now confirm their current password before self-deleting (`DELETE /api/auth/account`; passwordless OIDC accounts are unaffected), unreferenced uploaded warranty and claim files are deleted from disk when a user or account is deleted, password-reset emails dispatch asynchronously to avoid SMTP timing enumeration, and warranty/document web URLs are validated to `http://` or `https://` (auto-prefixing bare domains with `https://`).
+ - _Files: `nginx.conf`, `Docker/entrypoint.sh`, `backend/__init__.py`, `backend/admin_routes.py`, `backend/auth_routes.py`, `backend/auth_utils.py`, `backend/gunicorn_config.py`, `backend/oidc_handler.py`, `backend/paperless_access.py`, `backend/warranties_routes.py`, `frontend/about.html`, `frontend/settings-new.html`, `frontend/settings-new.js`, `frontend/sw.js`, `tests/test_security_headers.py`, `tests/test_user_account_and_preferences.py`, `tests/test_hardening_pass2.py`_
+
+- **Security hardening — file containment, owner protection, XSS/SSRF defenses, and container permissions (#302):**
+ - Local file routes (`/api/files/` and `/api/secure-file/`) now require a matching warranty or claim database reference even for admins, reject dotfiles (such as `.secret_key`), and reject symlinks or paths escaping `UPLOAD_FOLDER`.
+ - Document serving (`/api/files/`, `/api/secure-file/`, `/api/paperless-file/`) and frontend blob viewers allow inline rendering only for passive MIME types (PDF, PNG, JPEG, WebP, GIF, plain text) with `Content-Security-Policy: default-src 'none'; frame-ancestors 'self'`; active or unrecognized types are forced to download as `application/octet-stream` with `Content-Security-Policy: sandbox`.
+ - Admin user updates (`PUT /api/admin/users/<id>`) strictly require boolean types for `is_admin`/`is_active`, block non-owner admins from editing any field (including email) on an Application Owner account, and perform case-insensitive email uniqueness checks.
+ - Hardened the product-photo SSRF IP check to also reject RFC 8215 local-use NAT64 (`64:ff9b:1::/48`), SIIT IPv4-translated (`::ffff:0:0:0/96`), multicast, reserved, and unspecified addresses; separated `root` vs `warracker` ownership in the Docker image, moved staged Nginx config from `/tmp` to root-only `/run/nginx-init`, and prevented `fix_permissions.py` from following symlinks.
+ - Escaped remaining frontend XSS sinks across `login.html`, `settings-new.js`, `script.js`, `paperless.js`, `status.js`, and `currency.js`, hardened URL control-character sanitization, made OIDC code exchange and password-reset token redemption atomic (`DELETE ... RETURNING`), fixed OIDC string-group substring matching and inactive OIDC user redirects, closed the Paperless `search-and-link` title oracle, redacted other users' emails and private `other_document` metadata from Global View responses for non-admins, bounded rate-limiter memory with a secondary per-IP login cap, released DB connections before outbound Paperless/photo HTTP calls, redacted Apprise URL credentials from logs, removed raw `str(e)` details from 500 responses, and set `DefaultConfig.DEBUG = False`.
+ - _Files: `Dockerfile`, `Docker/entrypoint.sh`, `Docker/nginx-wrapper.sh`, `backend/admin_routes.py`, `backend/apprise_handler.py`, `backend/audit_logger.py`, `backend/auth_routes.py`, `backend/config.py`, `backend/file_routes.py`, `backend/fix_permissions.py`, `backend/notifications.py`, `backend/oidc_handler.py`, `backend/rate_limit.py`, `backend/statistics_routes.py`, `backend/warranties_routes.py`, `frontend/file-utils.js`, `frontend/js/components/claims.js`, `frontend/js/components/paperless.js`, `frontend/js/components/warrantyRenderer.js`, `frontend/js/lib/currency.js`, `frontend/login.html`, `frontend/script.js`, `frontend/settings-new.js`, `frontend/status.js`, `tests/test_hardening_regressions.py`_
+
- **Product photo fetch pins the connection to the validated address (GHSA-7rwc-pg49-r48w):** the photo-by-URL fetch used to validate a hostname and then let the HTTP client resolve it again at connect time, so a DNS answer that changed between the two lookups could steer the connection to a private address the guard never saw. The fetch now resolves each hop hostname exactly once, validates every returned address, and connects to a validated public address (preferring IPv4 on dual-stack hosts so IPv4-only Docker containers can still connect, and falling back to IPv6 for IPv6-only hosts), with no second lookup and no failover. For https the connection still presents the original hostname as SNI and verifies the certificate against it, and the Host header still carries the original hostname. The fetch also no longer follows environment proxy settings, since a proxy would resolve the hostname itself.
- _Files: `backend/warranties_routes.py`, `tests/test_photo_url.py`_
diff --git a/Docker/entrypoint.sh b/Docker/entrypoint.sh
index ba3a4cc..abe726b 100644
--- a/Docker/entrypoint.sh
+++ b/Docker/entrypoint.sh
@@ -109,8 +109,26 @@ if ! echo "${EFFECTIVE_SIZE}" | grep -Eq "^[0-9]+[mMkKgG]?$"; then
log "Warning: Invalid NGINX_MAX_BODY_SIZE_VALUE. Using default 32M"
EFFECTIVE_SIZE="32M"
fi
+TRUST_PROXY_MODE="${TRUST_PROXY_HEADERS:-}"
+case "${TRUST_PROXY_MODE,,}" in
+ true)
+ NGINX_TRUST_ALL_PROXIES=1
+ NGINX_TRUST_PRIVATE_PROXIES=1
+ ;;
+ false)
+ NGINX_TRUST_ALL_PROXIES=0
+ NGINX_TRUST_PRIVATE_PROXIES=0
+ ;;
+ *)
+ NGINX_TRUST_ALL_PROXIES=0
+ NGINX_TRUST_PRIVATE_PROXIES=1
+ ;;
+esac
mkdir -p -m 700 /run/nginx-init
-sed "s|__NGINX_MAX_BODY_SIZE_CONFIG_VALUE__|${EFFECTIVE_SIZE}|g" \
+sed \
+ -e "s|__NGINX_MAX_BODY_SIZE_CONFIG_VALUE__|${EFFECTIVE_SIZE}|g" \
+ -e "s|__NGINX_TRUST_ALL_PROXIES__|${NGINX_TRUST_ALL_PROXIES}|g" \
+ -e "s|__NGINX_TRUST_PRIVATE_PROXIES__|${NGINX_TRUST_PRIVATE_PROXIES}|g" \
/etc/nginx/conf.d/default.conf.template > /run/nginx-init/default.conf
log "Nginx config prepared (size: ${EFFECTIVE_SIZE})"
diff --git a/backend/__init__.py b/backend/__init__.py
index 455ede1..7d56020 100644
--- a/backend/__init__.py
+++ b/backend/__init__.py
@@ -175,23 +175,22 @@ def ensure_owner_exists():
# styles throughout, so script-src and style-src keep 'unsafe-inline';
# the policy still pins the fetchable origins, blocks plugins and
# foreign framing, and keeps form submissions and base URIs
-# same-origin. The third-party allowances are load-bearing: the About
-# page loads the Buy Me a Coffee button script, which fetches its
-# font and images from the buymeacoffee and Google Fonts hosts,
-# version-checker.js fetches the latest release from api.github.com,
-# and style.css uses an Unsplash photo as a page background.
+# same-origin. The third-party allowances are load-bearing: Google
+# Fonts serves stylesheet/font assets, version-checker.js fetches the
+# latest release from api.github.com, and style.css uses an Unsplash
+# photo as a page background.
# upgrade-insecure-requests is intentionally omitted: self-hosted
# installs on plain HTTP (LAN IP, localhost, Unraid, Proxmox, TrueNAS)
# would otherwise have browsers rewrite same-origin subresources to
# https:// and fail to load.
_CONTENT_SECURITY_POLICY = (
"default-src 'self'; "
- "script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; "
+ "script-src 'self' 'unsafe-inline'; "
"style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; "
- "img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; "
+ "img-src 'self' data: blob: https://images.unsplash.com; "
"font-src 'self' data: https://fonts.gstatic.com; "
"connect-src 'self' https://api.github.com; "
- "frame-src 'self' https://*.buymeacoffee.com; "
+ "frame-src 'self'; "
"object-src 'none'; "
"base-uri 'self'; "
"form-action 'self'; "
@@ -231,6 +230,8 @@ def create_app(config_name=None):
# origin cross-origin, and nothing on an HTTPS to HTTP drop.
response.headers.setdefault(
'Referrer-Policy', 'strict-origin-when-cross-origin')
+ # Prevent MIME-type sniffing globally on all Flask responses.
+ response.headers.setdefault('X-Content-Type-Options', 'nosniff')
return response
# Load configuration
diff --git a/backend/admin_routes.py b/backend/admin_routes.py
index 1ada3fb..40e971c 100644
--- a/backend/admin_routes.py
+++ b/backend/admin_routes.py
@@ -248,6 +248,33 @@ def delete_user(user_id):
return jsonify({"message": "The application owner cannot be deleted."}), 403
logger.info(f"Deleting user {user[1]} (ID: {user[0]})")
+
+ # Collect local uploaded file paths owned by this user before deleting
+ # their rows so orphaned files on disk can be removed post-commit.
+ user_file_paths = []
+ cur.execute('''
+ SELECT invoice_path, manual_path, other_document_path, product_photo_path
+ FROM warranties
+ WHERE user_id = %s
+ ''', (user_id,))
+ for row in cur.fetchall():
+ for p in row:
+ if p:
+ user_file_paths.append(p)
+ try:
+ cur.execute('''
+ SELECT d.file_path
+ 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.file_path IS NOT NULL
+ ''', (user_id,))
+ for (p,) in cur.fetchall():
+ if p:
+ user_file_paths.append(p)
+ except Exception as claim_doc_err:
+ logger.warning(f"Could not collect claim document paths for user {user_id}: {claim_doc_err}")
+ conn.rollback()
# Delete user's warranties first
cur.execute('DELETE FROM warranties WHERE user_id = %s', (user_id,))
@@ -277,6 +304,16 @@ def delete_user(user_id):
conn.commit()
logger.info(f"User {user_id} deleted successfully")
+ # Remove unreferenced local files on disk after commit succeeds.
+ if user_file_paths:
+ try:
+ from .warranties_routes import _delete_stored_file
+ except ImportError:
+ from warranties_routes import _delete_stored_file
+ for stored_path in set(user_file_paths):
+ _delete_stored_file(cur, stored_path)
+ conn.rollback()
+
# Audit log for user deletion
try:
create_audit_log('DELETE_USER', target_type='User', target_id=user_id, details=f"Deleted user {user[1]} (ID: {user_id})")
@@ -417,6 +454,7 @@ SITE_SETTING_KEYS = frozenset({
'paperless_enabled',
'paperless_url',
'paperless_api_token',
+ 'paperless_strict_ownership',
})
# Setting keys whose values must never appear in audit entries, beyond
@@ -499,6 +537,7 @@ def get_site_settings():
# Paperless-ngx integration settings
'paperless_enabled': 'false',
'paperless_url': '',
+ 'paperless_strict_ownership': 'false',
# 'paperless_api_token': '', # Not returned directly
}
@@ -512,7 +551,7 @@ def get_site_settings():
continue
# For boolean-like string settings, ensure they are 'true' or 'false'
- if key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'oidc_skip_login_screen', 'apprise_enabled', 'global_view_enabled', 'global_view_admin_only', 'paperless_enabled']:
+ if key in ['registration_enabled', 'oidc_enabled', 'oidc_only_mode', 'oidc_skip_login_screen', 'apprise_enabled', 'global_view_enabled', 'global_view_admin_only', 'paperless_enabled', 'paperless_strict_ownership']:
settings_to_return[key] = 'true' if value.lower() == 'true' else 'false'
else:
settings_to_return[key] = value
diff --git a/backend/auth_routes.py b/backend/auth_routes.py
index 56f4f54..e4da906 100644
--- a/backend/auth_routes.py
+++ b/backend/auth_routes.py
@@ -10,6 +10,7 @@ import hashlib
import json
import os
import re
+import threading
import pytz
import psycopg2
from psycopg2.extras import Json
@@ -438,23 +439,23 @@ def get_user():
# Try to get user with is_owner column, fall back to without it if column doesn't exist
try:
cur.execute(
- 'SELECT id, username, email, first_name, last_name, is_admin, is_owner, oidc_sub FROM users WHERE id = %s',
+ 'SELECT id, username, email, first_name, last_name, is_admin, is_owner, oidc_sub, (password_hash IS NOT NULL) FROM users WHERE id = %s',
(user_id,)
)
user_data = cur.fetchone()
has_owner_column = True
- columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin', 'is_owner', 'oidc_managed']
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin', 'is_owner', 'oidc_managed', 'has_password']
except Exception as e:
# If the query fails (likely because is_owner column doesn't exist), rollback and try again
current_app.logger.warning(f"Failed to query with is_owner column in get_user, falling back: {e}")
conn.rollback() # Rollback the failed transaction
cur.execute(
- 'SELECT id, username, email, first_name, last_name, is_admin FROM users WHERE id = %s',
+ 'SELECT id, username, email, first_name, last_name, is_admin, (password_hash IS NOT NULL) FROM users WHERE id = %s',
(user_id,)
)
user_data = cur.fetchone()
has_owner_column = False
- columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin', 'oidc_managed']
+ columns = ['id', 'username', 'email', 'first_name', 'last_name', 'is_admin', 'has_password']
# --- END DATABASE QUERY ---
if not user_data:
@@ -466,9 +467,11 @@ def get_user():
# Add is_owner field if it wasn't included in the query
if not has_owner_column:
user_info['is_owner'] = False
-
- # Turn oidc_sub into a boolean
- user_info['oidc_managed'] = user_info['oidc_managed'] is not None
+ user_info['oidc_managed'] = False
+ else:
+ # Turn oidc_sub into a boolean
+ user_info['oidc_managed'] = user_info['oidc_managed'] is not None
+ user_info['has_password'] = bool(user_info.get('has_password', False))
# Return the full user information
return jsonify(user_info), 200
@@ -494,8 +497,8 @@ def request_password_reset():
conn = db_handler.get_db_connection()
with conn.cursor() as cur:
- # Check if user exists
- cur.execute('SELECT id, oidc_sub FROM users WHERE email = %s', (email,))
+ # Check if user exists (case-insensitive)
+ cur.execute('SELECT id, oidc_sub, email FROM users WHERE LOWER(email) = LOWER(%s)', (email,))
user = cur.fetchone()
if not user:
@@ -503,6 +506,7 @@ def request_password_reset():
return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
user_id = user[0]
+ stored_email = user[2]
# AUTH-12: under OIDC-only mode, an OIDC-managed account must
# never gain a local password from a reset. Answer with the
@@ -515,9 +519,9 @@ def request_password_reset():
# gets the same generic 200 as an unknown address, and no
# token is minted and no mail is sent, so the endpoint
# cannot be used as an unauthenticated mail relay.
- if reset_request_limited(email):
+ if reset_request_limited(stored_email):
current_app.logger.warning(
- f"Password reset requests rate-limited for {email}.")
+ f"Password reset requests rate-limited for {stored_email}.")
return jsonify({'message': 'If your email is registered, you will receive a password reset link.'}), 200
# Generate reset token. Only its hash is stored (AUTH-08), so
@@ -536,7 +540,7 @@ def request_password_reset():
)
conn.commit()
- record_reset_request(email)
+ record_reset_request(stored_email)
# Get email base URL from settings with correct precedence
# Priority: Environment Variable > Database Setting > Hardcoded Default
@@ -553,28 +557,35 @@ def request_password_reset():
current_app.logger.warning("email_base_url setting not found for password reset, using default.")
except Exception as e:
current_app.logger.error(f"Error fetching email_base_url from settings for password reset: {e}. Using default.")
-
- # Ensure base URL doesn't end with a slash
- email_base_url = email_base_url.rstrip('/')
- # Construct the full reset link
- reset_link = f"{email_base_url}/reset-password.html?token={reset_token}" # Use base URL and correct page
-
- # Send password reset email
- current_app.logger.info(f"Password reset requested for user {user_id}. Preparing to send email.")
- try:
- send_password_reset_email(email, reset_link)
- current_app.logger.info(f"Password reset email initiated for {email}")
- except Exception as e:
- current_app.logger.error(f"Failed to send password reset email to {email}: {e}")
- # Even if email fails, don't tell the user.
- # This prevents leaking information about registered emails or email server issues.
- # The user journey remains the same: "If registered, you'll get an email."
-
- # Always return success to the user, regardless of email success/failure
- return jsonify({
- 'message': 'If your email is registered, you will receive a password reset link.'
- }), 200
+ # Release the DB connection before dispatching background SMTP work.
+ db_handler.release_db_connection(conn)
+ conn = None
+
+ # Ensure base URL doesn't end with a slash
+ email_base_url = email_base_url.rstrip('/')
+
+ # Construct the full reset link
+ reset_link = f"{email_base_url}/reset-password.html?token={reset_token}"
+
+ # Dispatch email asynchronously so SMTP latency cannot be used as a
+ # timing oracle to enumerate registered email addresses (L-03).
+ current_app.logger.info(f"Password reset requested for user {user_id}. Dispatching async email.")
+ app_obj = current_app._get_current_object()
+
+ def _send_async():
+ with app_obj.app_context():
+ try:
+ send_password_reset_email(stored_email, reset_link)
+ except Exception as mail_err:
+ app_obj.logger.error(f"Failed to send password reset email to {stored_email}: {mail_err}")
+
+ threading.Thread(target=_send_async, daemon=True).start()
+
+ # Always return success to the user, regardless of email success/failure
+ return jsonify({
+ 'message': 'If your email is registered, you will receive a password reset link.'
+ }), 200
except Exception as e:
current_app.logger.error(f"Password reset request error: {e}")
@@ -719,6 +730,8 @@ def update_profile():
@token_required
def delete_account():
user_id = request.user['id']
+ data = request.get_json(silent=True) or {}
+ supplied_password = data.get('password')
try:
# Get database connection
@@ -729,21 +742,65 @@ def delete_account():
# Begin transaction
cursor.execute("BEGIN")
- # Check if the current user is the owner
+ # Check if the current user is the owner and whether they have a local password
try:
- cursor.execute('SELECT is_owner FROM users WHERE id = %s', (user_id,))
+ cursor.execute('SELECT is_owner, password_hash FROM users WHERE id = %s', (user_id,))
user_data = cursor.fetchone()
is_owner = user_data[0] if user_data and len(user_data) > 0 else False
+ current_password_hash = user_data[1] if user_data and len(user_data) > 1 else None
except Exception as e:
# If the query fails (likely because is_owner column doesn't exist), try without it
current_app.logger.warning(f"Failed to query with is_owner column in delete_account, falling back: {e}")
cursor.execute("ROLLBACK") # Rollback the failed transaction
cursor.execute("BEGIN") # Start a new transaction
+ cursor.execute('SELECT password_hash FROM users WHERE id = %s', (user_id,))
+ pw_row = cursor.fetchone()
is_owner = False
+ current_password_hash = pw_row[0] if pw_row else None
if is_owner:
cursor.execute("ROLLBACK")
return jsonify({'message': 'The application owner cannot delete their own account. Please transfer ownership first.'}), 403
+
+ # Require current password confirmation for local accounts (L-03).
+ # Passwordless OIDC-only accounts (password_hash IS NULL) are unaffected.
+ if current_password_hash:
+ if not supplied_password or not isinstance(supplied_password, str):
+ cursor.execute("ROLLBACK")
+ return jsonify({'message': 'Current password is required to delete your account'}), 400
+ if not bcrypt.check_password_hash(current_password_hash, supplied_password):
+ cursor.execute("ROLLBACK")
+ return jsonify({'message': 'Incorrect password'}), 401
+
+ # Collect local uploaded file paths owned by this user before deleting
+ # their rows so orphaned files on disk can be removed post-commit.
+ user_file_paths = []
+ cursor.execute('''
+ SELECT invoice_path, manual_path, other_document_path, product_photo_path
+ FROM warranties
+ WHERE user_id = %s
+ ''', (user_id,))
+ for row in cursor.fetchall():
+ for p in row:
+ if p:
+ user_file_paths.append(p)
+ try:
+ cursor.execute("SAVEPOINT collect_claim_docs")
+ cursor.execute('''
+ SELECT d.file_path
+ 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.file_path IS NOT NULL
+ ''', (user_id,))
+ for (p,) in cursor.fetchall():
+ if p:
+ user_file_paths.append(p)
+ cursor.execute("RELEASE SAVEPOINT collect_claim_docs")
+ except Exception as claim_doc_err:
+ current_app.logger.warning(f"Could not collect claim document paths for user {user_id}: {claim_doc_err}")
+ cursor.execute("ROLLBACK TO SAVEPOINT collect_claim_docs")
+ cursor.execute("RELEASE SAVEPOINT collect_claim_docs")
# Delete user's warranties
cursor.execute("DELETE FROM warranties WHERE user_id = %s", (user_id,))
@@ -768,6 +825,16 @@ def delete_account():
# Commit transaction
cursor.execute("COMMIT")
+
+ # Remove unreferenced local files on disk after commit succeeds.
+ if user_file_paths:
+ try:
+ from .warranties_routes import _delete_stored_file
+ except ImportError:
+ from warranties_routes import _delete_stored_file
+ for stored_path in set(user_file_paths):
+ _delete_stored_file(cursor, stored_path)
+ conn.rollback()
return jsonify({'message': 'Account deleted successfully'}), 200
@@ -1015,9 +1082,7 @@ def send_password_reset_email(recipient_email, reset_link):
app_name = "Warracker"
subject = f"Password Reset - {app_name}"
-
- app_base_url = os.environ.get('APP_BASE_URL', request.url_root.rstrip('/'))
-
+
html_content = f"""
<html>
<body>
diff --git a/backend/auth_utils.py b/backend/auth_utils.py
index 7767f21..593fd26 100644
--- a/backend/auth_utils.py
+++ b/backend/auth_utils.py
@@ -69,19 +69,13 @@ def token_required(f):
def decorated(*args, **kwargs):
token = None
- # Get token from Authorization header
+ # Get token exclusively from the Authorization Bearer header (L-01).
+ # Query-string ?token= and form-field fallbacks are rejected so JWTs
+ # never leak into browser history, referrer headers, or access logs.
auth_header = request.headers.get('Authorization')
if auth_header and auth_header.startswith('Bearer '):
- token = auth_header.split(' ')[1]
-
- # If no token in header, check form data for POST requests
- if not token and request.method == 'POST':
- token = request.form.get('auth_token') # Check form data
-
- # If still no token, check URL query parameters
- if not token:
- token = request.args.get('token') # Check query parameters
-
+ token = auth_header.split(' ', 1)[1].strip()
+
# If no token is provided
if not token:
current_app.logger.warning(f"Authentication attempt without token: {request.path}")
diff --git a/backend/gunicorn_config.py b/backend/gunicorn_config.py
index be3bf89..2610836 100644
--- a/backend/gunicorn_config.py
+++ b/backend/gunicorn_config.py
@@ -42,7 +42,30 @@ import multiprocessing
# Server configurations - Dynamic based on memory mode
bind = "0.0.0.0:5000"
-forwarded_allow_ips = '*' # Trust proxy headers from any source (safe in containerized environment)
+
+
+def _resolve_forwarded_allow_ips():
+ """Limit which peers Gunicorn trusts for X-Forwarded-* headers (H-03).
+
+ In the default container, bundled Nginx connects over loopback so only
+ 127.0.0.1/::1 should be trusted. When DISABLE_NGINX=true, allow loopback
+ and private LAN/Docker proxy CIDRs matching backend._forwarded_headers_trusted.
+ Operators can override via GUNICORN_FORWARDED_ALLOW_IPS or TRUST_PROXY_HEADERS.
+ """
+ explicit = os.environ.get('GUNICORN_FORWARDED_ALLOW_IPS', '').strip()
+ if explicit:
+ return explicit
+ trust_override = os.environ.get('TRUST_PROXY_HEADERS', '').strip().lower()
+ if trust_override == 'true':
+ return '*'
+ if trust_override == 'false':
+ return ''
+ if os.environ.get('DISABLE_NGINX', 'false').strip().lower() == 'true':
+ return '127.0.0.1,::1,10.0.0.0/8,172.16.0.0/12,192.168.0.0/16,169.254.0.0/16,fc00::/7,fe80::/10'
+ return '127.0.0.1,::1'
+
+
+forwarded_allow_ips = _resolve_forwarded_allow_ips()
# Determine worker class first, then apply appropriate monkey patching
if memory_mode == 'ultra-light':
diff --git a/backend/oidc_handler.py b/backend/oidc_handler.py
index fe610bc..59b6d95 100644
--- a/backend/oidc_handler.py
+++ b/backend/oidc_handler.py
@@ -154,8 +154,15 @@ def oidc_login_route():
logger.error("[OIDC_HANDLER] OIDC is enabled but provider name not configured.")
return jsonify({'message': 'OIDC provider not configured correctly.'}), 500
- # Corrected url_for to use blueprint name
- redirect_uri = url_for('oidc.oidc_callback_route', _external=True)
+ # Prefer an explicitly configured public base URL so OIDC redirect_uri
+ # cannot be influenced by spoofed Host/X-Forwarded-* headers (H-03).
+ # Falls back to url_for(..., _external=True) for zero-config installs.
+ configured_base = (os.environ.get('APP_BASE_URL') or os.environ.get('FRONTEND_URL') or '').strip()
+ if configured_base.startswith(('http://', 'https://')):
+ callback_path = url_for('oidc.oidc_callback_route', _external=False)
+ redirect_uri = f"{configured_base.rstrip('/')}{callback_path}"
+ else:
+ redirect_uri = url_for('oidc.oidc_callback_route', _external=True)
# HTTPS check for production
if os.environ.get('FLASK_ENV') == 'production' and not redirect_uri.startswith('https'):
diff --git a/backend/paperless_access.py b/backend/paperless_access.py
index 2a7f185..333023e 100644
--- a/backend/paperless_access.py
+++ b/backend/paperless_access.py
@@ -118,6 +118,19 @@ def _referenced_by(cur, document_id, user_id, own):
return cur.fetchone() is not None
+def is_paperless_strict_ownership_enabled(cur):
+ """True when admin enabled strict ownership (preventing non-admins from
+ claiming pre-existing unowned Paperless documents)."""
+ try:
+ cur.execute(
+ "SELECT value FROM site_settings WHERE key = 'paperless_strict_ownership'"
+ )
+ row = cur.fetchone()
+ return bool(row and str(row[0]).lower() == 'true')
+ except Exception:
+ return False
+
+
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."""
@@ -132,6 +145,10 @@ def user_can_link_paperless_document(cur, user_id, is_admin, document_id):
return True
if _referenced_by(cur, document_id, user_id, own=False):
return False
+ # Unowned and unreferenced document: allowed by default for first-linker
+ # claiming, or restricted to admins when paperless_strict_ownership=true.
+ if is_paperless_strict_ownership_enabled(cur):
+ return False
return True
diff --git a/backend/warranties_routes.py b/backend/warranties_routes.py
index 2650c52..dc8ca21 100644
--- a/backend/warranties_routes.py
+++ b/backend/warranties_routes.py
@@ -220,6 +220,42 @@ def _ip_address_is_public(addr):
return _is_strictly_public_unicast(addr)
+def _validate_http_url(raw_url, field_label="URL"):
+ """Validate and normalize an optional user-supplied web URL (M-01).
+
+ Empty/None values pass through unchanged. Control characters and
+ non-HTTP(S) schemes (javascript:, data:, vbscript:, file:, ftp:, etc.)
+ are rejected with ValueError. Bare hostnames without a scheme (e.g.
+ 'example.com/item') are normalized to 'https://...' so existing user
+ entry habits continue to work without surprises.
+ """
+ if raw_url is None:
+ return None
+ if not isinstance(raw_url, str):
+ raise ValueError(f"{field_label} must be a valid http:// or https:// URL")
+ trimmed = raw_url.strip()
+ if not trimmed:
+ return ''
+ if any(ord(ch) < 0x20 or ord(ch) == 0x7f for ch in trimmed):
+ raise ValueError(f"{field_label} contains invalid control characters")
+ parsed = urllib.parse.urlparse(trimmed)
+ if parsed.scheme:
+ if parsed.scheme.lower() not in ('http', 'https') or not parsed.netloc:
+ raise ValueError(f"{field_label} must use an http:// or https:// URL")
+ return trimmed
+ # Reject protocol-relative or ambiguous colon-before-slash strings
+ # (e.g. '//evil.com' or 'javascript:alert(1)' obfuscations).
+ first_part = trimmed.split('/', 1)[0]
+ if trimmed.startswith('//') or ':' in first_part:
+ raise ValueError(f"{field_label} must use an http:// or https:// URL")
+ candidate = f"https://{trimmed}"
+ parsed_candidate = urllib.parse.urlparse(candidate)
+ host = parsed_candidate.hostname or ''
+ if not parsed_candidate.netloc or ('.' not in host and host.lower() != 'localhost'):
+ raise ValueError(f"{field_label} must use an http:// or https:// URL")
+ return candidate
+
+
class _PhotoHostRejectedError(Exception):
"""A photo URL host failed SSRF validation inside the transport
adapter. Deliberately not a ValueError: requests converts a
@@ -704,10 +740,17 @@ def add_warranty():
warranty_type = request.form.get('warranty_type', None)
model_number = request.form.get('model_number', None)
- # Get URL fields for documents
+ # Get URL fields for documents and validate HTTP(S) schemes (M-01)
invoice_url = request.form.get('invoice_url', None)
manual_url = request.form.get('manual_url', None)
other_document_url = request.form.get('other_document_url', None)
+ try:
+ product_url = _validate_http_url(product_url, "Product URL")
+ invoice_url = _validate_http_url(invoice_url, "Invoice URL")
+ manual_url = _validate_http_url(manual_url, "Manual URL")
+ other_document_url = _validate_http_url(other_document_url, "Other document URL")
+ except ValueError as url_err:
+ return jsonify({"error": str(url_err)}), 400
# Get tag IDs if provided
tag_ids = []
@@ -1296,10 +1339,17 @@ def update_warranty(warranty_id):
warranty_type = request.form.get('warranty_type', None)
model_number = request.form.get('model_number', None)
- # Get URL fields for documents
+ # Get URL fields for documents and validate HTTP(S) schemes (M-01)
invoice_url = request.form.get('invoice_url', None)
manual_url = request.form.get('manual_url', None)
other_document_url = request.form.get('other_document_url', None)
+ try:
+ product_url = _validate_http_url(product_url, "Product URL")
+ invoice_url = _validate_http_url(invoice_url, "Invoice URL")
+ manual_url = _validate_http_url(manual_url, "Manual URL")
+ other_document_url = _validate_http_url(other_document_url, "Other document URL")
+ except ValueError as url_err:
+ return jsonify({"error": str(url_err)}), 400
tag_ids = []
if request.form.get('tag_ids'):
try:
@@ -1619,16 +1669,16 @@ def update_warranty(warranty_id):
sql_fields.append("paperless_other_id = %s")
sql_values.append(paperless_other_id)
- # Handle URL fields for documents
+ # Handle URL fields for documents (validated above)
if 'invoice_url' in request.form:
sql_fields.append("invoice_url = %s")
- sql_values.append(request.form.get('invoice_url'))
+ sql_values.append(invoice_url)
if 'manual_url' in request.form:
sql_fields.append("manual_url = %s")
- sql_values.append(request.form.get('manual_url'))
+ sql_values.append(manual_url)
if 'other_document_url' in request.form:
sql_fields.append("other_document_url = %s")
- sql_values.append(request.form.get('other_document_url'))
+ sql_values.append(other_document_url)
sql_fields.append("updated_at = NOW()") # Use SQL function, no parameter needed
sql_values.append(warranty_id)
@@ -1860,6 +1910,11 @@ def import_warranties():
errors.append("ProductName must be 255 characters or less.")
if not purchase_date_str:
errors.append("PurchaseDate is required.")
+ if product_url:
+ try:
+ product_url = _validate_http_url(product_url, "ProductURL")
+ except ValueError as url_err:
+ errors.append(str(url_err))
# --- Type/Format Validation ---
try:
diff --git a/frontend/about.html b/frontend/about.html
index d70a0c2..678c341 100644
--- a/frontend/about.html
+++ b/frontend/about.html
@@ -232,6 +232,27 @@
font-size: 1.1rem;
}
+ .bmc-static-btn {
+ display: inline-flex;
+ align-items: center;
+ gap: 10px;
+ padding: 12px 24px;
+ border-radius: 8px;
+ background: #FFDD00;
+ color: #000000;
+ border: 2px solid #000000;
+ font-weight: 600;
+ font-size: 1rem;
+ text-decoration: none;
+ transition: transform 0.2s ease, box-shadow 0.2s ease;
+ }
+
+ .bmc-static-btn:hover {
+ transform: translateY(-2px);
+ box-shadow: 0 4px 12px rgba(0, 0, 0, 0.15);
+ color: #000000;
+ }
+
/* Dark mode adjustments */
[data-theme="dark"] .social-link.github {
border-color: #f0f6fc;
@@ -404,7 +425,10 @@
<div class="coffee-section">
<h3><i class="fas fa-coffee"></i> <span data-i18n="about.support_project">Support the Project</span></h3>
<p data-i18n="about.support_description">If you find Warracker useful, consider supporting its development!</p>
- <script type="text/javascript" src="https://cdnjs.buymeacoffee.com/1.0.0/button.prod.min.js" data-name="bmc-button" data-slug="sassanix" data-color="#FFDD00" data-emoji="" data-font="Poppins" data-text="Buy me a coffee" data-outline-color="#000000" data-font-color="#000000" data-coffee-color="#ffffff" ></script>
+ <a href="https://www.buymeacoffee.com/sassanix" target="_blank" rel="noopener noreferrer" class="bmc-static-btn">
+ <i class="fas fa-coffee" aria-hidden="true"></i>
+ <span>Buy me a coffee</span>
+ </a>
</div>
</div>
diff --git a/frontend/settings-new.html b/frontend/settings-new.html
index 9a436d3..f59f1e4 100644
--- a/frontend/settings-new.html
+++ b/frontend/settings-new.html
@@ -724,6 +724,19 @@
</div>
</div>
+ <div class="form-group">
+ <div class="preference-item">
+ <div>
+ <label for="paperlessStrictOwnership">Restrict Pre-Existing Documents to Admins</label>
+ <p class="text-muted">When enabled, non-admin users can only link Paperless documents they uploaded through Warracker (prevents claiming unowned documents in a shared Paperless-ngx instance).</p>
+ </div>
+ <label class="toggle-switch">
+ <input type="checkbox" id="paperlessStrictOwnership">
+ <span class="toggle-slider"></span>
+ </label>
+ </div>
+ </div>
+
<div class="form-group" style="margin-top: 20px;">
<label data-i18n="settings.connection_testing">Connection Testing</label>
<div class="paperless-button-group">
@@ -996,6 +1009,10 @@
<div class="modal-body">
<p class="text-danger"><strong>Warning: This action cannot be undone.</strong></p>
<p>All your data, including warranties, will be permanently deleted.</p>
+ <div id="deleteAccountPasswordGroup" class="form-group" style="margin-bottom: 12px;">
+ <label for="deleteAccountPassword">Current Password</label>
+ <input type="password" id="deleteAccountPassword" class="form-control" placeholder="Enter your current password" autocomplete="current-password">
+ </div>
<p>To confirm, please type "DELETE" in the field below:</p>
<input type="text" id="deleteConfirmInput" class="form-control" placeholder="Type DELETE to confirm">
</div>
diff --git a/frontend/settings-new.js b/frontend/settings-new.js
index ede75a7..eeab0e8 100644
--- a/frontend/settings-new.js
+++ b/frontend/settings-new.js
@@ -112,10 +112,13 @@ const paperlessEnabledToggle = document.getElementById('paperlessEnabled');
const paperlessUrlInput = document.getElementById('paperlessUrl');
const paperlessApiTokenInput = document.getElementById('paperlessApiToken');
const paperlessViewInAppToggle = document.getElementById('paperlessViewInApp');
+const paperlessStrictOwnershipToggle = document.getElementById('paperlessStrictOwnership');
const paperlessSettingsContainer = document.getElementById('paperlessSettingsContainer');
const testPaperlessConnectionBtn = document.getElementById('testPaperlessConnectionBtn');
const savePaperlessSettingsBtn = document.getElementById('savePaperlessSettingsBtn');
const paperlessConnectionStatus = document.getElementById('paperlessConnectionStatus');
+const deleteAccountPasswordGroup = document.getElementById('deleteAccountPasswordGroup');
+const deleteAccountPasswordInput = document.getElementById('deleteAccountPassword');
// Global variable to store currencies data for currency code lookup
let globalCurrenciesData = [];
@@ -1295,18 +1298,44 @@ function setupEventListeners() {
});
}
+ function requiresDeletePassword() {
+ const user = window.auth && window.auth.getCurrentUser ? window.auth.getCurrentUser() : null;
+ if (!user) return true;
+ if (typeof user.has_password === 'boolean') return user.has_password;
+ return !user.oidc_managed;
+ }
+
+ function updateDeleteAccountButtonState() {
+ if (!confirmDeleteAccountBtn || !deleteConfirmInput) return;
+ const confirmedText = deleteConfirmInput.value === 'DELETE';
+ const needsPassword = requiresDeletePassword();
+ const hasPasswordInput = !needsPassword || Boolean(deleteAccountPasswordInput && deleteAccountPasswordInput.value);
+ confirmDeleteAccountBtn.disabled = !(confirmedText && hasPasswordInput);
+ }
+
// Delete account button
if (deleteAccountBtn) {
deleteAccountBtn.addEventListener('click', function() {
+ if (deleteAccountPasswordGroup) {
+ deleteAccountPasswordGroup.style.display = requiresDeletePassword() ? '' : 'none';
+ }
+ if (deleteAccountPasswordInput) {
+ deleteAccountPasswordInput.value = '';
+ }
+ if (deleteConfirmInput) {
+ deleteConfirmInput.value = '';
+ }
+ updateDeleteAccountButtonState();
openModal(deleteAccountModal);
});
}
// Delete confirm input
if (deleteConfirmInput) {
- deleteConfirmInput.addEventListener('input', function() {
- confirmDeleteAccountBtn.disabled = this.value !== 'DELETE';
- });
+ deleteConfirmInput.addEventListener('input', updateDeleteAccountButtonState);
+ }
+ if (deleteAccountPasswordInput) {
+ deleteAccountPasswordInput.addEventListener('input', updateDeleteAccountButtonState);
}
// Confirm delete account button
@@ -1922,16 +1951,29 @@ async function deleteAccount() {
showToast('Please type DELETE to confirm', 'error');
return;
}
+
+ const passwordVisible = deleteAccountPasswordGroup && deleteAccountPasswordGroup.style.display !== 'none';
+ const password = deleteAccountPasswordInput ? deleteAccountPasswordInput.value : '';
+ if (passwordVisible && !password) {
+ showToast('Please enter your current password to confirm', 'error');
+ return;
+ }
showLoading();
try {
- const response = await fetch('/api/auth/account', {
+ const headers = {
+ 'Authorization': `Bearer ${window.auth.getToken()}`
+ };
+ const fetchOptions = {
method: 'DELETE',
- headers: {
- 'Authorization': `Bearer ${window.auth.getToken()}`
- }
- });
+ headers
+ };
+ if (passwordVisible) {
+ headers['Content-Type'] = 'application/json';
+ fetchOptions.body = JSON.stringify({ password });
+ }
+ const response = await fetch('/api/auth/account', fetchOptions);
if (response.ok) {
// Clear auth data
@@ -1976,8 +2018,11 @@ async function deleteAccount() {
// Close modal
deleteAccountModal.style.display = 'none';
- // Reset delete confirm input
+ // Reset delete confirm inputs
deleteConfirmInput.value = '';
+ if (deleteAccountPasswordInput) {
+ deleteAccountPasswordInput.value = '';
+ }
confirmDeleteAccountBtn.disabled = true;
}
}
@@ -4919,6 +4964,9 @@ async function loadPaperlessSettings() {
if (paperlessUrlInput && settings.paperless_url) {
paperlessUrlInput.value = settings.paperless_url;
}
+ if (paperlessStrictOwnershipToggle) {
+ paperlessStrictOwnershipToggle.checked = settings.paperless_strict_ownership === 'true';
+ }
// Update API token field placeholder to indicate if token is saved
if (paperlessApiTokenInput) {
@@ -4956,7 +5004,8 @@ async function savePaperlessSettings() {
// Prepare settings data
const settingsData = {
paperless_enabled: paperlessEnabledToggle.checked.toString(),
- paperless_url: url
+ paperless_url: url,
+ paperless_strict_ownership: paperlessStrictOwnershipToggle ? paperlessStrictOwnershipToggle.checked.toString() : 'false'
};
// Only include API token if it's provided (not empty)
diff --git a/frontend/sw.js b/frontend/sw.js
index d6ef79c..3bea0c6 100644
--- a/frontend/sw.js
+++ b/frontend/sw.js
@@ -1,4 +1,4 @@
-const CACHE_NAME = 'warracker-cache-v20261123001';
+const CACHE_NAME = 'warracker-cache-v20261126001';
const urlsToCache = [
// HTML pages
'./',
@@ -70,6 +70,17 @@ self.addEventListener('install', event => {
self.skipWaiting();
});
+function responseAllowsCaching(networkResponse) {
+ if (!networkResponse || networkResponse.status !== 200) {
+ return false;
+ }
+ const cacheControl = (networkResponse.headers.get('Cache-Control') || '').toLowerCase();
+ if (cacheControl.includes('no-store')) {
+ return false;
+ }
+ return true;
+}
+
self.addEventListener('fetch', event => {
if (event.request.method !== 'GET') {
return;
@@ -78,13 +89,18 @@ self.addEventListener('fetch', event => {
const requestUrl = new URL(event.request.url);
const isSameOrigin = requestUrl.origin === self.location.origin;
+ // Never intercept or cache authenticated API / file-download endpoints (L-01).
+ if (isSameOrigin && requestUrl.pathname.startsWith('/api/')) {
+ return;
+ }
+
// Network-first for scripts: always fetch fresh JS so code updates are
// picked up immediately, falling back to cache only when offline.
if (event.request.destination === 'script') {
event.respondWith(
fetch(event.request)
.then(networkResponse => {
- if (isSameOrigin && networkResponse && networkResponse.status === 200) {
+ if (isSameOrigin && responseAllowsCaching(networkResponse)) {
const responseToCache = networkResponse.clone();
caches.open(CACHE_NAME).then(cache => cache.put(event.request, responseToCache));
}
@@ -105,7 +121,7 @@ self.addEventListener('fetch', event => {
caches.match(event.request).then(cachedResponse => {
const fetchPromise = fetch(event.request)
.then(networkResponse => {
- const okToCache = isSameOrigin && networkResponse && networkResponse.status === 200 &&
+ const okToCache = isSameOrigin && responseAllowsCaching(networkResponse) &&
['document', 'style', 'image', 'font'].includes(event.request.destination);
if (okToCache) {
diff --git a/nginx.conf b/nginx.conf
index 0fcb06e..bb8ebd4 100644
--- a/nginx.conf
+++ b/nginx.conf
@@ -1,3 +1,23 @@
+# Trust X-Forwarded-Proto only from loopback/private/link-local proxies
+# (matching _forwarded_headers_trusted in backend/__init__.py), or from any
+# peer when TRUST_PROXY_HEADERS=true (or none when TRUST_PROXY_HEADERS=false).
+geo $warracker_trusted_proxy {
+ default __NGINX_TRUST_ALL_PROXIES__;
+ 127.0.0.0/8 __NGINX_TRUST_PRIVATE_PROXIES__;
+ 10.0.0.0/8 __NGINX_TRUST_PRIVATE_PROXIES__;
+ 172.16.0.0/12 __NGINX_TRUST_PRIVATE_PROXIES__;
+ 192.168.0.0/16 __NGINX_TRUST_PRIVATE_PROXIES__;
+ 169.254.0.0/16 __NGINX_TRUST_PRIVATE_PROXIES__;
+ ::1/128 __NGINX_TRUST_PRIVATE_PROXIES__;
+ fc00::/7 __NGINX_TRUST_PRIVATE_PROXIES__;
+ fe80::/10 __NGINX_TRUST_PRIVATE_PROXIES__;
+}
+
+map "$warracker_trusted_proxy:$http_x_forwarded_proto" $warracker_forwarded_proto {
+ default $scheme;
+ "~^1:(https?)$" $1;
+}
+
server {
listen 80;
listen [::]:80;
@@ -11,10 +31,12 @@ server {
# responses, which pass through the proxy untouched. Keep the CSP
# value identical to _CONTENT_SECURITY_POLICY in backend/__init__.py.
# Locations below that define their own add_header directives do
- # not inherit these, so the HTML location repeats them.
+ # not inherit these, so the HTML location repeats them and static
+ # locations repeat X-Content-Type-Options: nosniff.
add_header X-Frame-Options "SAMEORIGIN" always;
- add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self' https://*.buymeacoffee.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
+ add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
+ add_header X-Content-Type-Options "nosniff" always;
# Suppress the nginx version number in error pages and the Server
# header (CFG-08). Valid in the server context; this file is
@@ -31,11 +53,6 @@ server {
gzip_types text/plain text/css application/javascript application/json;
client_max_body_size __NGINX_MAX_BODY_SIZE_CONFIG_VALUE__; # Configurable global limit
- # Add CORS headers globally
- add_header 'Access-Control-Allow-Origin' '*';
- add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE';
- add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization';
-
# MIME types - fixed duplicate js entry
types {
text/html html htm shtml;
@@ -60,6 +77,7 @@ server {
try_files $uri =404;
add_header Content-Type "application/json; charset=utf-8";
add_header Cache-Control "no-cache, no-store, must-revalidate";
+ add_header X-Content-Type-Options "nosniff" always;
expires -1;
}
@@ -71,13 +89,13 @@ server {
# $host drops the port, which broke OIDC redirect_uri generation
# (issue #238) for anyone serving Warracker on a nonstandard port.
proxy_set_header Host $http_host;
- # Pass through the outer proxy's scheme when present (issues #190/#97).
- # An empty value means nginx omits the header, so gunicorn falls back
- # to the direct connection scheme.
- proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;
- # Clear the other scheme headers: gunicorn 400s on contradictory
- # scheme headers, and a single X-Forwarded-Proto is unambiguous.
- # (Empty values are not sent by nginx.)
+ # Pass through the outer proxy's scheme only from trusted proxy peers
+ # (issues #190/#97, H-03); direct public clients always get $scheme.
+ proxy_set_header X-Forwarded-Proto $warracker_forwarded_proto;
+ # Clear spoofable forwarded headers not used by Warracker and
+ # contradictory scheme headers (empty values are omitted by nginx).
+ proxy_set_header X-Forwarded-Host "";
+ proxy_set_header X-Forwarded-Prefix "";
proxy_set_header X-Forwarded-Ssl "";
proxy_set_header X-Forwarded-Protocol "";
proxy_set_header X-Real-IP $remote_addr;
@@ -97,25 +115,6 @@ server {
# Prevent proxy from modifying response headers that could cause issues
proxy_set_header Connection "";
proxy_http_version 1.1;
-
- # Add debug headers to see what's happening
- add_header X-Debug-Message "API request proxied to backend" always;
-
- # CORS for API
- add_header 'Access-Control-Allow-Origin' '*' always;
- add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
- add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
-
- # CORS preflight
- if ($request_method = 'OPTIONS') {
- add_header 'Access-Control-Allow-Origin' '*' always;
- add_header 'Access-Control-Allow-Methods' 'GET, POST, OPTIONS, PUT, DELETE' always;
- add_header 'Access-Control-Allow-Headers' 'DNT,User-Agent,X-Requested-With,If-Modified-Since,Cache-Control,Content-Type,Range,Authorization' always;
- add_header 'Access-Control-Max-Age' 1728000 always;
- add_header 'Content-Type' 'text/plain charset=UTF-8' always;
- add_header 'Content-Length' 0 always;
- return 204;
- }
}
# Uploads - serve files from uploads directory
@@ -130,8 +129,9 @@ server {
# Repeated: locations with their own add_header do not inherit
# the server-level security headers (CFG-07a/b/d).
add_header X-Frame-Options "SAMEORIGIN" always;
- add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline' https://cdnjs.buymeacoffee.com; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://*.buymeacoffee.com https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self' https://*.buymeacoffee.com; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
+ add_header Content-Security-Policy "default-src 'self'; script-src 'self' 'unsafe-inline'; style-src 'self' 'unsafe-inline' https://fonts.googleapis.com; img-src 'self' data: blob: https://images.unsplash.com; font-src 'self' data: https://fonts.gstatic.com; connect-src 'self' https://api.github.com; frame-src 'self'; object-src 'none'; base-uri 'self'; form-action 'self'; frame-ancestors 'self'" always;
add_header Referrer-Policy "strict-origin-when-cross-origin" always;
+ add_header X-Content-Type-Options "nosniff" always;
}
# Favicon - specific handling
@@ -141,12 +141,14 @@ server {
try_files $uri =404;
expires 7d;
add_header Cache-Control "public, max-age=604800";
+ add_header X-Content-Type-Options "nosniff" always;
}
# Service Worker - no cache to ensure updates
location = /sw.js {
try_files $uri =404;
add_header Cache-Control "no-cache, no-store, must-revalidate";
+ add_header X-Content-Type-Options "nosniff" always;
expires -1;
}
@@ -155,6 +157,7 @@ server {
try_files $uri =404;
expires -1;
add_header Cache-Control "no-cache, must-revalidate";
+ add_header X-Content-Type-Options "nosniff" always;
}
# Static assets (CSS, images) - long cache is fine since these change rarely
@@ -162,27 +165,12 @@ server {
try_files $uri =404;
expires 7d;
add_header Cache-Control "public, max-age=604800";
- }
-
- # Test uploads path
- location = /test-uploads {
- add_header Content-Type text/plain;
- return 200 "Uploads directory exists: $document_root\n";
+ add_header X-Content-Type-Options "nosniff" always;
}
# Specific handling for manifest.json
location = /manifest.json {
alias /var/www/html/manifest.json; # Serve from this specific path
- # The global types block should set the correct Content-Type
- # (application/manifest+json for 'manifest' extension)
- # If not found by alias, it will result in a 404, which is correct.
- # No need for try_files here if alias is used and file must exist.
- # If you want to be explicit about 404 if alias target doesn't exist:
- # if (!-f /var/www/html/manifest.json) { return 404; }
- # However, alias itself should handle this.
- # Add caching headers if desired, e.g.:
- # expires 1d;
- # add_header Cache-Control "public, must-revalidate";
}
# Default location
diff --git a/tests/test_hardening_pass2.py b/tests/test_hardening_pass2.py
new file mode 100644
index 0000000..37a080e
--- /dev/null
+++ b/tests/test_hardening_pass2.py
@@ -0,0 +1,405 @@
+"""Defensive regression tests for the second (safe/non-breaking) hardening pass.
+
+Covers:
+- H-03: Nginx trusted-proxy forwarded-header handling, Gunicorn scoped
+ forwarded_allow_ips, and OIDC redirect_uri pinning to APP_BASE_URL.
+- M-05: Opt-in paperless_strict_ownership toggle (default false; blocks
+ non-admin claiming of unowned Paperless docs only when enabled).
+- M-08: Removal of duplicate Nginx CORS, X-Debug-Message, /test-uploads,
+ and remote Buy Me a Coffee JS widget; global X-Content-Type-Options: nosniff.
+- L-01: Header-only JWT auth (rejects ?token= and form auth_token) and
+ Service Worker exclusion of /api/ and Cache-Control: no-store.
+- L-03: Passwordless OIDC account deletion still works without password,
+ unreferenced uploaded files are removed on account/user deletion, and
+ password-reset emails dispatch asynchronously (no SMTP timing oracle).
+- M-01: Backend HTTP(S) URL scheme allowlist (with bare-domain https://
+ normalization) on warranty create, update, and CSV import.
+"""
+import io
+import os
+import threading
+import time
+import types
+import uuid
+
+import pytest
+
+from backend import auth_routes, oidc_handler
+from backend.admin_routes import SITE_SETTING_KEYS
+from backend.warranties_routes import _validate_http_url
+
+REPO_ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
+PDF_BYTES = b"%PDF-1.4\n1 0 obj<<>>endobj\ntrailer<<>>\n%%EOF"
+
+
+def _read(relpath):
+ with open(os.path.join(REPO_ROOT, relpath), encoding="utf-8") as fh:
+ return fh.read()
+
+
+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 _set_site_setting(db_connection, key, value):
+ with db_connection, db_connection.cursor() as cur:
+ if value is None:
+ cur.execute("DELETE FROM site_settings WHERE key = %s", (key,))
+ else:
+ cur.execute(
+ "INSERT INTO site_settings (key, value) VALUES (%s, %s) "
+ "ON CONFLICT (key) DO UPDATE SET value = EXCLUDED.value",
+ (key, value),
+ )
+
+
+def _get_site_setting(db_connection, key):
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT value FROM site_settings WHERE key = %s", (key,))
+ row = cur.fetchone()
+ return row[0] if row else None
+
+
+# ---------------------------------------------------------------------------
+# H-03: Forwarded-header hardening & OIDC redirect_uri pinning
+# ---------------------------------------------------------------------------
+
+def test_h03_nginx_and_gunicorn_forwarded_header_hardening(monkeypatch):
+ nginx_conf = _read("nginx.conf")
+ assert "geo $warracker_trusted_proxy" in nginx_conf
+ assert 'map "$warracker_trusted_proxy:$http_x_forwarded_proto" $warracker_forwarded_proto' in nginx_conf
+ assert 'proxy_set_header X-Forwarded-Proto $warracker_forwarded_proto;' in nginx_conf
+ assert 'proxy_set_header X-Forwarded-Proto $http_x_forwarded_proto;' not in nginx_conf
+ assert 'proxy_set_header X-Forwarded-Host "";' in nginx_conf
+ assert 'proxy_set_header X-Forwarded-Prefix "";' in nginx_conf
+
+ # Test _resolve_forwarded_allow_ips without triggering gevent monkey patching.
+ gconf_src = _read("backend/gunicorn_config.py")
+ ns = {"os": os}
+ fn_start = gconf_src.index("def _resolve_forwarded_allow_ips():")
+ fn_end = gconf_src.index("\nforwarded_allow_ips =")
+ exec(gconf_src[fn_start:fn_end], ns)
+ resolve = ns["_resolve_forwarded_allow_ips"]
+
+ for var in ("GUNICORN_FORWARDED_ALLOW_IPS", "TRUST_PROXY_HEADERS", "DISABLE_NGINX"):
+ monkeypatch.delenv(var, raising=False)
+ assert resolve() == "127.0.0.1,::1"
+
+ monkeypatch.setenv("DISABLE_NGINX", "true")
+ assert "172.16.0.0/12" in resolve()
+ assert resolve() != "*"
+
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "true")
+ assert resolve() == "*"
+
+ monkeypatch.setenv("TRUST_PROXY_HEADERS", "false")
+ assert resolve() == ""
+
+ monkeypatch.setenv("GUNICORN_FORWARDED_ALLOW_IPS", "10.0.0.5")
+ assert resolve() == "10.0.0.5"
+
+
+def test_h03_oidc_login_uses_configured_app_base_url(client, app, monkeypatch):
+ captured = {}
+
+ class _StubOIDCClient:
+ def authorize_redirect(self, redirect_uri):
+ captured["redirect_uri"] = redirect_uri
+ return ("ok", 200)
+
+ monkeypatch.setattr(oidc_handler.oauth, "create_client", lambda name: _StubOIDCClient())
+ monkeypatch.setenv("APP_BASE_URL", "https://warracker.trusted.example")
+ app.config["OIDC_ENABLED"] = True
+ app.config["OIDC_PROVIDER_NAME"] = "testidp"
+ try:
+ r = client.get(
+ "/api/oidc/login",
+ headers={
+ "Host": "evil.attacker.invalid",
+ "X-Forwarded-Host": "evil.attacker.invalid",
+ "X-Forwarded-Proto": "http",
+ },
+ )
+ assert r.status_code == 200
+ assert captured["redirect_uri"] == "https://warracker.trusted.example/api/oidc/callback"
+ finally:
+ app.config["OIDC_ENABLED"] = False
+ app.config.pop("OIDC_PROVIDER_NAME", None)
+
+
+# ---------------------------------------------------------------------------
+# M-05: Opt-in paperless_strict_ownership toggle
+# ---------------------------------------------------------------------------
+
+def test_m05_paperless_strict_ownership_opt_in(
+ client, admin_user, user_factory, warranty_factory, paperless_configured, db_connection
+):
+ assert "paperless_strict_ownership" in SITE_SETTING_KEYS
+ prev = _get_site_setting(db_connection, "paperless_strict_ownership")
+
+ # Default must be false so existing workflows are unaffected.
+ r_get = client.get("/api/admin/settings", headers=admin_user["headers"])
+ assert r_get.status_code == 200
+ assert r_get.get_json().get("paperless_strict_ownership") == "false"
+
+ regular = user_factory()
+ unowned_doc_id = "99542"
+ try:
+ # Turn strict ownership ON via admin settings API.
+ r_put = client.put(
+ "/api/admin/settings",
+ headers=admin_user["headers"],
+ json={"paperless_strict_ownership": "true"},
+ )
+ assert r_put.status_code == 200
+
+ # Non-admin CANNOT claim an unowned Paperless document when strict mode is on.
+ r_blocked = warranty_factory(
+ regular["headers"],
+ product_name="StrictBlocked",
+ paperless_invoice_id=unowned_doc_id,
+ )
+ assert r_blocked.status_code == 403
+
+ # Non-admin CAN still upload and link their own document.
+ r_up = client.post(
+ "/api/paperless/upload",
+ headers=regular["headers"],
+ data={
+ "file": (io.BytesIO(PDF_BYTES), "mine.pdf"),
+ "title": f"StrictOwn-{uuid.uuid4().hex[:6]}",
+ },
+ content_type="multipart/form-data",
+ )
+ assert r_up.status_code == 200, r_up.get_data(as_text=True)
+ own_doc_id = str(r_up.get_json()["document_id"])
+ r_own = warranty_factory(
+ regular["headers"],
+ product_name="StrictOwnAllowed",
+ paperless_invoice_id=own_doc_id,
+ )
+ assert r_own.status_code == 201, r_own.get_data(as_text=True)
+
+ # Admin CAN still link an unowned document.
+ r_admin = warranty_factory(
+ admin_user["headers"],
+ product_name="StrictAdminAllowed",
+ paperless_invoice_id=unowned_doc_id,
+ )
+ assert r_admin.status_code == 201, r_admin.get_data(as_text=True)
+ finally:
+ _set_site_setting(db_connection, "paperless_strict_ownership", prev or "false")
+
+
+# ---------------------------------------------------------------------------
+# M-08: Nginx cleanup, nosniff, and static about.html donation button
+# ---------------------------------------------------------------------------
+
+def test_m08_nginx_cleanup_and_static_bmc_button():
+ nginx_conf = _read("nginx.conf")
+ assert "Access-Control-Allow-Origin" not in nginx_conf
+ assert "X-Debug-Message" not in nginx_conf
+ assert "/test-uploads" not in nginx_conf
+ assert "buymeacoffee.com" not in nginx_conf
+
+ about_html = _read("frontend/about.html")
+ assert "cdnjs.buymeacoffee.com" not in about_html
+ assert 'href="https://www.buymeacoffee.com/sassanix"' in about_html
+ assert 'rel="noopener noreferrer"' in about_html
+
+
+# ---------------------------------------------------------------------------
+# L-01: Header-only JWT and Service Worker API/no-store exclusions
+# ---------------------------------------------------------------------------
+
+def test_l01_rejects_query_and_form_tokens_and_sw_skips_api(client, user_factory):
+ user = user_factory()
+ raw_jwt = user["headers"]["Authorization"].split(" ", 1)[1]
+
+ # Header works.
+ assert client.get("/api/auth/user", headers=user["headers"]).status_code == 200
+
+ # Query-string ?token= is rejected.
+ r_qs = client.get(f"/api/auth/user?token={raw_jwt}")
+ assert r_qs.status_code == 401
+
+ # Form field auth_token is rejected.
+ r_form = client.post(
+ "/api/warranties",
+ data={
+ "auth_token": raw_jwt,
+ "product_name": "ShouldFail",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ },
+ )
+ assert r_form.status_code == 401
+
+ sw_js = _read("frontend/sw.js")
+ assert "requestUrl.pathname.startsWith('/api/')" in sw_js
+ assert "no-store" in sw_js
+
+
+# ---------------------------------------------------------------------------
+# L-03: Passwordless OIDC deletion, file cleanup on delete, async reset email
+# ---------------------------------------------------------------------------
+
+def test_l03_passwordless_oidc_self_delete_and_file_cleanup(
+ client, admin_user, user_factory, db_connection
+):
+ upload_dir = os.environ["UPLOAD_FOLDER"]
+
+ # 1. Self-deletion of a passwordless OIDC account works without a password
+ # and deletes its uploaded warranty + claim files from disk.
+ oidc_user = user_factory()
+ oidc_uid = _user_id(db_connection, oidc_user["username"])
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute("UPDATE users SET password_hash = NULL WHERE id = %s", (oidc_uid,))
+
+ # GET /api/auth/user reports has_password=False for passwordless accounts.
+ me = client.get("/api/auth/user", headers=oidc_user["headers"]).get_json()
+ assert me["has_password"] is False
+
+ r_w = client.post(
+ "/api/warranties",
+ headers=oidc_user["headers"],
+ data={
+ "product_name": "OidcDeleteCleanup",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ "invoice": (io.BytesIO(PDF_BYTES), "oidc_inv.pdf"),
+ },
+ content_type="multipart/form-data",
+ )
+ assert r_w.status_code == 201
+ wid = r_w.get_json()["id"]
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT invoice_path FROM warranties WHERE id = %s", (wid,))
+ inv_rel = cur.fetchone()[0]
+ inv_disk = os.path.join(upload_dir, os.path.basename(inv_rel))
+ assert os.path.exists(inv_disk)
+
+ r_del = client.delete("/api/auth/account", headers=oidc_user["headers"])
+ assert r_del.status_code == 200, r_del.get_data(as_text=True)
+ assert not os.path.exists(inv_disk)
+
+ # 2. Admin deletion of a user also removes their unreferenced uploaded files.
+ victim = user_factory()
+ victim_uid = _user_id(db_connection, victim["username"])
+ r_vw = client.post(
+ "/api/warranties",
+ headers=victim["headers"],
+ data={
+ "product_name": "AdminDeleteCleanup",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ "manual": (io.BytesIO(PDF_BYTES), "victim_manual.pdf"),
+ },
+ content_type="multipart/form-data",
+ )
+ assert r_vw.status_code == 201
+ vwid = r_vw.get_json()["id"]
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT manual_path FROM warranties WHERE id = %s", (vwid,))
+ man_rel = cur.fetchone()[0]
+ man_disk = os.path.join(upload_dir, os.path.basename(man_rel))
+ assert os.path.exists(man_disk)
+
+ r_adel = client.delete(f"/api/admin/users/{victim_uid}", headers=admin_user["headers"])
+ assert r_adel.status_code == 200, r_adel.get_data(as_text=True)
+ assert not os.path.exists(man_disk)
+
+
+def test_l03_password_reset_email_dispatched_async(client, user_factory, monkeypatch):
+ user = user_factory()
+ email = f"{user['username']}@test.local"
+ called = threading.Event()
+
+ def _slow_mail(recipient, link):
+ called.set()
+ time.sleep(1.0)
+ return True
+
+ monkeypatch.setattr(auth_routes, "send_password_reset_email", _slow_mail)
+
+ started = time.monotonic()
+ r = client.post("/api/auth/password/reset-request", json={"email": email.upper()})
+ elapsed = time.monotonic() - started
+
+ assert r.status_code == 200
+ # Endpoint must return immediately without blocking on the 1s SMTP send.
+ assert elapsed < 0.5, f"reset-request blocked for {elapsed:.2f}s"
+ assert called.wait(timeout=2.0), "async reset email worker was not invoked"
+
+
+# ---------------------------------------------------------------------------
+# M-01: Backend HTTP(S) URL scheme allowlist
+# ---------------------------------------------------------------------------
+
+def test_m01_backend_http_url_validation_unit_and_api(client, user_factory, warranty_factory):
+ # Unit checks
+ assert _validate_http_url(None) is None
+ assert _validate_http_url("") == ""
+ assert _validate_http_url("https://example.com/item?x=1") == "https://example.com/item?x=1"
+ assert _validate_http_url("http://localhost:8080/p") == "http://localhost:8080/p"
+ assert _validate_http_url("www.example.com/product") == "https://www.example.com/product"
+
+ for bad in (
+ "javascript:alert(1)",
+ "JAVASCRIPT:alert(1)",
+ "java\tscript:alert(1)",
+ "data:text/html,<script>alert(1)</script>",
+ "vbscript:msgbox(1)",
+ "file:///etc/passwd",
+ "ftp://files.example.com/a",
+ "//evil.example.com/x",
+ "https://example.com/\nheader",
+ ):
+ with pytest.raises(ValueError):
+ _validate_http_url(bad)
+
+ # API checks: create, update, and CSV import
+ user = user_factory()
+ h = user["headers"]
+
+ r_bad_create = warranty_factory(h, product_url="javascript:alert(1)")
+ assert r_bad_create.status_code == 400
+
+ r_bad_doc_url = warranty_factory(h, invoice_url="data:text/html,hi")
+ assert r_bad_doc_url.status_code == 400
+
+ # Bare domain auto-prefixes https:// so legitimate user habits stay seamless.
+ r_bare = warranty_factory(h, product_name="BareUrlWidget", product_url="example.com/dp/123")
+ assert r_bare.status_code == 201, r_bare.get_data(as_text=True)
+ wid = r_bare.get_json()["id"]
+ items = client.get("/api/warranties", headers=h).get_json()
+ items_list = items["warranties"] if isinstance(items, dict) else items
+ created = next(w for w in items_list if w["id"] == wid)
+ assert created["product_url"] == "https://example.com/dp/123"
+
+ r_bad_update = client.put(
+ f"/api/warranties/{wid}",
+ headers=h,
+ data={
+ "product_name": "BareUrlWidget",
+ "purchase_date": "2025-01-01",
+ "exact_expiration_date": "2027-01-01",
+ "other_document_url": "file:///etc/passwd",
+ },
+ )
+ assert r_bad_update.status_code == 400
+
+ csv_body = (
+ "ProductName,PurchaseDate,ExpirationDate,ProductURL\n"
+ "BadUrlCsv,2025-01-01,2027-01-01,javascript:alert(1)\n"
+ ).encode("utf-8")
+ r_csv = client.post(
+ "/api/warranties/import",
+ headers=h,
+ data={"csv_file": (io.BytesIO(csv_body), "bad_url.csv")},
+ content_type="multipart/form-data",
+ )
+ assert r_csv.status_code == 400
+ assert r_csv.get_json()["failure_count"] == 1
diff --git a/tests/test_security_headers.py b/tests/test_security_headers.py
index 49d2365..eeeee35 100644
--- a/tests/test_security_headers.py
+++ b/tests/test_security_headers.py
@@ -20,6 +20,7 @@ def test_csp_and_referrer_policy_on_api_response(client):
assert r.status_code == 200
assert r.headers.get("Content-Security-Policy") == _CONTENT_SECURITY_POLICY
assert r.headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"
+ assert r.headers.get("X-Content-Type-Options") == "nosniff"
def test_csp_and_referrer_policy_on_error_response(client):
@@ -27,6 +28,7 @@ def test_csp_and_referrer_policy_on_error_response(client):
assert r.status_code == 404
assert r.headers.get("Content-Security-Policy") == _CONTENT_SECURITY_POLICY
assert r.headers.get("Referrer-Policy") == "strict-origin-when-cross-origin"
+ assert r.headers.get("X-Content-Type-Options") == "nosniff"
def test_nginx_conf_repeats_the_same_csp_and_referrer_policy():
@@ -41,6 +43,9 @@ def test_nginx_conf_repeats_the_same_csp_and_referrer_policy():
assert all(
value == "strict-origin-when-cross-origin"
for value in referrer_values)
+ nosniff_values = re.findall(
+ r'add_header X-Content-Type-Options "nosniff" always;', text)
+ assert len(nosniff_values) >= 2
def test_csp_keeps_inline_scripts_and_styles_working():
@@ -48,9 +53,8 @@ def test_csp_keeps_inline_scripts_and_styles_working():
assert "style-src 'self' 'unsafe-inline'" in _CONTENT_SECURITY_POLICY
-def test_csp_allows_the_about_page_widget_and_version_check():
- assert "https://cdnjs.buymeacoffee.com" in _CONTENT_SECURITY_POLICY
- assert "https://*.buymeacoffee.com" in _CONTENT_SECURITY_POLICY
+def test_csp_allows_version_check_and_drops_remote_bmc_script():
+ assert "buymeacoffee.com" not in _CONTENT_SECURITY_POLICY
assert "https://api.github.com" in _CONTENT_SECURITY_POLICY
assert "https://images.unsplash.com" in _CONTENT_SECURITY_POLICY
diff --git a/tests/test_user_account_and_preferences.py b/tests/test_user_account_and_preferences.py
index 47e96d0..d182239 100644
--- a/tests/test_user_account_and_preferences.py
+++ b/tests/test_user_account_and_preferences.py
@@ -204,7 +204,15 @@ def test_self_account_deletion_cleans_data_and_blocks_owner(
"/api/auth/preferences", headers=h, json={"theme": "dark"}
).status_code == 200
- r_del = client.delete("/api/auth/account", headers=h)
+ # Missing or wrong password must be rejected for local accounts (L-03).
+ assert client.delete("/api/auth/account", headers=h).status_code == 400
+ assert client.delete(
+ "/api/auth/account", headers=h, json={"password": "WrongPassword999!"}
+ ).status_code == 401
+
+ r_del = client.delete(
+ "/api/auth/account", headers=h, json={"password": "TestPass123!"}
+ )
assert r_del.status_code == 200, r_del.get_data(as_text=True)
# Old token is immediately rejected, and DB rows are gone.
@@ -219,7 +227,11 @@ def test_self_account_deletion_cleans_data_and_blocks_owner(
# Owner cannot delete their own account.
if owner_row is None or owner_row[1] == admin_user["username"]:
- r_owner_del = client.delete("/api/auth/account", headers=admin_user["headers"])
+ r_owner_del = client.delete(
+ "/api/auth/account",
+ headers=admin_user["headers"],
+ json={"password": "TestPass123!"},
+ )
assert r_owner_del.status_code == 403