ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
fix(notifications): escape interpolated values in Telegram alerts
Juan Denisf724a1fbca97
diff --git a/backend/app/services/notification_service.py b/backend/app/services/notification_service.pyindex 606a299f..17de391b 100644--- a/backend/app/services/notification_service.py+++ b/backend/app/services/notification_service.py@@ -10,6 +10,7 @@ Handles sending notifications to various channels:"""import os+import htmlimport jsonimport requestsimport smtplib@@ -333,22 +334,33 @@ class NotificationService:return {'success': True, 'message': 'No alerts to send'}try:- # Build message- lines = [f"<b>π ServerKit Alert</b>", f"<i>Host: {cls.get_hostname()}</i>", ""]+ # parse_mode='HTML' means Telegram parses the body as markup, so every+ # interpolated value has to be escaped. Unescaped, an alert message as+ # ordinary as "Disk usage > 90% on /var & /tmp" makes the API reject+ # the request with "can't parse entities" and the whole notification+ # is dropped -- exactly when something is already wrong. Only the+ # literal tags below are markup; everything substituted in is data.+ def esc(value):+ return html.escape(str(value), quote=False)++ lines = [f"<b>π ServerKit Alert</b>", f"<i>Host: {esc(cls.get_hostname())}</i>", ""]for alert in alerts:severity = alert.get('severity', 'info')color_info = cls.SEVERITY_COLORS.get(severity, cls.SEVERITY_COLORS['info'])- lines.append(f"{color_info['emoji']} <b>{severity.upper()}: {alert.get('type', 'Alert').upper()}</b>")- lines.append(alert.get('message', 'No message'))+ lines.append(+ f"{color_info['emoji']} <b>{esc(severity.upper())}: "+ f"{esc(alert.get('type', 'Alert').upper())}</b>"+ )+ lines.append(esc(alert.get('message', 'No message')))if 'value' in alert or 'threshold' in alert:details = []if 'value' in alert:- details.append(f"Current: {alert['value']}")+ details.append(f"Current: {esc(alert['value'])}")if 'threshold' in alert:- details.append(f"Threshold: {alert['threshold']}")+ details.append(f"Threshold: {esc(alert['threshold'])}")lines.append(f"<code>{' | '.join(details)}</code>")lines.append("")diff --git a/backend/tests/test_notification_telegram_format.py b/backend/tests/test_notification_telegram_format.pynew file mode 100644index 00000000..86a3362e--- /dev/null+++ b/backend/tests/test_notification_telegram_format.py@@ -0,0 +1,106 @@+"""Telegram alerts are sent with parse_mode='HTML', so every interpolated+value has to be escaped.++Unescaped, an alert message as ordinary as "Disk usage > 90% on /var & /tmp"+makes the Bot API reject the request with "can't parse entities" and the whole+notification is dropped β precisely when something is already wrong on the box.+These pin the escaping and that the literal markup survives it.+"""++from unittest.mock import patch++from app.services.notification_service import NotificationService+++TELEGRAM_CONFIG = {+ 'enabled': True,+ 'bot_token': 'test-token',+ 'chat_id': '123456',+ 'notify_on': ['critical', 'warning', 'info'],+}+++class _FakeResponse:+ def __init__(self, payload):+ self._payload = payload++ def json(self):+ return self._payload+++def _send(alerts, hostname='test-host'):+ """Run send_telegram against a stubbed API and return the posted payload."""+ captured = {}++ def fake_post(url, json=None, timeout=None):+ captured['url'] = url+ captured['payload'] = json+ return _FakeResponse({'ok': True})++ with patch('app.services.notification_service.requests.post', side_effect=fake_post), \+ patch.object(NotificationService, 'get_hostname', return_value=hostname):+ result = NotificationService.send_telegram(alerts, config=dict(TELEGRAM_CONFIG))++ assert result['success'] is True, result+ return captured['payload']+++def test_alert_message_with_html_metacharacters_is_escaped():+ """The regression: > and & in a message used to reach Telegram raw."""+ payload = _send([{+ 'severity': 'warning',+ 'type': 'disk',+ 'message': 'Disk usage > 90% on /var & /tmp',+ }])++ text = payload['text']+ assert 'Disk usage > 90% on /var & /tmp' in text+ # The raw form must be gone, or the API rejects the whole message.+ assert 'Disk usage > 90%' not in text+++def test_angle_bracket_payload_cannot_inject_markup():+ """A value that looks like a tag is data, not markup."""+ payload = _send([{+ 'severity': 'critical',+ 'type': 'service',+ 'message': 'container <b>web</b> exited',+ }])++ text = payload['text']+ assert '<b>web</b>' in text+ assert '<b>web</b>' not in text+++def test_hostname_and_threshold_values_are_escaped():+ """Every interpolated field, not just the message."""+ payload = _send(+ [{+ 'severity': 'warning',+ 'type': 'cpu',+ 'message': 'high load',+ 'value': '95% > limit',+ 'threshold': '90% & rising',+ }],+ hostname='box<1>&2',+ )++ text = payload['text']+ assert 'box<1>&2' in text+ assert 'Current: 95% > limit' in text+ assert 'Threshold: 90% & rising' in text+++def test_literal_markup_and_parse_mode_survive_escaping():+ """Escaping data must not escape the template's own tags."""+ payload = _send([{+ 'severity': 'info',+ 'type': 'test',+ 'message': 'plain message',+ }])++ text = payload['text']+ assert payload['parse_mode'] == 'HTML'+ assert '<b>π ServerKit Alert</b>' in text+ assert '<i>Host: test-host</i>' in text+ assert '<b>INFO: TEST</b>' in text