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.

refactor(security): run durable scans through job system

Juan Denisf744646b3fd9
diff --git a/backend/app/api/security.py b/backend/app/api/security.py
index d5625c78..4f6df5b8 100644
--- a/backend/app/api/security.py
+++ b/backend/app/api/security.py
@@ -4,6 +4,7 @@ from flask import Blueprint, request, jsonify
from flask_jwt_extended import jwt_required
from app.middleware.rbac import admin_required
from app.services.security_service import SecurityService
+from app.services.image_scanner_service import ImageScannerService
from app.services.malware_scan_service import MalwareScanService
from app.services.yara_scan_service import YaraScanService
@@ -13,6 +14,8 @@ security_bp = Blueprint('security', __name__)
# imported by create_app); registration is idempotent and also re-asserted on
# every enqueue.
MalwareScanService.register_jobs()
+ImageScannerService.register_jobs()
+SecurityService.register_jobs()
# ==========================================
@@ -527,7 +530,6 @@ def disable_auto_updates():
@admin_required
def install_image_scanner():
"""Install grype and syft scanner binaries."""
- from app.services.image_scanner_service import ImageScannerService
grype = ImageScannerService.install_grype()
syft = ImageScannerService.install_syft()
return jsonify({'grype': grype, 'syft': syft}), 200
@@ -537,7 +539,6 @@ def install_image_scanner():
@admin_required
def scan_application_image(application_id):
"""Trigger a CVE scan for an application image."""
- from app.services.image_scanner_service import ImageScannerService
result = ImageScannerService.scan_application(application_id)
return jsonify(result), 200 if result['success'] else 400
@@ -546,7 +547,6 @@ def scan_application_image(application_id):
@admin_required
def get_application_image_scans(application_id):
"""Get scan history for an application."""
- from app.services.image_scanner_service import ImageScannerService
limit = request.args.get('limit', 20, type=int)
scans = ImageScannerService.scan_history(application_id, limit=limit)
latest = ImageScannerService.latest_scan(application_id)
diff --git a/backend/app/jobs/thread_ownership.py b/backend/app/jobs/thread_ownership.py
new file mode 100644
index 00000000..505ddac3
--- /dev/null
+++ b/backend/app/jobs/thread_ownership.py
@@ -0,0 +1,177 @@
+"""Ownership registry for raw ``threading.Thread`` call sites.
+
+Raw threads are allowed only when their lifecycle is intentionally coupled to
+the process/request or when a persisted parent operation already owns recovery.
+Bounded user work that needs restart recovery, retries, or global observability
+belongs in :class:`app.jobs.service.JobService` instead.
+
+``backend/tests/test_thread_ownership.py`` keeps this registry exact: adding or
+removing a raw thread requires an explicit lifecycle decision here.
+"""
+
+LIFECYCLE_PROCESS_LOOP = 'process_loop'
+LIFECYCLE_REQUEST_STREAM = 'request_stream'
+LIFECYCLE_BOUNDED_DELIVERY = 'bounded_delivery'
+LIFECYCLE_BOUNDED_FANOUT = 'bounded_fanout'
+LIFECYCLE_DURABLE_CANDIDATE = 'durable_candidate'
+
+
+THREAD_OWNERSHIP = {
+ 'app/api/ai.py:chat_stream:producer': {
+ 'owner': 'AI SSE response',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Producer lifetime is coupled to one streaming HTTP response.',
+ },
+ 'app/jobs/consumer.py:start:self._run': {
+ 'owner': 'unified job runtime',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'The process-level consumer is the executor for durable jobs.',
+ },
+ 'app/jobs/scheduler.py:start:self._run': {
+ 'owner': 'unified job runtime',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'The process-level ticker publishes persisted scheduled jobs.',
+ },
+ 'app/middleware/api_analytics.py:start_analytics_flush_thread:flush_loop': {
+ 'owner': 'API analytics middleware',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Flushes an in-memory request metrics buffer owned by this process.',
+ },
+ 'app/notifications/consumer.py:start:self._run': {
+ 'owner': 'notification queue',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived consumer for already-persisted notification messages.',
+ },
+ 'app/plugins/serverkit-analytics/ingest_service.py:ensure_flush_thread:_flush_loop': {
+ 'owner': 'analytics extension ingest',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Flushes an in-memory analytics batch owned by this process.',
+ },
+ 'app/queue_bus/consumers/webhook_consumer.py:start:self._run': {
+ 'owner': 'webhook queue',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived consumer for persisted webhook messages.',
+ },
+ 'app/services/agent_fleet_service.py:staged_rollout:self._run_staged_rollout': {
+ 'owner': 'agent fleet rollout',
+ 'lifecycle': LIFECYCLE_DURABLE_CANDIDATE,
+ 'rationale': 'User-triggered bounded rollout; migrate after restart/resume semantics are specified.',
+ },
+ 'app/services/agent_fleet_service.py:retry_command:self._deliver_single_command': {
+ 'owner': 'agent command delivery',
+ 'lifecycle': LIFECYCLE_BOUNDED_DELIVERY,
+ 'rationale': 'Low-latency delivery attempt is owned and recoverable by its persisted command row.',
+ },
+ 'app/services/agent_fleet_service.py:upgrade_servers:agent_registry.send_command': {
+ 'owner': 'agent fleet upgrade',
+ 'lifecycle': LIFECYCLE_BOUNDED_FANOUT,
+ 'rationale': 'Parallel delivery fan-out creates persisted agent command state.',
+ },
+ 'app/services/agent_fleet_service.py:deliver_queued_commands:self._deliver_single_command': {
+ 'owner': 'agent command delivery',
+ 'lifecycle': LIFECYCLE_BOUNDED_DELIVERY,
+ 'rationale': 'Delivery attempt is selected from and recorded in the persisted command queue.',
+ },
+ 'app/services/agent_fleet_service.py:process_scheduled_retries:self._deliver_single_command': {
+ 'owner': 'agent command retry',
+ 'lifecycle': LIFECYCLE_BOUNDED_DELIVERY,
+ 'rationale': 'Retry attempt is scheduled and tracked by the persisted command row.',
+ },
+ 'app/services/agent_registry.py:_start_heartbeat_checker:self._check_heartbeats': {
+ 'owner': 'agent registry',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived liveness checker for connected agents.',
+ },
+ 'app/services/anomaly_detection_service.py:__init__:self._cleanup_loop': {
+ 'owner': 'anomaly detector',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Maintains process-local anomaly detector state and retention.',
+ },
+ 'app/services/discovery_service.py:start_scan:self._listen_for_responses': {
+ 'owner': 'LAN discovery session',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Bounded UDP listener belongs to one active discovery window.',
+ },
+ 'app/services/environment_health_service.py:_dispatch_health_alert:_send': {
+ 'owner': 'environment health alerts',
+ 'lifecycle': LIFECYCLE_DURABLE_CANDIDATE,
+ 'rationale': 'Alert delivery should move to the notification queue after deduplication is defined.',
+ },
+ 'app/services/linked_panel_agent.py:start:self._run': {
+ 'owner': 'linked-panel agent',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived poll loop maintaining the linked-panel connection.',
+ },
+ 'app/services/linked_panel_agent.py:_poll_loop:self._dispatch': {
+ 'owner': 'linked-panel dispatch',
+ 'lifecycle': LIFECYCLE_BOUNDED_DELIVERY,
+ 'rationale': 'Parallel dispatch prevents one remote request from blocking the poll loop.',
+ },
+ 'app/services/log_service.py:start_stream:LogService.tail_log': {
+ 'owner': 'log stream session',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Tail lifetime is coupled to a caller-provided stop event.',
+ },
+ 'app/services/metrics_history_service.py:start_collection:collection_loop': {
+ 'owner': 'metrics history collector',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived host metrics sampler.',
+ },
+ 'app/services/monitoring_service.py:start_monitoring:cls._monitor_loop': {
+ 'owner': 'legacy monitoring runtime',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived monitor loop; periodic migration is separate from one-shot work.',
+ },
+ 'app/services/nonce_service.py:__init__:self._cleanup_loop': {
+ 'owner': 'nonce store',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Expires process-local nonce state.',
+ },
+ 'app/services/security_service.py:scan_directory:cls._run_directory_scan': {
+ 'owner': 'legacy ClamAV directory scan',
+ 'lifecycle': LIFECYCLE_DURABLE_CANDIDATE,
+ 'rationale': 'Compatibility endpoint remains; new callers should use security.malware_scan jobs.',
+ },
+ 'app/services/test_sandbox_service.py:start_run:cls._execute': {
+ 'owner': 'test sandbox run',
+ 'lifecycle': LIFECYCLE_DURABLE_CANDIDATE,
+ 'rationale': 'Persisted user run should become a job after cancellation is made job-aware.',
+ },
+ 'app/services/test_sandbox_service.py:_execute:cls._run_distro': {
+ 'owner': 'test sandbox run',
+ 'lifecycle': LIFECYCLE_BOUNDED_FANOUT,
+ 'rationale': 'Parallel distro workers are children of one persisted sandbox run.',
+ },
+ 'app/services/uptime_service.py:start_tracking:cls._tracking_loop': {
+ 'owner': 'uptime tracker',
+ 'lifecycle': LIFECYCLE_PROCESS_LOOP,
+ 'rationale': 'Long-lived uptime sampler.',
+ },
+ 'app/sockets.py:handle_subscribe_logs:emit_logs': {
+ 'owner': 'Socket.IO log subscription',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Emitter lifetime is coupled to one socket subscription.',
+ },
+ 'app/sockets.py:handle_subscribe_container_logs:stream_logs': {
+ 'owner': 'Socket.IO container log subscription',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Emitter lifetime is coupled to one socket subscription.',
+ },
+ 'app/sockets.py:handle_subscribe_metrics:broadcast_metrics': {
+ 'owner': 'Socket.IO metrics subscription',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Broadcaster lifetime is coupled to an active socket subscription set.',
+ },
+ 'app/sockets.py:handle_subscribe_container_status:broadcast_container_status': {
+ 'owner': 'Socket.IO container status subscription',
+ 'lifecycle': LIFECYCLE_REQUEST_STREAM,
+ 'rationale': 'Broadcaster lifetime is coupled to an active socket subscription set.',
+ },
+}
+
+
+MIGRATED_TO_JOBS = {
+ 'ImageScannerService.scan_application': 'security.image_scan',
+ 'SecurityService.run_lynis_scan': 'security.lynis_scan',
+}
+
diff --git a/backend/app/services/image_scanner_service.py b/backend/app/services/image_scanner_service.py
index 497e94cb..2c9215d6 100644
--- a/backend/app/services/image_scanner_service.py
+++ b/backend/app/services/image_scanner_service.py
@@ -16,6 +16,7 @@ logger = logging.getLogger(__name__)
SCANNERS_DIR = '/var/lib/serverkit/scanners'
GRYPE_BIN = os.path.join(SCANNERS_DIR, 'grype')
SYFT_BIN = os.path.join(SCANNERS_DIR, 'syft')
+IMAGE_SCAN_JOB_KIND = 'security.image_scan'
class ImageScannerService:
@@ -180,8 +181,15 @@ class ImageScannerService:
@classmethod
def scan_application(cls, application_id: int) -> Dict:
- """Run a CVE scan for the Docker image of an application."""
- # query_active: a scan spawns Grype and pulls from the registry.
+ """Queue a CVE scan for the Docker image of an application.
+
+ ``scan_id`` and ``status`` are retained for callers of the legacy
+ thread-backed surface; ``job_id`` and ``kind`` expose the durable job
+ that now owns execution, retries, and observability.
+ """
+ from app.jobs.service import JobService
+
+ # query_active: a queued scan pulls from the registry after this request.
app = Application.query_active().filter_by(id=application_id).first()
if not app:
return {'success': False, 'error': 'Application not found'}
@@ -197,30 +205,87 @@ class ImageScannerService:
db.session.add(scan)
db.session.commit()
- def _run():
- try:
- result = cls._run_grype(image_ref)
- scan.completed_at = datetime.utcnow()
- if not result['success']:
- scan.status = 'failed'
- scan.error_message = result.get('error')
- else:
- data = result['data']
- scan.status = 'completed'
- scan.scanner_version = data.get('descriptor', {}).get('version')
- scan.set_counts(cls._parse_grype_counts(data))
- scan.set_findings(cls._normalize_findings(data))
- db.session.commit()
- except Exception as e:
- logger.exception('Image scan failed')
+ cls.register_jobs()
+ try:
+ job = JobService.enqueue(
+ IMAGE_SCAN_JOB_KIND,
+ payload={
+ 'scan_id': scan.id,
+ 'application_id': application_id,
+ 'image_ref': image_ref,
+ },
+ owner_type='application',
+ owner_id=application_id,
+ )
+ except Exception as exc:
+ scan.status = 'failed'
+ scan.error_message = f'Could not enqueue image scan: {exc}'
+ scan.completed_at = datetime.utcnow()
+ db.session.commit()
+ logger.exception('Could not enqueue image scan %s', scan.id)
+ return {'success': False, 'error': scan.error_message, 'scan_id': scan.id}
+
+ return {
+ 'success': True,
+ 'scan_id': scan.id,
+ 'status': 'running',
+ 'job_id': job.id,
+ 'kind': job.kind,
+ }
+
+ @classmethod
+ def run_image_scan_job(cls, job) -> Dict:
+ """Execute one persisted image scan job."""
+ payload = job.get_payload() or {}
+ scan_id = payload.get('scan_id')
+ if scan_id is None:
+ raise ValueError('security.image_scan payload requires scan_id')
+
+ scan = db.session.get(ImageVulnerabilityScan, scan_id)
+ if not scan:
+ raise ValueError(f'Image scan {scan_id} not found')
+
+ image_ref = payload.get('image_ref') or scan.image_ref
+ scan.status = 'running'
+ scan.error_message = None
+ scan.completed_at = None
+ db.session.commit()
+
+ try:
+ result = cls._run_grype(image_ref)
+ if not result.get('success'):
+ raise RuntimeError(result.get('error') or 'Image scanner failed')
+
+ data = result['data']
+ scan.status = 'completed'
+ scan.scanner_version = data.get('descriptor', {}).get('version')
+ scan.set_counts(cls._parse_grype_counts(data))
+ scan.set_findings(cls._normalize_findings(data))
+ scan.completed_at = datetime.utcnow()
+ db.session.commit()
+ return {
+ 'success': True,
+ 'scan_id': scan.id,
+ 'application_id': scan.application_id,
+ 'status': scan.status,
+ 'severity_counts': scan.get_counts(),
+ }
+ except Exception as exc:
+ db.session.rollback()
+ scan = db.session.get(ImageVulnerabilityScan, scan_id)
+ if scan:
scan.status = 'failed'
- scan.error_message = str(e)
+ scan.error_message = str(exc)
scan.completed_at = datetime.utcnow()
db.session.commit()
+ logger.exception('Image scan %s failed', scan_id)
+ raise
- thread = threading.Thread(target=_run, daemon=True)
- thread.start()
- return {'success': True, 'scan_id': scan.id, 'status': 'running'}
+ @classmethod
+ def register_jobs(cls) -> None:
+ """Register the durable image-scan handler (safe to call repeatedly)."""
+ from app.jobs import registry
+ registry.register(IMAGE_SCAN_JOB_KIND, cls.run_image_scan_job, replace=True)
@classmethod
def generate_sbom(cls, application_id: int) -> Dict:
diff --git a/backend/app/services/security_service.py b/backend/app/services/security_service.py
index 8b42bd81..35603236 100644
--- a/backend/app/services/security_service.py
+++ b/backend/app/services/security_service.py
@@ -28,6 +28,8 @@ from app.utils.system import (
run_privileged,
)
+LYNIS_SCAN_JOB_KIND = 'security.lynis_scan'
+
class SecurityService:
"""Service for security scanning and monitoring."""
@@ -1546,12 +1548,18 @@ class SecurityService:
return {'success': False, 'error': str(e)}
_lynis_scan = None
- _lynis_thread = None
@classmethod
def run_lynis_scan(cls) -> Dict:
- """Run a Lynis security audit scan."""
- if cls._lynis_thread and cls._lynis_thread.is_alive():
+ """Queue a durable Lynis security audit scan."""
+ from app.jobs.models import Job
+ from app.jobs.service import JobService
+
+ active = Job.query.filter(
+ Job.kind == LYNIS_SCAN_JOB_KIND,
+ Job.status.in_((Job.STATUS_PENDING, Job.STATUS_RUNNING)),
+ ).order_by(Job.created_at.desc()).first()
+ if active:
return {'success': False, 'error': 'A scan is already in progress'}
status = cls.get_lynis_status()
@@ -1567,14 +1575,45 @@ class SecurityService:
'hardening_index': None
}
- cls._lynis_thread = threading.Thread(target=cls._run_lynis_scan_thread, daemon=True)
- cls._lynis_thread.start()
+ cls.register_jobs()
+ job = JobService.enqueue(
+ LYNIS_SCAN_JOB_KIND,
+ payload={},
+ owner_type='system',
+ owner_id='host',
+ )
+ cls._lynis_scan['job_id'] = job.id
+ cls._lynis_scan['kind'] = job.kind
- return {'success': True, 'message': 'Lynis scan started'}
+ return {
+ 'success': True,
+ 'message': 'Lynis scan started',
+ 'job_id': job.id,
+ 'kind': job.kind,
+ 'status': 'running',
+ }
+
+ @classmethod
+ def run_lynis_scan_job(cls, job) -> Dict:
+ """Unified-job handler for a Lynis audit."""
+ cls._lynis_scan = {
+ 'status': 'running',
+ 'started_at': datetime.now().isoformat(),
+ 'output': '',
+ 'warnings': [],
+ 'suggestions': [],
+ 'hardening_index': None,
+ 'job_id': job.id,
+ 'kind': job.kind,
+ }
+ result = cls._execute_lynis_scan()
+ if result['status'] != 'completed':
+ raise RuntimeError(result.get('error') or f"Lynis scan {result['status']}")
+ return result
@classmethod
- def _run_lynis_scan_thread(cls) -> None:
- """Execute Lynis scan in background thread."""
+ def _execute_lynis_scan(cls) -> Dict:
+ """Execute Lynis and update the compatibility status snapshot."""
try:
result = subprocess.run(
['lynis', 'audit', 'system', '--quick', '--no-colors'],
@@ -1605,13 +1644,40 @@ class SecurityService:
except Exception as e:
cls._lynis_scan['status'] = 'error'
cls._lynis_scan['error'] = str(e)
+ return cls._lynis_scan.copy()
@classmethod
def get_lynis_scan_status(cls) -> Dict:
- """Get current Lynis scan status."""
- if cls._lynis_scan is None:
+ """Get current Lynis status, backed by the latest persisted job."""
+ from app.jobs.models import Job
+
+ job = (Job.query.filter_by(kind=LYNIS_SCAN_JOB_KIND)
+ .order_by(Job.created_at.desc()).first())
+ if job is None and cls._lynis_scan is None:
return {'status': 'idle', 'message': 'No scan in progress'}
- return cls._lynis_scan.copy()
+
+ status = cls._lynis_scan.copy() if cls._lynis_scan else {}
+ if job:
+ status.update({'job_id': job.id, 'kind': job.kind,
+ 'job_status': job.status})
+ if job.status == Job.STATUS_SUCCEEDED and job.get_result():
+ status.update(job.get_result())
+ elif job.status in (Job.STATUS_PENDING, Job.STATUS_RUNNING):
+ status['status'] = 'running'
+ status.setdefault('started_at',
+ (job.started_at or job.created_at).isoformat())
+ elif job.status == Job.STATUS_FAILED:
+ status['status'] = 'error'
+ status['error'] = job.error_message or 'Lynis scan failed'
+ elif job.status == Job.STATUS_CANCELLED:
+ status['status'] = 'cancelled'
+ return status
+
+ @classmethod
+ def register_jobs(cls) -> None:
+ """Register the durable Lynis handler (safe to call repeatedly)."""
+ from app.jobs import registry
+ registry.register(LYNIS_SCAN_JOB_KIND, cls.run_lynis_scan_job, replace=True)
# ==========================================
# AUTOMATIC SECURITY UPDATES
diff --git a/backend/tests/test_security_scan_jobs.py b/backend/tests/test_security_scan_jobs.py
new file mode 100644
index 00000000..475e4aa6
--- /dev/null
+++ b/backend/tests/test_security_scan_jobs.py
@@ -0,0 +1,163 @@
+"""Job-convergence tests for image CVE scans and Lynis audits."""
+
+from unittest.mock import patch
+
+import pytest
+
+from app import db
+from app.jobs.consumer import JobConsumer
+from app.jobs.models import Job
+from app.jobs.service import GROUP_SLUG, QUEUE_SLUG
+from app.models import Application, ImageVulnerabilityScan, User
+from app.queue_bus.service import QueueBusService
+from app.services.image_scanner_service import (
+ IMAGE_SCAN_JOB_KIND,
+ ImageScannerService,
+)
+from app.services.security_service import LYNIS_SCAN_JOB_KIND, SecurityService
+
+
[email protected](autouse=True)
+def isolated_jobs(app):
+ QueueBusService.reset_broker()
+ ImageScannerService.register_jobs()
+ SecurityService.register_jobs()
+ SecurityService._lynis_scan = None
+ yield
+ SecurityService._lynis_scan = None
+
+
+def image_app(app):
+ owner = User(
+ username='image-owner',
+ password_hash='unused',
+ is_active=True,
+ )
+ db.session.add(owner)
+ db.session.flush()
+ application = Application(
+ name='image-scan-app',
+ app_type='docker',
+ docker_image='registry.example.test/demo:latest',
+ user_id=owner.id,
+ )
+ db.session.add(application)
+ db.session.commit()
+ return application
+
+
+def _drain_once():
+ messages = QueueBusService.receive(GROUP_SLUG, QUEUE_SLUG, max_messages=1)
+ assert messages, 'expected one queued job'
+ JobConsumer().process_message(messages[0])
+
+
+def test_image_scan_keeps_legacy_fields_and_runs_as_a_job(image_app, monkeypatch):
+ grype = {
+ 'descriptor': {'version': '1.2.3'},
+ 'matches': [{
+ 'vulnerability': {
+ 'id': 'CVE-TEST-1',
+ 'severity': 'High',
+ 'fix': {'versions': ['2.0']},
+ },
+ 'artifact': {'name': 'demo', 'version': '1.0', 'type': 'deb'},
+ }],
+ }
+ monkeypatch.setattr(
+ ImageScannerService,
+ '_run_grype',
+ classmethod(lambda cls, image_ref: {'success': True, 'data': grype}),
+ )
+
+ response = ImageScannerService.scan_application(image_app.id)
+
+ assert response['success'] is True
+ assert response['status'] == 'running'
+ assert response['scan_id']
+ assert response['job_id']
+ assert response['kind'] == IMAGE_SCAN_JOB_KIND
+ job = db.session.get(Job, response['job_id'])
+ assert job.owner_type == 'application'
+ assert job.owner_id == str(image_app.id)
+ assert job.get_payload()['scan_id'] == response['scan_id']
+
+ _drain_once()
+
+ job = db.session.get(Job, response['job_id'])
+ scan = db.session.get(ImageVulnerabilityScan, response['scan_id'])
+ assert job.status == Job.STATUS_SUCCEEDED
+ assert job.get_result()['scan_id'] == scan.id
+ assert scan.status == 'completed'
+ assert scan.scanner_version == '1.2.3'
+ assert scan.get_counts()['high'] == 1
+ assert scan.get_findings()[0]['id'] == 'CVE-TEST-1'
+
+
+def test_image_scan_api_preserves_200_and_adds_job_identity(
+ client, auth_headers, image_app, monkeypatch):
+ monkeypatch.setattr(
+ ImageScannerService,
+ '_run_grype',
+ classmethod(lambda cls, image_ref: {'success': True, 'data': {'matches': []}}),
+ )
+ response = client.post(
+ f'/api/v1/security/image-scans/applications/{image_app.id}',
+ headers=auth_headers,
+ )
+ assert response.status_code == 200
+ body = response.get_json()
+ assert {'scan_id', 'status', 'job_id', 'kind'} <= set(body)
+ assert body['kind'] == IMAGE_SCAN_JOB_KIND
+
+
+def test_lynis_scan_runs_as_a_job_and_status_remains_compatible(monkeypatch):
+ monkeypatch.setattr(
+ SecurityService,
+ 'get_lynis_status',
+ classmethod(lambda cls: {'installed': True, 'version': '3.1'}),
+ )
+
+ class Completed:
+ returncode = 0
+ stderr = ''
+ stdout = '\n'.join([
+ 'Warning: test warning',
+ 'Suggestion: test suggestion',
+ 'Hardening index : 72 [############## ]',
+ ])
+
+ monkeypatch.setattr('app.services.security_service.subprocess.run',
+ lambda *args, **kwargs: Completed())
+
+ response = SecurityService.run_lynis_scan()
+ assert response['success'] is True
+ assert response['status'] == 'running'
+ assert response['job_id']
+ assert response['kind'] == LYNIS_SCAN_JOB_KIND
+
+ _drain_once()
+
+ job = db.session.get(Job, response['job_id'])
+ status = SecurityService.get_lynis_scan_status()
+ assert job.status == Job.STATUS_SUCCEEDED
+ assert status['status'] == 'completed'
+ assert status['job_id'] == job.id
+ assert status['job_status'] == Job.STATUS_SUCCEEDED
+ assert status['hardening_index'] == 72
+ assert status['warnings'] == ['Warning: test warning']
+ assert status['suggestions'] == ['Suggestion: test suggestion']
+
+
+def test_lynis_rejects_a_second_active_job(monkeypatch):
+ monkeypatch.setattr(
+ SecurityService,
+ 'get_lynis_status',
+ classmethod(lambda cls: {'installed': True, 'version': '3.1'}),
+ )
+ first = SecurityService.run_lynis_scan()
+ second = SecurityService.run_lynis_scan()
+ assert first['success'] is True
+ assert second == {'success': False, 'error': 'A scan is already in progress'}
diff --git a/backend/tests/test_thread_ownership.py b/backend/tests/test_thread_ownership.py
new file mode 100644
index 00000000..d7df7de5
--- /dev/null
+++ b/backend/tests/test_thread_ownership.py
@@ -0,0 +1,81 @@
+"""Structural guard for intentional raw-thread ownership."""
+
+import ast
+from pathlib import Path
+
+from app.jobs.thread_ownership import (
+ LIFECYCLE_BOUNDED_DELIVERY,
+ LIFECYCLE_BOUNDED_FANOUT,
+ LIFECYCLE_DURABLE_CANDIDATE,
+ LIFECYCLE_PROCESS_LOOP,
+ LIFECYCLE_REQUEST_STREAM,
+ THREAD_OWNERSHIP,
+)
+
+
+APP_ROOT = Path(__file__).resolve().parents[1] / 'app'
+BACKEND_ROOT = APP_ROOT.parent
+
+
+def _raw_thread_sites():
+ sites = set()
+ for path in APP_ROOT.rglob('*.py'):
+ tree = ast.parse(path.read_text(encoding='utf-8'), filename=str(path))
+ parents = {}
+ for node in ast.walk(tree):
+ for child in ast.iter_child_nodes(node):
+ parents[child] = node
+
+ for node in ast.walk(tree):
+ if not isinstance(node, ast.Call):
+ continue
+ func = node.func
+ qualified = (
+ isinstance(func, ast.Attribute)
+ and func.attr == 'Thread'
+ and isinstance(func.value, ast.Name)
+ and func.value.id == 'threading'
+ )
+ direct = isinstance(func, ast.Name) and func.id == 'Thread'
+ if not (qualified or direct):
+ continue
+
+ parent = parents.get(node)
+ enclosing = '<module>'
+ while parent is not None:
+ if isinstance(parent, (ast.FunctionDef, ast.AsyncFunctionDef)):
+ enclosing = parent.name
+ break
+ parent = parents.get(parent)
+
+ target = next(
+ (ast.unparse(kw.value) for kw in node.keywords if kw.arg == 'target'),
+ '?',
+ )
+ relative = path.relative_to(BACKEND_ROOT).as_posix()
+ sites.add(f'{relative}:{enclosing}:{target}')
+ return sites
+
+
+def test_every_raw_thread_has_an_exact_owner_classification():
+ discovered = _raw_thread_sites()
+ classified = set(THREAD_OWNERSHIP)
+ assert discovered == classified, (
+ f'unclassified={sorted(discovered - classified)}; '
+ f'stale={sorted(classified - discovered)}'
+ )
+
+
+def test_thread_classifications_are_actionable():
+ valid_lifecycles = {
+ LIFECYCLE_PROCESS_LOOP,
+ LIFECYCLE_REQUEST_STREAM,
+ LIFECYCLE_BOUNDED_DELIVERY,
+ LIFECYCLE_BOUNDED_FANOUT,
+ LIFECYCLE_DURABLE_CANDIDATE,
+ }
+ for site, decision in THREAD_OWNERSHIP.items():
+ assert decision['owner'].strip(), site
+ assert decision['lifecycle'] in valid_lifecycles, site
+ assert decision['rationale'].strip(), site
+