Skip to content

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.

ci(security): expand scans and narrow Bandit exceptions

Juan Denisda0f18146bce
diff --git a/.github/workflows/security-scan.yml b/.github/workflows/security-scan.yml
index 1861401c..b9694441 100644
--- a/.github/workflows/security-scan.yml
+++ b/.github/workflows/security-scan.yml
@@ -5,12 +5,28 @@ on:
branches: [dev]
paths:
- 'backend/**'
+ - 'builtin-extensions/**'
+ - '**/requirements*.txt'
+ - 'frontend/package*.json'
+ - 'scripts/check-bandit-report.py'
+ - 'scripts/security/**'
- '.github/workflows/security-scan.yml'
pull_request:
branches: [main]
paths:
- 'backend/**'
+ - 'builtin-extensions/**'
+ - '**/requirements*.txt'
+ - 'frontend/package*.json'
+ - 'scripts/check-bandit-report.py'
+ - 'scripts/security/**'
- '.github/workflows/security-scan.yml'
+ schedule:
+ - cron: '17 9 * * 1' # Weekly; advisories change even without repository changes.
+ workflow_dispatch:
+
+permissions:
+ contents: read
jobs:
# ──────────────────────────────────────────────────────────────────
@@ -28,30 +44,21 @@ jobs:
python-version: '3.11'
- name: Install Bandit
- run: pip install bandit
+ run: pip install bandit==1.9.3
- name: Run Bandit scan
- working-directory: backend
run: |
- echo "## Full report (MEDIUM+ severity, MEDIUM+ confidence)"
- echo ""
- bandit -r app/ \
- --severity-level medium \
- --confidence-level medium \
- -f txt \
- --exit-zero
- echo ""
- echo "---"
- echo ""
- echo "## Strict gate (HIGH severity, HIGH confidence, new issues only)"
- echo "Known accepts: B602 (shell=True for build/deploy scripts),"
- echo " B402/B321 (FTP management feature), B202 (tarfile for backups)"
- echo ""
- bandit -r app/ \
- --severity-level high \
- --confidence-level high \
- --skip B602,B402,B321,B202 \
- -f txt
+ python -m unittest discover -s scripts/security -p 'test_*.py'
+ bandit -r backend/app builtin-extensions -f json -o bandit-report.json --exit-zero
+ python scripts/check-bandit-report.py bandit-report.json
+
+ - name: Upload full Bandit report
+ if: always()
+ uses: actions/upload-artifact@v4
+ with:
+ name: bandit-report
+ path: bandit-report.json
+ if-no-files-found: warn
# ──────────────────────────────────────────────────────────────────
# Job 2: pip-audit — dependency vulnerability scanning (the gate)
@@ -87,6 +94,28 @@ jobs:
- name: Audit test-harness requirements
run: pip-audit -r scripts/test/harness/requirements.txt --progress-spinner off
+ - name: Audit extension requirements
+ shell: bash
+ run: |
+ while IFS= read -r -d '' requirements; do
+ pip-audit -r "$requirements" --progress-spinner off
+ done < <(find builtin-extensions -type f -name 'requirements*.txt' -print0)
+
+ npm-audit:
+ name: Frontend Production Dependency Scan
+ runs-on: ubuntu-latest
+ steps:
+ - uses: actions/checkout@v4
+ - uses: actions/setup-node@v4
+ with:
+ node-version: '22'
+ cache: npm
+ cache-dependency-path: frontend/package-lock.json
+ - name: Audit production dependency lockfile
+ working-directory: frontend
+ # No installation or package scripts are needed to audit the lockfile.
+ run: npm audit --package-lock-only --omit=dev --audit-level=high
+
# ──────────────────────────────────────────────────────────────────
# Job 3: Safety — advisory only
#
diff --git a/scripts/check-bandit-report.py b/scripts/check-bandit-report.py
new file mode 100644
index 00000000..f0e6a692
--- /dev/null
+++ b/scripts/check-bandit-report.py
@@ -0,0 +1,89 @@
+"""Gate HIGH/HIGH Bandit findings with explicit, function-scoped exceptions.
+
+Run from the repository root after producing a Bandit JSON report. Only
+git-tracked sources are evaluated, excluding locally installed plugin copies.
+An exception binds to a path, rule, function AST and occurrence count: adding
+another unsafe call or changing its guard requires reviewing the exception.
+"""
+import ast
+from collections import Counter
+import hashlib
+import json
+from pathlib import Path
+import subprocess
+import sys
+
+
+def normalized_path(filename):
+ return filename.replace('\\', '/').removeprefix('./')
+
+
+def function_fingerprint(root, filename, line):
+ tree = ast.parse((root / filename).read_text(encoding='utf-8-sig'))
+ matches = []
+
+ def visit(node, scope=''):
+ if isinstance(node, (ast.ClassDef, ast.FunctionDef, ast.AsyncFunctionDef)):
+ scope = f'{scope}.{node.name}'.lstrip('.')
+ if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ if node.lineno <= line <= node.end_lineno:
+ matches.append((node.end_lineno - node.lineno, scope, node))
+ for child in ast.iter_child_nodes(node):
+ visit(child, scope)
+
+ visit(tree)
+ if not matches:
+ return '<module>', hashlib.sha256(ast.dump(tree).encode()).hexdigest()
+ _, scope, node = min(matches, key=lambda match: match[0])
+ return scope, hashlib.sha256(ast.dump(node).encode()).hexdigest()
+
+
+def check_report(report, exceptions, root, tracked):
+ failures, accepted = [], Counter()
+ expected = {}
+ for entry in exceptions:
+ key = (entry['path'], entry['test_id'], entry['function'], entry['sha256'])
+ if key in expected or not entry.get('reason') or entry.get('count') != 1:
+ raise ValueError('Each exception must be unique, documented and accept exactly one finding')
+ expected[key] = entry['count']
+
+ for error in report.get('errors', []):
+ if normalized_path(error['filename']) in tracked:
+ failures.append(f"Scan error: {error['filename']}: {error['reason']}")
+
+ for issue in report['results']:
+ filename = normalized_path(issue['filename'])
+ if filename not in tracked:
+ continue
+ if (issue['issue_severity'], issue['issue_confidence']) != ('HIGH', 'HIGH'):
+ continue
+ function, fingerprint = function_fingerprint(root, filename, issue['line_number'])
+ key = (filename, issue['test_id'], function, fingerprint)
+ accepted[key] += 1
+ if accepted[key] > expected.get(key, 0):
+ failures.append(f"{filename}:{issue['line_number']} {issue['test_id']}: {issue['issue_text']}")
+
+ for key, count in expected.items():
+ if accepted[key] < count:
+ failures.append(f'Stale or changed exception: {key[0]} {key[1]} {key[2]}; review or remove it')
+ return failures
+
+
+def main():
+ root = Path(__file__).resolve().parents[1]
+ report = json.loads(Path(sys.argv[1]).read_text(encoding='utf-8'))
+ exceptions = json.loads((root / 'scripts/security/bandit-exceptions.json').read_text())['exceptions']
+ tracked = set(subprocess.check_output(
+ ['git', 'ls-files', '-z'], cwd=root, text=True).split('\0'))
+ failures = check_report(report, exceptions, root, tracked)
+ for failure in failures:
+ print(failure)
+ if failures:
+ print(f'Bandit gate failed: {len(failures)} issue(s).')
+ return 1
+ print(f'Bandit HIGH/HIGH gate passed; {len(exceptions)} explicit findings accepted.')
+ return 0
+
+
+if __name__ == '__main__':
+ sys.exit(main())
diff --git a/scripts/security/README.md b/scripts/security/README.md
new file mode 100644
index 00000000..70add14a
--- /dev/null
+++ b/scripts/security/README.md
@@ -0,0 +1,26 @@
+# Security scan exceptions
+
+Security Scan runs weekly and on relevant changes. Bandit scans backend and
+builtin-extension Python sources; the full report is uploaded even if the gate
+fails. HIGH severity / HIGH confidence findings block CI. Lower-level findings
+remain visible in the report.
+
+Run the same gate locally with Python 3.11 and Bandit 1.9.3:
+
+```sh
+python -m unittest discover -s scripts/security -p 'test_*.py'
+bandit -r backend/app builtin-extensions -f json -o bandit-report.json --exit-zero
+python scripts/check-bandit-report.py bandit-report.json
+```
+
+The gate evaluates git-tracked source files; locally installed copies of
+extensions are excluded because their canonical source is in `builtin-extensions`.
+The exception file accepts two specific findings in the existing admin-only FTP
+connection probe. FTP still transmits credentials without encryption; this is a
+documented compatibility limitation, not an assertion that the protocol is safe.
+
+Each exception binds its rule to one function's AST fingerprint and one finding.
+Changing the function, adding another finding, or fixing an accepted finding
+requires reviewing and updating/removing the entry. Do not regenerate exceptions
+from an entire report or suppress a Bandit category. Review the function, its
+callers and guards, record the justification/date, and update only that entry.
diff --git a/scripts/security/bandit-exceptions.json b/scripts/security/bandit-exceptions.json
new file mode 100644
index 00000000..95651525
--- /dev/null
+++ b/scripts/security/bandit-exceptions.json
@@ -0,0 +1,23 @@
+{
+ "bandit_version": "1.9.3",
+ "exceptions": [
+ {
+ "path": "builtin-extensions/serverkit-ftp/backend/ftp_service.py",
+ "test_id": "B402",
+ "function": "FTPService.test_connection",
+ "sha256": "77ea0cc9afcb77e596beea5a8d9fc63786807bcb9a190f4d0dc8070bdb5195ba",
+ "count": 1,
+ "reviewed_on": "2026-09-05",
+ "reason": "Existing FTP-management compatibility probe: admin-only POST /api/v1/ftp/test explicitly authenticates to an operator-selected legacy FTP server. FTP credentials are unencrypted; this remains a known protocol limitation, not a safe general-purpose transport. Acceptance is limited to this unchanged function; migrate the probe to explicit FTPS/SFTP support before retiring it."
+ },
+ {
+ "path": "builtin-extensions/serverkit-ftp/backend/ftp_service.py",
+ "test_id": "B321",
+ "function": "FTPService.test_connection",
+ "sha256": "77ea0cc9afcb77e596beea5a8d9fc63786807bcb9a190f4d0dc8070bdb5195ba",
+ "count": 1,
+ "reviewed_on": "2026-09-05",
+ "reason": "Existing FTP-management compatibility probe: admin-only POST /api/v1/ftp/test explicitly authenticates to an operator-selected legacy FTP server. FTP credentials are unencrypted; this remains a known protocol limitation, not a safe general-purpose transport. Acceptance is limited to this unchanged function; migrate the probe to explicit FTPS/SFTP support before retiring it."
+ }
+ ]
+}
diff --git a/scripts/security/test_bandit_gate.py b/scripts/security/test_bandit_gate.py
new file mode 100644
index 00000000..500e7d26
--- /dev/null
+++ b/scripts/security/test_bandit_gate.py
@@ -0,0 +1,65 @@
+"""The security gate must reject new findings even in an excepted function."""
+import copy
+import importlib.util
+from pathlib import Path
+import tempfile
+import unittest
+
+
+spec = importlib.util.spec_from_file_location(
+ 'bandit_gate', Path(__file__).resolve().parents[1] / 'check-bandit-report.py')
+gate = importlib.util.module_from_spec(spec)
+spec.loader.exec_module(gate)
+
+
+class BanditGateTests(unittest.TestCase):
+ def setUp(self):
+ self.directory = tempfile.TemporaryDirectory()
+ self.addCleanup(self.directory.cleanup)
+ self.root = Path(self.directory.name)
+ self.file = self.root / 'example.py'
+ self.file.write_text('def legacy():\n return unsafe()\n')
+ function, sha = gate.function_fingerprint(self.root, 'example.py', 2)
+ self.exceptions = [{
+ 'path': 'example.py', 'test_id': 'B321', 'function': function,
+ 'sha256': sha, 'count': 1, 'reason': 'Synthetic reviewed fixture',
+ }]
+ self.issue = {
+ 'filename': './example.py', 'test_id': 'B321', 'line_number': 2,
+ 'issue_severity': 'HIGH', 'issue_confidence': 'HIGH',
+ 'issue_text': 'synthetic finding',
+ }
+
+ def check(self, results=None, errors=None):
+ return gate.check_report(
+ {'results': [self.issue] if results is None else results, 'errors': errors or []},
+ self.exceptions, self.root, {'example.py'})
+
+ def test_exact_accepted_finding_passes(self):
+ self.assertEqual(self.check(), [])
+
+ def test_duplicate_finding_in_accepted_function_fails(self):
+ self.assertTrue(self.check([self.issue, copy.deepcopy(self.issue)]))
+
+ def test_changed_function_requires_review(self):
+ self.file.write_text('def legacy():\n return unsafe(other_secret)\n')
+ self.assertTrue(self.check())
+
+ def test_new_finding_in_same_file_is_not_accepted(self):
+ self.file.write_text(self.file.read_text() + '\ndef additional():\n return unsafe()\n')
+ issue = dict(self.issue, line_number=5)
+ self.assertTrue(self.check([self.issue, issue]))
+
+ def test_unused_exception_must_be_removed(self):
+ self.assertTrue(self.check([]))
+
+ def test_scanner_errors_fail_closed(self):
+ self.assertTrue(self.check(errors=[{'filename': './example.py', 'reason': 'syntax error'}]))
+
+ def test_runtime_plugin_copies_are_not_baselined(self):
+ copied = dict(self.issue, filename='backend/app/plugins/local-copy.py')
+ self.assertEqual(self.check([self.issue, copied]), [])
+
+
+if __name__ == '__main__':
+ unittest.main()