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
feat(security): daily GHSA feed check with admin notifications
Juan Denis0b0bfcce70ad
diff --git a/backend/app/jobs/builtin_handlers.py b/backend/app/jobs/builtin_handlers.pyindex 5ea9ebaf..9587f07f 100644--- a/backend/app/jobs/builtin_handlers.py+++ b/backend/app/jobs/builtin_handlers.py@@ -286,6 +286,22 @@ def run_job_retention():return None+def run_security_feed_check():+ """Daily security-advisory feed check.++ Pulls the normalized GHSA feed from serverkit.ai and notifies admins when+ the running panel version falls inside a published advisory's affected+ range, plus one-time post-fix reminders (e.g. key rotation) after an+ upgrade crosses a fix boundary. Fails silent on outbound errors."""+ from app.services.security_feed_service import check_security_feed++ try:+ return check_security_feed()+ except Exception as e:+ logger.debug(f'Security feed check skipped: {e}')+ return None++def run_extension_update_check():"""Daily registry check for installed-extension updates (#50).@@ -350,6 +366,7 @@ _BUILTINS = [('builtin.registrar_expiry', run_registrar_expiry, 'registrar-expiry', 86400, 300),('builtin.backup_scheduler', run_backup_scheduler, 'backup-scheduler', 30, 30),('builtin.extension_updates', run_extension_update_check, 'extension-updates', 86400, 600),+ ('builtin.security_feed', run_security_feed_check, 'security-feed', 86400, 600),('builtin.job_retention', run_job_retention, 'job-retention', 21600, 1500),]diff --git a/backend/app/services/security_feed_service.py b/backend/app/services/security_feed_service.pynew file mode 100644index 00000000..a6849406--- /dev/null+++ b/backend/app/services/security_feed_service.py@@ -0,0 +1,159 @@+"""Security-advisory feed check.++Once a day (builtin job `security-feed`) the panel pulls the normalized GHSA+feed from https://serverkit.ai/api/security-feed.json (a cached proxy of the+repo's published GitHub Security Advisories) and:++1. notifies admins when the RUNNING version falls inside an advisory's+ affected range ("you are vulnerable — update"), once per advisory;+2. after an upgrade crosses a fix boundary, fires a one-time post-fix+ reminder when the advisory declares follow-up actions (e.g. rotating+ JWT_SECRET_KEY after GHSA-rm3m-9mvw-68fh).++Dedupe + last-good feed + the previously-seen version live in SystemSettings,+so restarts never re-notify. Outbound failures are silent: a panel with no+internet access simply never notifies. Set the `security_feed.enabled`+setting to false to opt out of the outbound call entirely.+"""+import json+import logging+import urllib.request++from app import db+from app.models.system_settings import SystemSettings+from app.utils.version import compare_versions, get_panel_version++logger = logging.getLogger(__name__)++FEED_URL = 'https://serverkit.ai/api/security-feed.json'+FEED_TIMEOUT = 8 # seconds++ENABLED_KEY = 'security_feed.enabled'+NOTIFIED_KEY = 'security_feed.notified' # json list of dedupe keys+LAST_VERSION_KEY = 'security_feed.last_version'+LAST_GOOD_KEY = 'security_feed.last_good' # json {"advisories": [...]}++_OPERATORS = {+ '<': lambda c: c < 0,+ '<=': lambda c: c <= 0,+ '>': lambda c: c > 0,+ '>=': lambda c: c >= 0,+ '=': lambda c: c == 0,+ '==': lambda c: c == 0,+}+++def version_in_range(version, range_str):+ """Evaluate a GHSA-style version range (e.g. '< 1.7.68', '>= 1.2.0, < 1.5')+ against `version`. Comma-separated clauses AND together. An empty or+ unparseable range matches nothing (fail closed — never cry wolf)."""+ if not version or not range_str:+ return False+ for clause in range_str.split(','):+ clause = clause.strip()+ if not clause:+ continue+ op, _, bound = clause.partition(' ')+ pred = _OPERATORS.get(op.strip())+ bound = bound.strip()+ if pred is None or not bound:+ return False+ if not pred(compare_versions(version, bound)):+ return False+ return True+++def is_enabled():+ """Opt-out switch for the outbound feed call. Default on."""+ return SystemSettings.get(ENABLED_KEY, True) not in (False, 'false', '0')+++def fetch_feed():+ """GET the advisory feed; fall back to the last-good copy on any failure.++ Returns a list of advisory dicts (possibly empty). Never raises."""+ try:+ req = urllib.request.Request(+ FEED_URL, headers={'User-Agent': 'ServerKit-SecurityFeed/1.0'})+ with urllib.request.urlopen(req, timeout=FEED_TIMEOUT) as resp:+ data = json.loads(resp.read().decode('utf-8'))+ advisories = data.get('advisories') or []+ SystemSettings.set(LAST_GOOD_KEY, {'advisories': advisories}, 'json')+ db.session.commit()+ return advisories+ except Exception as e:+ logger.debug(f'Security feed fetch failed (using last-good): {e}')+ cached = SystemSettings.get(LAST_GOOD_KEY) or {}+ return cached.get('advisories') or []+++def _notify(alert_type, message):+ from app.notifications.service import NotificationBusService+ NotificationBusService.send(+ 'security.alert',+ to='admins',+ data={'alert_type': alert_type, 'message': message},+ action_path='/settings/system',+ action_label='Review update',+ )+++def check_security_feed(current_version=None):+ """Daily job entry point. Returns a small result dict for the job log."""+ if not is_enabled():+ return {'skipped': 'disabled'}++ current = current_version or get_panel_version()+ advisories = fetch_feed()++ notified = set(SystemSettings.get(NOTIFIED_KEY, []) or [])+ alerts = 0++ # 1) Running version inside an affected range -> "update now" alert.+ for adv in advisories:+ ghsa = adv.get('ghsa')+ affected = adv.get('affected')+ if not ghsa or not affected:+ continue+ if f'{ghsa}:affected' in notified:+ continue+ if not version_in_range(current, affected):+ continue+ fixed = adv.get('fixed_in') or 'a newer release'+ _notify(+ f'Known vulnerability {ghsa}',+ f'{adv.get("summary", "Security advisory")} — this panel runs '+ f'{current}, which is in the affected range ({affected}). '+ f'Fixed in {fixed}. Update with: sudo serverkit update. '+ f'Details: {adv.get("url", "")}',+ )+ notified.add(f'{ghsa}:affected')+ alerts += 1++ # 2) Upgrade crossing: previously-seen version was affected, current is+ # not -> one-time post-fix reminder (key rotation, etc.).+ previous = SystemSettings.get(LAST_VERSION_KEY)+ if previous and previous != current:+ for adv in advisories:+ ghsa = adv.get('ghsa')+ affected = adv.get('affected')+ post_fix = adv.get('post_fix_action')+ if not ghsa or not affected or not post_fix:+ continue+ if f'{ghsa}:postfix' in notified:+ continue+ if version_in_range(previous, affected) and not version_in_range(current, affected):+ _notify(+ f'Post-update action required ({ghsa})',+ f'This panel previously ran {previous}, which was affected '+ f'by {ghsa} ({adv.get("summary", "security advisory")}). '+ f'The update is installed — complete these follow-up steps: '+ f'{post_fix}',+ )+ notified.add(f'{ghsa}:postfix')+ alerts += 1+ SystemSettings.set(LAST_VERSION_KEY, current)+ SystemSettings.set(NOTIFIED_KEY, sorted(notified), 'json')+ db.session.commit()++ return {'advisories': len(advisories), 'alerts': alerts}diff --git a/backend/tests/test_jobs.py b/backend/tests/test_jobs.pyindex fc39acd3..269260c6 100644--- a/backend/tests/test_jobs.py+++ b/backend/tests/test_jobs.py@@ -175,18 +175,20 @@ class TestBuiltins:assert 'builtin.health_check' in kindsassert 'builtin.backup_scheduler' in kindsassert 'builtin.extension_updates' in kinds+ assert 'builtin.security_feed' in kindsassert 'builtin.job_retention' in kindsassert 'builtin.monitor_check' in kinds- assert len([k for k in kinds if k.startswith('builtin.')]) == 12+ assert len([k for k in kinds if k.startswith('builtin.')]) == 13builtin_handlers.seed_builtin_schedules()- # 12 builtin.* schedules (incl. job-retention and the monitor sweep) ++ # 13 builtin.* schedules (incl. job-retention, the monitor sweep and the+ # security-feed check) +# login-link/SSO reapers + drift/FIM/bandwidth sweeps + the host doctor# sweep (plan 26) + the setup-health nag (plan 22).- assert ScheduledJob.query.count() == 19+ assert ScheduledJob.query.count() == 20# Seeding twice doesn't duplicate.builtin_handlers.seed_builtin_schedules()- assert ScheduledJob.query.count() == 19+ assert ScheduledJob.query.count() == 20class TestApi:diff --git a/backend/tests/test_security_feed.py b/backend/tests/test_security_feed.pynew file mode 100644index 00000000..4a618e30--- /dev/null+++ b/backend/tests/test_security_feed.py@@ -0,0 +1,143 @@+"""Tests for the security-advisory feed check (security_feed_service)."""+import pytest++from app import db as _db+from app.models.system_settings import SystemSettings+from app.services import security_feed_service as sfs++FEED = [+ {+ 'ghsa': 'GHSA-test-0001',+ 'cve': None,+ 'severity': 'high',+ 'summary': 'Test advisory one',+ 'affected': '< 1.7.68',+ 'fixed_in': '1.7.68',+ 'url': 'https://example.test/GHSA-test-0001',+ 'published_at': '2026-08-01T00:00:00Z',+ 'post_fix_action': 'Rotate JWT_SECRET_KEY.',+ },+ {+ 'ghsa': 'GHSA-test-0002',+ 'cve': None,+ 'severity': 'medium',+ 'summary': 'Test advisory two',+ 'affected': '>= 1.5.0, < 1.6.0',+ 'fixed_in': '1.6.0',+ 'url': 'https://example.test/GHSA-test-0002',+ 'published_at': '2026-08-01T00:00:00Z',+ 'post_fix_action': None,+ },+]+++def feed_env(app, monkeypatch):+ """Feed stub + notification recorder, inside an app context."""+ sent = []+ monkeypatch.setattr(sfs, 'fetch_feed', lambda: FEED)+ from app.notifications.service import NotificationBusService+ monkeypatch.setattr(+ NotificationBusService, 'send',+ classmethod(lambda cls, event, to, data=None, **kw: sent.append(+ {'event': event, 'to': to, 'data': data, **kw})))+ with app.app_context():+ yield sent+++# --------------------------------------------------------------------------- #+# version range evaluation+# --------------------------------------------------------------------------- #+[email protected]('version,range_str,expected', [+ ('1.7.59', '< 1.7.68', True),+ ('1.7.68', '< 1.7.68', False),+ ('1.7.67', '< 1.7.68', True),+ ('1.5.4', '>= 1.5.0, < 1.6.0', True),+ ('1.6.0', '>= 1.5.0, < 1.6.0', False),+ ('1.4.9', '>= 1.5.0, < 1.6.0', False),+ ('1.7.59', '', False),+ ('1.7.59', None, False),+ ('1.7.59', 'banana', False),+])+def test_version_in_range(version, range_str, expected):+ assert sfs.version_in_range(version, range_str) is expected+++# --------------------------------------------------------------------------- #+# affected-version alerting+# --------------------------------------------------------------------------- #++def test_alerts_when_current_version_affected(feed_env):+ result = sfs.check_security_feed(current_version='1.7.59')+ assert result['alerts'] == 1+ assert len(feed_env) == 1+ note = feed_env[0]+ assert note['event'] == 'security.alert'+ assert note['to'] == 'admins'+ assert 'GHSA-test-0001' in note['data']['alert_type']+ assert '1.7.59' in note['data']['message']+++def test_no_alert_when_version_not_affected(feed_env):+ result = sfs.check_security_feed(current_version='1.7.77')+ assert result['alerts'] == 0+ assert feed_env == []+++def test_alert_fires_once_per_advisory(feed_env):+ sfs.check_security_feed(current_version='1.7.59')+ result = sfs.check_security_feed(current_version='1.7.59')+ assert result['alerts'] == 0+ assert len(feed_env) == 1+++def test_multi_clause_range_alerts(feed_env):+ result = sfs.check_security_feed(current_version='1.5.4')+ assert result['alerts'] == 2 # both advisories match 1.5.4+++def test_disabled_skips_everything(app, feed_env):+ SystemSettings.set(sfs.ENABLED_KEY, False, 'boolean')+ _db.session.commit()+ result = sfs.check_security_feed(current_version='1.7.59')+ assert result == {'skipped': 'disabled'}+ assert feed_env == []+++# --------------------------------------------------------------------------- #+# post-fix reminders after an upgrade crosses the fix boundary+# --------------------------------------------------------------------------- #++def test_post_fix_reminder_after_upgrade_crossing(feed_env):+ # Panel was last seen on an affected version...+ sfs.check_security_feed(current_version='1.7.59')+ assert len(feed_env) == 1+ # ...and comes up fixed: the advisory carries a post_fix_action.+ result = sfs.check_security_feed(current_version='1.7.77')+ assert result['alerts'] == 1+ note = feed_env[-1]+ assert 'Post-update action' in note['data']['alert_type']+ assert 'Rotate JWT_SECRET_KEY' in note['data']['message']+++def test_no_post_fix_reminder_without_action(feed_env):+ # 1.5.4 -> 1.6.0 crosses GHSA-test-0002, which declares no post-fix action.+ sfs.check_security_feed(current_version='1.5.4')+ sent_before = len(feed_env)+ sfs.check_security_feed(current_version='1.6.0')+ assert len(feed_env) == sent_before+++def test_post_fix_reminder_fires_once(feed_env):+ sfs.check_security_feed(current_version='1.7.59')+ sfs.check_security_feed(current_version='1.7.77')+ result = sfs.check_security_feed(current_version='1.7.77')+ assert result['alerts'] == 0+++def test_first_seen_version_records_without_reminder(feed_env):+ """A fresh panel (no last_version) never gets post-fix reminders."""+ result = sfs.check_security_feed(current_version='1.7.77')+ assert result['alerts'] == 0+ assert SystemSettings.get(sfs.LAST_VERSION_KEY) == '1.7.77'