🛡️ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Harden file access, owner controls, XSS defenses, SSRF checks, and container permissions
sassanix5dd5ec7fe188
diff --git a/Docker/entrypoint.sh b/Docker/entrypoint.shindex c547dd8..ba3a4cc 100644--- a/Docker/entrypoint.sh+++ b/Docker/entrypoint.sh@@ -102,15 +102,16 @@ log "Compiling translations..."cd /apppybabel compile -d locales 2>/dev/null || log "Warning: Translation compilation failed"-# Nginx configuration (create temp file, root will move it)+# Nginx configuration (written into root-only /run/nginx-init, never world-writable /tmp)log "Preparing nginx configuration..."EFFECTIVE_SIZE="${NGINX_MAX_BODY_SIZE_VALUE:-32M}"if ! echo "${EFFECTIVE_SIZE}" | grep -Eq "^[0-9]+[mMkKgG]?$"; thenlog "Warning: Invalid NGINX_MAX_BODY_SIZE_VALUE. Using default 32M"EFFECTIVE_SIZE="32M"fi+mkdir -p -m 700 /run/nginx-initsed "s|__NGINX_MAX_BODY_SIZE_CONFIG_VALUE__|${EFFECTIVE_SIZE}|g" \- /etc/nginx/conf.d/default.conf.template > /tmp/nginx-default.conf+ /etc/nginx/conf.d/default.conf.template > /run/nginx-init/default.conflog "Nginx config prepared (size: ${EFFECTIVE_SIZE})"diff --git a/Docker/nginx-wrapper.sh b/Docker/nginx-wrapper.shindex d45a253..a61c952 100644--- a/Docker/nginx-wrapper.sh+++ b/Docker/nginx-wrapper.sh@@ -4,8 +4,8 @@ echo "[$(date '+%Y-%m-%d %H:%M:%S')] Starting Nginx..."# Wait for setup to create the nginx configfor i in {1..30}; do- if [ -f /tmp/nginx-default.conf ]; then- mv /tmp/nginx-default.conf /etc/nginx/conf.d/default.conf+ if [ -f /run/nginx-init/default.conf ]; then+ mv /run/nginx-init/default.conf /etc/nginx/conf.d/default.confecho "[$(date '+%Y-%m-%d %H:%M:%S')] Nginx configuration applied"breakfidiff --git a/Dockerfile b/Dockerfileindex 5b607a0..ccdc864 100644--- a/Dockerfile+++ b/Dockerfile@@ -68,37 +68,40 @@ COPY --from=builder /opt/venv /opt/venvENV PATH="/opt/venv/bin:$PATH"# Configure directories with proper permissions-RUN mkdir -p /app /var/www/html /var/log/supervisor /run/nginx && \- chown -R warracker:warracker /app /var/www/html /var/log/supervisor /run/nginx /home/warracker && \- chown -R warracker:warracker /var/log/nginx+RUN mkdir -p /app /var/www/html /var/log/supervisor /run/nginx /run/nginx-init && \+ chown -R root:root /app /var/www/html /run/nginx-init && \+ chmod 700 /run/nginx-init && \+ chown -R warracker:warracker /var/log/supervisor /run/nginx /home/warracker /var/log/nginx# Set working directoryWORKDIR /app# 1. Configuration and static files first (rarely change)-COPY --chown=warracker:warracker nginx.conf /etc/nginx/conf.d/default.conf.template-COPY --chown=warracker:warracker babel.cfg ./+# Owned by root:root so the unprivileged gunicorn worker (warracker) cannot+# tamper with root-executed scripts, nginx templates, or application code.+COPY --chown=root:root nginx.conf /etc/nginx/conf.d/default.conf.template+COPY --chown=root:root babel.cfg ./# 2. Migration scripts and utilities-COPY --chown=warracker:warracker backend/fix_permissions.py backend/fix_permissions.sql ./-COPY --chown=warracker:warracker backend/migrations/ ./migrations/+COPY --chown=root:root backend/fix_permissions.py backend/fix_permissions.sql ./+COPY --chown=root:root backend/migrations/ ./migrations/# 3. Localization files-COPY --chown=warracker:warracker locales/ ./locales/-COPY --chown=warracker:warracker locales/ /var/www/html/locales/+COPY --chown=root:root locales/ ./locales/+COPY --chown=root:root locales/ /var/www/html/locales/# 4. Frontend (static files, no build step)-COPY --chown=warracker:warracker frontend/ /var/www/html/+COPY --chown=root:root frontend/ /var/www/html/# 5. Backend (bundled in one instruction)-COPY --chown=warracker:warracker backend/ ./backend/-COPY --chown=warracker:warracker backend/app.py backend/gunicorn_config.py ./+COPY --chown=root:root backend/ ./backend/+COPY --chown=root:root backend/app.py backend/gunicorn_config.py ./# Copy configuration files and scripts from Docker directoryCOPY --chown=root:root Docker/supervisord.conf /etc/supervisor/conf.d/supervisord.confCOPY --chown=root:root Docker/logrotate-nginx /etc/logrotate.d/nginx-warracker-COPY --chown=warracker:warracker Docker/entrypoint.sh /app/entrypoint.sh+COPY --chown=root:root Docker/entrypoint.sh /app/entrypoint.shCOPY --chown=root:root Docker/nginx-wrapper.sh /app/nginx-wrapper.sh# Make scripts executablediff --git a/backend/admin_routes.py b/backend/admin_routes.pyindex 6237ffe..1ada3fb 100644--- a/backend/admin_routes.py+++ b/backend/admin_routes.py@@ -123,13 +123,24 @@ def update_user(user_id):if not user:return jsonify({"message": "User not found"}), 404+ # Validate boolean fields up front so non-boolean falsy values+ # (0, "", null) cannot bypass the owner guard while bool() turns+ # them into FALSE in SQL.+ if 'is_admin' in data and not isinstance(data['is_admin'], bool):+ return jsonify({"message": "is_admin must be a boolean"}), 400+ if 'is_active' in data and not isinstance(data['is_active'], bool):+ return jsonify({"message": "is_active must be a boolean"}), 400+# Check if the user being updated is the ownerif is_owner:- # If the user is the owner, prevent demotion or deactivation- if 'is_admin' in data and data['is_admin'] is False:+ # If the user is the owner, prevent demotion, deactivation,+ # or modification (e.g. email takeover) by another admin.+ if 'is_admin' in data and not data['is_admin']:return jsonify({"message": "The application owner cannot be demoted from admin status."}), 403- if 'is_active' in data and data['is_active'] is False:+ if 'is_active' in data and not data['is_active']:return jsonify({"message": "The application owner's account cannot be deactivated."}), 403+ if not request.user.get('is_owner'):+ return jsonify({"message": "The application owner's account cannot be modified by another administrator."}), 403# Validate an email change up front: format plus# uniqueness across the other accounts.@@ -142,7 +153,7 @@ def update_user(user_id):raw_email.strip())):return jsonify({"message": "Invalid email address"}), 400new_email = raw_email.strip()- cur.execute('SELECT id FROM users WHERE email = %s AND id != %s',+ cur.execute('SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s',(new_email, user_id))if cur.fetchone():return jsonify({"message": "Email address is already in use by another account"}), 400@@ -193,7 +204,7 @@ def update_user(user_id):logger.error(f"Error updating user: {e}")if conn:conn.rollback()- return jsonify({"message": f"Failed to update user: {str(e)}"}), 500+ return jsonify({"message": "Failed to update user"}), 500finally:if conn:release_db_connection(conn)@@ -277,7 +288,7 @@ def delete_user(user_id):logger.error(f"Error deleting user: {e}")if conn:conn.rollback()- return jsonify({"message": f"Failed to delete user: {str(e)}"}), 500+ return jsonify({"message": "Failed to delete user"}), 500finally:if conn:release_db_connection(conn)@@ -656,6 +667,9 @@ def update_site_settings():def get_audit_trail():"""Fetch audit trail records for administrators."""limit = request.args.get('limit', 100, type=int)+ if limit is None or limit < 1:+ limit = 100+ limit = min(limit, 1000)conn = Nonetry:conn = get_db_connection()@@ -693,9 +707,8 @@ def trigger_notifications():result, status_code = notifications.trigger_notifications_manually(get_db_connection, release_db_connection)return jsonify(result), status_codeexcept Exception as e:- error_msg = f"Error triggering notifications: {str(e)}"- logger.error(error_msg)- return jsonify({'message': 'Failed to trigger notifications', 'error': error_msg}), 500+ logger.error(f"Error triggering notifications: {e}")+ return jsonify({'message': 'Failed to trigger notifications', 'error': 'Internal server error'}), 500@admin_bp.route('/scheduler-status', methods=['GET'])@admin_required@@ -708,7 +721,7 @@ def get_scheduler_status():return jsonify(status), 200except Exception as e:logger.error(f"Error getting scheduler status: {e}")- return jsonify({'error': f'Failed to get scheduler status: {str(e)}'}), 500+ return jsonify({'error': 'Failed to get scheduler status'}), 500# ============================# Apprise Admin Routes@@ -760,7 +773,7 @@ def test_apprise_notification():logger.error(f"Error sending test Apprise notification: {e}")create_audit_log('APPRISE_TEST', target_type='Apprise', target_id='test-notification',details='Test notification attempt errored')- return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500+ return jsonify({'success': False, 'message': 'Failed to send test notification'}), 500@admin_bp.route('/apprise/validate-url', methods=['POST'])@admin_required@@ -785,7 +798,7 @@ def validate_apprise_url():except Exception as e:logger.error(f"Error validating Apprise URL: {e}")- return jsonify({'valid': False, 'message': f'Error: {str(e)}'}), 500+ return jsonify({'valid': False, 'message': 'Failed to validate URL'}), 500@admin_bp.route('/apprise/supported-services', methods=['GET'])@admin_required@@ -800,7 +813,7 @@ def get_supported_apprise_services():except Exception as e:logger.error(f"Error getting supported Apprise services: {e}")- return jsonify({'services': [], 'message': f'Error: {str(e)}'}), 500+ return jsonify({'services': [], 'message': 'Failed to retrieve supported services'}), 500@admin_bp.route('/apprise/send-expiration', methods=['POST'])@admin_required@@ -872,7 +885,7 @@ def trigger_apprise_expiration_notifications():except Exception as e:logger.error(f"Error triggering Apprise expiration notifications: {e}")- return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500+ return jsonify({'success': False, 'message': 'Failed to trigger Apprise expiration notifications'}), 500@admin_bp.route('/apprise/reload-config', methods=['POST'])@admin_required@@ -893,7 +906,7 @@ def reload_apprise_configuration():except Exception as e:logger.error(f"Error reloading Apprise configuration: {e}")- return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500+ return jsonify({'success': False, 'message': 'Failed to reload Apprise configuration'}), 500@admin_bp.route('/apprise/send-custom', methods=['POST'])@admin_required@@ -924,7 +937,7 @@ def send_custom_apprise_notification():logger.error(f"Error sending custom Apprise notification: {e}")create_audit_log('APPRISE_SEND_CUSTOM', target_type='Apprise', target_id='custom-notification',details='Custom notification attempt errored')- return jsonify({'success': False, 'message': f'Error: {str(e)}'}), 500+ return jsonify({'success': False, 'message': 'Failed to send custom notification'}), 500@admin_bp.route('/apprise/status', methods=['GET'])@admin_required@@ -956,5 +969,5 @@ def get_apprise_status():return jsonify({'available': False,'enabled': False,- 'message': f'Error: {str(e)}'+ 'message': 'Failed to retrieve Apprise status'}), 500\ No newline at end of filediff --git a/backend/apprise_handler.py b/backend/apprise_handler.pyindex bf96235..837e994 100644--- a/backend/apprise_handler.py+++ b/backend/apprise_handler.py@@ -152,11 +152,12 @@ class AppriseNotificationHandler:for url in self.notification_urls:if url:+ scheme = self._safe_url_scheme(url)result = self.apprise_obj.add(url)if result:- logger.info(f"Successfully added Apprise URL: {url[:20]}...")+ logger.info(f"Successfully added Apprise URL (scheme: {scheme})")else:- logger.error(f"Failed to add Apprise URL: {url[:20]}...")+ logger.error(f"Failed to add Apprise URL (scheme: {scheme})")if len(self.apprise_obj) == 0:logger.warning("No valid Apprise URLs configured")@@ -166,6 +167,15 @@ class AppriseNotificationHandler:logger.error(f"Error initializing Apprise: {e}")self.enabled = False+ @staticmethod+ def _safe_url_scheme(url: str) -> str:+ """Extract only the scheme from an Apprise URL so credentials are never logged."""+ try:+ from urllib.parse import urlparse+ return urlparse(str(url)).scheme or 'unknown'+ except Exception:+ return 'unknown'+def is_available(self):"""Check if Apprise is available and properly configured"""return APPRISE_AVAILABLE and self.enabled and self.apprise_obj is not None@@ -207,7 +217,7 @@ class AppriseNotificationHandler:# Use specific test URLtest_apprise = apprise.Apprise()if not test_apprise.add(test_url):- logger.error(f"Failed to add test URL: {test_url}")+ logger.error(f"Failed to add test Apprise URL (scheme: {self._safe_url_scheme(test_url)})")return Falsetitle = f"{self.title_prefix} Test Notification"diff --git a/backend/audit_logger.py b/backend/audit_logger.pyindex 872acbc..f1f07b5 100644--- a/backend/audit_logger.py+++ b/backend/audit_logger.py@@ -1,9 +1,21 @@+import ipaddress+import loggingfrom flask import requestfrom .db_handler import get_db_connection, release_db_connection-import logginglogger = logging.getLogger(__name__)++def _validated_ip(raw_ip):+ """Return a canonical IP string, or None if the value is not a valid IP."""+ if not raw_ip:+ return None+ try:+ return str(ipaddress.ip_address(str(raw_ip).strip()))+ except ValueError:+ return None++def create_audit_log(action, target_type=None, target_id=None, details=None):"""Helper function to insert a new record into the audit log."""user_id = None@@ -11,7 +23,7 @@ def create_audit_log(action, target_type=None, target_id=None, details=None):ip_address = Noneif request:- ip_address = request.remote_addr+ ip_address = _validated_ip(request.remote_addr)if hasattr(request, 'user') and request.user:user_id = request.user.get('id')username = request.user.get('username')diff --git a/backend/auth_routes.py b/backend/auth_routes.pyindex 26c6c0c..56f4f54 100644--- a/backend/auth_routes.py+++ b/backend/auth_routes.py@@ -7,7 +7,9 @@ import smtplibfrom email.mime.multipart import MIMEMultipartfrom email.mime.text import MIMETextimport hashlib+import jsonimport os+import reimport pytzimport psycopg2from psycopg2.extras import Json@@ -149,8 +151,8 @@ def register():# already ran, so the lock is never held during hashing.acquire_first_user_lock(cur)- # Check if username or email already exists- cur.execute('SELECT id FROM users WHERE username = %s OR email = %s', (username, email))+ # Check if username or email already exists (case-insensitive email)+ cur.execute('SELECT id FROM users WHERE username = %s OR LOWER(email) = LOWER(%s)', (username, email))existing_user = cur.fetchone()if existing_user:@@ -159,6 +161,19 @@ def register():# Check if this is the first user (who will be an admin and owner)cur.execute('SELECT COUNT(*) FROM users')user_count = cur.fetchone()[0]++ # Re-check OIDC-only and registration gates under the lock so a+ # concurrent second signup cannot bypass registration_enabled=false.+ if _oidc_only_mode_enabled(cur):+ return jsonify({'message': 'Local registration is disabled. Please use single sign-on!'}), 403+ if table_exists:+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")+ reg_row = cur.fetchone()+ if reg_row:+ registration_enabled = reg_row[0].lower() == 'true'+ if not registration_enabled and user_count > 0:+ return jsonify({'message': 'Registration is currently disabled!'}), 403+is_admin = user_count == 0is_owner = user_count == 0 # First user is also the owner@@ -379,21 +394,19 @@ def oidc_exchange():cur.execute("DELETE FROM oidc_login_codes ""WHERE expires_at <= (NOW() AT TIME ZONE 'UTC')")+ # Single use: atomically claim and remove the code in one statement+ # so concurrent POSTs under READ COMMITTED cannot mint two sessions.cur.execute(- "SELECT user_id, is_new_user FROM oidc_login_codes "+ "DELETE FROM oidc_login_codes ""WHERE code_hash = %s "- "AND expires_at > (NOW() AT TIME ZONE 'UTC')",+ "AND expires_at > (NOW() AT TIME ZONE 'UTC') "+ "RETURNING user_id, is_new_user",(code_hash,))row = cur.fetchone()if not row:conn.rollback()return jsonify({"error": "Invalid or expired login code!"}), 400user_id, is_new_user = row- # Single use: delete before minting so a concurrent replay- # finds nothing.- cur.execute(- "DELETE FROM oidc_login_codes WHERE code_hash = %s",- (code_hash,))token, session_jti = generate_token(user_id)expires_at = datetime.now(UTC) + current_app.config['JWT_EXPIRATION_DELTA']cur.execute(@@ -788,6 +801,8 @@ def has_currency_symbol_column(cursor):def is_valid_timezone(tz):"""Validate if a timezone string is valid"""+ if not isinstance(tz, str) or not tz.strip():+ return Falsetry:pytz.timezone(tz)return True@@ -852,25 +867,28 @@ def reset_password():if is_password_too_long(password):return jsonify({'message': 'Password must not exceed 72 characters!'}), 400+ # Hash the new password BEFORE borrowing a pooled DB connection so+ # slow bcrypt work never holds a connection or widens the race window.+ password_hash = bcrypt.generate_password_hash(password).decode('utf-8')+conn = db_handler.get_db_connection()with conn.cursor() as cur:- # Check if token exists and is valid (stored as a hash, AUTH-08)- cur.execute('SELECT user_id, expires_at FROM password_reset_tokens WHERE token = %s', (_hash_reset_token(token),))+ # Atomically consume a valid, unexpired reset token in one SQL+ # statement (AUTH-08 / TOCTOU fix) so concurrent requests cannot+ # redeem the same token twice.+ cur.execute(+ "DELETE FROM password_reset_tokens "+ "WHERE token = %s "+ "AND expires_at > (NOW() AT TIME ZONE 'UTC') "+ "RETURNING user_id",+ (_hash_reset_token(token),),+ )token_info = cur.fetchone()-+if not token_info:+ conn.rollback()return jsonify({'message': 'Invalid or expired token!'}), 400- expires_at = token_info[1]- if expires_at is not None and expires_at.tzinfo is None:- # expires_at is TIMESTAMP WITHOUT TIME ZONE, so psycopg2- # returns it offset-naive. Tokens are created with- # datetime.now(UTC), so interpret the stored value as UTC- # before comparing with the offset-aware current time.- expires_at = expires_at.replace(tzinfo=UTC)- if expires_at is None or expires_at < datetime.now(UTC):- return jsonify({'message': 'Invalid or expired token!'}), 400-user_id = token_info[0]# AUTH-12: a reset token minted before OIDC-only mode was@@ -879,16 +897,11 @@ def reset_password():cur.execute('SELECT oidc_sub FROM users WHERE id = %s', (user_id,))owner = cur.fetchone()if owner and owner[0] is not None and _oidc_only_mode_enabled(cur):+ conn.rollback()return jsonify({'message': 'Invalid or expired token!'}), 400-- # Hash the new password- password_hash = bcrypt.generate_password_hash(password).decode('utf-8')-+# Update user's passwordcur.execute('UPDATE users SET password_hash = %s WHERE id = %s', (password_hash, user_id))-- # Delete the used token- cur.execute('DELETE FROM password_reset_tokens WHERE token = %s', (_hash_reset_token(token),))# AUTH-01: a completed reset revokes every session for this# user, so a token captured before the reset stops working.@@ -939,6 +952,8 @@ def change_password():return jsonify({'message': 'User not found!'}), 404current_password_hash = user_data[0]+ if not current_password_hash:+ return jsonify({'message': 'Password changes are not available for SSO-managed accounts!'}), 400# Verify the current passwordif not bcrypt.check_password_hash(current_password_hash, current_password):@@ -1279,9 +1294,9 @@ def update_preferences():expiring_soon_days = int(expiring_soon_days)if expiring_soon_days < 1 or expiring_soon_days > 365:return jsonify({'message': 'Expiring soon days must be between 1 and 365'}), 400- except ValueError:+ except (TypeError, ValueError):return jsonify({'message': 'Expiring soon days must be a valid number'}), 400- if currency_symbol and len(currency_symbol) > 8:+ if currency_symbol is not None and (not isinstance(currency_symbol, str) or len(currency_symbol) > 8):return jsonify({'message': 'Currency symbol must be 8 characters or less'}), 400if currency_position and currency_position not in ['left', 'right']:return jsonify({'message': 'Invalid currency position'}), 400@@ -1289,10 +1304,37 @@ def update_preferences():return jsonify({'message': 'Invalid date format'}), 400if notification_channel and notification_channel not in ['none', 'email', 'apprise', 'both']:return jsonify({'message': 'Invalid notification channel'}), 400+ valid_frequencies = ('daily', 'weekly', 'monthly')+ if notification_frequency is not None and notification_frequency != '':+ if not isinstance(notification_frequency, str) or notification_frequency not in valid_frequencies:+ return jsonify({'message': 'Invalid notification frequency'}), 400+ if apprise_notification_frequency is not None and apprise_notification_frequency != '':+ if not isinstance(apprise_notification_frequency, str) or apprise_notification_frequency not in valid_frequencies:+ return jsonify({'message': 'Invalid Apprise notification frequency'}), 400+ time_pattern = r'^(?:[01]\d|2[0-3]):[0-5]\d(?::[0-5]\d)?$'+ if notification_time is not None and notification_time != '':+ if not isinstance(notification_time, str) or not re.match(time_pattern, notification_time):+ return jsonify({'message': 'Invalid notification time format'}), 400+ if apprise_notification_time is not None and apprise_notification_time != '':+ if not isinstance(apprise_notification_time, str) or not re.match(time_pattern, apprise_notification_time):+ return jsonify({'message': 'Invalid Apprise notification time format'}), 400+ if timezone is not None and timezone != '':+ if not is_valid_timezone(timezone):+ return jsonify({'message': 'Invalid timezone'}), 400+ if apprise_timezone is not None and apprise_timezone != '':+ if not is_valid_timezone(apprise_timezone):+ return jsonify({'message': 'Invalid Apprise timezone'}), 400if paperless_view_in_app is not None and not isinstance(paperless_view_in_app, bool):return jsonify({'message': 'paperless_view_in_app must be a boolean'}), 400if preferred_language and preferred_language not in SUPPORTED_LANGUAGES:return jsonify({'message': 'Invalid language preference'}), 400+ if saved_filters is not None:+ try:+ serialized_filters = json.dumps(saved_filters)+ except (TypeError, ValueError):+ return jsonify({'message': 'Invalid saved filters payload'}), 400+ if len(serialized_filters.encode('utf-8')) > 65536:+ return jsonify({'message': 'Saved filters payload exceeds maximum allowed size'}), 400conn = db_handler.get_db_connection()cursor = conn.cursor()@@ -1328,22 +1370,22 @@ def update_preferences():if notification_channel is not None:update_fields.append("notification_channel = %s")update_values.append(notification_channel)- if notification_frequency is not None:+ if notification_frequency:update_fields.append("notification_frequency = %s")update_values.append(notification_frequency)- if notification_time is not None:+ if notification_time:update_fields.append("notification_time = %s")update_values.append(notification_time)- if apprise_notification_time is not None:+ if apprise_notification_time:update_fields.append("apprise_notification_time = %s")update_values.append(apprise_notification_time)- if apprise_notification_frequency is not None:+ if apprise_notification_frequency:update_fields.append("apprise_notification_frequency = %s")update_values.append(apprise_notification_frequency)- if timezone is not None:+ if timezone:update_fields.append("timezone = %s")update_values.append(timezone)- if apprise_timezone is not None:+ if apprise_timezone:update_fields.append("apprise_timezone = %s")update_values.append(apprise_timezone)if paperless_view_in_app is not None:@@ -1449,7 +1491,7 @@ def generate_secure_token(length=40):def request_email_change():"""Request email change with verification"""current_user_id = request.user['id']- data = request.get_json()+ data = request.get_json(silent=True) or {}new_email = data.get('new_email')password = data.get('password')@@ -1473,14 +1515,17 @@ def request_email_change():current_password_hash, current_email = user_data+ if not current_password_hash:+ return jsonify({'message': 'Password authentication is not configured for this account.'}), 400+if not bcrypt.check_password_hash(current_password_hash, password):return jsonify({'message': 'Incorrect password'}), 401if new_email.lower() == current_email.lower():return jsonify({'message': 'New email cannot be the same as the current email'}), 400- # Check if the new email is already in use by another user- cur.execute("SELECT id FROM users WHERE email = %s AND id != %s", (new_email.lower(), current_user_id))+ # Check if the new email is already in use by another user (case-insensitive)+ cur.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND id != %s", (new_email, current_user_id))if cur.fetchone():return jsonify({'message': 'This email address is already in use by another account.'}), 409diff --git a/backend/config.py b/backend/config.pyindex 4a74b0a..e0f9f91 100644--- a/backend/config.py+++ b/backend/config.py@@ -159,7 +159,7 @@ class Config:JSON_SORT_KEYS = FalseJSONIFY_PRETTYPRINT_REGULAR = FalseSEND_FILE_MAX_AGE_DEFAULT = 31536000 # Cache static files for 1 year- PROPAGATE_EXCEPTIONS = True+ PROPAGATE_EXCEPTIONS = False# Session ConfigurationSESSION_COOKIE_SECURE = False # Set to True in production with HTTPS@@ -224,14 +224,13 @@ class Config:def _upgrade_session_cookie_secure(app):"""Emit the session cookie with Secure when the deployment serves HTTPS.- The default configuration is DevelopmentConfig, whose session- cookie has no Secure flag (CFG-01c). Flipping the default to the- production config would break plain-HTTP installs, whose browsers- would refuse to store a Secure cookie and break the OIDC login- flow state kept in the session. Instead, upgrade to Secure when- the deployment's own public URL uses https, which the operator- already configures for login redirects. This only ever adds the- flag, never removes a Secure setting the active config provides.+ The default configuration keeps SESSION_COOKIE_SECURE=False so+ plain-HTTP self-hosted installs still work (browsers refuse to+ store a Secure cookie over HTTP, which would break the OIDC+ login state). Upgrade to Secure when the deployment's own public+ URL uses https, which the operator already configures for login+ redirects. This only ever adds the flag, never removes a Secure+ setting the active config provides."""if app.config.get('SESSION_COOKIE_SECURE'):return@@ -261,6 +260,15 @@ class Config:# Log configuration statuslogger.info("Application configuration initialized successfully")+class DefaultConfig(Config):+ """Default runtime configuration (non-debug, plain-HTTP compatible)."""+ DEBUG = False++ @staticmethod+ def init_app(app):+ Config.init_app(app)+ logger.info("Default configuration loaded")+class DevelopmentConfig(Config):"""Development configuration."""DEBUG = True@@ -286,6 +294,7 @@ class TestingConfig(Config):"""Testing configuration."""TESTING = TrueDEBUG = True+ PROPAGATE_EXCEPTIONS = True# Use in-memory database for testingDB_HOST = 'localhost'@@ -301,5 +310,5 @@ config = {'development': DevelopmentConfig,'production': ProductionConfig,'testing': TestingConfig,- 'default': DevelopmentConfig+ 'default': DefaultConfig}\ No newline at end of filediff --git a/backend/file_routes.py b/backend/file_routes.pyindex b9fb7e8..a9885b0 100644--- a/backend/file_routes.py+++ b/backend/file_routes.py@@ -1,6 +1,8 @@# backend/file_routes.pyfrom flask import Blueprint, request, jsonify, current_app, send_from_directory, Responsefrom datetime import datetime, UTC+from pathlib import PurePosixPath+from werkzeug.security import safe_joinimport osimport mimetypesimport logging@@ -39,23 +41,91 @@ file_bp = Blueprint('file_bp', __name__)# Set up logginglogger = logging.getLogger(__name__)+# Strictly passive MIME types that may be rendered inline in a browser tab.+# Active formats (text/html, image/svg+xml, application/xhtml+xml, XML, etc.)+# are forced to application/octet-stream + attachment + sandbox CSP so an+# uploaded or Paperless-ingested document can never execute script on our origin.+_SAFE_INLINE_MIME_TYPES = frozenset({+ 'application/pdf',+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ 'image/gif',+ 'text/plain',+})+++def _safe_serving_headers(raw_mimetype, filename_for_disposition):+ """Return (mimetype, content_disposition, csp) safe for serving user/Paperless files."""+ base_mime = (raw_mimetype or '').split(';', 1)[0].strip().lower()+ safe_name = os.path.basename(filename_for_disposition or 'document').replace('"', '').replace('\r', '').replace('\n', '')+ if base_mime in _SAFE_INLINE_MIME_TYPES:+ return (+ base_mime,+ f'inline; filename="{safe_name}"',+ "default-src 'none'; frame-ancestors 'self'",+ )+ return (+ 'application/octet-stream',+ f'attachment; filename="{safe_name}"',+ 'sandbox',+ )+++def _is_safe_upload_subpath(rel_path):+ """Reject traversal, backslashes, absolute paths, and dotfiles (e.g. .secret_key)."""+ if not rel_path or rel_path.startswith('/') or '\\' in rel_path or '\x00' in rel_path:+ return False+ parts = PurePosixPath(rel_path).parts+ if not parts:+ return False+ for part in parts:+ if part in ('', '.', '..') or part.startswith('.'):+ return False+ return True+++def _resolve_upload_file_path(upload_dir, rel_path):+ """Safely resolve a file inside upload_dir, rejecting symlinks and escapes."""+ if not _is_safe_upload_subpath(rel_path):+ return None+ joined = safe_join(upload_dir, rel_path)+ if not joined:+ return None+ if os.path.islink(joined):+ return None+ real_root = os.path.realpath(upload_dir)+ real_target = os.path.realpath(joined)+ try:+ if os.path.commonpath([real_root, real_target]) != real_root or real_target == real_root:+ return None+ except ValueError:+ return None+ return real_target++# ============================# Shared file authorization# ============================-def _check_file_authorization(cur, db_search_path, user_id, is_admin):+def _check_file_access(cur, db_search_path, user_id, is_admin):"""Shared authorization check for serving uploaded files.db_search_path is the path as stored in the DB (e.g. 'uploads/abc.pdf').- Returns True when the user may access the file, False otherwise.+ Returns:+ - 'ok' when the user may access the file+ - 'not_found' when no warranty or claim row references the path and caller is admin+ - 'forbidden' when unauthorized (or unreferenced for non-admins)Rules (identical for /files/ and /secure-file/):- - admins: always allowed- - the owner of the warranty the file is attached to: allowed- - anyone else: allowed only for shared document types (product photo,- invoice, manual) when the admin setting global_view_enabled is true- (and, if global_view_admin_only is true, only admins)- Files not linked to any warranty are unauthorized for non-admins.+ - only paths referenced by a warranty or claim_documents row may ever+ be served (even for admins, so unreferenced files such as .secret_key+ in UPLOAD_FOLDER are never downloadable)+ - admins: allowed for any referenced warranty or claim file+ - the owner of the warranty/claim the file is attached to: allowed+ - anyone else: allowed only for shared warranty document types (product+ photo, invoice, manual) when global_view_enabled is true and+ global_view_admin_only is false"""query = """SELECT w.id, w.user_id@@ -65,12 +135,7 @@ def _check_file_authorization(cur, db_search_path, user_id, is_admin):cur.execute(query, (db_search_path, db_search_path, db_search_path, db_search_path))results = cur.fetchall()- if is_admin:- logger.info(f"[FILE_AUTH] Admin access granted for '{db_search_path}'")- return True-- # Claim documents (issue #148): owner-only, like warranty "other- # documents" they never participate in global view.+ claim_owners = []if not results:cur.execute("""SELECT w.user_id@@ -79,18 +144,30 @@ def _check_file_authorization(cur, db_search_path, user_id, is_admin):JOIN warranties w ON c.warranty_id = w.idWHERE d.file_path = %s""", (db_search_path,))- for (claim_owner_id,) in (cur.fetchall() or []):- if claim_owner_id == user_id:- logger.info(f"[FILE_AUTH] Claim document ownership confirmed for '{db_search_path}'")- return True+ claim_owners = [row[0] for row in (cur.fetchall() or [])]++ if not results and not claim_owners:+ logger.warning(f"[FILE_AUTH] Unreferenced file access attempt: '{db_search_path}' by user {user_id}")+ return "not_found" if is_admin else "forbidden"++ if is_admin:+ logger.info(f"[FILE_AUTH] Admin access granted for referenced file '{db_search_path}'")+ return "ok"++ # Claim documents (issue #148): owner-only, like warranty "other+ # documents" they never participate in global view.+ if not results:+ if user_id in claim_owners:+ logger.info(f"[FILE_AUTH] Claim document ownership confirmed for '{db_search_path}'")+ return "ok"logger.warning(f"[FILE_AUTH] Unauthorized file access attempt: '{db_search_path}' by user {user_id}")- return False+ return "forbidden"# Ownership authorizationfor warranty_id_db, warranty_user_id_db in (results or []):if warranty_user_id_db == user_id:logger.info(f"[FILE_AUTH] Ownership confirmed for warranty_id={warranty_id_db}")- return True+ return "ok"# Global view permissions for shared documents (photos, invoices, manuals)if results:@@ -107,10 +184,15 @@ def _check_file_authorization(cur, db_search_path, user_id, is_admin):if global_view_enabled and (not admin_only or is_admin):logger.info(f"[FILE_AUTH] Global view access granted for shared document: '{db_search_path}'")- return True+ return "ok"logger.warning(f"[FILE_AUTH] Unauthorized file access attempt: '{db_search_path}' by user {user_id}")- return False+ return "forbidden"+++def _check_file_authorization(cur, db_search_path, user_id, is_admin):+ """Backward-compatible boolean wrapper around _check_file_access."""+ return _check_file_access(cur, db_search_path, user_id, is_admin) == "ok"def _paperless_next_path(next_url):@@ -142,29 +224,37 @@ def serve_file(filename):logger.warning(f"Attempted access to non-uploads file: {filename}")return jsonify({"message": "Access denied"}), 403- # Security check for path traversal- if '..' in filename or filename.startswith('/'):- logger.warning(f"Potential path traversal attempt detected: {filename} by user {request.user['id']}")+ # Remove 'uploads/' prefix and validate subpath (rejects traversal and dotfiles)+ file_path = filename[8:]+ if not _is_safe_upload_subpath(file_path):+ logger.warning(f"Potential path traversal or hidden file access attempt: {filename} by user {request.user['id']}")return jsonify({"message": "Invalid file path"}), 400conn = get_db_connection()with conn.cursor() as cur:user_id = request.user['id']is_admin = request.user.get('is_admin', False)- if not _check_file_authorization(cur, filename, user_id, is_admin):- return jsonify({"message": "You are not authorized to access this file"}), 403+ access = _check_file_access(cur, filename, user_id, is_admin)+ release_db_connection(conn)+ conn = None- # Remove 'uploads/' prefix for send_from_directory- file_path = filename[8:] if filename.startswith('uploads/') else filename+ if access == "not_found":+ return jsonify({"message": "File not found"}), 404+ if access != "ok":+ return jsonify({"message": "You are not authorized to access this file"}), 403- full_path = os.path.join(current_app.config['UPLOAD_FOLDER'], file_path)- if not os.path.isfile(full_path):+ full_path = _resolve_upload_file_path(current_app.config['UPLOAD_FOLDER'], file_path)+ if not full_path or not os.path.isfile(full_path):return jsonify({"message": "File not found"}), 404# FILE-01: these bytes are authorization-gated, so they must not# sit in a shared cache for a year (the Flask default) and must# not be content-sniffed. Match the /secure-file/ headers.response = send_from_directory(current_app.config['UPLOAD_FOLDER'], file_path)+ safe_mime, disposition, csp = _safe_serving_headers(response.mimetype, file_path)+ response.mimetype = safe_mime+ response.headers['Content-Disposition'] = disposition+ response.headers['Content-Security-Policy'] = cspresponse.headers['Cache-Control'] = 'no-cache, no-store, must-revalidate'response.headers['Pragma'] = 'no-cache'response.headers['Expires'] = '0'@@ -196,108 +286,95 @@ def secure_file_access(filename):logger.info(f"[SECURE_FILE] Raw filename from route: '{filename}' (len: {len(filename)})")logger.info(f"[SECURE_FILE] repr(filename): {repr(filename)}")- # Security check for path traversal- if '..' in filename or filename.startswith('/'):- logger.warning(f"[SECURE_FILE] Potential path traversal attempt detected: {filename} by user {request.user['id']}")+ # Security check for path traversal and dotfiles (e.g. .secret_key)+ if not _is_safe_upload_subpath(filename):+ logger.warning(f"[SECURE_FILE] Potential path traversal or hidden file attempt: {filename} by user {request.user['id']}")return jsonify({"message": "Invalid file path"}), 400+ user_id = request.user['id']+ is_admin = request.user.get('is_admin', False)+ db_search_path = f"uploads/{filename}"+conn = get_db_connection()with conn.cursor() as cur:- db_search_path = f"uploads/{filename}"logger.info(f"[SECURE_FILE] Searching DB for paths like: '{db_search_path}' (repr: {repr(db_search_path)})")+ access = _check_file_access(cur, db_search_path, user_id, is_admin)+ release_db_connection(conn)+ conn = None- user_id = request.user['id']- is_admin = request.user.get('is_admin', False)+ if access == "not_found":+ return jsonify({"message": "File not found"}), 404+ if access != "ok":+ logger.warning(f"[SECURE_FILE] Unauthorized file access attempt: '{filename}' (repr: {repr(filename)}) by user {user_id}")+ return jsonify({"message": "You are not authorized to access this file"}), 403- # Shared authorization (same rules as /files/)- if not _check_file_authorization(cur, db_search_path, user_id, is_admin):- logger.warning(f"[SECURE_FILE] Unauthorized file access attempt: '{filename}' (repr: {repr(filename)}) by user {user_id}")- return jsonify({"message": "You are not authorized to access this file"}), 403+ upload_dir = current_app.config['UPLOAD_FOLDER']+ logger.info(f"[SECURE_FILE] User {user_id} authorized for file '{filename}'. Attempting to serve from {upload_dir}.")- upload_dir = current_app.config['UPLOAD_FOLDER']-- logger.info(f"[SECURE_FILE] User {user_id} authorized for file '{filename}'. Attempting to serve from {upload_dir}.")-- # Construct the full file path- target_file_path_for_send = os.path.join(upload_dir, filename)- logger.info(f"[SECURE_FILE] Path for verification: '{target_file_path_for_send}' (repr: {repr(target_file_path_for_send)})")-- # Enhanced file existence and readability checks- if not os.path.exists(target_file_path_for_send):- logger.error(f"[SECURE_FILE] File '{target_file_path_for_send}' does not exist")+ target_file_path_for_send = _resolve_upload_file_path(upload_dir, filename)+ if not target_file_path_for_send or not os.path.exists(target_file_path_for_send):+ logger.error(f"[SECURE_FILE] File '{filename}' does not exist in {upload_dir}")+ return jsonify({"message": "File not found"}), 404++ if not os.path.isfile(target_file_path_for_send):+ logger.error(f"[SECURE_FILE] Path '{target_file_path_for_send}' exists but is not a file")+ return jsonify({"message": "Invalid file"}), 400++ # Check file size and readability+ try:+ file_size = os.path.getsize(target_file_path_for_send)+ logger.info(f"[SECURE_FILE] File size: {file_size} bytes")++ with open(target_file_path_for_send, 'rb') as f:+ f.read(1)+ f.seek(0)++ except (OSError, IOError) as e:+ logger.error(f"[SECURE_FILE] Cannot read file '{target_file_path_for_send}': {e}")+ return jsonify({"message": "File read error"}), 500++ try:+ guessed_mime, _ = mimetypes.guess_type(target_file_path_for_send)+ safe_mime, disposition, csp = _safe_serving_headers(guessed_mime, filename)++ logger.info(f"[SECURE_FILE] Serving file with size {file_size} bytes, mimetype: {safe_mime}")++ def generate():try:- dir_contents = os.listdir(upload_dir)- logger.info(f"[SECURE_FILE] Contents of {upload_dir}: {dir_contents}")- except Exception as list_err:- logger.error(f"[SECURE_FILE] Error listing {upload_dir}: {list_err}")- return jsonify({"message": "File not found"}), 404-- if not os.path.isfile(target_file_path_for_send):- logger.error(f"[SECURE_FILE] Path '{target_file_path_for_send}' exists but is not a file")- return jsonify({"message": "Invalid file"}), 400-- # Check file size and readability- try:- file_size = os.path.getsize(target_file_path_for_send)- logger.info(f"[SECURE_FILE] File size: {file_size} bytes")-- # Verify we can read the file- with open(target_file_path_for_send, 'rb') as f:- # Try to read first byte to ensure file is readable- f.read(1)- f.seek(0) # Reset file pointer-- except (OSError, IOError) as e:- logger.error(f"[SECURE_FILE] Cannot read file '{target_file_path_for_send}': {e}")- return jsonify({"message": "File read error"}), 500-- # Use Flask's send_from_directory with enhanced error handling- try:- # Get MIME type- mimetype, _ = mimetypes.guess_type(target_file_path_for_send)- if not mimetype:- mimetype = 'application/octet-stream'-- logger.info(f"[SECURE_FILE] Serving file with size {file_size} bytes, mimetype: {mimetype}")-- # Use streaming for ALL files to prevent Content-Length mismatches- logger.info(f"[SECURE_FILE] Using streaming response for file: {filename}")-- def generate():- try:- with open(target_file_path_for_send, 'rb') as f:- chunk_size = 4096 # 4KB chunks- total_sent = 0- while True:- chunk = f.read(chunk_size)- if not chunk:- break- total_sent += len(chunk)- logger.debug(f"[SECURE_FILE] Streaming chunk: {len(chunk)} bytes, total sent: {total_sent}/{file_size}")- yield chunk- logger.info(f"[SECURE_FILE] Streaming completed: {total_sent}/{file_size} bytes sent")- except Exception as e:- logger.error(f"[SECURE_FILE] Error during streaming: {e}")- raise-- response = Response(- generate(),- mimetype=mimetype,- headers={- 'Content-Length': str(file_size),- 'Content-Disposition': f'inline; filename="{os.path.basename(filename)}"',- 'Accept-Ranges': 'bytes',- 'Cache-Control': 'no-cache, no-store, must-revalidate',- 'Pragma': 'no-cache',- 'Expires': '0',- 'X-Content-Type-Options': 'nosniff',- 'Connection': 'close'- }- )- return response- except Exception as send_error:- logger.error(f"[SECURE_FILE] Error serving file: {send_error}")- return jsonify({"message": "Error serving file"}), 500+ with open(target_file_path_for_send, 'rb') as f:+ chunk_size = 4096 # 4KB chunks+ total_sent = 0+ while True:+ chunk = f.read(chunk_size)+ if not chunk:+ break+ total_sent += len(chunk)+ logger.debug(f"[SECURE_FILE] Streaming chunk: {len(chunk)} bytes, total sent: {total_sent}/{file_size}")+ yield chunk+ logger.info(f"[SECURE_FILE] Streaming completed: {total_sent}/{file_size} bytes sent")+ except Exception as e:+ logger.error(f"[SECURE_FILE] Error during streaming: {e}")+ raise++ response = Response(+ generate(),+ mimetype=safe_mime,+ headers={+ 'Content-Length': str(file_size),+ 'Content-Disposition': disposition,+ 'Content-Security-Policy': csp,+ 'Accept-Ranges': 'bytes',+ 'Cache-Control': 'no-cache, no-store, must-revalidate',+ 'Pragma': 'no-cache',+ 'Expires': '0',+ 'X-Content-Type-Options': 'nosniff',+ 'Connection': 'close'+ }+ )+ return response+ except Exception as send_error:+ logger.error(f"[SECURE_FILE] Error serving file: {send_error}")+ return jsonify({"message": "Error serving file"}), 500except Exception as e:logger.error(f"[SECURE_FILE] Error in secure file access for '{filename}' (repr: {repr(filename)}): {e}", exc_info=True)@@ -315,23 +392,22 @@ def serve_paperless_document(paperless_id: int):user_id = request.user['id']is_admin = request.user.get('is_admin', False)- # Get database connection+ # Authorize and fetch Paperless settings, then release the pooled+ # DB connection BEFORE performing outbound HTTP I/O to Paperless.conn = get_db_connection()-- # 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: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- 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-- # Get Paperless handler and retrieve document+ 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+ 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+paperless_handler = get_paperless_handler(conn)+ release_db_connection(conn)+ conn = None+if not paperless_handler:return jsonify({"message": "Paperless-ngx integration not available"}), 503@@ -340,7 +416,7 @@ def serve_paperless_document(paperless_id: int):if not success:logger.error(f"[PAPERLESS_FILE] Failed to retrieve document {paperless_id}: {message}")- return jsonify({"message": message}), 404+ return jsonify({"message": "Document not found"}), 404# Stream the document contentdef generate():@@ -354,14 +430,19 @@ def serve_paperless_document(paperless_id: int):total_sent += chunk_size_actualremaining -= chunk_size_actualyield chunk-- # Return streaming response++ # Only passive MIME types (PDF, raster images, plain text) may be served+ # inline; active content (HTML, SVG, XML, etc.) is forced to download+ # as application/octet-stream with a sandbox CSP.+ safe_mime, disposition, csp = _safe_serving_headers(content_type, f"paperless_document_{paperless_id}")+response = Response(generate(),- mimetype=content_type or 'application/octet-stream',+ mimetype=safe_mime,headers={'Content-Length': str(len(content)),- 'Content-Disposition': f'inline; filename="paperless_document_{paperless_id}"',+ 'Content-Disposition': disposition,+ 'Content-Security-Policy': csp,'Cache-Control': 'no-cache, no-store, must-revalidate','Pragma': 'no-cache','Expires': '0',@@ -445,7 +526,7 @@ def paperless_upload():logger.info(f"File content read successfully: {len(file_content)} bytes")except Exception as file_read_error:logger.error(f"Error reading file content: {file_read_error}")- return jsonify({"error": f"Error reading file: {str(file_read_error)}"}), 400+ return jsonify({"error": "Error reading uploaded file"}), 400# Upload to Paperless-ngx. The start time bounds the PPL-03# reclaim window: claims recorded after it cannot predate the@@ -463,7 +544,7 @@ def paperless_upload():logger.info(f"Upload result: success={success}, document_id={document_id}, message='{message}'")except Exception as upload_error:logger.error(f"Error during paperless upload: {upload_error}")- return jsonify({"error": f"Upload to Paperless-ngx failed: {str(upload_error)}"}), 500+ return jsonify({"error": "Upload to Paperless-ngx failed"}), 500if success:logger.info("Upload successful")@@ -515,7 +596,7 @@ def paperless_upload():except Exception as e:logger.error(f"Error in Paperless upload: {e}")- return jsonify({"error": f"Upload failed: {str(e)}"}), 500+ return jsonify({"error": "Upload failed"}), 500finally:if conn:release_db_connection(conn)@@ -543,6 +624,8 @@ def test_paperless_connection():else:conn = get_db_connection()paperless_handler = get_paperless_handler(conn)+ release_db_connection(conn)+ conn = Noneif not paperless_handler:return jsonify({"error": "Paperless-ngx integration is not enabled or configured"}), 400@@ -575,8 +658,15 @@ def paperless_search():"""conn = Nonetry:+ is_admin = request.user.get('is_admin', False)+ visible_ids = Noneconn = get_db_connection()paperless_handler = get_paperless_handler(conn)+ if paperless_handler and not is_admin:+ with conn.cursor() as cur:+ visible_ids = visible_paperless_document_ids(cur, request.user['id'], False)+ release_db_connection(conn)+ conn = Noneif not paperless_handler:return jsonify({'success': False, 'message': 'Paperless-ngx not configured'}), 400@@ -668,9 +758,7 @@ def paperless_search():# 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)+ if not is_admin:filtered = [d for d in search_result.get('results', []) if d.get('id') in visible_ids]search_result['results'] = filteredsearch_result['count'] = len(filtered)@@ -699,8 +787,15 @@ def paperless_tags():"""conn = Nonetry:+ is_admin = request.user.get('is_admin', False)+ visible_ids = Noneconn = get_db_connection()paperless_handler = get_paperless_handler(conn)+ if paperless_handler and not is_admin:+ with conn.cursor() as cur:+ visible_ids = visible_paperless_document_ids(cur, request.user['id'], False)+ release_db_connection(conn)+ conn = Noneif not paperless_handler:return jsonify({'success': False, 'message': 'Paperless-ngx integration not available'}), 400@@ -721,23 +816,27 @@ def paperless_tags():# PPL-06: non-admin users only receive tags attached to# documents they may see. Without this, any signed-in user# learned every instance tag, including tags used only on- # other users' documents.- if not request.user.get('is_admin', False):- with conn.cursor() as cur:- visible_ids = visible_paperless_document_ids(cur, request.user['id'], False)+ # other users' documents. Batch via id__in so large Paperless+ # instances are not scanned end-to-end per user request.+ if not is_admin:if not visible_ids:all_tags = []else:used_tag_ids = set()- url = '/api/documents/?page_size=100'- while url:- response = paperless_handler.get(url, timeout=30)- response.raise_for_status()- page = response.json()- for doc in page.get('results', []):- if doc.get('id') in visible_ids:- used_tag_ids.update(doc.get('tags') or [])- url = _paperless_next_path(page.get('next'))+ sorted_ids = sorted(visible_ids)+ batch_size = 50+ for idx in range(0, len(sorted_ids), batch_size):+ batch = sorted_ids[idx:idx + batch_size]+ id_csv = ','.join(str(doc_id) for doc_id in batch)+ url = f'/api/documents/?id__in={id_csv}&page_size={batch_size}'+ while url:+ response = paperless_handler.get(url, timeout=30)+ response.raise_for_status()+ page = response.json()+ for doc in page.get('results', []):+ if doc.get('id') in visible_ids:+ used_tag_ids.update(doc.get('tags') or [])+ url = _paperless_next_path(page.get('next'))all_tags = [t for t in all_tags if t.get('id') in used_tag_ids]except Exception as e:# See CFG-10 in paperless_search: exception text can carry@@ -819,32 +918,37 @@ def paperless_debug():"test_connection_result": None}- # Try to get paperless handler+ # Try to get paperless handler, then release DB connection before network probe+ paperless_handler = Nonetry:paperless_handler = get_paperless_handler(conn)debug_info["paperless_handler_available"] = paperless_handler is not None-- if paperless_handler:- # Test connection- try:- success, message = paperless_handler.test_connection()- debug_info["test_connection_result"] = {- "success": success,- "message": message- }- except Exception as test_error:- debug_info["test_connection_result"] = {- "success": False,- "error": str(test_error)- }except Exception as handler_error:- debug_info["paperless_handler_error"] = str(handler_error)+ logger.error(f"Error initializing Paperless handler in debug: {handler_error}")+ debug_info["paperless_handler_error"] = "Failed to initialize Paperless handler"+ finally:+ release_db_connection(conn)+ conn = None++ if paperless_handler:+ try:+ success, message = paperless_handler.test_connection()+ debug_info["test_connection_result"] = {+ "success": success,+ "message": message+ }+ except Exception as test_error:+ logger.error(f"Error testing Paperless connection in debug: {test_error}")+ debug_info["test_connection_result"] = {+ "success": False,+ "error": "Connection test failed"+ }return jsonify(debug_info), 200except Exception as e:logger.error(f"Error in Paperless debug: {e}")- return jsonify({"error": f"Debug failed: {str(e)}"}), 500+ return jsonify({"error": "Debug failed"}), 500finally:if conn:release_db_connection(conn)@@ -882,7 +986,7 @@ def test_file_upload():except Exception as e:logger.error(f"Test upload error: {e}", exc_info=True)- return jsonify({"error": f"Test upload failed: {str(e)}"}), 500+ return jsonify({"error": "Test upload failed"}), 500@file_bp.route('/paperless/debug-document/<int:document_id>', methods=['GET'])@admin_required@@ -898,10 +1002,7 @@ def paperless_debug_document(document_id: int):if not paperless_handler:return jsonify({"error": "Paperless-ngx integration not available"}), 400- # Get debug information about the document- debug_info = paperless_handler.debug_document_status(document_id)-- # Also check if this document ID exists in our database+ # Query DB references before releasing connection prior to Paperless HTTP callswith conn.cursor() as cur:cur.execute("""SELECT w.id, w.product_name, w.user_id,@@ -919,21 +1020,26 @@ def paperless_debug_document(document_id: int):document_id, document_id, document_id, document_id))db_results = cur.fetchall()- debug_info['database_references'] = [- {- 'warranty_id': row[0],- 'product_name': row[1],- 'user_id': row[2],- 'document_type': row[3]- }- for row in db_results- ]+ release_db_connection(conn)+ conn = None++ # Get debug information about the document+ debug_info = paperless_handler.debug_document_status(document_id)+ debug_info['database_references'] = [+ {+ 'warranty_id': row[0],+ 'product_name': row[1],+ 'user_id': row[2],+ 'document_type': row[3]+ }+ for row in db_results+ ]return jsonify(debug_info), 200except Exception as e:logger.error(f"Error in Paperless document debug: {e}")- return jsonify({"error": f"Debug failed: {str(e)}"}), 500+ return jsonify({"error": "Debug failed"}), 500finally:if conn:release_db_connection(conn)@@ -988,56 +1094,61 @@ def cleanup_invalid_paperless_documents():""", (user_id,))warranties = cur.fetchall()+ # Release pooled DB connection before performing outbound Paperless checks+ release_db_connection(conn)+ conn = None++ to_clear = []+ for warranty in warranties:+ warranty_id, product_name, invoice_id, manual_id, photo_id, other_id = warranty- for warranty in warranties:- warranty_id, product_name, invoice_id, manual_id, photo_id, other_id = warranty-- # Check each document ID- document_fields = [- ('paperless_invoice_id', invoice_id),- ('paperless_manual_id', manual_id),- ('paperless_photo_id', photo_id),- ('paperless_other_id', other_id)- ]-- for field_name, doc_id in document_fields:- if doc_id is not None:- cleanup_results['checked'] += 1-- try:- existence = paperless_handler.document_existence(doc_id)- if existence == 'unknown':- # Paperless is unreachable or answered- # oddly: leave the reference in place and- # report it, never unlink on an outage.- cleanup_results['skipped'] += 1- cleanup_results['errors'].append(- f"Could not check document {doc_id}: "- "Paperless-ngx is unreachable; "- "reference left in place.")- logger.warning(- f"Cleanup skipped document {doc_id}: "- "Paperless-ngx unreachable, reference kept")- continue- if existence == 'gone':- cleanup_results['invalid_found'] += 1- logger.info(f"Found invalid Paperless document ID {doc_id} in warranty {warranty_id} ({product_name})")-- # Clear the invalid reference- cur.execute(f"""- UPDATE warranties- SET {field_name} = NULL- WHERE id = %s- """, (warranty_id,))-- cleanup_results['cleaned_up'] += 1- logger.info(f"Cleaned up invalid {field_name} reference for warranty {warranty_id}")-- except Exception as e:- error_msg = f"Error checking document {doc_id}: {str(e)}"- cleanup_results['errors'].append(error_msg)- logger.error(error_msg)+ # Check each document ID+ document_fields = [+ ('paperless_invoice_id', invoice_id),+ ('paperless_manual_id', manual_id),+ ('paperless_photo_id', photo_id),+ ('paperless_other_id', other_id)+ ]+ for field_name, doc_id in document_fields:+ if doc_id is not None:+ cleanup_results['checked'] += 1++ try:+ existence = paperless_handler.document_existence(doc_id)+ if existence == 'unknown':+ # Paperless is unreachable or answered+ # oddly: leave the reference in place and+ # report it, never unlink on an outage.+ cleanup_results['skipped'] += 1+ cleanup_results['errors'].append(+ f"Could not check document {doc_id}: "+ "Paperless-ngx is unreachable; "+ "reference left in place.")+ logger.warning(+ f"Cleanup skipped document {doc_id}: "+ "Paperless-ngx unreachable, reference kept")+ continue+ if existence == 'gone':+ cleanup_results['invalid_found'] += 1+ logger.info(f"Found invalid Paperless document ID {doc_id} in warranty {warranty_id} ({product_name})")+ to_clear.append((field_name, warranty_id, doc_id))+ except Exception as e:+ logger.error(f"Error checking document {doc_id}: {e}")+ cleanup_results['errors'].append(f"Error checking document {doc_id}")++ if to_clear:+ conn = get_db_connection()+ with conn.cursor() as cur:+ for field_name, warranty_id, doc_id in to_clear:+ cur.execute(f"""+ UPDATE warranties+ SET {field_name} = NULL+ WHERE id = %s AND {field_name} = %s+ """, (warranty_id, doc_id))+ if cur.rowcount > 0:+ cleanup_results['cleaned_up'] += 1+ logger.info(f"Cleaned up invalid {field_name} reference for warranty {warranty_id}")conn.commit()message = (@@ -1057,7 +1168,7 @@ def cleanup_invalid_paperless_documents():except Exception as e:logger.error(f"Error in Paperless cleanup: {e}")- return jsonify({"error": f"Cleanup failed: {str(e)}"}), 500+ return jsonify({"error": "Cleanup failed"}), 500finally:if conn:release_db_connection(conn)@@ -1067,7 +1178,7 @@ def cleanup_invalid_paperless_documents():def paperless_search_and_link():"""Search for a Paperless document by title and link it to a warranty."""- conn = None # Single connection for the full request lifecycle+ conn = Nonetry:logger.info("paperless_search_and_link called by user: %s", request.user)@@ -1092,11 +1203,13 @@ def paperless_search_and_link():if document_type not in valid_types:return jsonify({"success": False, "message": "Invalid document type"}), 400- # Get DB connection once and reuse it throughout+ # Fetch Paperless settings and release the pooled DB connection+ # BEFORE performing outbound HTTP search to Paperless-ngx.conn = get_db_connection()-- # Obtain Paperless handler (uses same connection to fetch settings)paperless_handler = get_paperless_handler(conn)+ release_db_connection(conn)+ conn = None+if not paperless_handler:return jsonify({"success": False, "message": "Paperless-ngx not configured"}), 400@@ -1105,11 +1218,14 @@ def paperless_search_and_link():logger.info("Paperless search result: success=%s, document_id=%s, message=%s", success, document_id, message)if not success or not document_id:- return jsonify({"success": False, "message": f"Document not found: {message}"}), 404+ # PPL-05: answer identically to the foreign-owner rejection below+ # so neither status nor message reveals whether a title exists.+ return jsonify({"success": False, "message": "Document not found"}), 404# Update warranty with the found document IDdb_field = valid_types[document_type]+ conn = get_db_connection()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@@ -1182,7 +1298,7 @@ def get_paperless_url():except Exception as e:logger.error(f"Error getting Paperless URL: {e}")- return jsonify({'success': False, 'message': str(e)}), 500+ return jsonify({'success': False, 'message': 'Failed to retrieve Paperless URL'}), 500finally:if conn:release_db_connection(conn)\ No newline at end of filediff --git a/backend/fix_permissions.py b/backend/fix_permissions.pyindex dd7cbc1..0a057af 100644--- a/backend/fix_permissions.py+++ b/backend/fix_permissions.py@@ -126,13 +126,19 @@ def fix_upload_folder_permissions():logger.info(f"Fixing upload folder ownership from {current_owner} to warracker:warracker ({warracker_uid}:{warracker_gid})...")- # Fix ownership recursively- for root, dirs, files in os.walk(upload_folder):- os.chown(root, warracker_uid, warracker_gid)+ # Fix ownership recursively without following symlinks so a symlink+ # inside the writable uploads volume cannot redirect root chown outside it.+ for root, dirs, files in os.walk(upload_folder, followlinks=False):+ if not os.path.islink(root):+ os.lchown(root, warracker_uid, warracker_gid)for directory in dirs:- os.chown(os.path.join(root, directory), warracker_uid, warracker_gid)+ dir_path = os.path.join(root, directory)+ if not os.path.islink(dir_path):+ os.lchown(dir_path, warracker_uid, warracker_gid)for file in files:- os.chown(os.path.join(root, file), warracker_uid, warracker_gid)+ file_path = os.path.join(root, file)+ if not os.path.islink(file_path):+ os.lchown(file_path, warracker_uid, warracker_gid)logger.info("Upload folder permissions fixed successfully!")diff --git a/backend/notifications.py b/backend/notifications.pyindex c3b75ce..0afde80 100644--- a/backend/notifications.py+++ b/backend/notifications.py@@ -921,7 +921,14 @@ def _master_scheduler_status_path(master_pid=None):"""Path to the live scheduler status snapshot written by the gunicorn master."""import tempfilepid = master_pid or os.environ.get('WARRACKER_GUNICORN_MASTER_PID') or os.getpid()- return os.path.join(tempfile.gettempdir(), f'warracker_scheduler_status_{pid}.json')+ uid = os.getuid() if hasattr(os, 'getuid') else 0+ runtime_dir = os.path.join(tempfile.gettempdir(), f'warracker-runtime-{uid}')+ try:+ os.makedirs(runtime_dir, mode=0o700, exist_ok=True)+ os.chmod(runtime_dir, 0o700)+ except OSError:+ runtime_dir = tempfile.gettempdir()+ return os.path.join(runtime_dir, f'scheduler_status_{pid}.json')def _collect_local_scheduler_jobs():diff --git a/backend/oidc_handler.py b/backend/oidc_handler.pyindex 9ca3b68..fe610bc 100644--- a/backend/oidc_handler.py+++ b/backend/oidc_handler.py@@ -231,17 +231,32 @@ def oidc_callback_route():if not first_name and not last_name:first_name = token_id_claims.get('name') or userinfo.get('name', '')- user_groups = token_id_claims.get('groups') or userinfo.get('groups') or []+ raw_groups = token_id_claims.get('groups')+ if raw_groups is None:+ raw_groups = userinfo.get('groups')+ # Only treat groups as a collection of discrete group names — never run+ # `in` against a raw string, where `"admin" in "non-admin"` would be True.+ if isinstance(raw_groups, (list, tuple, set)):+ user_groups = [str(g) for g in raw_groups if isinstance(g, str)]+ else:+ user_groups = []conn = Nonetry:conn = get_db_connection()with conn.cursor() as cur:- # Check for existing OIDC user- cur.execute("SELECT id, username, email, first_name, last_name, is_admin, is_owner FROM users WHERE oidc_sub = %s AND oidc_issuer = %s AND is_active = TRUE",+ # Check for existing OIDC user (including inactive accounts so a+ # deactivated user is rejected cleanly instead of hitting the+ # new-user provisioning path and failing on the unique constraint).+ cur.execute("SELECT id, username, email, first_name, last_name, is_admin, is_owner, is_active FROM users WHERE oidc_sub = %s AND oidc_issuer = %s",(oidc_subject, oidc_issuer))user_db_data = cur.fetchone()+ if user_db_data and not user_db_data[7]:+ logger.warning(f"[OIDC_HANDLER] Inactive OIDC user ID {user_db_data[0]} attempted login.")+ frontend_login_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"+ return redirect(f"{frontend_login_url}?oidc_error=account_inactive")+user_id = Noneis_new_user = False@@ -308,7 +323,7 @@ def oidc_callback_route():return redirect(f"{frontend_login_url}?oidc_error=email_missing_for_new_user")# Check for email conflict with local account- cur.execute("SELECT id FROM users WHERE email = %s AND (oidc_sub IS NULL OR oidc_issuer IS NULL)", (email,))+ cur.execute("SELECT id FROM users WHERE LOWER(email) = LOWER(%s) AND (oidc_sub IS NULL OR oidc_issuer IS NULL)", (email,))if cur.fetchone():logger.warning(f"[OIDC_HANDLER] Email {email} already exists for a local account. OIDC user cannot be created.")frontend_login_url = os.environ.get('FRONTEND_URL', 'http://localhost:8080').rstrip('/') + "/login.html"@@ -329,6 +344,19 @@ def oidc_callback_route():cur.execute('SELECT COUNT(*) FROM users')user_count = cur.fetchone()[0]+ # Re-check registration gate under the lock so a concurrent+ # second signup cannot slip past registration_enabled=false.+ if table_exists:+ cur.execute("SELECT value FROM site_settings WHERE key = 'registration_enabled'")+ result = cur.fetchone()+ if result:+ registration_enabled = result[0].lower() == 'true'+ if not registration_enabled and user_count > 0:+ logger.warning(f"[OIDC_HANDLER] New OIDC user registration denied after lock - registrations are disabled. Subject: {oidc_subject}")+ conn.rollback()+ frontend_login_url = os.environ.get('FRONTEND_URL', current_app.config.get('APP_BASE_URL', 'http://localhost:8080')).rstrip('/') + "/login.html"+ return redirect(f"{frontend_login_url}?oidc_error=registration_disabled")+if admin_oidc_group:is_admin = admin_oidc_group in user_groupsif is_admin:diff --git a/backend/rate_limit.py b/backend/rate_limit.pyindex 556c29e..f6fb5a5 100644--- a/backend/rate_limit.py+++ b/backend/rate_limit.py@@ -18,34 +18,69 @@ Registration is deliberately not limited here: the first-user race(AUTH-07) is fixed with a database lock instead, and a registrationcap would break legitimate bulk onboarding."""+from collections import OrderedDictimport threadingimport timeLOGIN_MAX_FAILURES = 10+LOGIN_IP_MAX_FAILURES = 100LOGIN_WINDOW_SECONDS = 300RESET_MAX_REQUESTS = 5RESET_WINDOW_SECONDS = 3600+MAX_TRACKED_KEYS = 10000class _AttemptTracker:- """Thread-safe per-key timestamp lists with window pruning."""+ """Thread-safe per-key timestamp lists with bounded memory and window pruning."""- def __init__(self):+ def __init__(self, max_keys=MAX_TRACKED_KEYS, default_window=RESET_WINDOW_SECONDS):self._lock = threading.Lock()- self._attempts = {}+ self._attempts = OrderedDict()+ self._max_keys = max_keys+ self._default_window = default_window+ self._writes_since_sweep = 0def _prune(self, key, window):cutoff = time.monotonic() - windowstamps = [t for t in self._attempts.get(key, []) if t > cutoff]if stamps:self._attempts[key] = stamps+ self._attempts.move_to_end(key)else:self._attempts.pop(key, None)return stamps- def record(self, key):+ def _sweep_expired(self, window):+ cutoff = time.monotonic() - window+ expired_keys = [+ k for k, stamps in self._attempts.items()+ if not stamps or stamps[-1] <= cutoff+ ]+ for k in expired_keys:+ self._attempts.pop(k, None)++ def record(self, key, window=None):+ now = time.monotonic()+ effective_window = window if window is not None else self._default_windowwith self._lock:- self._attempts.setdefault(key, []).append(time.monotonic())+ self._writes_since_sweep += 1+ if self._writes_since_sweep >= 256:+ self._sweep_expired(effective_window)+ self._writes_since_sweep = 0++ stamps = self._attempts.get(key)+ if stamps is None:+ if len(self._attempts) >= self._max_keys:+ self._sweep_expired(effective_window)+ while len(self._attempts) >= self._max_keys:+ self._attempts.popitem(last=False)+ self._attempts[key] = [now]+ else:+ cutoff = now - effective_window+ stamps = [t for t in stamps if t > cutoff]+ stamps.append(now)+ self._attempts[key] = stamps+ self._attempts.move_to_end(key)def count(self, key, window):with self._lock:@@ -59,22 +94,37 @@ class _AttemptTracker:self._attempts.pop(key, None)-_login_tracker = _AttemptTracker()-_reset_tracker = _AttemptTracker()+_login_tracker = _AttemptTracker(default_window=LOGIN_WINDOW_SECONDS)+_login_ip_tracker = _AttemptTracker(default_window=LOGIN_WINDOW_SECONDS)+_reset_tracker = _AttemptTracker(default_window=RESET_WINDOW_SECONDS)def _login_key(ip_address, username):return (ip_address or "", (username or "").lower())+def _login_ip_key(ip_address):+ return ip_address or ""++def login_limited(ip_address, username):- return _login_tracker.is_limited(+ if _login_tracker.is_limited(_login_key(ip_address, username),- LOGIN_MAX_FAILURES, LOGIN_WINDOW_SECONDS)+ LOGIN_MAX_FAILURES, LOGIN_WINDOW_SECONDS,+ ):+ return True+ if ip_address and _login_ip_tracker.is_limited(+ _login_ip_key(ip_address),+ LOGIN_IP_MAX_FAILURES, LOGIN_WINDOW_SECONDS,+ ):+ return True+ return Falsedef record_login_failure(ip_address, username):- _login_tracker.record(_login_key(ip_address, username))+ _login_tracker.record(_login_key(ip_address, username), LOGIN_WINDOW_SECONDS)+ if ip_address:+ _login_ip_tracker.record(_login_ip_key(ip_address), LOGIN_WINDOW_SECONDS)def clear_login_failures(ip_address, username):@@ -87,4 +137,4 @@ def reset_request_limited(email):def record_reset_request(email):- _reset_tracker.record((email or "").lower())+ _reset_tracker.record((email or "").lower(), RESET_WINDOW_SECONDS)diff --git a/backend/statistics_routes.py b/backend/statistics_routes.pyindex 4ffd71d..31c2efe 100644--- a/backend/statistics_routes.py+++ b/backend/statistics_routes.py@@ -402,7 +402,7 @@ def get_global_statistics():days_later_for_recent = expiring_soon_datecur.execute("""SELECT- w.id, w.product_name, w.purchase_date,+ w.id, w.user_id, w.product_name, w.purchase_date,w.warranty_duration_years, w.warranty_duration_months, w.warranty_duration_days,w.expiration_date, w.invoice_path, w.manual_path, w.other_document_path,w.product_url, w.purchase_price, w.is_lifetime,@@ -416,6 +416,7 @@ def get_global_statistics():columns = [desc[0] for desc in cur.description]recent_warranties = []+ is_admin_viewer = request.user.get('is_admin', False)for row in cur.fetchall():warranty = dict(zip(columns, row))@@ -445,6 +446,10 @@ def get_global_statistics():display_name = 'Unknown User'warranty['user_display_name'] = display_name++ if not is_admin_viewer and warranty.get('user_id') != user_id:+ warranty.pop('email', None)+ warranty['other_document_path'] = Nonerecent_warranties.append(warranty)@@ -509,6 +514,10 @@ def get_global_statistics():display_name = 'Unknown User'warranty['user_display_name'] = display_name++ if not is_admin_viewer and warranty.get('user_id') != user_id:+ warranty.pop('email', None)+ warranty['other_document_path'] = Noneall_warranties_list.append(warranty)diff --git a/backend/warranties_routes.py b/backend/warranties_routes.pyindex 6cc03bb..2650c52 100644--- a/backend/warranties_routes.py+++ b/backend/warranties_routes.py@@ -166,35 +166,58 @@ def unique_upload_filename(original_name, infix=""):stamp = datetime.now().strftime('%Y%m%d%H%M%S')return f"{stamp}_{uuid.uuid4().hex[:8]}_{infix}{safe}"-# NAT64 well-known prefix (RFC 6052): the low 32 bits embed an IPv4-# address, so 64:ff9b::/96 can smuggle a private IPv4 past is_global.+# NAT64 well-known prefix (RFC 6052), NAT64 local-use prefix (RFC 8215),+# and SIIT IPv4-translated prefix (RFC 2765): the low 32 bits embed an IPv4+# address and Python's ipaddress.is_global reports True for them._NAT64_WELL_KNOWN_PREFIX = ipaddress.ip_network('64:ff9b::/96')+_NAT64_LOCAL_USE_PREFIX = ipaddress.ip_network('64:ff9b:1::/48')+_IPV4_TRANSLATED_PREFIX = ipaddress.ip_network('::ffff:0:0:0/96')+++def _is_strictly_public_unicast(addr):+ """True only for globally routable unicast addresses (never private,+ loopback, link-local, multicast, reserved, or unspecified)."""+ return (+ addr.is_global+ and not addr.is_private+ and not addr.is_loopback+ and not addr.is_link_local+ and not addr.is_multicast+ and not addr.is_reserved+ and not addr.is_unspecified+ )def _ip_address_is_public(addr):- """True when an address is a genuine public destination (SSRF-02).-- ipaddress.is_global alone is not enough: on the interpreters tested- it reports True for the NAT64 well-known prefix embedding a private- IPv4 (64:ff9b::a9fe:a9fe, the cloud metadata address, passes). The- NAT64 prefix is rejected wholesale, and translation addresses- (IPv4-mapped, 6to4, Teredo) must pass both the wrapper check and- the check on the IPv4 they embed. Nothing previously allowed- becomes allowed; only translation tricks are removed.+ """True when an address is a genuine public unicast destination (SSRF-02).++ ipaddress.is_global alone is not enough: it reports True for the NAT64+ prefix (64:ff9b::/96), SIIT IPv4-translated addresses (::ffff:0:0:0/96),+ and multicast ranges (224.0.0.0/4, ff00::/8). Translation prefixes are+ rejected wholesale, and IPv4-mapped / 6to4 / Teredo wrappers must pass+ the strict public-unicast check on both the wrapper and embedded IPv4."""if addr.version == 6:- if addr in _NAT64_WELL_KNOWN_PREFIX:+ if (+ addr in _NAT64_WELL_KNOWN_PREFIX+ or addr in _NAT64_LOCAL_USE_PREFIX+ or addr in _IPV4_TRANSLATED_PREFIX+ ):return Falsemapped = addr.ipv4_mappedif mapped is not None:- return addr.is_global and mapped.is_global+ return _is_strictly_public_unicast(mapped)sixtofour = addr.sixtofourif sixtofour is not None:- return addr.is_global and sixtofour.is_global+ return _is_strictly_public_unicast(addr) and _is_strictly_public_unicast(sixtofour)teredo = addr.teredoif teredo is not None:- return addr.is_global and teredo[0].is_global and teredo[1].is_global- return addr.is_global+ return (+ _is_strictly_public_unicast(addr)+ and _is_strictly_public_unicast(teredo[0])+ and _is_strictly_public_unicast(teredo[1])+ )+ return _is_strictly_public_unicast(addr)class _PhotoHostRejectedError(Exception):@@ -373,7 +396,7 @@ def download_product_photo(url):if resp.status_code != 200:resp.close()raise ValueError("Could not fetch the photo URL.")- chunks, total = [], 0+ buf = bytearray()# A per-chunk deadline check alone does not bound a slow drip:# a read for a full chunk blocks until the chunk fills or the# connection closes, so the check may never run. A timer shuts@@ -390,10 +413,9 @@ def download_product_photo(url):for chunk in resp.iter_content(chunk_size=65536):if time.monotonic() >= deadline:raise ValueError("Timed out fetching the photo URL.")- total += len(chunk)- if total > max_bytes:+ if len(buf) + len(chunk) > max_bytes:raise ValueError("Photo URL file is too large.")- chunks.append(chunk)+ buf.extend(chunk)except requests.RequestException:if time.monotonic() >= deadline:raise ValueError("Timed out fetching the photo URL.")@@ -403,11 +425,10 @@ def download_product_photo(url):resp.close()if time.monotonic() >= deadline:raise ValueError("Timed out fetching the photo URL.")- data = b''.join(chunks)- ext = _detect_image_extension(data)+ ext = _detect_image_extension(buf)if not ext:raise ValueError("Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)")- return data, ext+ return bytes(buf), extraise ValueError("Too many redirects fetching the photo URL.")finally:session.close()@@ -1329,6 +1350,26 @@ def update_warranty(warranty_id):logger.info(f"[UPDATE] Converted Paperless IDs: invoice={paperless_invoice_id}, manual={paperless_manual_id}, photo={paperless_photo_id}, other={paperless_other_id}")+ # Validate uploaded file extensions up front before touching disk or+ # running outbound photo URL downloads.+ if not paperless_invoice_id and 'invoice' in request.files and request.files['invoice'].filename != '':+ if not allowed_file(request.files['invoice'].filename):+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400+ if not paperless_manual_id and 'manual' in request.files and request.files['manual'].filename != '':+ if not allowed_file(request.files['manual'].filename):+ return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400+ if not paperless_other_id and 'other_document' in request.files and request.files['other_document'].filename != '':+ if not allowed_file(request.files['other_document'].filename):+ return jsonify({"error": "File type not allowed for other document. Use PDF, PNG, JPG, JPEG, ZIP, or RAR"}), 400+ has_uploaded_photo = (+ not paperless_photo_id+ and 'product_photo' in request.files+ and request.files['product_photo'].filename != ''+ )+ if has_uploaded_photo:+ if not (request.files['product_photo'].filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif'))):+ return jsonify({"error": "Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)"}), 400+# 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@@ -1338,324 +1379,340 @@ def update_warranty(warranty_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- if not paperless_invoice_id and 'invoice' in request.files:- invoice = request.files['invoice']- if invoice.filename != '':- if not allowed_file(invoice.filename):- return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400- cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))- old_invoice_path = cur.fetchone()[0]++ # Fetch existing file paths while holding the initial connection.+ cur.execute(+ 'SELECT invoice_path, manual_path, other_document_path, product_photo_path '+ 'FROM warranties WHERE id = %s',+ (warranty_id,),+ )+ old_paths_row = cur.fetchone() or (None, None, None, None)+ old_invoice_path, old_manual_path, old_other_document_path, old_product_photo_path = old_paths_row++ # Product photo by URL (#207): download BEFORE holding a pooled DB+ # connection open for the update transaction so slow hosts cannot+ # starve the connection pool.+ product_photo_url = (request.form.get('product_photo_url') or '').strip()+ downloaded_photo = None+ if (not has_uploaded_photo and not paperless_photo_id and product_photo_url+ and request.form.get('delete_product_photo', 'false').lower() != 'true'):+ release_db_connection(conn)+ conn = None+ try:+ downloaded_photo = download_product_photo(product_photo_url)+ except ValueError as e:+ return jsonify({"error": str(e)}), 400+ conn = get_db_connection()++ newly_saved_files = []+ deferred_deletes = []++ def _cleanup_new_files():+ for saved_path in newly_saved_files:+ try:+ if os.path.exists(saved_path):+ os.remove(saved_path)+ except OSError as cleanup_err:+ logger.error(f"Error cleaning up newly saved file {saved_path}: {cleanup_err}")++ try:+ with conn.cursor() as cur:+ # File handling for invoice+ db_invoice_path = None+ if not paperless_invoice_id and 'invoice' in request.files:+ invoice = request.files['invoice']+ if invoice.filename != '':+ if old_invoice_path:+ deferred_deletes.append((old_invoice_path, ('warranties', 'invoice_path', warranty_id)))+ filename = unique_upload_filename(invoice.filename)+ invoice_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ logger.info(f"Attempting to save updated invoice to: {invoice_path}")+ try:+ invoice.save(invoice_path)+ newly_saved_files.append(invoice_path)+ db_invoice_path = os.path.join('uploads', filename)+ logger.info(f"Successfully saved updated invoice: {db_invoice_path}")+ except Exception as e:+ logger.error(f"Error saving updated invoice {filename} to {invoice_path}: {e}")+ _cleanup_new_files()+ return jsonify({"error": "Failed to save updated invoice"}), 500+ elif paperless_invoice_id:+ logger.info(f"Invoice updated to Paperless-ngx with ID: {paperless_invoice_id}")if old_invoice_path:- _delete_stored_file(cur, old_invoice_path, exclude=('warranties', 'invoice_path', warranty_id))- filename = unique_upload_filename(invoice.filename)- invoice_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)- logger.info(f"Attempting to save updated invoice to: {invoice_path}")- try:- invoice.save(invoice_path)- db_invoice_path = os.path.join('uploads', filename)- logger.info(f"Successfully saved updated invoice: {db_invoice_path}")- except Exception as e:- logger.error(f"Error saving updated invoice {filename} to {invoice_path}: {e}")- return jsonify({"error": f"Failed to save updated invoice: {str(e)}"}), 500- elif paperless_invoice_id:- logger.info(f"Invoice updated to Paperless-ngx with ID: {paperless_invoice_id}")- # Clear local path when storing in Paperless-ngx- cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))- old_invoice_path = cur.fetchone()[0]- if old_invoice_path:- _delete_stored_file(cur, old_invoice_path, exclude=('warranties', 'invoice_path', warranty_id))- db_invoice_path = None # Clear local path- elif request.form.get('delete_invoice', 'false').lower() == 'true':- cur.execute('SELECT invoice_path FROM warranties WHERE id = %s', (warranty_id,))- old_invoice_path = cur.fetchone()[0]- if old_invoice_path:- _delete_stored_file(cur, old_invoice_path, exclude=('warranties', 'invoice_path', warranty_id))- db_invoice_path = None # Set to None to clear in DB-- # File handling for manual- db_manual_path = None- if not paperless_manual_id and 'manual' in request.files:- manual = request.files['manual']- if manual.filename != '':- if not allowed_file(manual.filename):- return jsonify({"error": "File type not allowed. Use PDF, PNG, JPG, or JPEG"}), 400- cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))- old_manual_path = cur.fetchone()[0]+ deferred_deletes.append((old_invoice_path, ('warranties', 'invoice_path', warranty_id)))+ db_invoice_path = None+ elif request.form.get('delete_invoice', 'false').lower() == 'true':+ if old_invoice_path:+ deferred_deletes.append((old_invoice_path, ('warranties', 'invoice_path', warranty_id)))+ db_invoice_path = None++ # File handling for manual+ db_manual_path = None+ if not paperless_manual_id and 'manual' in request.files:+ manual = request.files['manual']+ if manual.filename != '':+ if old_manual_path:+ deferred_deletes.append((old_manual_path, ('warranties', 'manual_path', warranty_id)))+ filename = unique_upload_filename(manual.filename, "manual_")+ manual_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ logger.info(f"Attempting to save updated manual to: {manual_path}")+ try:+ manual.save(manual_path)+ newly_saved_files.append(manual_path)+ db_manual_path = os.path.join('uploads', filename)+ logger.info(f"Successfully saved updated manual: {db_manual_path}")+ except Exception as e:+ logger.error(f"Error saving updated manual {filename} to {manual_path}: {e}")+ _cleanup_new_files()+ return jsonify({"error": "Failed to save updated manual"}), 500+ elif paperless_manual_id:+ logger.info(f"Manual updated to Paperless-ngx with ID: {paperless_manual_id}")if old_manual_path:- _delete_stored_file(cur, old_manual_path, exclude=('warranties', 'manual_path', warranty_id))- filename = unique_upload_filename(manual.filename, "manual_")- manual_path = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)- logger.info(f"Attempting to save updated manual to: {manual_path}")- try:- manual.save(manual_path)- db_manual_path = os.path.join('uploads', filename)- logger.info(f"Successfully saved updated manual: {db_manual_path}")- except Exception as e:- logger.error(f"Error saving updated manual {filename} to {manual_path}: {e}")- return jsonify({"error": f"Failed to save updated manual: {str(e)}"}), 500- elif paperless_manual_id:- logger.info(f"Manual updated to Paperless-ngx with ID: {paperless_manual_id}")- # Clear local path when storing in Paperless-ngx- cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))- old_manual_path = cur.fetchone()[0]- if old_manual_path:- _delete_stored_file(cur, old_manual_path, exclude=('warranties', 'manual_path', warranty_id))- db_manual_path = None # Clear local path- elif request.form.get('delete_manual', 'false').lower() == 'true':- cur.execute('SELECT manual_path FROM warranties WHERE id = %s', (warranty_id,))- old_manual_path = cur.fetchone()[0]- if old_manual_path:- _delete_stored_file(cur, old_manual_path, exclude=('warranties', 'manual_path', warranty_id))- db_manual_path = None # Set to None to clear in DB-- # File handling for other document- db_other_document_path = None- if not paperless_other_id and 'other_document' in request.files:- other_document = request.files['other_document']- if other_document.filename != '':- if not allowed_file(other_document.filename):- return jsonify({"error": "File type not allowed for other document. Use PDF, PNG, JPG, JPEG, ZIP, or RAR"}), 400- cur.execute('SELECT other_document_path FROM warranties WHERE id = %s', (warranty_id,))- old_other_document_path = cur.fetchone()[0]+ deferred_deletes.append((old_manual_path, ('warranties', 'manual_path', warranty_id)))+ db_manual_path = None+ elif request.form.get('delete_manual', 'false').lower() == 'true':+ if old_manual_path:+ deferred_deletes.append((old_manual_path, ('warranties', 'manual_path', warranty_id)))+ db_manual_path = None++ # File handling for other document+ db_other_document_path = None+ if not paperless_other_id and 'other_document' in request.files:+ other_document = request.files['other_document']+ if other_document.filename != '':+ if old_other_document_path:+ deferred_deletes.append((old_other_document_path, ('warranties', 'other_document_path', warranty_id)))+ filename = unique_upload_filename(other_document.filename, "other_")+ other_document_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ logger.info(f"Attempting to save updated other_document to: {other_document_path_on_disk}")+ try:+ other_document.save(other_document_path_on_disk)+ newly_saved_files.append(other_document_path_on_disk)+ db_other_document_path = os.path.join('uploads', filename)+ logger.info(f"Successfully saved updated other_document: {db_other_document_path}")+ except Exception as e:+ logger.error(f"Error saving updated other_document {filename} to {other_document_path_on_disk}: {e}")+ _cleanup_new_files()+ return jsonify({"error": "Failed to save updated other document"}), 500+ elif paperless_other_id:+ logger.info(f"Other document updated to Paperless-ngx with ID: {paperless_other_id}")if old_other_document_path:- _delete_stored_file(cur, old_other_document_path, exclude=('warranties', 'other_document_path', warranty_id))- filename = unique_upload_filename(other_document.filename, "other_")- other_document_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)- logger.info(f"Attempting to save updated other_document to: {other_document_path_on_disk}")- try:- other_document.save(other_document_path_on_disk)- db_other_document_path = os.path.join('uploads', filename)- logger.info(f"Successfully saved updated other_document: {db_other_document_path}")- except Exception as e:- logger.error(f"Error saving updated other_document {filename} to {other_document_path_on_disk}: {e}")- return jsonify({"error": f"Failed to save updated other_document: {str(e)}"}), 500- elif paperless_other_id:- logger.info(f"Other document updated to Paperless-ngx with ID: {paperless_other_id}")- # Clear local path when storing in Paperless-ngx- cur.execute('SELECT other_document_path FROM warranties WHERE id = %s', (warranty_id,))- old_other_document_path = cur.fetchone()[0]- if old_other_document_path:- _delete_stored_file(cur, old_other_document_path, exclude=('warranties', 'other_document_path', warranty_id))- db_other_document_path = None # Clear local path- elif request.form.get('delete_other_document', 'false').lower() == 'true':- cur.execute('SELECT other_document_path FROM warranties WHERE id = %s', (warranty_id,))- old_other_document_path = cur.fetchone()[0]- if old_other_document_path:- _delete_stored_file(cur, old_other_document_path, exclude=('warranties', 'other_document_path', warranty_id))- db_other_document_path = None # Set to None to clear in DB-- # Handle product photo file upload (only if not stored in Paperless-ngx)- db_product_photo_path = None- if not paperless_photo_id and 'product_photo' in request.files:- product_photo = request.files['product_photo']- if product_photo.filename != '':- # Check if it's an image file- if not (product_photo.filename.lower().endswith(('.png', '.jpg', '.jpeg', '.webp', '.gif'))):- return jsonify({"error": "Product photo must be an image file (PNG, JPG, JPEG, WEBP, GIF)"}), 400-- # Delete old photo if it exists- cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))- old_product_photo_path = cur.fetchone()[0]+ deferred_deletes.append((old_other_document_path, ('warranties', 'other_document_path', warranty_id)))+ db_other_document_path = None+ elif request.form.get('delete_other_document', 'false').lower() == 'true':+ if old_other_document_path:+ deferred_deletes.append((old_other_document_path, ('warranties', 'other_document_path', warranty_id)))+ db_other_document_path = None++ # Handle product photo file upload (only if not stored in Paperless-ngx)+ db_product_photo_path = None+ if has_uploaded_photo:+ product_photo = request.files['product_photo']if old_product_photo_path:- _delete_stored_file(cur, old_product_photo_path, exclude=('warranties', 'product_photo_path', warranty_id))-+ deferred_deletes.append((old_product_photo_path, ('warranties', 'product_photo_path', warranty_id)))filename = unique_upload_filename(product_photo.filename, "photo_")product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)logger.info(f"Attempting to save updated product_photo to: {product_photo_path_on_disk}")try:product_photo.save(product_photo_path_on_disk)+ newly_saved_files.append(product_photo_path_on_disk)db_product_photo_path = os.path.join('uploads', filename)logger.info(f"Successfully saved updated product_photo: {db_product_photo_path}")except Exception as e:logger.error(f"Error saving updated product_photo {filename} to {product_photo_path_on_disk}: {e}")- return jsonify({"error": f"Failed to save updated product_photo: {str(e)}"}), 500- elif paperless_photo_id:- logger.info(f"Product photo updated to Paperless-ngx with ID: {paperless_photo_id}")- # Clear local path when storing in Paperless-ngx- cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))- old_product_photo_path = cur.fetchone()[0]- if old_product_photo_path:- _delete_stored_file(cur, old_product_photo_path, exclude=('warranties', 'product_photo_path', warranty_id))- db_product_photo_path = None # Clear local path- elif request.form.get('delete_product_photo', 'false').lower() == 'true':- cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))- old_product_photo_path = cur.fetchone()[0]- if old_product_photo_path:- _delete_stored_file(cur, old_product_photo_path, exclude=('warranties', 'product_photo_path', warranty_id))- db_product_photo_path = None # Set to None to clear in DB-- # Product photo by URL (#207): replace the photo with a downloaded- # image when no file was uploaded and no delete was requested.- product_photo_url = (request.form.get('product_photo_url') or '').strip()- if (not db_product_photo_path and not paperless_photo_id and product_photo_url- and request.form.get('delete_product_photo', 'false').lower() != 'true'):- try:- photo_bytes, photo_ext = download_product_photo(product_photo_url)- except ValueError as e:- return jsonify({"error": str(e)}), 400- cur.execute('SELECT product_photo_path FROM warranties WHERE id = %s', (warranty_id,))- old_product_photo_path = cur.fetchone()[0]- if old_product_photo_path:- _delete_stored_file(cur, old_product_photo_path, exclude=('warranties', 'product_photo_path', warranty_id))- filename = unique_upload_filename(f"downloaded{photo_ext}", "photo_")- product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)- try:- with open(product_photo_path_on_disk, 'wb') as fh:- fh.write(photo_bytes)- db_product_photo_path = os.path.join('uploads', filename)- logger.info(f"Successfully saved updated product_photo from URL: {db_product_photo_path}")- except Exception as e:- logger.error(f"Error saving updated product_photo from URL {filename}: {e}")- return jsonify({"error": f"Failed to save product_photo: {str(e)}"}), 500-- # Prepare update parameters- update_params = {- 'product_name': product_name,- 'purchase_date': purchase_date,- 'is_lifetime': is_lifetime,- 'warranty_duration_years': warranty_duration_years,- 'warranty_duration_months': warranty_duration_months,- 'warranty_duration_days': warranty_duration_days,- 'expiration_date': expiration_date, # Will be None if lifetime- 'product_url': product_url,- 'purchase_price': purchase_price,- 'vendor': vendor,- 'warranty_type': warranty_type,- 'currency': currency,- 'model_number': model_number- }- sql_fields = []- sql_values = []- for key, value in update_params.items():- sql_fields.append(f"{key} = %s")- sql_values.append(value)- if notes is not None:- sql_fields.append("notes = %s")- sql_values.append(notes)- if db_invoice_path is not None:- sql_fields.append("invoice_path = %s")- sql_values.append(db_invoice_path)- elif 'delete_invoice' in request.form and request.form.get('delete_invoice', 'false').lower() == 'true':- sql_fields.append("invoice_path = NULL")- sql_fields.append("paperless_invoice_id = NULL") # Also clear Paperless ID- if db_manual_path is not None:- sql_fields.append("manual_path = %s")- sql_values.append(db_manual_path)- elif 'delete_manual' in request.form and request.form.get('delete_manual', 'false').lower() == 'true':- sql_fields.append("manual_path = NULL")- sql_fields.append("paperless_manual_id = NULL") # Also clear Paperless ID- if db_other_document_path is not None:- sql_fields.append("other_document_path = %s")- sql_values.append(db_other_document_path)- elif 'delete_other_document' in request.form and request.form.get('delete_other_document', 'false').lower() == 'true':- sql_fields.append("other_document_path = NULL")- sql_fields.append("paperless_other_id = NULL") # Also clear Paperless ID- if db_product_photo_path is not None:- sql_fields.append("product_photo_path = %s")- sql_values.append(db_product_photo_path)- elif 'delete_product_photo' in request.form and request.form.get('delete_product_photo', 'false').lower() == 'true':- sql_fields.append("product_photo_path = NULL")- sql_fields.append("paperless_photo_id = NULL") # Also clear Paperless ID-- # Handle Paperless-ngx document IDs- if paperless_invoice_id is not None:- sql_fields.append("paperless_invoice_id = %s")- sql_values.append(paperless_invoice_id)- if paperless_manual_id is not None:- sql_fields.append("paperless_manual_id = %s")- sql_values.append(paperless_manual_id)- if paperless_photo_id is not None:- sql_fields.append("paperless_photo_id = %s")- sql_values.append(paperless_photo_id)- if paperless_other_id is not None:- sql_fields.append("paperless_other_id = %s")- sql_values.append(paperless_other_id)-- # Handle URL fields for documents- if 'invoice_url' in request.form:- sql_fields.append("invoice_url = %s")- sql_values.append(request.form.get('invoice_url'))- if 'manual_url' in request.form:- sql_fields.append("manual_url = %s")- sql_values.append(request.form.get('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_fields.append("updated_at = NOW()") # Use SQL function, no parameter needed- sql_values.append(warranty_id)- update_sql = f"UPDATE warranties SET {', '.join(sql_fields)} WHERE id = %s"- cur.execute(update_sql, sql_values)- logger.info(f"Updated warranty with SQL: {update_sql}")- logger.info(f"Parameters: {sql_values}")-- # Record expiration date or lifetime transitions (issue #209)- new_is_lifetime = bool(is_lifetime)- expiry_changed = (- existing_is_lifetime != new_is_lifetime- or (not existing_is_lifetime and not new_is_lifetime and existing_expiration_date != expiration_date)- )- if expiry_changed:- cur.execute('''- INSERT INTO warranty_expiry_history (+ _cleanup_new_files()+ return jsonify({"error": "Failed to save updated product photo"}), 500+ elif paperless_photo_id:+ logger.info(f"Product photo updated to Paperless-ngx with ID: {paperless_photo_id}")+ if old_product_photo_path:+ deferred_deletes.append((old_product_photo_path, ('warranties', 'product_photo_path', warranty_id)))+ db_product_photo_path = None+ elif request.form.get('delete_product_photo', 'false').lower() == 'true':+ if old_product_photo_path:+ deferred_deletes.append((old_product_photo_path, ('warranties', 'product_photo_path', warranty_id)))+ db_product_photo_path = None+ elif downloaded_photo is not None:+ photo_bytes, photo_ext = downloaded_photo+ if old_product_photo_path:+ deferred_deletes.append((old_product_photo_path, ('warranties', 'product_photo_path', warranty_id)))+ filename = unique_upload_filename(f"downloaded{photo_ext}", "photo_")+ product_photo_path_on_disk = os.path.join(current_app.config['UPLOAD_FOLDER'], filename)+ try:+ with open(product_photo_path_on_disk, 'wb') as fh:+ fh.write(photo_bytes)+ newly_saved_files.append(product_photo_path_on_disk)+ db_product_photo_path = os.path.join('uploads', filename)+ logger.info(f"Successfully saved updated product_photo from URL: {db_product_photo_path}")+ except Exception as e:+ logger.error(f"Error saving updated product_photo from URL {filename}: {e}")+ _cleanup_new_files()+ return jsonify({"error": "Failed to save product photo"}), 500++ # Prepare update parameters+ update_params = {+ 'product_name': product_name,+ 'purchase_date': purchase_date,+ 'is_lifetime': is_lifetime,+ 'warranty_duration_years': warranty_duration_years,+ 'warranty_duration_months': warranty_duration_months,+ 'warranty_duration_days': warranty_duration_days,+ 'expiration_date': expiration_date, # Will be None if lifetime+ 'product_url': product_url,+ 'purchase_price': purchase_price,+ 'vendor': vendor,+ 'warranty_type': warranty_type,+ 'currency': currency,+ 'model_number': model_number+ }+ sql_fields = []+ sql_values = []+ for key, value in update_params.items():+ sql_fields.append(f"{key} = %s")+ sql_values.append(value)+ if notes is not None:+ sql_fields.append("notes = %s")+ sql_values.append(notes)+ if db_invoice_path is not None:+ sql_fields.append("invoice_path = %s")+ sql_values.append(db_invoice_path)+ elif paperless_invoice_id is not None:+ sql_fields.append("invoice_path = NULL")+ elif 'delete_invoice' in request.form and request.form.get('delete_invoice', 'false').lower() == 'true':+ sql_fields.append("invoice_path = NULL")+ sql_fields.append("paperless_invoice_id = NULL") # Also clear Paperless ID+ if db_manual_path is not None:+ sql_fields.append("manual_path = %s")+ sql_values.append(db_manual_path)+ elif paperless_manual_id is not None:+ sql_fields.append("manual_path = NULL")+ elif 'delete_manual' in request.form and request.form.get('delete_manual', 'false').lower() == 'true':+ sql_fields.append("manual_path = NULL")+ sql_fields.append("paperless_manual_id = NULL") # Also clear Paperless ID+ if db_other_document_path is not None:+ sql_fields.append("other_document_path = %s")+ sql_values.append(db_other_document_path)+ elif paperless_other_id is not None:+ sql_fields.append("other_document_path = NULL")+ elif 'delete_other_document' in request.form and request.form.get('delete_other_document', 'false').lower() == 'true':+ sql_fields.append("other_document_path = NULL")+ sql_fields.append("paperless_other_id = NULL") # Also clear Paperless ID+ if db_product_photo_path is not None:+ sql_fields.append("product_photo_path = %s")+ sql_values.append(db_product_photo_path)+ elif paperless_photo_id is not None:+ sql_fields.append("product_photo_path = NULL")+ elif 'delete_product_photo' in request.form and request.form.get('delete_product_photo', 'false').lower() == 'true':+ sql_fields.append("product_photo_path = NULL")+ sql_fields.append("paperless_photo_id = NULL") # Also clear Paperless ID++ # Handle Paperless-ngx document IDs+ if paperless_invoice_id is not None:+ sql_fields.append("paperless_invoice_id = %s")+ sql_values.append(paperless_invoice_id)+ if paperless_manual_id is not None:+ sql_fields.append("paperless_manual_id = %s")+ sql_values.append(paperless_manual_id)+ if paperless_photo_id is not None:+ sql_fields.append("paperless_photo_id = %s")+ sql_values.append(paperless_photo_id)+ if paperless_other_id is not None:+ sql_fields.append("paperless_other_id = %s")+ sql_values.append(paperless_other_id)++ # Handle URL fields for documents+ if 'invoice_url' in request.form:+ sql_fields.append("invoice_url = %s")+ sql_values.append(request.form.get('invoice_url'))+ if 'manual_url' in request.form:+ sql_fields.append("manual_url = %s")+ sql_values.append(request.form.get('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_fields.append("updated_at = NOW()") # Use SQL function, no parameter needed+ sql_values.append(warranty_id)+ update_sql = f"UPDATE warranties SET {', '.join(sql_fields)} WHERE id = %s"+ cur.execute(update_sql, sql_values)+ logger.info(f"Updated warranty with SQL: {update_sql}")+ logger.info(f"Parameters: {sql_values}")++ # Record expiration date or lifetime transitions (issue #209)+ new_is_lifetime = bool(is_lifetime)+ expiry_changed = (+ existing_is_lifetime != new_is_lifetime+ or (not existing_is_lifetime and not new_is_lifetime and existing_expiration_date != expiration_date)+ )+ if expiry_changed:+ cur.execute('''+ INSERT INTO warranty_expiry_history (+ warranty_id,+ previous_expiration_date,+ new_expiration_date,+ previous_is_lifetime,+ new_is_lifetime,+ reason,+ changed_by_user_id+ )+ VALUES (%s, %s, %s, %s, %s, %s, %s)+ ''', (warranty_id,- previous_expiration_date,- new_expiration_date,- previous_is_lifetime,+ existing_expiration_date,+ expiration_date,+ existing_is_lifetime,new_is_lifetime,- reason,- changed_by_user_id- )- VALUES (%s, %s, %s, %s, %s, %s, %s)- ''', (- warranty_id,- existing_expiration_date,- expiration_date,- existing_is_lifetime,- new_is_lifetime,- expiry_change_reason,- user_id,- ))-- # Update serial numbers- cur.execute('DELETE FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))- if serial_numbers:- for serial_number in serial_numbers:- if serial_number.strip(): # Only insert non-empty serial numbers- cur.execute('''- INSERT INTO serial_numbers (warranty_id, serial_number)- VALUES (%s, %s)- ''', (warranty_id, serial_number.strip()))-- # Update tags if provided- if tag_ids is not None:- # Remove existing tags- cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))+ expiry_change_reason,+ user_id,+ ))- # Add new tags- for tag_id in tag_ids:- # Verify tag exists and belongs to this user (FILE-03).- cur.execute('SELECT id FROM tags WHERE id = %s AND user_id = %s', (tag_id, user_id))- if cur.fetchone():- cur.execute('''- INSERT INTO warranty_tags (warranty_id, tag_id)- VALUES (%s, %s)- ''', (warranty_id, tag_id))- else:- logger.warning(f"Skipping non-existent or foreign tag ID: {tag_id}")+ # Update serial numbers+ cur.execute('DELETE FROM serial_numbers WHERE warranty_id = %s', (warranty_id,))+ if serial_numbers:+ for serial_number in serial_numbers:+ if serial_number.strip(): # Only insert non-empty serial numbers+ cur.execute('''+ INSERT INTO serial_numbers (warranty_id, serial_number)+ VALUES (%s, %s)+ ''', (warranty_id, serial_number.strip()))++ # Update tags if provided+ if tag_ids is not None:+ # Remove existing tags+ cur.execute('DELETE FROM warranty_tags WHERE warranty_id = %s', (warranty_id,))++ # Add new tags+ for tag_id in tag_ids:+ # Verify tag exists and belongs to this user (FILE-03).+ cur.execute('SELECT id FROM tags WHERE id = %s AND user_id = %s', (tag_id, user_id))+ if cur.fetchone():+ cur.execute('''+ INSERT INTO warranty_tags (warranty_id, tag_id)+ VALUES (%s, %s)+ ''', (warranty_id, tag_id))+ else:+ logger.warning(f"Skipping non-existent or foreign 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)+ # 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()+ conn.commit()- return jsonify({"message": "Warranty updated successfully"}), 200+ # Delete replaced/removed old files ONLY after the DB commit+ # succeeds, so a failed update never causes permanent file loss.+ if deferred_deletes:+ for old_path, _exclude in deferred_deletes:+ _delete_stored_file(cur, old_path)+ # Close the read-only reference-check transaction before+ # returning the connection to the pool.+ conn.rollback()++ return jsonify({"message": "Warranty updated successfully"}), 200+ except Exception:+ _cleanup_new_files()+ raiseexcept RequestEntityTooLarge:# Let the app-wide 413 handler produce the JSON response@@ -1755,8 +1812,14 @@ def import_warranties():# unchanged.next_suffix = {}+ MAX_CSV_IMPORT_ROWS = 10000for row in csv_reader:row_number += 1 # Increment for each data row (header is row 1)+ if row_number > MAX_CSV_IMPORT_ROWS:+ conn.rollback()+ return jsonify({+ "error": f"CSV import exceeds maximum of {MAX_CSV_IMPORT_ROWS} rows."+ }), 400errors = []processed_row = {}@@ -1907,6 +1970,7 @@ def import_warranties():if tags_to_create:default_color = '#808080' # Default color for new tagsfor tag_data in tags_to_create:+ cur.execute('SAVEPOINT csv_tag_insert')try:# Insert new tag with default color, preserving original case for name, AND user_idcur.execute(@@ -1914,11 +1978,14 @@ def import_warranties():(tag_data['name'], default_color, user_id) # Add user_id)new_tag_id = cur.fetchone()[0]+ cur.execute('RELEASE SAVEPOINT csv_tag_insert')processed_tag_ids.append(new_tag_id)logger.info(f"Created new tag '{(tag_data['name'])}' with ID {new_tag_id} for user {user_id} during CSV import.")except Exception as tag_insert_err:- # If tag creation fails (e.g., unique constraint conflict due to race condition),- # ensure the constraint includes user_id+ # Roll back the failed sub-statement so the transaction+ # stays usable before the fallback SELECT.+ cur.execute('ROLLBACK TO SAVEPOINT csv_tag_insert')+ cur.execute('RELEASE SAVEPOINT csv_tag_insert')logger.error(f"Error creating tag '{(tag_data['name'])}' for user {user_id} during import: {tag_insert_err}")# Attempt to fetch the ID again in case it was created by another processcur.execute("SELECT id FROM tags WHERE LOWER(name) = %s AND user_id = %s", (tag_data['name_lower'], user_id))@@ -1956,8 +2023,10 @@ def import_warranties():breaksuffix_index += 1- # --- If errors, skip row ---+ # --- If errors, roll back any row-scoped work (e.g. tags) and skip row ---if errors:+ cur.execute('ROLLBACK TO SAVEPOINT csv_row')+ cur.execute('RELEASE SAVEPOINT csv_row')failed_rows.append({"row": row_number, "errors": errors})continue@@ -2068,7 +2137,7 @@ def import_warranties():except Exception as e:logger.error(f"Error processing CSV row {row_number}: {e}")- failed_rows.append({"row": row_number, "errors": [f"Internal processing error: {str(e)}"]})+ failed_rows.append({"row": row_number, "errors": ["Internal processing error while importing row"]})# Roll the failed row back to its savepoint so the# transaction stays usable for the remaining rows.try:@@ -2123,7 +2192,7 @@ def import_warranties():if conn:conn.rollback() # Rollback on general errorlogger.error(f"Error importing CSV: {e}")- return jsonify({"error": f"Failed to import CSV: {str(e)}"}), 500+ return jsonify({"error": "Failed to import CSV"}), 500finally:if conn:release_db_connection(conn)@@ -2222,6 +2291,7 @@ def get_global_warranties():conn = Nonetry:# Check if global view is enabled for this user+ user_id = request.user['id']user_is_admin = request.user.get('is_admin', False)conn = get_db_connection()@@ -2318,6 +2388,14 @@ def get_global_warranties():warranty_dict['user_display_name'] = usernameelse:warranty_dict['user_display_name'] = 'Unknown User'++ # Do not expose another user's email address or private+ # "other document" references in global view to non-admins.+ if not user_is_admin and warranty_dict.get('user_id') != user_id:+ warranty_dict.pop('email', None)+ warranty_dict['other_document_path'] = None+ warranty_dict['other_document_url'] = None+ warranty_dict['paperless_other_id'] = Nonewarranties_list.append(warranty_dict)@@ -2337,6 +2415,7 @@ def get_global_warranties_archived():conn = Nonetry:# Check if global view is enabled for this user+ user_id = request.user['id']user_is_admin = request.user.get('is_admin', False)conn = get_db_connection()@@ -2434,6 +2513,14 @@ def get_global_warranties_archived():else:warranty_dict['user_display_name'] = 'Unknown User'+ # Do not expose another user's email address or private+ # "other document" references in global view to non-admins.+ if not user_is_admin and warranty_dict.get('user_id') != user_id:+ warranty_dict.pop('email', None)+ warranty_dict['other_document_path'] = None+ warranty_dict['other_document_url'] = None+ warranty_dict['paperless_other_id'] = None+warranties_list.append(warranty_dict)return jsonify(warranties_list)@@ -2648,6 +2735,15 @@ def get_warranty_debug(warranty_id):warranty_dict['user_display_name'] = usernameelse:warranty_dict['user_display_name'] = 'Unknown User'++ # Do not expose another user's email address or private+ # "other document" references in global view to non-admins.+ if not is_admin and warranty_dict.get('user_id') != user_id:+ warranty_dict.pop('email', None)+ warranty_dict['other_document_path'] = None+ if 'other_document_url' in warranty_dict:+ warranty_dict['other_document_url'] = None+ warranty_dict['paperless_other_id'] = Nonereturn jsonify(warranty_dict)diff --git a/frontend/file-utils.js b/frontend/file-utils.jsindex fcaa07f..cbb6765 100644--- a/frontend/file-utils.js+++ b/frontend/file-utils.js@@ -64,9 +64,35 @@ function openSecureFile(path) {return response.blob();}).then(blob => {- // Create a URL for the blob and open it in a new window- const url = URL.createObjectURL(blob);- window.open(url, '_blank');+ const safeInlineTypes = new Set([+ 'application/pdf',+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ 'image/gif',+ 'text/plain'+ ]);+ const mimeType = (blob.type || '').split(';')[0].trim().toLowerCase();+ if (safeInlineTypes.has(mimeType)) {+ // Create a URL for the blob and open it in a new window+ const url = URL.createObjectURL(blob);+ const win = window.open(url, '_blank');+ if (win) {+ try { win.opener = null; } catch (_) {}+ }+ setTimeout(() => URL.revokeObjectURL(url), 10000);+ } else {+ const downloadBlob = new Blob([blob], { type: 'application/octet-stream' });+ const url = URL.createObjectURL(downloadBlob);+ const a = document.createElement('a');+ a.style.display = 'none';+ a.href = url;+ a.download = path.split('/').pop() || 'document';+ document.body.appendChild(a);+ a.click();+ document.body.removeChild(a);+ setTimeout(() => URL.revokeObjectURL(url), 10000);+ }}).catch(error => {console.error('Error opening file:', error);diff --git a/frontend/js/components/claims.js b/frontend/js/components/claims.jsindex aa5137f..10d01ed 100644--- a/frontend/js/components/claims.js+++ b/frontend/js/components/claims.js@@ -432,6 +432,15 @@ function getClaimDocFileInput() {return claimDocFileInput;}+const SAFE_INLINE_CLAIM_BLOB_TYPES = new Set([+ 'application/pdf',+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ 'image/gif',+ 'text/plain',+]);+async function openClaimDocument(doc) {if (doc.paperless_document_id) {const token = getToken();@@ -445,9 +454,26 @@ async function openClaimDocument(doc) {});if (!response.ok) throw new Error('download failed');const blob = await response.blob();- const blobUrl = window.URL.createObjectURL(blob);- window.open(blobUrl, '_blank');- setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ const mimeType = (blob.type || '').split(';')[0].trim().toLowerCase();+ if (SAFE_INLINE_CLAIM_BLOB_TYPES.has(mimeType)) {+ const blobUrl = window.URL.createObjectURL(blob);+ const win = window.open(blobUrl, '_blank');+ if (win) {+ try { win.opener = null; } catch (_) {}+ }+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ } else {+ const downloadBlob = new Blob([blob], { type: 'application/octet-stream' });+ const blobUrl = window.URL.createObjectURL(downloadBlob);+ const link = document.createElement('a');+ link.style.display = 'none';+ link.href = blobUrl;+ link.download = doc.file_name || `claim-document-${doc.paperless_document_id}`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ }} catch (error) {console.error('[claims] paperless document open failed', error);showToast(t('claims.document_open_failed', 'Failed to open document'), 'error');diff --git a/frontend/js/components/paperless.js b/frontend/js/components/paperless.jsindex b80ad61..580932c 100644--- a/frontend/js/components/paperless.js+++ b/frontend/js/components/paperless.js@@ -327,6 +327,26 @@ async function getUserPaperlessViewPreference(warrantyContext = null) {}}+const SAFE_INLINE_BLOB_MIME_TYPES = new Set([+ 'application/pdf',+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ 'image/gif',+ 'text/plain',+]);++function extractFilenameFromResponse(response, fallbackName) {+ const cd = response?.headers?.get?.('Content-Disposition') || '';+ const utf8Match = cd.match(/filename\*\s*=\s*UTF-8''([^;]+)/i);+ if (utf8Match) {+ try { return decodeURIComponent(utf8Match[1].trim()); } catch (_) {}+ }+ const plainMatch = cd.match(/filename\s*=\s*"?([^";]+)"?/i);+ if (plainMatch && plainMatch[1]) return plainMatch[1].trim();+ return fallbackName;+}+export async function openPaperlessDocument(paperlessId, warrantyContext = null) {try {const debugInfo = await debugPaperlessConfiguration();@@ -349,10 +369,28 @@ export async function openPaperlessDocument(paperlessId, warrantyContext = null)});if (!fileResponse.ok) throw new Error('Failed to open document');const blob = await fileResponse.blob();- const blobUrl = window.URL.createObjectURL(blob);- const win = window.open(blobUrl, '_blank');- setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);- if (!win) showToast(window.t ? window.t('paperless.popup_blocked') : 'Please allow popups to view documents', 'warning');+ const mimeType = (blob.type || '').split(';')[0].trim().toLowerCase();+ if (SAFE_INLINE_BLOB_MIME_TYPES.has(mimeType)) {+ const blobUrl = window.URL.createObjectURL(blob);+ const win = window.open(blobUrl, '_blank');+ if (win) {+ try { win.opener = null; } catch (_) {}+ }+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ if (!win) showToast(window.t ? window.t('paperless.popup_blocked') : 'Please allow popups to view documents', 'warning');+ } else {+ // Never render active or unrecognized content types in a same-origin blob tab.+ const downloadBlob = new Blob([blob], { type: 'application/octet-stream' });+ const blobUrl = window.URL.createObjectURL(downloadBlob);+ const link = document.createElement('a');+ link.style.display = 'none';+ link.href = blobUrl;+ link.download = extractFilenameFromResponse(fileResponse, `document-${paperlessId}`);+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ }return;}const response = await fetch('/api/paperless/url', {@@ -364,7 +402,11 @@ export async function openPaperlessDocument(paperlessId, warrantyContext = null)const baseUrl = result.url.replace(/\/$/, '');const docUrl = `${baseUrl}/documents/${paperlessId}/details`;const win = window.open(docUrl, '_blank');- if (!win) showToast(window.t ? window.t('paperless.popup_blocked') : 'Please allow popups to view documents in Paperless-ngx', 'warning');+ if (win) {+ try { win.opener = null; } catch (_) {}+ } else {+ showToast(window.t ? window.t('paperless.popup_blocked') : 'Please allow popups to view documents in Paperless-ngx', 'warning');+ }} catch (error) {console.error('[paperless] openPaperlessDocument failed', error);showToast(error.message || 'Error opening document', 'error');@@ -671,8 +713,8 @@ function showPaperlessError(message) {if (!container) return;container.innerHTML = `<div class="no-documents-message"><i class="fas fa-exclamation-triangle"></i>- <h4>${window.t ? window.t('errors.error') : 'Error'}</h4>- <p>${message}</p>+ <h4>${escapeHtml(window.t ? window.t('errors.error') : 'Error')}</h4>+ <p>${escapeHtml(message == null ? '' : message)}</p></div>`;}diff --git a/frontend/js/components/warrantyRenderer.js b/frontend/js/components/warrantyRenderer.jsindex 19aed03..0b4c787 100644--- a/frontend/js/components/warrantyRenderer.js+++ b/frontend/js/components/warrantyRenderer.js@@ -47,10 +47,13 @@ const escapeHtml = (text) => {}[s]));};-// Block javascript:/data:/vbscript: URLs in href attributes.+// Block javascript:/data:/vbscript: URLs in href attributes, including+// obfuscations using ASCII control characters (tabs/newlines) stripped by+// the WHATWG URL parser.const sanitizeUrl = (url) => {const s = String(url || '').trim();- if (/^\s*(javascript|data|vbscript)\s*:/i.test(s)) return '#';+ const normalized = s.replace(/[\u0000-\u0020\u007f]+/g, '');+ if (/^(javascript|data|vbscript):/i.test(normalized)) return '#';return s;};diff --git a/frontend/js/lib/currency.js b/frontend/js/lib/currency.jsindex c4f105d..8262bbc 100644--- a/frontend/js/lib/currency.js+++ b/frontend/js/lib/currency.js@@ -87,10 +87,13 @@ export function formatCurrencyHTML(amount, symbol, position) {minimumFractionDigits: 2,maximumFractionDigits: 2,});+ const safeSymbol = String(symbol ?? '').replace(/[&<>"']/g, (ch) => ({+ '&': '&', '<': '<', '>': '>', '"': '"', "'": ''',+ }[ch]));if (position === 'right') {- return `<span>${formatted}</span><span class="currency-symbol currency-right">${symbol}</span>`;+ return `<span>${formatted}</span><span class="currency-symbol currency-right">${safeSymbol}</span>`;}- return `<span class="currency-symbol">${symbol}</span><span>${formatted}</span>`;+ return `<span class="currency-symbol">${safeSymbol}</span><span>${formatted}</span>`;}export function setupDynamicCurrencyPosition(input, currencySymbol) {diff --git a/frontend/login.html b/frontend/login.htmlindex 072a2a1..12bdfb3 100644--- a/frontend/login.html+++ b/frontend/login.html@@ -270,11 +270,16 @@break;}- // Update button styling and content (preserve alignment and baseline styles)+ // Update button styling and content safely via DOM APIs+ // (oidc_provider_display_name is server/admin-provided text).const classList = ['btn', 'btn-secondary', 'btn-block', 'btn-sso'];if (buttonClass && buttonClass !== 'btn-sso') classList.push(buttonClass);oidcButton.className = classList.join(' ');- oidcButton.innerHTML = `<i class="${iconClass}"></i> ${buttonText}`;+ oidcButton.textContent = '';+ const iconEl = document.createElement('i');+ iconEl.className = iconClass;+ oidcButton.appendChild(iconEl);+ oidcButton.appendChild(document.createTextNode(' ' + buttonText));}}).catch(error => {diff --git a/frontend/script.js b/frontend/script.jsindex 34f09e2..c0bea0f 100644--- a/frontend/script.js+++ b/frontend/script.js@@ -4035,22 +4035,50 @@ function openSecureFile(filePath) {}).then(blob => {console.log(`[openSecureFile] Successfully received blob of size: ${blob.size}`);-- // Create a URL for the blob- const blobUrl = window.URL.createObjectURL(blob);-- // Open in new tab- const newWindow = window.open(blobUrl, '_blank');-- // Clean up the blob URL after a delay to prevent memory leaks- setTimeout(() => {- window.URL.revokeObjectURL(blobUrl);- }, 10000); // Clean up after 10 seconds-- // Check if window was blocked by popup blocker- if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {- showToast(window.t('messages.popup_blocked'), 'warning');- window.URL.revokeObjectURL(blobUrl); // Clean up immediately if blocked++ const safeInlineTypes = new Set([+ 'application/pdf',+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ 'image/gif',+ 'text/plain'+ ]);+ const mimeType = (blob.type || '').split(';')[0].trim().toLowerCase();++ if (safeInlineTypes.has(mimeType)) {+ // Create a URL for the blob+ const blobUrl = window.URL.createObjectURL(blob);++ // Open in new tab+ const newWindow = window.open(blobUrl, '_blank');+ if (newWindow) {+ try { newWindow.opener = null; } catch (_) {}+ }++ // Clean up the blob URL after a delay to prevent memory leaks+ setTimeout(() => {+ window.URL.revokeObjectURL(blobUrl);+ }, 10000); // Clean up after 10 seconds++ // Check if window was blocked by popup blocker+ if (!newWindow || newWindow.closed || typeof newWindow.closed === 'undefined') {+ showToast(window.t('messages.popup_blocked'), 'warning');+ window.URL.revokeObjectURL(blobUrl); // Clean up immediately if blocked+ }+ } else {+ const downloadBlob = new Blob([blob], { type: 'application/octet-stream' });+ const blobUrl = window.URL.createObjectURL(downloadBlob);+ const link = document.createElement('a');+ link.style.display = 'none';+ link.href = blobUrl;+ link.download = fileName.split('/').pop() || 'document';+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ setTimeout(() => {+ window.URL.revokeObjectURL(blobUrl);+ }, 10000);}}).catch(error => {@@ -4334,7 +4362,7 @@ function renderTagsList(searchTerm = '') {if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {const createOption = document.createElement('div');createOption.className = 'tag-option create-tag';- createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;+ createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${escapeHtml(searchTerm)}"`;createOption.addEventListener('click', () => {createTag(searchTerm).then(newTag => {// Add the new tag to selectedTags@@ -4401,7 +4429,7 @@ function renderEditTagsList(searchTerm = '') {if (searchTerm && !filteredTags.some(tag => tag.name.toLowerCase() === searchTerm.toLowerCase())) {const createOption = document.createElement('div');createOption.className = 'tag-option create-tag';- createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${searchTerm}"`;+ createOption.innerHTML = `<i class="fas fa-plus"></i> Create "${escapeHtml(searchTerm)}"`;createOption.addEventListener('click', () => {createTag(searchTerm).then(newTag => {// Add the new tag to editSelectedTags@@ -6767,11 +6795,12 @@ function formatCurrencyHTML(amount, symbol, position) {minimumFractionDigits: 2,maximumFractionDigits: 2});+ const safeSymbol = escapeHtml(symbol == null ? '' : String(symbol));if (position === 'right') {- return `<span>${formattedAmount}</span><span class="currency-symbol currency-right">${symbol}</span>`;+ return `<span>${formattedAmount}</span><span class="currency-symbol currency-right">${safeSymbol}</span>`;} else {- return `<span class="currency-symbol">${symbol}</span><span>${formattedAmount}</span>`;+ return `<span class="currency-symbol">${safeSymbol}</span><span>${formattedAmount}</span>`;}}@@ -7679,13 +7708,40 @@ async function openPaperlessDocument(paperlessId, warrantyContext = null) {throw new Error(`Failed to open document: ${fileResponse.status}`);}const blob = await fileResponse.blob();- const blobUrl = window.URL.createObjectURL(blob);- const newTab = window.open(blobUrl, '_blank');- setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);- if (!newTab) {- showToast('Please allow popups to view documents', 'warning');+ const safeInlineTypes = new Set([+ 'application/pdf',+ 'image/png',+ 'image/jpeg',+ 'image/webp',+ 'image/gif',+ 'text/plain'+ ]);+ const mimeType = (blob.type || '').split(';')[0].trim().toLowerCase();+ if (safeInlineTypes.has(mimeType)) {+ const blobUrl = window.URL.createObjectURL(blob);+ const newTab = window.open(blobUrl, '_blank');+ if (newTab) {+ try { newTab.opener = null; } catch (_) {}+ }+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);+ if (!newTab) {+ showToast('Please allow popups to view documents', 'warning');+ } else {+ showToast('Opening document in Warracker...', 'info');+ }} else {- showToast('Opening document in Warracker...', 'info');+ const downloadBlob = new Blob([blob], { type: 'application/octet-stream' });+ const blobUrl = window.URL.createObjectURL(downloadBlob);+ const cd = fileResponse.headers?.get?.('Content-Disposition') || '';+ const match = cd.match(/filename\s*=\s*"?([^";]+)"?/i);+ const link = document.createElement('a');+ link.style.display = 'none';+ link.href = blobUrl;+ link.download = (match && match[1]) ? match[1].trim() : `document-${paperlessId}`;+ document.body.appendChild(link);+ link.click();+ document.body.removeChild(link);+ setTimeout(() => window.URL.revokeObjectURL(blobUrl), 10000);}} catch (fileError) {console.error('[openPaperlessDocument] Failed to open document:', fileError);@@ -7724,10 +7780,11 @@ async function openPaperlessDocument(paperlessId, warrantyContext = null) {// Open the document directly in Paperless-ngx interfaceconst newTab = window.open(documentUrl, '_blank');- if (!newTab) {- showToast('Please allow popups to view documents in Paperless-ngx', 'warning');- } else {+ if (newTab) {+ try { newTab.opener = null; } catch (_) {}showToast('Opening document in Paperless-ngx...', 'info');+ } else {+ showToast('Please allow popups to view documents in Paperless-ngx', 'warning');}} catch (error) {@@ -7741,6 +7798,7 @@ async function openPaperlessDocument(paperlessId, warrantyContext = null) {const fallbackTab = window.open(fallbackUrl, '_blank');if (fallbackTab) {+ try { fallbackTab.opener = null; } catch (_) {}showToast('Opened with fallback URL - please check if Paperless-ngx is accessible', 'warning');}} else {@@ -7750,6 +7808,7 @@ async function openPaperlessDocument(paperlessId, warrantyContext = null) {const genericTab = window.open(genericFallbackUrl, '_blank');if (genericTab) {+ try { genericTab.opener = null; } catch (_) {}showToast('Opened with generic fallback URL', 'warning');}}@@ -8638,7 +8697,7 @@ function renderPaperlessDocuments() {<div class="document-title">${escapeHtml(doc.title)}</div><div class="document-meta"><span><i class="fas fa-calendar"></i> ${createdDate}</span>- <span><i class="fas fa-file"></i> ${fileType}</span>+ <span><i class="fas fa-file"></i> ${escapeHtml(fileType)}</span>${doc.correspondent ? `<span><i class="fas fa-user"></i> ${escapeHtml(doc.correspondent)}</span>` : ''}</div>${tags.length > 0 ? `diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex 4f6276a..ede75a7 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -577,7 +577,7 @@ function renderAuditTrail(logs) {const details = log.details ? escapeHtmlSafe(log.details) : 'N/A';row.innerHTML = `- <td title='${log.ip_address || ''}'>${timestamp}</td>+ <td title='${escapeHtmlSafe(log.ip_address || '')}'>${escapeHtmlSafe(timestamp)}</td><td>${escapeHtmlSafe(username)}</td><td><span class='badge'>${escapeHtmlSafe(action)}</span></td><td style='white-space: pre-wrap; word-break: break-word;'>${details}</td>diff --git a/frontend/status.js b/frontend/status.jsindex 8e3fecf..d950046 100644--- a/frontend/status.js+++ b/frontend/status.js@@ -143,11 +143,12 @@if (!toastContainer) return;const toast = document.createElement('div');toast.className = `toast toast-${type}`;- toast.innerHTML = `${message} <button class="toast-close">×</button>`;- const closeButton = toast.querySelector('.toast-close');- if (closeButton) {- closeButton.addEventListener('click', () => toast.remove());- }+ toast.appendChild(document.createTextNode(`${message == null ? '' : String(message)} `));+ const closeButton = document.createElement('button');+ closeButton.className = 'toast-close';+ closeButton.textContent = '\u00d7';+ closeButton.addEventListener('click', () => toast.remove());+ toast.appendChild(closeButton);toastContainer.appendChild(toast);setTimeout(() => { if (toast.parentElement) toast.remove(); }, 3000);}@@ -984,7 +985,13 @@let dHtml = '<div class="warranty-details-content" style="display: flex; flex-wrap: wrap; gap: 20px;">';dHtml += '<div style="flex: 1 1 300px;"><h4>Core Information</h4>';- dHtml += `<p><strong>Product URL:</strong> ${warrantyDetails.product_url ? `<a href="${escapeHTML(String(warrantyDetails.product_url).trim().replace(/^\s*(javascript|data|vbscript)\s*:/i, '#'))}" target="_blank" rel="noopener noreferrer">${escapeHTML(warrantyDetails.product_url)}</a>` : 'N/A'}</p>`;+ const safeProductUrl = (() => {+ if (!warrantyDetails.product_url) return '';+ const rawUrl = String(warrantyDetails.product_url).trim();+ const normalizedUrl = rawUrl.replace(/[\u0000-\u0020\u007f]+/g, '');+ return /^(javascript|data|vbscript):/i.test(normalizedUrl) ? '#' : rawUrl;+ })();+ dHtml += `<p><strong>Product URL:</strong> ${warrantyDetails.product_url ? `<a href="${escapeHTML(safeProductUrl)}" target="_blank" rel="noopener noreferrer">${escapeHTML(warrantyDetails.product_url)}</a>` : 'N/A'}</p>`;dHtml += `<p><strong>Purchase Price:</strong> ${warrantyDetails.purchase_price !== null && warrantyDetails.purchase_price !== undefined ? escapeHTML(userCurrencySymbol) + parseFloat(warrantyDetails.purchase_price).toFixed(2) : 'N/A'}</p>`;dHtml += `<p><strong>Vendor:</strong> ${escapeHTML(warrantyDetails.vendor || '') || 'N/A'}</p>`;dHtml += `<p><strong>Warranty Type:</strong> ${escapeHTML(warrantyDetails.warranty_type || '') || 'N/A'}</p></div>`;diff --git a/tests/test_hardening_regressions.py b/tests/test_hardening_regressions.pynew file mode 100644index 0000000..78a34ac--- /dev/null+++ b/tests/test_hardening_regressions.py@@ -0,0 +1,802 @@+"""Defensive regression tests for the non-breaking hardening pass.++Covers:+- C-01: Local file serving rejects dotfiles (e.g. .secret_key), symlinks,+ and unreferenced files even for admin callers.+- H-01: PUT /api/admin/users/<id> validates boolean types strictly,+ protects owner accounts against all modifications by non-owner admins,+ and enforces case-insensitive email uniqueness.+- H-02: File serving restricts inline rendering to passive MIME types and+ forces attachment + sandbox CSP for active/unrecognized types.+- H-04: SSRF IP guard rejects multicast, RFC 2765/8215 SIIT, and local-use+ NAT64 prefixes alongside existing private/loopback blocks.+- H-05: Docker/Nginx init uses root-only /run/nginx-init and fix_permissions+ never follows symlinks.+- M-01: Frontend escaping and URL control-character sanitization pins.+- M-02: Password reset tokens are single-use (atomic consumption).+- M-03: OIDC string `groups` claim never matches substrings for admin role;+ inactive OIDC users redirect with account_inactive instead of failing.+- M-05: Paperless search-and-link returns identical 404 responses for+ missing vs foreign-owned documents (no title oracle).+- M-06: Global view endpoints omit foreign users' email addresses and+ private "other document" metadata for non-owners/non-admins.+- M-07: Rate limiter buckets are memory-bounded, audit-trail limit is+ clamped, and saved_filters payload is size-capped.+- L-02/L-03/L-04/L-05: Apprise URL scheme redaction, passwordless OIDC+ guard on change-password/change-email, preference time/timezone/frequency+ validation, clearing local file path when switching to Paperless, safe+ DefaultConfig DEBUG=False, and private scheduler snapshot directory.+"""+import base64+import hashlib+import io+import ipaddress+import os+import stat+import subprocess+import types+import uuid+from datetime import datetime, timedelta, UTC+from urllib.parse import parse_qs, urlparse++import pytest++from backend import file_routes, oidc_handler+from backend.apprise_handler import AppriseNotificationHandler+from backend.config import config as app_config_map+from backend.notifications import _master_scheduler_status_path+from backend.rate_limit import _AttemptTracker+from backend.warranties_routes import _ip_address_is_public++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"+PNG_BYTES = base64.b64decode(+ "iVBORw0KGgoAAAANSUhEUgAAAAEAAAABCAQAAAC1HAwCAAAAC0lEQVR42mP8/x8AAwMCAO+ip1sAAAAASUVORK5CYII="+)+++def _read(relpath):+ with open(os.path.join(REPO_ROOT, relpath), encoding="utf-8") as fh:+ return fh.read()+++def _user_row(db_connection, username):+ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT id, email, is_admin, is_active, is_owner FROM users WHERE username = %s",+ (username,),+ )+ row = cur.fetchone()+ return {+ "id": row[0],+ "email": row[1],+ "is_admin": row[2],+ "is_active": row[3],+ "is_owner": row[4],+ }+++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+++# ---------------------------------------------------------------------------+# C-01: Local file serving rejects dotfiles, symlinks, and unreferenced files+# ---------------------------------------------------------------------------++def test_c01_blocks_dotfiles_and_unreferenced_files(client, admin_user, user_factory):+ upload_dir = os.environ["UPLOAD_FOLDER"]+ secret_path = os.path.join(upload_dir, ".secret_key")+ created_secret = not os.path.exists(secret_path)+ if created_secret:+ with open(secret_path, "wb") as fh:+ fh.write(b"super-secret-signing-key")++ unref_name = f"unreferenced_{uuid.uuid4().hex[:8]}.pdf"+ unref_path = os.path.join(upload_dir, unref_name)+ with open(unref_path, "wb") as fh:+ fh.write(PDF_BYTES)++ regular = user_factory()+ try:+ # Dotfiles under uploads are always rejected with 400 — even for admins.+ for endpoint in (+ "/api/files/uploads/.secret_key",+ "/api/secure-file/.secret_key",+ ):+ r_admin = client.get(endpoint, headers=admin_user["headers"])+ assert r_admin.status_code == 400, f"{endpoint}: {r_admin.status_code}"+ r_user = client.get(endpoint, headers=regular["headers"])+ assert r_user.status_code == 400, f"{endpoint}: {r_user.status_code}"++ # Non-uploads path prefix stays rejected with 403.+ assert client.get("/api/files/.secret_key", headers=admin_user["headers"]).status_code == 403++ # Unreferenced files on disk cannot be read by admins (404) or users (403).+ for endpoint in (+ f"/api/files/uploads/{unref_name}",+ f"/api/secure-file/{unref_name}",+ ):+ r_admin = client.get(endpoint, headers=admin_user["headers"])+ assert r_admin.status_code == 404, f"{endpoint}: {r_admin.status_code}"+ r_user = client.get(endpoint, headers=regular["headers"])+ assert r_user.status_code == 403, f"{endpoint}: {r_user.status_code}"+ finally:+ if created_secret and os.path.exists(secret_path):+ os.remove(secret_path)+ if os.path.exists(unref_path):+ os.remove(unref_path)+++def test_c01_rejects_symlink_inside_upload_folder(app, tmp_path):+ target_file = tmp_path / "outside.txt"+ target_file.write_text("outside-data", encoding="utf-8")+ upload_dir = os.environ["UPLOAD_FOLDER"]+ link_name = f"symlink_{uuid.uuid4().hex[:8]}.txt"+ link_path = os.path.join(upload_dir, link_name)+ os.symlink(str(target_file), link_path)+ try:+ with app.app_context():+ assert file_routes._resolve_upload_file_path(upload_dir, link_name) is None+ finally:+ if os.path.lexists(link_path):+ os.unlink(link_path)+++# ---------------------------------------------------------------------------+# H-01: Owner protection & strict boolean validation on admin user update+# ---------------------------------------------------------------------------++def test_h01_owner_protection_and_boolean_validation(+ client, admin_user, user_factory, db_connection+):+ owner = _user_row(db_connection, admin_user["username"])+ assert owner["is_owner"] is True++ co_admin = user_factory()+ co_admin_row = _user_row(db_connection, co_admin["username"])+ with db_connection, db_connection.cursor() as cur:+ cur.execute("UPDATE users SET is_admin = TRUE WHERE id = %s", (co_admin_row["id"],))++ # Non-boolean values must be rejected with 400 (no silent falsy bypass).+ for bad_body in (+ {"is_admin": 0},+ {"is_admin": ""},+ {"is_admin": None},+ {"is_admin": "false"},+ {"is_active": 0},+ {"is_active": ""},+ {"is_active": None},+ ):+ r = client.put(+ f"/api/admin/users/{owner['id']}",+ headers=co_admin["headers"],+ json=bad_body,+ )+ assert r.status_code == 400, f"expected 400 for {bad_body}, got {r.status_code}"++ # Non-owner admin cannot modify ANY field on the owner account (including email).+ for forbidden_body in (+ {"is_admin": False},+ {"is_active": False},+ {"email": f"hijack_{uuid.uuid4().hex[:6]}@test.local"},+ ):+ r = client.put(+ f"/api/admin/users/{owner['id']}",+ headers=co_admin["headers"],+ json=forbidden_body,+ )+ assert r.status_code == 403, f"expected 403 for {forbidden_body}, got {r.status_code}"++ owner_after = _user_row(db_connection, admin_user["username"])+ assert owner_after == owner++ # Case-insensitive email conflict detection on regular user update.+ plain_a = user_factory()+ plain_b = user_factory()+ rec_a = _user_row(db_connection, plain_a["username"])+ rec_b = _user_row(db_connection, plain_b["username"])+ r_dup = client.put(+ f"/api/admin/users/{rec_b['id']}",+ headers=admin_user["headers"],+ json={"email": rec_a["email"].upper()},+ )+ assert r_dup.status_code == 400+++# ---------------------------------------------------------------------------+# H-02: Safe inline MIME allowlist + CSP / Content-Disposition on file routes+# ---------------------------------------------------------------------------++def test_h02_paperless_active_content_forced_attachment_and_sandboxed(+ client, admin_user, monkeypatch+):+ samples = {+ 9801: (b"<html><body><script>1</script></body></html>", "text/html"),+ 9802: (b"<svg xmlns='http://www.w3.org/2000/svg'></svg>", "image/svg+xml"),+ 9803: (PDF_BYTES, "application/pdf"),+ 9804: (PNG_BYTES, "image/png"),+ }++ stub = types.SimpleNamespace(+ get_document_preview=lambda doc_id: (True, samples[doc_id][0], "ok", samples[doc_id][1]),+ )+ monkeypatch.setattr(file_routes, "get_paperless_handler", lambda conn: stub)++ # Active types: downgraded to application/octet-stream + attachment + CSP sandbox.+ for doc_id in (9801, 9802):+ r = client.get(f"/api/paperless-file/{doc_id}", headers=admin_user["headers"])+ assert r.status_code == 200, r.get_data(as_text=True)+ assert r.headers.get("Content-Type", "").startswith("application/octet-stream")+ assert r.headers.get("Content-Disposition", "").startswith("attachment")+ assert r.headers.get("Content-Security-Policy") == "sandbox"+ assert r.headers.get("X-Content-Type-Options") == "nosniff"++ # Passive types: stay inline with frame-ancestors 'self' (compatible with Chrome PDF viewer).+ for doc_id, expected_ct in ((9803, "application/pdf"), (9804, "image/png")):+ r = client.get(f"/api/paperless-file/{doc_id}", headers=admin_user["headers"])+ assert r.status_code == 200, r.get_data(as_text=True)+ assert r.headers.get("Content-Type", "").startswith(expected_ct)+ assert r.headers.get("Content-Disposition", "").startswith("inline")+ assert r.headers.get("Content-Security-Policy") == "default-src 'none'; frame-ancestors 'self'"+ assert r.headers.get("X-Content-Type-Options") == "nosniff"+++# ---------------------------------------------------------------------------+# H-04: SSRF IP classification edge cases+# ---------------------------------------------------------------------------++ "addr",+ [+ "::ffff:0:127.0.0.1",+ "::ffff:0:169.254.169.254",+ "64:ff9b:1::10.0.0.1",+ "64:ff9b:1::169.254.169.254",+ "224.0.0.1",+ "239.255.255.250",+ "ff02::1",+ "::ffff:224.0.0.1",+ "255.255.255.255",+ ],+)+def test_h04_ssrf_rejects_multicast_siit_and_local_nat64(addr):+ assert not _ip_address_is_public(ipaddress.ip_address(addr))+++ "addr",+ [+ "8.8.8.8",+ "1.1.1.1",+ "::ffff:8.8.8.8",+ "2001:4860:4860::8888",+ ],+)+def test_h04_ssrf_still_allows_public_unicast(addr):+ assert _ip_address_is_public(ipaddress.ip_address(addr))+++# ---------------------------------------------------------------------------+# H-05: Container root/warracker privilege separation & symlink-safe chown+# ---------------------------------------------------------------------------++def test_h05_docker_and_fix_permissions_hardening(tmp_path, monkeypatch):+ dockerfile = _read("Dockerfile")+ wrapper = _read("Docker/nginx-wrapper.sh")+ assert "chown -R root:root /app /var/www/html" in dockerfile+ assert "/run/nginx-init" in dockerfile+ assert "/run/nginx-init/default.conf" in wrapper+ assert "/tmp/nginx-default.conf" not in wrapper++ # Verify fix_permissions skips symlinks and uses lchown (never follows links).+ from backend import fix_permissions as fp++ outside_file = tmp_path / "outside.txt"+ outside_file.write_text("keep-me", encoding="utf-8")+ data_dir = tmp_path / "data"+ uploads_dir = data_dir / "uploads"+ uploads_dir.mkdir(parents=True)+ real_file = uploads_dir / "invoice.pdf"+ real_file.write_bytes(PDF_BYTES)+ symlink_file = uploads_dir / "escape_link"+ symlink_file.symlink_to(outside_file)++ chowned = []+ monkeypatch.setenv("UPLOAD_FOLDER", str(uploads_dir))+ monkeypatch.setattr(os, "lchown", lambda path, uid, gid: chowned.append(os.path.abspath(path)))++ fp.fix_upload_folder_permissions()++ assert os.path.abspath(str(real_file)) in chowned+ assert os.path.abspath(str(symlink_file)) not in chowned+ assert os.path.abspath(str(outside_file)) not in chowned+++# ---------------------------------------------------------------------------+# M-01: Frontend escaping & URL control-character sanitization pins+# ---------------------------------------------------------------------------++def test_m01_frontend_xss_and_url_sanitizer_pins():+ login_html = _read("frontend/login.html")+ assert "oidcButton.innerHTML =" not in login_html+ assert "document.createTextNode" in login_html++ settings_js = _read("frontend/settings-new.js")+ assert "escapeHtmlSafe(log.ip_address" in settings_js+ assert "<td>${log.ip_address" not in settings_js++ script_js = _read("frontend/script.js")+ assert 'Create "${searchTerm}"' not in script_js+ assert 'Create "${escapeHtml(searchTerm)}"' in script_js+ assert '<i class="fas fa-file"></i> ${escapeHtml(fileType)}' in script_js+ assert '<i class="fas fa-file"></i> ${fileType}' not in script_js++ paperless_js = _read("frontend/js/components/paperless.js")+ assert "<p>${message}</p>" not in paperless_js+ assert "SAFE_INLINE_BLOB_MIME_TYPES" in paperless_js++ currency_js = _read("frontend/js/lib/currency.js")+ assert "const safeSymbol = String(symbol ?? '').replace(" in currency_js+ assert "${symbol}</span>" not in currency_js++ status_js = _read("frontend/status.js")+ assert "toast.innerHTML =" not in status_js+ assert "document.createTextNode" in status_js+ assert r"[\u0000-\u0020\u007f]+" in status_js++ renderer_js = _read("frontend/js/components/warrantyRenderer.js")+ assert r"[\u0000-\u0020\u007f]+" in renderer_js++ # Execute Node to confirm control-char-obfuscated javascript: URLs are neutralized.+ node_code = (+ "const sanitizeUrl = (url = '') => {"+ " if (!url) return '';"+ " const trimmed = String(url).trim();"+ " const normalized = trimmed.replace(/[\\u0000-\\u0020\\u007f]+/g, '');"+ " if (/^(javascript|data|vbscript):/i.test(normalized)) return '#';"+ " return trimmed;"+ "};"+ "const assert = require('assert');"+ "assert.strictEqual(sanitizeUrl('java\\tscript:alert(1)'), '#');"+ "assert.strictEqual(sanitizeUrl('\\x01javascript:alert(1)'), '#');"+ "assert.strictEqual(sanitizeUrl('https://example.com/item'), 'https://example.com/item');"+ )+ subprocess.run(["node", "-e", node_code], check=True)+++# ---------------------------------------------------------------------------+# M-02: Single-use password reset token+# ---------------------------------------------------------------------------++def test_m02_password_reset_token_is_single_use(client, user_factory, db_connection):+ user = user_factory()+ row = _user_row(db_connection, user["username"])+ raw_token = "reset-" + uuid.uuid4().hex+ token_hash = hashlib.sha256(raw_token.encode()).hexdigest()++ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "INSERT INTO password_reset_tokens (user_id, token, expires_at) "+ "VALUES (%s, %s, %s)",+ (row["id"], token_hash, datetime.now(UTC) + timedelta(minutes=15)),+ )++ r1 = client.post(+ "/api/auth/password/reset",+ json={"token": raw_token, "password": "NewStrongPassword123!"},+ )+ assert r1.status_code == 200, r1.get_data(as_text=True)++ r2 = client.post(+ "/api/auth/password/reset",+ json={"token": raw_token, "password": "AnotherPassword456!"},+ )+ assert r2.status_code == 400+++# ---------------------------------------------------------------------------+# M-03 & L-03: OIDC string groups check & inactive OIDC user handling+# ---------------------------------------------------------------------------++class _GroupsOIDCClient:+ def __init__(self, sub, email, groups):+ self._sub = sub+ self._email = email+ self._groups = groups++ def authorize_access_token(self):+ return {+ "userinfo": {+ "sub": self._sub,+ "iss": "https://idp.example.com",+ "email": self._email,+ "given_name": "Group",+ "family_name": "Tester",+ "groups": self._groups,+ }+ }++ def userinfo(self, token=None):+ return {"sub": self._sub, "email": self._email, "groups": self._groups}+++def test_m03_oidc_string_groups_no_substring_admin_and_l03_inactive_redirect(+ client, app, monkeypatch, db_connection+):+ prev_group = _get_site_setting(db_connection, "admin_oidc_group")+ _set_site_setting(db_connection, "admin_oidc_group", "admin")+ app.config["OIDC_ENABLED"] = True+ app.config["OIDC_PROVIDER_NAME"] = "testidp"++ sub_str = "sub-str-" + uuid.uuid4().hex+ email_str = f"oidc-str-{uuid.uuid4().hex[:8]}@example.com"+ sub_list = "sub-list-" + uuid.uuid4().hex+ email_list = f"oidc-list-{uuid.uuid4().hex[:8]}@example.com"++ try:+ # String claim "non-admin" contains substring "admin" — MUST NOT grant admin.+ monkeypatch.setattr(+ oidc_handler.oauth,+ "create_client",+ lambda name: _GroupsOIDCClient(sub_str, email_str, "non-admin"),+ )+ r = client.get("/api/oidc/callback")+ assert r.status_code == 302, r.get_data(as_text=True)+ with db_connection.cursor() as cur:+ cur.execute("SELECT id, is_admin FROM users WHERE oidc_sub = %s", (sub_str,))+ uid_str, is_admin_str = cur.fetchone()+ assert is_admin_str is False++ # L-03: Deactivating the OIDC user must redirect cleanly with account_inactive.+ with db_connection, db_connection.cursor() as cur:+ cur.execute("UPDATE users SET is_active = FALSE WHERE id = %s", (uid_str,))+ r_inactive = client.get("/api/oidc/callback")+ assert r_inactive.status_code == 302+ qs = parse_qs(urlparse(r_inactive.headers["Location"]).query)+ assert qs.get("oidc_error") == ["account_inactive"]++ # Proper list claim ["admin"] still grants admin as intended.+ monkeypatch.setattr(+ oidc_handler.oauth,+ "create_client",+ lambda name: _GroupsOIDCClient(sub_list, email_list, ["users", "admin"]),+ )+ r2 = client.get("/api/oidc/callback")+ assert r2.status_code == 302, r2.get_data(as_text=True)+ with db_connection.cursor() as cur:+ cur.execute("SELECT is_admin FROM users WHERE oidc_sub = %s", (sub_list,))+ assert cur.fetchone()[0] is True+ finally:+ app.config["OIDC_ENABLED"] = False+ app.config.pop("OIDC_PROVIDER_NAME", None)+ _set_site_setting(db_connection, "admin_oidc_group", prev_group)+++# ---------------------------------------------------------------------------+# M-05: Paperless search-and-link error parity (no title existence oracle)+# ---------------------------------------------------------------------------++def test_m05_paperless_search_and_link_no_title_oracle(+ client, user_factory, warranty_factory, paperless_configured+):+ owner = user_factory()+ attacker = user_factory()+ unique_title = f"OwnerPrivateInvoice-{uuid.uuid4().hex[:8]}"++ # Owner uploads a unique document (automatically recorded as owned by owner),+ # leaving mock document id 1 untouched for test_paperless_security.py.+ r_up = client.post(+ "/api/paperless/upload",+ headers=owner["headers"],+ data={+ "file": (io.BytesIO(PDF_BYTES), "owner_invoice.pdf"),+ "title": unique_title,+ },+ content_type="multipart/form-data",+ )+ assert r_up.status_code == 200, r_up.get_data(as_text=True)++ w_resp = warranty_factory(attacker["headers"], product_name="OracleProbe")+ assert w_resp.status_code == 201+ wid = w_resp.get_json()["id"]++ r_foreign = client.post(+ "/api/paperless-search-and-link",+ headers=attacker["headers"],+ json={+ "warranty_id": wid,+ "document_type": "invoice",+ "search_title": unique_title,+ },+ )+ r_missing = client.post(+ "/api/paperless-search-and-link",+ headers=attacker["headers"],+ json={+ "warranty_id": wid,+ "document_type": "invoice",+ "search_title": "Definitely Missing Document Title 99999",+ },+ )++ assert r_foreign.status_code == 404+ assert r_missing.status_code == 404+ assert r_foreign.get_json() == r_missing.get_json() == {+ "success": False,+ "message": "Document not found",+ }+++# ---------------------------------------------------------------------------+# M-06: Global view omits foreign email & private other_document fields+# ---------------------------------------------------------------------------++def test_m06_global_view_redacts_foreign_email_and_other_document(+ client, admin_user, user_factory, db_connection+):+ prev_enabled = _get_site_setting(db_connection, "global_view_enabled")+ prev_admin_only = _get_site_setting(db_connection, "global_view_admin_only")+ _set_site_setting(db_connection, "global_view_enabled", "true")+ _set_site_setting(db_connection, "global_view_admin_only", "false")++ owner = user_factory()+ viewer = user_factory()++ try:+ r_create = client.post(+ "/api/warranties",+ headers=owner["headers"],+ data={+ "product_name": f"PrivateDocWidget_{uuid.uuid4().hex[:6]}",+ "purchase_date": "2025-02-01",+ "exact_expiration_date": "2028-02-01",+ "other_document": (io.BytesIO(PDF_BYTES), "private_note.pdf"),+ "other_document_url": "https://private.example.invalid/secret-doc",+ },+ content_type="multipart/form-data",+ )+ assert r_create.status_code == 201, r_create.get_data(as_text=True)+ wid = r_create.get_json()["id"]++ with db_connection, db_connection.cursor() as cur:+ cur.execute(+ "UPDATE warranties SET paperless_other_id = 7777 WHERE id = %s",+ (wid,),+ )++ # 1. /api/warranties/global+ g_viewer = client.get("/api/warranties/global", headers=viewer["headers"]).get_json()+ entry_v = next(w for w in g_viewer if w["id"] == wid)+ assert "email" not in entry_v+ assert entry_v["other_document_path"] is None+ assert entry_v["other_document_url"] is None+ assert entry_v["paperless_other_id"] is None++ # Owner and admin still see their fields.+ g_owner = client.get("/api/warranties/global", headers=owner["headers"]).get_json()+ entry_o = next(w for w in g_owner if w["id"] == wid)+ assert entry_o["other_document_path"] is not None+ assert entry_o["other_document_url"] == "https://private.example.invalid/secret-doc"+ assert entry_o["paperless_other_id"] == 7777++ g_admin = client.get("/api/warranties/global", headers=admin_user["headers"]).get_json()+ entry_a = next(w for w in g_admin if w["id"] == wid)+ assert "email" in entry_a+ assert entry_a["other_document_path"] is not None++ # 2. /api/debug/warranty/<id>+ dbg_viewer = client.get(+ f"/api/debug/warranty/{wid}", headers=viewer["headers"]+ ).get_json()+ assert "email" not in dbg_viewer+ assert dbg_viewer["other_document_path"] is None+ assert dbg_viewer["paperless_other_id"] is None++ # 3. /api/statistics/global+ stats_viewer = client.get(+ "/api/statistics/global", headers=viewer["headers"]+ ).get_json()+ stat_item = next(+ w for w in stats_viewer["all_warranties"] if w["id"] == wid+ )+ assert "email" not in stat_item+ assert stat_item["other_document_path"] is None+ for rec in stats_viewer.get("recent_warranties", []):+ if rec["id"] == wid:+ assert "email" not in rec+ assert rec["other_document_path"] is None++ # 4. /api/warranties/global/archived+ r_arch = client.patch(+ f"/api/warranties/{wid}/archive",+ headers=owner["headers"],+ json={"archived": True},+ )+ assert r_arch.status_code == 200+ arch_viewer = client.get(+ "/api/warranties/global/archived", headers=viewer["headers"]+ ).get_json()+ arch_entry = next(w for w in arch_viewer if w["id"] == wid)+ assert "email" not in arch_entry+ assert arch_entry["other_document_path"] is None+ assert arch_entry["other_document_url"] is None+ assert arch_entry["paperless_other_id"] is None+ finally:+ _set_site_setting(db_connection, "global_view_enabled", prev_enabled)+ _set_site_setting(db_connection, "global_view_admin_only", prev_admin_only)+++# ---------------------------------------------------------------------------+# M-07: Bounded rate-limit buckets, audit-trail clamp, saved_filters size cap+# ---------------------------------------------------------------------------++def test_m07_rate_limiter_buckets_are_bounded():+ tracker = _AttemptTracker(max_keys=20, default_window=60)+ for i in range(50):+ tracker.record(f"key-{i}")+ assert len(tracker._attempts) <= 20+++def test_m07_audit_trail_limit_clamped_and_saved_filters_capped(+ client, admin_user, user_factory+):+ r_audit = client.get(+ "/api/admin/audit-trail?limit=999999999", headers=admin_user["headers"]+ )+ assert r_audit.status_code == 200+ assert len(r_audit.get_json()) <= 1000++ user = user_factory()+ huge_filters = {"blob": "A" * 70000}+ r_big = client.put(+ "/api/auth/preferences", headers=user["headers"], json={"saved_filters": huge_filters}+ )+ assert r_big.status_code == 400+++# ---------------------------------------------------------------------------+# L-02 / L-03 / L-04 / L-05+# ---------------------------------------------------------------------------++def test_l02_apprise_safe_url_scheme_redacts_secrets():+ assert AppriseNotificationHandler._safe_url_scheme("discord://123456789/secret_webhook_token") == "discord"+ assert AppriseNotificationHandler._safe_url_scheme("https://user:[email protected]/tok") == "https"+ assert AppriseNotificationHandler._safe_url_scheme("not-a-url") == "unknown"+++def test_l03_passwordless_user_change_password_and_email_return_400(+ client, user_factory, db_connection+):+ user = user_factory()+ row = _user_row(db_connection, user["username"])+ with db_connection, db_connection.cursor() as cur:+ cur.execute("UPDATE users SET password_hash = NULL WHERE id = %s", (row["id"],))++ r_pw = client.post(+ "/api/auth/password/change",+ headers=user["headers"],+ json={"current_password": "anything", "new_password": "NewPassword123!"},+ )+ assert r_pw.status_code == 400++ r_em = client.post(+ "/api/auth/change-email",+ headers=user["headers"],+ json={"new_email": f"new_{uuid.uuid4().hex[:6]}@test.local", "password": "anything"},+ )+ assert r_em.status_code == 400+++def test_l03_preferences_validate_time_timezone_frequency_and_allow_empty(+ client, user_factory+):+ user = user_factory()+ h = user["headers"]++ # Seed valid preferences first.+ r_ok = client.put(+ "/api/auth/preferences",+ headers=h,+ json={+ "timezone": "America/New_York",+ "apprise_timezone": "Europe/London",+ "notification_time": "08:30",+ "apprise_notification_time": "17:45",+ "notification_frequency": "weekly",+ "apprise_notification_frequency": "monthly",+ },+ )+ assert r_ok.status_code == 200, r_ok.get_data(as_text=True)++ # Invalid values must return 400.+ for bad in (+ {"timezone": "Mars/Olympus_Mons"},+ {"apprise_timezone": "Not/A_Zone"},+ {"notification_time": "25:99"},+ {"apprise_notification_time": "morning"},+ {"notification_frequency": "hourly"},+ {"apprise_notification_frequency": "never"},+ ):+ r_bad = client.put("/api/auth/preferences", headers=h, json=bad)+ assert r_bad.status_code == 400, f"expected 400 for {bad}, got {r_bad.status_code}"++ # Empty strings sent by partially-loaded UI dropdowns must NOT error or wipe values.+ r_empty = client.put(+ "/api/auth/preferences",+ headers=h,+ json={"timezone": "", "notification_time": "", "notification_frequency": ""},+ )+ assert r_empty.status_code == 200+ body = r_empty.get_json()+ assert body["timezone"] == "America/New_York"+ assert body["notification_time"] == "08:30"+ assert body["notification_frequency"] == "weekly"+++def test_l04_switching_local_invoice_to_paperless_clears_local_path(+ client, user_factory, db_connection+):+ user = user_factory()+ r = client.post(+ "/api/warranties",+ headers=user["headers"],+ data={+ "product_name": "SwitchToPaperless",+ "purchase_date": "2025-03-01",+ "exact_expiration_date": "2027-03-01",+ "invoice": (io.BytesIO(PDF_BYTES), "local_inv.pdf"),+ },+ content_type="multipart/form-data",+ )+ assert r.status_code == 201, r.get_data(as_text=True)+ wid = r.get_json()["id"]++ r_upd = client.put(+ f"/api/warranties/{wid}",+ headers=user["headers"],+ data={+ "product_name": "SwitchToPaperless",+ "purchase_date": "2025-03-01",+ "exact_expiration_date": "2027-03-01",+ "paperless_invoice_id": "8844",+ },+ content_type="multipart/form-data",+ )+ assert r_upd.status_code == 200, r_upd.get_data(as_text=True)++ with db_connection.cursor() as cur:+ cur.execute(+ "SELECT invoice_path, paperless_invoice_id FROM warranties WHERE id = %s",+ (wid,),+ )+ inv_path, ppl_id = cur.fetchone()+ assert inv_path is None+ assert ppl_id == 8844+++def test_l05_default_config_safe_and_scheduler_snapshot_dir_private():+ default_cfg = app_config_map["default"]+ assert default_cfg.DEBUG is False+ assert default_cfg.PROPAGATE_EXCEPTIONS is False++ snap_path = _master_scheduler_status_path()+ snap_dir = os.path.dirname(snap_path)+ st = os.stat(snap_dir)+ assert stat.S_IMODE(st.st_mode) == 0o700+ assert st.st_uid == os.getuid()