From f7803e89dedafdcc253c53dd4cb509cc984c6068 Mon Sep 17 00:00:00 2001 From: danishkumar26 Date: Fri, 27 Nov 2026 21:05:30 +0000 Subject: [PATCH] fix: mark jobs failed and audit when job payload is invalid JSON run_job() let json.loads() of a corrupt job.payload escape uncaught, crashing the worker and leaving the job stuck in 'running' with no job.execute.failed audit (issue #19). The payload parse and target assessment now run under one failure handler: any parse or execution error marks the job failed, commits, writes the job.execute.failed audit entry, and returns {"job_id": ..., "status": "failed"} so the worker keeps processing other jobs. Adds regression test test_run_job_fails_when_payload_is_invalid_json. 56/56 tests pass; ruff, ruff format, mypy clean. --- backend/app/worker.py | 166 ++++++++++++++++++++--------------- backend/tests/test_worker.py | 33 +++++++ 2 files changed, 126 insertions(+), 73 deletions(-) diff --git a/backend/app/worker.py b/backend/app/worker.py index 8e74f5d..b2011de 100644 --- a/backend/app/worker.py +++ b/backend/app/worker.py @@ -62,84 +62,104 @@ def run_job(job_id: str, db: Session | None = None) -> dict: target_type = ( engine.supported_target_types[0] if engine.supported_target_types else "" ) - payload_text = job.payload - payload = json.loads(payload_text) if isinstance(payload_text, str) else None - targets: list[str] = ( - payload.get("targets", []) if isinstance(payload, dict) else [] - ) - - assessment = db.get(Assessment, job.assessment_id) - project = ( - db.get(Project, assessment.project_id) if assessment is not None else None - ) - - for target in targets: - if not isinstance(target, str): - continue - if project is None: - continue - scope = ( - db.query(Scope) - .filter_by( - project_id=project.id, - target=target, - target_type=target_type, - is_authorized=True, - ) - .first() + try: + payload_text = job.payload + payload = ( + json.loads(payload_text) if isinstance(payload_text, str) else None ) - if scope is None: - continue - try: - result = engine.execute(target, target_type) - except Exception as exc: # noqa: BLE001 — fail the job, never crash the worker - db.execute( - sa_update(Job).where(Job.id == job.id).values(status="failed") - ) - db.commit() - db.refresh(job) - _audit( - db, - None, - "job.execute.failed", - "job", - job.id, - json.dumps( - {"engine": job.engine, "target": target, "error": str(exc)} - ), - ) - db.commit() - return {"job_id": job_id, "status": "failed"} - asset = ( - db.query(Asset) - .filter_by( - organization_id=project.organization_id, - project_id=project.id, - target=target, - target_type=target_type, - ) - .first() + targets: list[str] = ( + payload.get("targets", []) if isinstance(payload, dict) else [] ) - if asset is None: - asset = Asset( - organization_id=project.organization_id, - project_id=project.id, - scope_id=scope.id, - target=target, - target_type=target_type, - is_active=True, + + assessment = db.get(Assessment, job.assessment_id) + project = ( + db.get(Project, assessment.project_id) + if assessment is not None + else None + ) + + for target in targets: + if not isinstance(target, str): + continue + if project is None: + continue + scope = ( + db.query(Scope) + .filter_by( + project_id=project.id, + target=target, + target_type=target_type, + is_authorized=True, + ) + .first() ) - db.add(asset) - db.flush() - for observation in result.observations: - db.add( - AssetObservation( - asset_id=asset.id, - job_id=job.id, - observation_type=observation["observation_type"], - value=observation["value"], + if scope is None: + continue + try: + result = engine.execute(target, target_type) + except Exception as exc: # noqa: BLE001 — fail the job, never crash the worker + db.execute( + sa_update(Job).where(Job.id == job.id).values(status="failed") ) + db.commit() + db.refresh(job) + _audit( + db, + None, + "job.execute.failed", + "job", + job.id, + json.dumps( + {"engine": job.engine, "target": target, "error": str(exc)} + ), + ) + db.commit() + return {"job_id": job_id, "status": "failed"} + asset = ( + db.query(Asset) + .filter_by( + organization_id=project.organization_id, + project_id=project.id, + target=target, + target_type=target_type, + ) + .first() ) + if asset is None: + asset = Asset( + organization_id=project.organization_id, + project_id=project.id, + scope_id=scope.id, + target=target, + target_type=target_type, + is_active=True, + ) + db.add(asset) + db.flush() + for observation in result.observations: + db.add( + AssetObservation( + asset_id=asset.id, + job_id=job.id, + observation_type=observation["observation_type"], + value=observation["value"], + ) + ) + except Exception as exc: # noqa: BLE001 — fail the job, never crash the worker + db.execute(sa_update(Job).where(Job.id == job.id).values(status="failed")) + db.commit() + db.refresh(job) + _audit( + db, + None, + "job.execute.failed", + "job", + job.id, + json.dumps({"engine": job.engine, "error": str(exc)}), + ) + db.commit() + return {"job_id": job_id, "status": "failed"} + db.execute(sa_update(Job).where(Job.id == job.id).values(status="completed")) db.commit() db.refresh(job) diff --git a/backend/tests/test_worker.py b/backend/tests/test_worker.py index bd239b0..10a8ef0 100644 --- a/backend/tests/test_worker.py +++ b/backend/tests/test_worker.py @@ -231,3 +231,36 @@ def test_run_job_skips_unauthorized_targets(client, db_session, monkeypatch): assert db_session.query(Asset).count() == 0 assert db_session.query(AssetObservation).count() == 0 + + +def test_run_job_fails_when_payload_is_invalid_json(client, db_session): + headers = signup(client, "wbadjson") + org_id = create_organization(client, headers, "Org WBADJSON", "org-wbadjson") + _project, assessment = _make_assessment_chain(db_session, org_id) + # corrupt payload simulates out-of-band DB corruption; the API always + # json.dumps()s payloads it writes + job = Job( + id=str(uuid.uuid4()), + assessment_id=assessment.id, + engine="discover.dns", + execution_class="PASSIVE", + status="queued", + payload="{not valid json", + ) + db_session.add(job) + db_session.flush() + + result = run_job(job.id, db=db_session) + assert result == {"job_id": job.id, "status": "failed"} + + db_session.expire_all() + job = db_session.get(Job, job.id) + assert job.status == "failed" + + audit = ( + db_session.query(AuditLog) + .filter_by(action="job.execute.failed", target_type="job") + .first() + ) + assert audit is not None + assert "Expecting" in audit.details