π‘οΈ Warracker is an open source, self-hostable warranty tracker to monitor expirations, store receipts, files. You own the data, your rules!
Introduced a new Administrator Audit Trail system for enhanced accountability and visibility of administrative changes.
sassanix286aa2b88a18
diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 872a4c0..36b6965 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -1,30 +1,99 @@# Changelog-## 0.10.1.15 - 2025-10-06+## 0.10.1.15 - 2025-10-19++### Added+- **Renovate Bot Integration**: Automated dependency management system+ - Complete configuration in `renovate.json` with intelligent grouping (Debian packages, Python packages, GitHub Actions)+ - GitHub Actions workflow for automatic execution every Monday at midnight+ - Advanced features: merge confidence badges, version pinning, OpenSSF Scorecard security checks, and separation of multiple major releases+ - _Files: `.github/workflows/renovate.yml`, `renovate.json`_++- **Model Number field**: New optional field for warranties to track product model numbers+ - Backend: Added `model_number` column and wired through all GET/POST/PUT routes+ - Frontend: New and Edit modals include Model Number input; displayed on warranty cards (all views including Global)+ - _Files: `backend/migrations/047_add_model_number_to_warranties.sql`, `backend/warranties_routes.py`, `frontend/index.html`, `frontend/status.html`, `frontend/script.js`, `locales/en/translation.json`_++- **Administrator Audit Trail (admin-only)**+ - Backend: New `audit_log` table and centralized `create_audit_log` helper. Logs site setting changes (with secrets masked), user updates, and deletions. Added `GET /api/admin/audit-trail` endpoint.+ - Frontend: Added standalone Audit Trail section in Settings (separate from Apprise) with safe HTML rendering of timestamp, user, action, and details.+ - _Files: `backend/migrations/048_create_audit_log_table.sql`, `backend/audit_logger.py`, `backend/admin_routes.py`, `frontend/settings-new.html`, `frontend/settings-new.js`_++- **Docker configuration files**: Dedicated setup for containerized environments+ - `Docker/entrypoint.sh` β main entry script+ - `Docker/nginx-wrapper.sh` β NGINX wrapper+ - `Docker/supervisord.conf` β Supervisor configuration+ - _Files: `Docker/entrypoint.sh`, `Docker/nginx-wrapper.sh`, `Docker/supervisord.conf`_+### Enhanced+- **Dockerfile optimization**: Complete refactor using a multi-stage build+ - Smaller image size, clear separation between build and runtime stages+ - Pinned dependencies and applied Docker security best practices+ - _Files: `Dockerfile` (major refactor)_++- **Git configuration**: Enforced LF line endings for shell scripts+ - _Files: `.gitattributes`_++- **OIDC handler improvements**: Refactored authentication handler for maintainability+ - _Files: `backend/oidc_handler.py`_++- **Database handler enhancements**: Improved connection and query management+ - _Files: `backend/db_handler.py`_++- **Add Warranty modal tabs β responsive alignment**+ - Adjusted label size and spacing below β€740px to prevent wrapping+ - Maintains icon+label pairing; five-step indicator consistent across breakpoints+ - _Files: `frontend/style.css`_++- **Frontend cache busting and version updates**+ - Updated service worker cache and version checker for new logic+ - Ensured clients receive updated assets+ - _Files: `frontend/sw.js`, `frontend/version-checker.js`, `frontend/*.html`_+++### Fixed+- **Global warranties view**: Global view on Index page now properly displays warranties from all users+ - Backend: Added `GET /api/warranties/global/archived` and unified global queries using correlated subqueries to avoid row collapse+ - Frontend: When scope = Global and Status = "All", merges archived warranties via the new endpoint+ - Archived Global view now uses the correct global archived endpoint+ - Cache bust applied to ensure updated logic+ - _Files: `backend/warranties_routes.py`, `frontend/script.js`, `frontend/sw.js`, `frontend/index.html`, `frontend/status.html`_++- **Global view: Model Number display**+ - Backend: Included `model_number` in global and archived global warranty queries so the UI can render it correctly+ - _Files: `backend/warranties_routes.py`_++### Dependencies+**Major updates:**+- **Python**: 3.13 β 3.14 (Docker base image)+- **gevent**: 24.2.1 β 25.9.1+- **flask-cors**: 4.0.1 β 6.0.1+- **Font Awesome**: 6.4.0 β 7.x+- **postgresql-client**: 15.10 β 17++**Minor/patch updates:**+- **Flask**: 3.0.3 β 3.1.2+- **Werkzeug**: 3.0.3 β 3.1.3+- **psycopg2**: 2.9.9 β 2.9.11+- **PyJWT**: 2.8.0 β 2.10.1+- **email-validator**: 2.1.1 β 2.3.0+- **APScheduler**: 3.10.4 β 3.11.0+- **python-dateutil**: 2.9.0 β 2.9.0.post0+- **Authlib**: 1.3.1 β 1.6.5+- **requests**: 2.32.3 β 2.32.5+- **setuptools**: <81 β 80.9.0+- **apprise**: 1.9.3 β 1.9.5+- **Babel**: 2.16.0 β 2.17.0+- **renovatebot/github-action**: v43.0.16 β v43.0.17+_Files: `backend/requirements.txt`, `Dockerfile`_+++### Migration Notes+- Database migration **047** adds the `model_number` column (auto-runs on startup)+- Rebuild Docker image for **Python 3.14** and updated dependencies+- Verify **CORS** compatibility with `flask-cors` v6+- Confirm **Font Awesome v7** icons render correctly+- Ensure PostgreSQL server compatibility with **client v17**-### Fixed-- Global view on Index page now shows warranties from all users as expected:- - Backend: Added `GET /api/warranties/global/archived` and unified global queries to return complete sets with correlated subqueries for claim status; no accidental row collapse.- - Frontend: When scope is Global and Status is "All", archived warranties are merged from the new global archived endpoint into the main list. Archived view in Global scope now uses the global archived endpoint.- - Cache bust: Bumped `script.js` and service worker cache to ensure clients receive the updated logic.- - Files: `backend/warranties_routes.py`, `frontend/script.js`, `frontend/sw.js`, `frontend/index.html`, `frontend/status.html`--- Global view: Model Number now displays on warranty cards:- - Backend: Included `model_number` in global and archived global warranty queries so the UI can render it.- - Files: `backend/warranties_routes.py`--### Added-- Model Number field added to warranties:- - Backend: Added `model_number` column and wired through GET/POST/PUT.- - Frontend: New and Edit modals now include a Model Number input.- - Cards: When present, Model Number displays on warranty cards (all views).- - Files: `backend/migrations/047_add_model_number_to_warranties.sql`, `backend/warranties_routes.py`, `frontend/index.html`, `frontend/status.html`, `frontend/script.js`, `locales/en/translation.json`--### Enhanced-- Add Warranty modal tabs responsive alignment:- - Shrink tab label text and spacing at β€740px to prevent wrapping and keep all five tabs aligned (Product, Warranty, Documents, Tags, Summary).- - Maintain icons with labels; no text hiding. Uses five-step progress indicator consistent across breakpoints.- - Files: `frontend/style.css`## 0.10.1.14 - 2025-10-06diff --git a/backend/admin_routes.py b/backend/admin_routes.pyindex 6f065fa..a5c17e2 100644--- a/backend/admin_routes.py+++ b/backend/admin_routes.py@@ -10,12 +10,14 @@ try:from .auth_utils import admin_requiredfrom .apprise_handler import apprise_handler, APPRISE_AVAILABLEfrom .db_handler import get_db_connection, release_db_connection+ from .audit_logger import create_audit_logexcept ImportError:import db_handlerimport notificationsfrom auth_utils import admin_requiredfrom apprise_handler import apprise_handler, APPRISE_AVAILABLEfrom db_handler import get_db_connection, release_db_connection+ from audit_logger import create_audit_log# Create the admin blueprintadmin_bp = Blueprint('admin_bp', __name__)@@ -143,7 +145,20 @@ def update_user(user_id):cur.execute(query, params)conn.commit()-++ # Audit log for user updates+ try:+ details_list = []+ if 'is_admin' in data:+ details_list.append(f"admin status to {data['is_admin']}")+ if 'is_active' in data:+ details_list.append(f"active status to {data['is_active']}")+ if details_list:+ details = 'Updated user: set ' + ', '.join(details_list)+ create_audit_log('UPDATE_USER', target_type='User', target_id=user_id, details=details)+ except Exception as audit_err:+ logger.warning(f"Failed to write audit log for user update {user_id}: {audit_err}")+return jsonify({"message": "User updated successfully"}), 200except Exception as e:logger.error(f"Error updating user: {e}")@@ -221,7 +236,13 @@ def delete_user(user_id):conn.commit()logger.info(f"User {user_id} deleted successfully")-++ # Audit log for user deletion+ try:+ create_audit_log('DELETE_USER', target_type='User', target_id=user_id, details=f"Deleted user {user[1]} (ID: {user_id})")+ except Exception as audit_err:+ logger.warning(f"Failed to write audit log for user delete {user_id}: {audit_err}")+return jsonify({"message": "User deleted successfully"}), 200except Exception as e:logger.error(f"Error deleting user: {e}")@@ -499,6 +520,17 @@ def update_site_settings():elif requires_restart: # This case might be redundant if all oidc_ keys trigger the aboveresponse_message += " An application restart is required for some settings to take full effect."+ # Audit log for updated settings (mask sensitive values)+ try:+ for key, val in data.items():+ masked_val = val+ key_lower = str(key).lower()+ if 'secret' in key_lower or 'token' in key_lower or 'password' in key_lower:+ masked_val = '********'+ create_audit_log('UPDATE_SETTING', target_type='SiteSetting', target_id=key, details=f'Set {key} to {masked_val}')+ except Exception as audit_err:+ logger.warning(f"Failed to write audit logs for settings update: {audit_err}")+return jsonify({"message": response_message}), 200except Exception as e:logger.error(f"Error updating site settings: {e}")@@ -509,6 +541,37 @@ def update_site_settings():if conn:release_db_connection(conn)++# ============================+# Audit Trail Routes+# ============================++@admin_bp.route('/audit-trail', methods=['GET'])+@admin_required+def get_audit_trail():+ """Fetch audit trail records for administrators."""+ limit = request.args.get('limit', 100, type=int)+ conn = None+ try:+ conn = get_db_connection()+ with conn.cursor() as cur:+ cur.execute("""+ SELECT id, timestamp, username, action, target_type, target_id, details, ip_address+ FROM audit_log+ ORDER BY timestamp DESC+ LIMIT %s+ """, (limit,))+ logs = cur.fetchall()+ columns = [desc[0] for desc in cur.description]+ result = [dict(zip(columns, row)) for row in logs]+ return jsonify(result)+ except Exception as e:+ logger.error(f'Error fetching audit trail: {e}')+ return jsonify({'error': 'Failed to fetch audit trail'}), 500+ finally:+ if conn:+ release_db_connection(conn)+# ============================# Notification & Scheduler Routes# ============================diff --git a/backend/audit_logger.py b/backend/audit_logger.pynew file mode 100644index 0000000..872acbc--- /dev/null+++ b/backend/audit_logger.py@@ -0,0 +1,37 @@+from flask import request+from .db_handler import get_db_connection, release_db_connection+import logging++logger = logging.getLogger(__name__)++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+ username = 'System'+ ip_address = None++ if request:+ ip_address = request.remote_addr+ if hasattr(request, 'user') and request.user:+ user_id = request.user.get('id')+ username = request.user.get('username')++ conn = None+ try:+ conn = get_db_connection()+ with conn.cursor() as cur:+ cur.execute("""+ INSERT INTO audit_log (user_id, username, action, target_type, target_id, details, ip_address)+ VALUES (%s, %s, %s, %s, %s, %s, %s)+ """, (user_id, username, action, target_type, str(target_id), details, ip_address))+ conn.commit()+ except Exception as e:+ logger.error(f'Failed to create audit log: {e}')+ if conn:+ conn.rollback()+ finally:+ if conn:+ release_db_connection(conn)+++diff --git a/backend/migrations/048_create_audit_log_table.sql b/backend/migrations/048_create_audit_log_table.sqlnew file mode 100644index 0000000..ef3dc44--- /dev/null+++ b/backend/migrations/048_create_audit_log_table.sql@@ -0,0 +1,20 @@+-- Migration: Create audit_log table+-- Description: Adds a table to store a log of important actions performed by users.+CREATE TABLE IF NOT EXISTS audit_log (+ id SERIAL PRIMARY KEY,+ timestamp TIMESTAMP WITH TIME ZONE DEFAULT CURRENT_TIMESTAMP,+ user_id INTEGER REFERENCES users(id) ON DELETE SET NULL,+ username VARCHAR(255),+ action VARCHAR(255) NOT NULL,+ target_type VARCHAR(50),+ target_id VARCHAR(255),+ details TEXT,+ ip_address VARCHAR(45)+);++CREATE INDEX IF NOT EXISTS idx_audit_log_timestamp ON audit_log(timestamp DESC);+CREATE INDEX IF NOT EXISTS idx_audit_log_user_id ON audit_log(user_id);+CREATE INDEX IF NOT EXISTS idx_audit_log_action ON audit_log(action);+CREATE INDEX IF NOT EXISTS idx_audit_log_target ON audit_log(target_type, target_id);++diff --git a/frontend/settings-new.html b/frontend/settings-new.htmlindex 1e59292..f2d9eaf 100644--- a/frontend/settings-new.html+++ b/frontend/settings-new.html@@ -880,8 +880,45 @@</div></div>++</div>+ <!-- Audit Trail Section (Standalone) -->+ <div id="auditTrailSection" class="admin-section" style="display: block; margin-top: 24px;">+ <h2><i class="fas fa-history" style="margin-right: 8px;"></i>Audit Trail</h2>+ <div class="card collapsible-card">+ <div class="card-header collapsible-header" data-target="auditTrailContent">+ <h3><i class="fas fa-list"></i> Recent Changes</h3>+ <i class="fas fa-chevron-down collapse-icon"></i>+ </div>+ <div class="card-body collapsible-content" id="auditTrailContent">+ <p class="text-muted">View a log of recent changes made by administrators and users.</p>+ <button id="viewAuditTrailBtn" class="btn btn-primary">+ <i class="fas fa-eye"></i> View Audit Log+ </button>+ <div id="auditTrailDisplay" style="display: none; margin-top: 20px;">+ <div id="auditTrailLoading" style="text-align: center;">+ <i class="fas fa-spinner fa-spin"></i> Loading log...+ </div>+ <div class="table-responsive">+ <table id="auditTrailTable" class="table" style="display: none; width: 100%;">+ <thead>+ <tr>+ <th>Timestamp</th>+ <th>User</th>+ <th>Action</th>+ <th>Details</th>+ </tr>+ </thead>+ <tbody id="auditTrailTableBody"></tbody>+ </table>+ </div>+ </div>+ </div>+ </div>+ </div>+<!-- Ownership Management Section - Only visible to the owner --><div id="ownershipSection" class="ownership-section" style="display: none;"><h2><i class="fas fa-crown" style="color: #f39c12; margin-right: 8px;"></i><span data-i18n="settings.ownership_management">Ownership Management</span></h2>diff --git a/frontend/settings-new.js b/frontend/settings-new.jsindex afba5ac..f9feb43 100644--- a/frontend/settings-new.js+++ b/frontend/settings-new.js@@ -436,6 +436,12 @@ document.addEventListener('DOMContentLoaded', function() {// Setup Apprise event listenerssetupAppriseEventListeners();++ // Audit Trail button handler (admin section)+ const viewAuditTrailBtn = document.getElementById('viewAuditTrailBtn');+ if (viewAuditTrailBtn) {+ viewAuditTrailBtn.addEventListener('click', loadAndDisplayAuditTrail);+ }// Initialize delete button handlingsetupDeleteButton();@@ -512,6 +518,76 @@ function initPage() {console.log('Settings page initialization complete');}+// ============================+// Audit Trail functions+// ============================++async function loadAndDisplayAuditTrail() {+ const displayArea = document.getElementById('auditTrailDisplay');+ const loadingIndicator = document.getElementById('auditTrailLoading');+ const table = document.getElementById('auditTrailTable');+ const tableBody = document.getElementById('auditTrailTableBody');++ if (!displayArea || !loadingIndicator || !table || !tableBody) return;++ displayArea.style.display = 'block';+ loadingIndicator.style.display = 'block';+ table.style.display = 'none';+ tableBody.innerHTML = '';++ try {+ const token = window.auth && window.auth.getToken ? window.auth.getToken() : localStorage.getItem('auth_token');+ const response = await fetch('/api/admin/audit-trail?limit=200', {+ headers: { 'Authorization': `Bearer ${token}` }+ });++ if (!response.ok) {+ throw new Error('Failed to fetch audit log');+ }++ const logs = await response.json();+ renderAuditTrail(logs);++ } catch (error) {+ console.error('Error loading audit trail:', error);+ loadingIndicator.textContent = 'Error loading audit trail.';+ }+}++function renderAuditTrail(logs) {+ const loadingIndicator = document.getElementById('auditTrailLoading');+ const table = document.getElementById('auditTrailTable');+ const tableBody = document.getElementById('auditTrailTableBody');++ loadingIndicator.style.display = 'none';++ if (!Array.isArray(logs) || logs.length === 0) {+ tableBody.innerHTML = '<tr><td colspan="4" style="text-align: center;">No audit records found.</td></tr>';+ } else {+ logs.forEach(log => {+ const row = tableBody.insertRow();+ const timestamp = log.timestamp ? new Date(log.timestamp).toLocaleString() : '';+ const username = (log.username || 'System');+ const action = (log.action || '');+ const details = log.details ? escapeHtmlSafe(log.details) : 'N/A';++ row.innerHTML = `+ <td title='${log.ip_address || ''}'>${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>+ `;+ });+ }+ table.style.display = 'table';+}++function escapeHtmlSafe(text) {+ if (typeof text !== 'string') return text;+ const map = { '&': '&', '<': '<', '>': '>', '"': '"', "'": ''' };+ return text.replace(/[&<>"']/g, m => map[m]);+}+/*** Setup critical event listeners that must work for core functionality*/