Skip to content

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

Security: audit Apprise test and send-custom attempts, schemes only (ADM-03)

Omega (QA)a5e26e40cba4
diff --git a/backend/admin_routes.py b/backend/admin_routes.py
index 0cf1762..b07cada 100644
--- a/backend/admin_routes.py
+++ b/backend/admin_routes.py
@@ -3,6 +3,7 @@ from datetime import datetime, date
import os
import re
import logging
+import urllib.parse
# Use try-except pattern for imports to handle both Docker and development environments
try:
@@ -638,26 +639,52 @@ def get_scheduler_status():
# Apprise Admin Routes
# ============================
+def _apprise_destination_summary(urls):
+ """Summarize per-request Apprise destinations for the audit log.
+
+ Apprise URLs embed credentials in the authority and path (bot
+ tokens, webhook ids, passwords), so only the URL schemes and the
+ count are recorded, never hosts, paths, queries, or the
+ notification content itself.
+ """
+ if not urls:
+ return 'configured URLs'
+ if isinstance(urls, str):
+ urls = [urls]
+ schemes = []
+ for url in urls:
+ try:
+ schemes.append(urllib.parse.urlparse(str(url)).scheme or '?')
+ except Exception:
+ schemes.append('?')
+ noun = 'URL' if len(schemes) == 1 else 'URLs'
+ return f"{len(schemes)} per-request {noun} (schemes: {', '.join(schemes)})"
+
+
@admin_bp.route('/apprise/test', methods=['POST'])
@admin_required
def test_apprise_notification():
"""Send a test Apprise notification"""
if not APPRISE_AVAILABLE or apprise_handler is None:
return jsonify({'success': False, 'message': 'Apprise notifications are not available'}), 503
-
+
try:
data = request.get_json()
test_url = data.get('test_url') if data else None
-
+
success = apprise_handler.send_test_notification(test_url)
-
+ create_audit_log('APPRISE_TEST', target_type='Apprise', target_id='test-notification',
+ details=f"Test notification via {_apprise_destination_summary(test_url)}: {'sent' if success else 'failed'}")
+
if success:
return jsonify({'success': True, 'message': 'Test notification sent successfully'}), 200
else:
return jsonify({'success': False, 'message': 'Failed to send test notification'}), 400
-
+
except Exception as e:
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
@admin_bp.route('/apprise/validate-url', methods=['POST'])
@@ -808,16 +835,20 @@ def send_custom_apprise_notification():
if not title or not message:
return jsonify({'success': False, 'message': 'Title and message are required'}), 400
-
+
success = apprise_handler.send_custom_notification(title, message, urls)
-
+ create_audit_log('APPRISE_SEND_CUSTOM', target_type='Apprise', target_id='custom-notification',
+ details=f"Custom notification via {_apprise_destination_summary(urls)}: {'sent' if success else 'failed'}")
+
if success:
return jsonify({'success': True, 'message': 'Custom notification sent successfully'}), 200
else:
return jsonify({'success': False, 'message': 'Failed to send custom notification'}), 400
-
+
except Exception as e:
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
@admin_bp.route('/apprise/status', methods=['GET'])
diff --git a/tests/test_apprise_audit.py b/tests/test_apprise_audit.py
new file mode 100644
index 0000000..cf2f7c8
--- /dev/null
+++ b/tests/test_apprise_audit.py
@@ -0,0 +1,141 @@
+"""ADM-03: the Apprise test and send-custom endpoints must write audit
+entries. Per-request URLs embed credentials, so the entries record
+only schemes and counts, never hosts, paths, or notification content.
+"""
+import types
+
+import pytest
+
+import backend.admin_routes as admin_routes
+
+
+def stub_handler(monkeypatch):
+ calls = {"test": [], "custom": []}
+ stub = types.SimpleNamespace(
+ send_test_notification=lambda url=None: (
+ calls["test"].append(url), True)[1],
+ send_custom_notification=lambda title, message, urls=None: (
+ calls["custom"].append((title, message, urls)), True)[1],
+ )
+ monkeypatch.setattr(admin_routes, "APPRISE_AVAILABLE", True)
+ monkeypatch.setattr(admin_routes, "apprise_handler", stub)
+ return calls
+
+
+def _promote(db_connection, username):
+ with db_connection, db_connection.cursor() as cur:
+ cur.execute("UPDATE users SET is_admin = TRUE WHERE username = %s",
+ (username,))
+
+
+def _new_audit_rows(db_connection, action, before_id):
+ with db_connection.cursor() as cur:
+ cur.execute(
+ "SELECT action, username, target_type, target_id, details "
+ "FROM audit_log WHERE action = %s AND id > %s ORDER BY id",
+ (action, before_id))
+ return cur.fetchall()
+
+
+def _max_audit_id(db_connection):
+ with db_connection.cursor() as cur:
+ cur.execute("SELECT COALESCE(MAX(id), 0) FROM audit_log")
+ return cur.fetchone()[0]
+
+
+def test_test_endpoint_audits_per_request_url(
+ client, admin_user, db_connection, stub_handler):
+ _promote(db_connection, admin_user["username"])
+ before = _max_audit_id(db_connection)
+ r = client.post("/api/admin/apprise/test", headers=admin_user["headers"],
+ json={"test_url": "tgram://SECRETTOKEN/12345"})
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert stub_handler["test"] == ["tgram://SECRETTOKEN/12345"]
+ rows = _new_audit_rows(db_connection, "APPRISE_TEST", before)
+ assert len(rows) == 1
+ _, username, target_type, target_id, details = rows[0]
+ assert username == admin_user["username"]
+ assert target_type == "Apprise"
+ assert "1 per-request URL (schemes: tgram)" in details
+ assert "sent" in details
+ assert "SECRETTOKEN" not in details
+ assert "12345" not in details
+
+
+def test_test_endpoint_audits_configured_urls(
+ client, admin_user, db_connection, stub_handler):
+ _promote(db_connection, admin_user["username"])
+ before = _max_audit_id(db_connection)
+ r = client.post("/api/admin/apprise/test", headers=admin_user["headers"], json={})
+ assert r.status_code == 200
+ rows = _new_audit_rows(db_connection, "APPRISE_TEST", before)
+ assert len(rows) == 1
+ assert "configured URLs" in rows[0][4]
+
+
+def test_test_endpoint_audits_failure(
+ client, admin_user, db_connection, monkeypatch):
+ _promote(db_connection, admin_user["username"])
+ stub = types.SimpleNamespace(send_test_notification=lambda url=None: False)
+ monkeypatch.setattr(admin_routes, "APPRISE_AVAILABLE", True)
+ monkeypatch.setattr(admin_routes, "apprise_handler", stub)
+ before = _max_audit_id(db_connection)
+ r = client.post("/api/admin/apprise/test", headers=admin_user["headers"],
+ json={"test_url": "json://127.0.0.1:8931/hook"})
+ assert r.status_code == 400
+ rows = _new_audit_rows(db_connection, "APPRISE_TEST", before)
+ assert len(rows) == 1
+ assert "failed" in rows[0][4]
+ assert "127.0.0.1" not in rows[0][4]
+ assert "8931" not in rows[0][4]
+
+
+def test_send_custom_audits_schemes_not_credentials(
+ client, admin_user, db_connection, stub_handler):
+ _promote(db_connection, admin_user["username"])
+ before = _max_audit_id(db_connection)
+ urls = ["discord://WEBHOOKID/WEBHOOKTOKEN", "json://user:[email protected]/x"]
+ r = client.post("/api/admin/apprise/send-custom", headers=admin_user["headers"],
+ json={"title": "Hi", "message": "Body",
+ "urls": urls})
+ assert r.status_code == 200, r.get_data(as_text=True)
+ assert stub_handler["custom"] == [("Hi", "Body", urls)]
+ rows = _new_audit_rows(db_connection, "APPRISE_SEND_CUSTOM", before)
+ assert len(rows) == 1
+ details = rows[0][4]
+ assert "2 per-request URLs (schemes: discord, json)" in details
+ for secret in ("WEBHOOKID", "WEBHOOKTOKEN", "user", "pass", "internal.local"):
+ assert secret not in details
+ assert "Hi" not in details and "Body" not in details
+
+
+def test_send_custom_without_urls_audits_configured(
+ client, admin_user, db_connection, stub_handler):
+ _promote(db_connection, admin_user["username"])
+ before = _max_audit_id(db_connection)
+ r = client.post("/api/admin/apprise/send-custom", headers=admin_user["headers"],
+ json={"title": "Hi", "message": "Body"})
+ assert r.status_code == 200
+ rows = _new_audit_rows(db_connection, "APPRISE_SEND_CUSTOM", before)
+ assert len(rows) == 1
+ assert "configured URLs" in rows[0][4]
+
+
+def test_send_custom_validation_failure_writes_no_audit(
+ client, admin_user, db_connection, stub_handler):
+ _promote(db_connection, admin_user["username"])
+ before = _max_audit_id(db_connection)
+ r = client.post("/api/admin/apprise/send-custom", headers=admin_user["headers"],
+ json={"message": "no title"})
+ assert r.status_code == 400
+ assert _new_audit_rows(db_connection, "APPRISE_SEND_CUSTOM", before) == []
+
+
+def test_non_admin_gets_no_audit_row(
+ client, user_factory, db_connection, stub_handler):
+ user = user_factory()
+ before = _max_audit_id(db_connection)
+ r = client.post("/api/admin/apprise/test", headers=user["headers"], json={})
+ assert r.status_code == 403
+ assert _new_audit_rows(db_connection, "APPRISE_TEST", before) == []