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
10 changes: 10 additions & 0 deletions DECISIONS.md
Original file line number Diff line number Diff line change
Expand Up @@ -67,3 +67,13 @@ Context: Jobs are submitted with an explicit engine and execution class, but not
Decision: Job submission runs the job's registered engine synchronously in the request, stores observations as assets/asset_observations traced to the job, and marks the job completed or failed. Only targets covered by an authorized scope of the project are assessed, so execution never leaves the target allowlist. Unregistered engines are rejected with 400 before any job row is created.

Consequences: Simple and fully tested against SQLite with no new infrastructure. Request latency includes engine runtime (shortcut: ceiling = low job volume and fast passive checks; upgrade = Redis-backed worker that pulls queued jobs and reports status asynchronously).

## ADR-008 — Run jobs through a Redis-backed RQ worker

Status: Accepted

Context: Jobs run synchronously inside the HTTP request (ADR-007), so one job blocks the caller until every target is assessed; ceiling: low job volume with fast passive checks.

Decision: Job submission enqueues ``run_job`` (backend/app/worker.py) on an RQ ``jobs`` queue in Redis (already part of the docker-compose stack) and returns the job row as ``queued``. A worker process (``rq worker jobs``) pulls jobs, runs the engine, and marks each job completed or failed. ``run_job(job_id, db=None)`` opens its own session when run by the worker and accepts an injected session for tests. No schema change.

Consequences: submission returns promptly; clients poll GET /api/v1/jobs/{id}; a worker process must run alongside the API (added to docker-compose.yml); engine failures still mark the job failed and write a job.execute.failed audit entry.
11 changes: 6 additions & 5 deletions PROJECT_STATUS.md
Original file line number Diff line number Diff line change
Expand Up @@ -18,6 +18,7 @@ Current development phase: **Phase 1 — Foundation** (in development).
- Discovery SDK + passive DNS discovery engine (PR #12): shared Engine interface and registry (backend/app/engines/), DnsResolutionEngine (discover.dns), standard-library-only passive resolution; 6 tests
- Findings CRUD API (PR #16): POST /api/v1/findings/ (create), GET /api/v1/findings/ (list) and GET /api/v1/findings/{id} (get), tenant-scoped to the assessment's organization; FindingCreate/FindingOut schemas; 6 new tests; 44/44 pass; ruff, ruff format, mypy clean
- Evidence service CRUD API (PR #17): POST /api/v1/evidence/ (create), GET /api/v1/evidence/ (list) and GET /api/v1/evidence/{id} (get), job-scoped and tenant-scoped to the job's assessment's organization; EvidenceCreate/EvidenceOut schemas with SHA-256 hex-digest validation; 6 new tests; 50/50 pass; ruff, ruff format, mypy clean
- Async job worker (commit 195d200): job submission enqueues engine execution to an RQ queue on Redis instead of running synchronously in the HTTP request; worker (backend/app/worker.py) assesses allowlisted targets only, stores assets/asset_observations, marks jobs completed or failed, and audits job.execute / job.execute.failed; 5 new worker tests; 55/55 pass; ruff, ruff format, mypy clean
- Discovery engine wired into job execution (PR #13): jobs submitted via POST /api/v1/assessments/{assessment_id}/jobs/ run their registered engine synchronously against payload targets; only targets covered by an authorized project scope are assessed; observations stored as assets/asset_observations traced to the job; job status completed/failed; job.submit and job.execute audited; unregistered engines rejected with 400; 3 new tests; 37/37 tests pass; ruff, ruff format, mypy all clean
- GitHub issue templates (bug report, feature request, security vulnerability) and pull request template added
- Phase 1 backlog issues created: #1 assessment_profiles/assets/asset_observations migration (DONE via PR #8), #2 assessment profile CRUD endpoints (DONE via PR #8), #3 job submission/queue endpoints with execution-class validation (DONE via PR #9), #4 discovery asset model + scope allowlist validation (DONE via PR #10), #5 CI workflow fix
Expand All @@ -26,7 +27,7 @@ Current development phase: **Phase 1 — Foundation** (in development).
- Daily automation: Hermes cron job 'openpentest-daily-development' scheduled at 0 21 * * * (21:00 UTC = 02:00 PKT, within the preferred 01:00–04:00 PKT window)

## Features under development
- Assessment module: worker infrastructure
- None in flight (worker infrastructure landed via commit 195d200).

## Pending features
- Discovery module (asset model, scope management, asset import, initial discovery engine)
Expand Down Expand Up @@ -60,13 +61,13 @@ Modular monolith control plane (FastAPI) + PostgreSQL + Redis + MinIO, independe
- None (no released code yet).

## Latest successful test results
- 50/50 pytest pass locally against SQLite (38 existing + 6 findings + 6 evidence); ruff check clean; ruff format clean; mypy backend/app clean. CI green on PR #17: lint, type-check, test, secret-scan all pass.
- 55/55 pytest pass locally against SQLite (50 existing + 5 worker); ruff check clean; ruff format clean; mypy backend/app clean. CI green on main (lint, type-check, test, secret-scan; strict).
- Alembic migration 0003_target_type_check verified: registers as head; `alembic upgrade head --sql` produces valid PostgreSQL DDL.

- Latest Git commit
- 98e7739 Merge PR #17 — evidence service CRUD endpoints; squash-merged to main; CI green on main (lint, type-check, test, secret-scan; strict)
## Latest Git commit
- 195d200 feat: run jobs asynchronously through a Redis-backed worker (RQ); on feature/async-job-worker, CI pending via pull request.

## Next recommended tasks
1. Run ruff/mypy/pytest before every commit; keep CI green on main
2. Phase 3 follow-up: additional assessment engines (Nuclei, Trivy) and/or worker infrastructure; evidence service (job-scoped evidence, SHA-256) done via PR #17; finding schema (CRUD) done via PR #16
2. Phase 3 follow-up: additional assessment engines (Nuclei, Trivy) against the finding schema; worker infrastructure done via commit 195d200
3. Next daily cron run at 21:00 UTC (02:00 PKT)
2 changes: 1 addition & 1 deletion ROADMAP.md
Original file line number Diff line number Diff line change
Expand Up @@ -24,7 +24,7 @@ Development is incremental; working features ship before ambitious ones. Status

## Phase 3 — Assessment (Planned)
- Engine SDK
- Worker infrastructure
- Worker infrastructure — Supported
- Finding schema — Supported (findings CRUD API landed via PR #16)
- Nuclei integration
- Trivy integration
Expand Down
127 changes: 20 additions & 107 deletions backend/app/api/v1/assessments.py
Original file line number Diff line number Diff line change
Expand Up @@ -9,25 +9,24 @@
import json
from typing import Annotated

import redis as redis_lib
from fastapi import APIRouter, Depends, HTTPException, status
from sqlalchemy import update as sa_update
from rq import Queue
from sqlalchemy.orm import Session

from app.api.deps import (
ensure_organization_access,
get_current_user,
get_db,
)
from app.core.config import settings
from app.engines.registry import get as get_engine
from app.models.core import (
Assessment,
Asset,
AssetObservation,
AuditLog,
Job,
Membership,
Project,
Scope,
User,
)
from app.schemas.core import (
Expand All @@ -37,6 +36,7 @@
JobCreate,
JobOut,
)
from app.worker import run_job

router = APIRouter(tags=["assessments"])

Expand All @@ -53,11 +53,16 @@ def _validate_execution_class(execution_class: str) -> None:


def _audit(
db: Session, current_user, action: str, target_type: str, target_id, details: str
db: Session,
user_id: str | None,
action: str,
target_type: str,
target_id,
details: str,
) -> None:
db.add(
AuditLog(
user_id=current_user.id,
user_id=user_id,
action=action,
target_type=target_type,
target_id=str(target_id),
Expand Down Expand Up @@ -215,10 +220,12 @@ def submit_job(
db.add(job)
db.commit()
db.refresh(job)
_run_job(db, job, job_in.payload, project, current_user)
# Commit the job row before enqueuing: a submission stays visible as
# "queued" even if the queue is temporarily down.
_enqueue(str(job.id))
_audit(
db,
current_user,
str(current_user.id),
"job.submit",
"job",
job.id,
Expand All @@ -234,104 +241,10 @@ def submit_job(
return job


def _run_job(
db: Session,
job: Job,
payload: dict | None,
project: Project,
current_user: User,
) -> None:
"""Run a queued job through its registered engine and store observations.

shortcut: engines run synchronously in the HTTP request, so one job
blocks the caller until every target is assessed; ceiling: low job
volume with fast passive checks; upgrade: a Redis-backed worker
(architecture layers 6 and 8) that pulls queued jobs and reports
status asynchronously.
def _get_queue() -> Queue:
return Queue("jobs", connection=redis_lib.Redis.from_url(settings.REDIS_URL))

Only targets covered by an authorized scope of the project are
assessed, so job execution never leaves the target allowlist.
"""
engine = get_engine(str(job.engine))
if engine is None:
db.execute(sa_update(Job).where(Job.id == job.id).values(status="failed"))
db.commit()
return

target_type = (
engine.supported_target_types[0] if engine.supported_target_types else ""
)
targets = payload.get("targets", []) if isinstance(payload, dict) else []
for target in targets:
if not isinstance(target, str):
continue
scope = (
db.query(Scope)
.filter_by(
project_id=project.id,
target=target,
target_type=target_type,
is_authorized=True,
)
.first()
)
if scope is None:
continue
try:
result = engine.execute(target, target_type)
except Exception as exc: # noqa: BLE001 — engine failure: fail the job instead of a 500 or a stuck "queued" job
db.execute(sa_update(Job).where(Job.id == job.id).values(status="failed"))
db.commit()
db.refresh(job)
_audit(
db,
current_user,
"job.execute.failed",
"job",
job.id,
json.dumps({"engine": job.engine, "target": target, "error": str(exc)}),
)
db.commit()
return
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"],
)
)
db.execute(sa_update(Job).where(Job.id == job.id).values(status="completed"))
db.commit()
db.refresh(job)
_audit(
db,
current_user,
"job.execute",
"job",
job.id,
json.dumps({"engine": job.engine, "targets": len(targets)}),
)
db.commit()
def _enqueue(job_id: str) -> None:
"""Queue one job for the Redis worker (rq worker jobs)."""
_get_queue().enqueue(run_job, job_id)
Loading
Loading