Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
166 changes: 93 additions & 73 deletions backend/app/worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down
33 changes: 33 additions & 0 deletions backend/tests/test_worker.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Loading