Open-source AI Security Operations Center: alert fusion, LLM-agent triage, MITRE ATT&CK investigation, and a replayable decision ledger for every agent step. Self-hostable, runs with no API keys, MIT licensed. Ships an MCP server for Claude, Cursor and Continue.
Python agentic-aiai-securityalert-triageblue-teamcybersecuritydetection-engineeringincident-responselanggraphllm-agentsmcpmitre-attackmodel-context-protocolpurple-teamsecurity-operationsself-hostedsiemsoarsocthreat-detectionthreat-intelligence
test(hunt-reports): 14 cases, live Postgres, three negative controls in CI
Beenu Arora1fe294187858
diff --git a/.github/workflows/hunt-report-live.yml b/.github/workflows/hunt-report-live.ymlnew file mode 100644index 000000000..1d289f5f2--- /dev/null+++ b/.github/workflows/hunt-report-live.yml@@ -0,0 +1,164 @@+# Hunt reports — through the real app and real Postgres (depth 9.5).+#+# Why live rather than the usual SQLite stand-in: the report row has JSONB+# citations with a `jsonb_typeof` CHECK and two columns named with reserved+# words (`"where"`, `"when"`), and the builders read `alerts.entities`,+# `alerts.affected_hosts` (a JSONB *array*, not the singular text column a+# reader expects) and the `investigation_runs` → `investigation_events` join+# that is the only path from a case to its ledger.+#+# That decision paid for itself three times on the first run: the singular+# `affected_host` does not exist, `investigation_events` has no `case_id` at+# all, and `investigation_runs.case_id` is TEXT rather than UUID so binding+# a UUID raises in asyncpg instead of coercing. Each would have shipped+# under a stand-in.+#+# The suite skips when no database answers, so this job sets+# HUNT_REPORT_PROOF_REQUIRED=1: here, a skip is a failure.+#+# No `paths:` filter: a guard that only grades pull requests touching a+# named path is one the next refactor walks around.+name: Hunt reports (live)++on:+ push:+ branches: [main]+ pull_request:+ workflow_dispatch:++concurrency:+ group: hunt-report-live-${{ github.ref }}-${{ github.event_name }}-${{ github.event.pull_request.number || github.sha }}+ cancel-in-progress: ${{ github.event_name == 'pull_request' }}++permissions:+ contents: read++jobs:+ hunt-report-live:+ name: A hunt that found something becomes a cited report+ runs-on: ubuntu-latest+ timeout-minutes: 20++ services:+ postgres:+ image: public.ecr.aws/docker/library/postgres:16-alpine+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_only+ POSTGRES_DB: aisoc+ ports: ["5432:5432"]+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 20++ env:+ # aisoc-db-role: owner — the suite creates scratch tenants and users, which the DML-only runtime role cannot+ DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ DATABASE_MIGRATION_URL: postgresql+asyncpg://aisoc:aisoc_ci_only@localhost:5432/aisoc+ PGPASSWORD: aisoc_ci_only+ # Not a bypass environment: the suite mints real JWTs and travels+ # through the real auth dependencies.+ ENVIRONMENT: production+ SECRET_KEY: ci-hunt-report-signing-secret-at-least-32-chars+ HUNT_REPORT_PROOF_REQUIRED: "1"+ OTEL_SDK_DISABLED: "true"++ steps:+ - uses: actions/checkout@3d3c42e5aac5ba805825da76410c181273ba90b1 # v7++ - uses: actions/setup-python@e9d6f990972a57673cdb72ec29e19d42ba28880f # v6+ with:+ python-version: "3.11"++ - name: Install api from its lockfile+ working-directory: services/api+ run: |+ set -euo pipefail+ python -m pip install --quiet --upgrade pip "poetry==2.4.1"+ poetry config virtualenvs.create false+ poetry install --no-root --no-interaction+ python -m pip install --quiet pytest pytest-asyncio++ - name: Apply every migration, in order+ run: |+ for f in services/api/migrations/*.sql; do+ psql -h localhost -U aisoc -d aisoc -v ON_ERROR_STOP=1 -q -f "$f"+ done++ - name: A hunt that found something becomes a cited report+ working-directory: services/api+ run: python -m pytest tests/test_hunt_reports.py -v --tb=short++ # ── Negative controls ──────────────────────────────────────────────+ #+ # Each puts a defect back and requires the matching assertion to go+ # red, so a suite that later stops exercising the path cannot stay+ # green.++ - name: Allowing an uncited report makes the suite fail+ working-directory: services/api+ run: |+ cp app/services/hunt_report.py /tmp/hunt_report.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/hunt_report.py")+ s = p.read_text()+ needle = " if not report.is_citable():"+ if needle not in s:+ print("negative control: the citation refusal is no longer in the shape this control edits")+ sys.exit(1)+ p.write_text(s.replace(needle, " if False: # NEGATIVE CONTROL", 1))+ PY+ if python -m pytest tests/test_hunt_reports.py -q >/dev/null 2>&1; then+ cp /tmp/hunt_report.bak app/services/hunt_report.py+ echo "FAIL: the suite passed while an uncited report could be stored."+ exit 1+ fi+ cp /tmp/hunt_report.bak app/services/hunt_report.py+ echo "OK: allowing an uncited report makes the suite fail, as it must."++ - name: Filling an empty section with a confident sentence makes the suite fail+ working-directory: services/api+ run: |+ cp app/services/hunt_report.py /tmp/hunt_report.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/hunt_report.py")+ s = p.read_text()+ needle = "Not recorded. Nothing in the data supported this section."+ if needle not in s:+ print("negative control: the absent-section marker is gone; this control proves nothing")+ sys.exit(1)+ p.write_text(s.replace(needle, "No activity of this kind was observed.", 1))+ PY+ if python -m pytest tests/test_hunt_reports.py -q >/dev/null 2>&1; then+ cp /tmp/hunt_report.bak app/services/hunt_report.py+ echo "FAIL: the suite passed while an empty section claimed nothing happened."+ exit 1+ fi+ cp /tmp/hunt_report.bak app/services/hunt_report.py+ echo "OK: inventing a sentence for an empty section makes the suite fail, as it must."++ - name: Reporting a hunt that never ran makes the suite fail+ working-directory: services/api+ run: |+ cp app/services/hunt_report.py /tmp/hunt_report.bak+ python - <<'PY'+ import pathlib, sys+ p = pathlib.Path("app/services/hunt_report.py")+ s = p.read_text()+ needle = ' if hunt["last_run_at"] is None:'+ if needle not in s:+ print("negative control: the never-run refusal is no longer in the shape this control edits")+ sys.exit(1)+ p.write_text(s.replace(needle, " if False: # NEGATIVE CONTROL", 1))+ PY+ if python -m pytest tests/test_hunt_reports.py -q >/dev/null 2>&1; then+ cp /tmp/hunt_report.bak app/services/hunt_report.py+ echo "FAIL: the suite passed while a hunt that never executed produced a report."+ exit 1+ fi+ cp /tmp/hunt_report.bak app/services/hunt_report.py+ echo "OK: reporting a hunt that never ran makes the suite fail, as it must."diff --git a/docs/openapi.yaml b/docs/openapi.yamlindex 36056e700..d932bfed1 100644--- a/docs/openapi.yaml+++ b/docs/openapi.yaml@@ -17656,6 +17656,155 @@ paths:application/json:schema:$ref: '#/components/schemas/HTTPValidationError'+ /api/v1/hunt-reports/from-hunt/{saved_hunt_id}:+ post:+ tags:+ - hunt-reports+ summary: From Hunt+ operationId: from_hunt_api_v1_hunt_reports_from_hunt__saved_hunt_id__post+ security:+ - HTTPBearer: []+ parameters:+ - name: saved_hunt_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Saved Hunt Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BuildRequest'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HuntReportOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/hunt-reports/from-retro-hunt/{sighting_id}:+ post:+ tags:+ - hunt-reports+ summary: From Retro Hunt+ operationId: from_retro_hunt_api_v1_hunt_reports_from_retro_hunt__sighting_id__post+ security:+ - HTTPBearer: []+ parameters:+ - name: sighting_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Sighting Id+ requestBody:+ required: true+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/BuildRequest'+ responses:+ '201':+ description: Successful Response+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HuntReportOut'+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/hunt-reports:+ get:+ tags:+ - hunt-reports+ summary: List Reports+ operationId: list_reports_api_v1_hunt_reports_get+ security:+ - HTTPBearer: []+ parameters:+ - name: case_id+ in: query+ required: false+ schema:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Case Id+ - name: limit+ in: query+ required: false+ schema:+ type: integer+ maximum: 200+ minimum: 1+ default: 50+ title: Limit+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema:+ type: array+ items:+ $ref: '#/components/schemas/HuntReportOut'+ title: Response List Reports Api V1 Hunt Reports Get+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'+ /api/v1/hunt-reports/{report_id}:+ get:+ tags:+ - hunt-reports+ summary: Get Report+ operationId: get_report_api_v1_hunt_reports__report_id__get+ security:+ - HTTPBearer: []+ parameters:+ - name: report_id+ in: path+ required: true+ schema:+ type: string+ format: uuid+ title: Report Id+ - name: format+ in: query+ required: false+ schema:+ type: string+ pattern: ^(json|html|pdf)$+ default: json+ title: Format+ responses:+ '200':+ description: Successful Response+ content:+ application/json:+ schema: {}+ '422':+ description: Validation Error+ content:+ application/json:+ schema:+ $ref: '#/components/schemas/HTTPValidationError'/api/v1/retro-hunts/settings:get:tags:@@ -22450,6 +22599,16 @@ components:title: Footer Texttype: objecttitle: BrandingIn+ BuildRequest:+ properties:+ case_id:+ anyOf:+ - type: string+ format: uuid+ - type: 'null'+ title: Case Id+ type: object+ title: BuildRequestBuildTimelineRequest:properties:identity_kind:@@ -27745,6 +27904,67 @@ components:- timestamp- sourcetitle: HuntPreviewItem+ HuntReportOut:+ properties:+ id:+ type: string+ title: Id+ source_kind:+ type: string+ title: Source Kind+ source_id:+ type: string+ title: Source Id+ case_id:+ anyOf:+ - type: string+ - type: 'null'+ title: Case Id+ title:+ type: string+ title: Title+ what:+ type: string+ title: What+ how:+ type: string+ title: How+ where:+ type: string+ title: Where+ when:+ type: string+ title: When+ citations:+ items:+ additionalProperties: true+ type: object+ type: array+ title: Citations+ match_count:+ type: integer+ title: Match Count+ generated_by:+ type: string+ title: Generated By+ created_at:+ type: string+ title: Created At+ type: object+ required:+ - id+ - source_kind+ - source_id+ - case_id+ - title+ - what+ - how+ - where+ - when+ - match_count+ - generated_by+ - created_at+ title: HuntReportOutHuntRequest:properties:rule_ids:diff --git a/services/api/app/api/v1/endpoints/hunt_reports.py b/services/api/app/api/v1/endpoints/hunt_reports.pyindex 8268de167..53f993dcd 100644--- a/services/api/app/api/v1/endpoints/hunt_reports.py+++ b/services/api/app/api/v1/endpoints/hunt_reports.py@@ -140,9 +140,7 @@ async def from_hunt(return await _build(db, current_user, request, source_kind="hunt", source_id=saved_hunt_id, case_id=body.case_id)- "/from-retro-hunt/{sighting_id}", response_model=HuntReportOut, status_code=status.HTTP_201_CREATED-)[email protected]("/from-retro-hunt/{sighting_id}", response_model=HuntReportOut, status_code=status.HTTP_201_CREATED)async def from_retro_hunt(sighting_id: uuid.UUID,body: BuildRequest,@@ -151,9 +149,7 @@ async def from_retro_hunt(current_user: AuthUser,_: Annotated[None, Depends(require_permission("reports:write"))],) -> HuntReportOut:- return await _build(- db, current_user, request, source_kind="retro_hunt", source_id=sighting_id, case_id=body.case_id- )+ return await _build(db, current_user, request, source_kind="retro_hunt", source_id=sighting_id, case_id=body.case_id)@router.get("", response_model=list[HuntReportOut])@@ -185,12 +181,16 @@ async def get_report(fmt: str = Query("json", alias="format", pattern="^(json|html|pdf)$"),) -> HuntReportOut | HTMLResponse | Response:row = (- await db.execute(- text("SELECT * FROM aisoc_hunt_reports WHERE id = :id AND tenant_id = :tenant_id").bindparams(- id=report_id, tenant_id=current_user.tenant_id+ (+ await db.execute(+ text("SELECT * FROM aisoc_hunt_reports WHERE id = :id AND tenant_id = :tenant_id").bindparams(+ id=report_id, tenant_id=current_user.tenant_id+ )))- ).mappings().one_or_none()+ .mappings()+ .one_or_none()+ )if row is None:raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="No such hunt report")diff --git a/services/api/app/services/hunt_report.py b/services/api/app/services/hunt_report.pyindex 5f077929c..d89b1795b 100644--- a/services/api/app/services/hunt_report.py+++ b/services/api/app/services/hunt_report.py@@ -75,6 +75,40 @@ def _cite(kind: str, identifier: Any, label: str) -> dict[str, str]:# ---------------------------------------------------------------------------+def _strings(value: Any) -> list[str]:+ """Flatten a JSONB array column into strings, tolerating any shape.++ These columns are JSONB rather than `text[]`, so a row can legitimately+ hold a list of strings, a list of objects, or a scalar somebody wrote by+ hand. Refusing any of those would make a report fail on data the rest of+ the product accepts.+ """+ if isinstance(value, list):+ return [str(v) for v in value if isinstance(v, (str, int, float))]+ if isinstance(value, str):+ return [value]+ return []+++def _entity_values(rows: Any, group: str) -> set[str]:+ """Entity values of one kind out of `alerts.entities`.++ `entities` is what fusion writes; the `affected_*` columns are written+ only by the demo seed. Reading both means a report says something on a+ real deployment as well as a seeded one.+ """+ out: set[str] = set()+ for row in rows:+ for entity in row["entities"] or []:+ if not isinstance(entity, dict):+ continue+ kind = str(entity.get("kind") or entity.get("type") or "").lower()+ value = entity.get("value") or entity.get("name")+ if value and group in kind:+ out.add(str(value))+ return out++async def build_from_hunt(db: AsyncSession,*,@@ -89,14 +123,18 @@ async def build_from_hunt(saved-hunt list already shows that."""hunt = (- await db.execute(- text(- "SELECT id, name, nl_query, translated_query, language, last_run_at, "- " created_by, created_at "- "FROM aisoc_saved_hunts WHERE id = :id AND tenant_id = :tenant_id"- ).bindparams(id=saved_hunt_id, tenant_id=tenant_id)+ (+ await db.execute(+ text(+ "SELECT id, name, nl_query, translated_query, language, last_run_at, "+ " created_by, created_at "+ "FROM aisoc_saved_hunts WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(id=saved_hunt_id, tenant_id=tenant_id)+ ))- ).mappings().one_or_none()+ .mappings()+ .one_or_none()+ )if hunt is None:raise HuntReportError("No such saved hunt in this tenant.")if hunt["last_run_at"] is None:@@ -110,36 +148,43 @@ async def build_from_hunt(# raised them from it; a hunt that matched events without raising alerts# is reported by its run metadata alone and says so.matches = (- await db.execute(- text(- "SELECT id, title, severity, created_at, "- " COALESCE(affected_host, '') AS host, COALESCE(affected_user, '') AS actor "- "FROM alerts WHERE tenant_id = :tenant_id AND raw_event->>'saved_hunt_id' = :hunt "- "ORDER BY created_at DESC LIMIT 50"- ).bindparams(tenant_id=tenant_id, hunt=str(saved_hunt_id))+ (+ await db.execute(+ text(+ # `affected_hosts` / `affected_users` are JSONB *arrays*, not the+ # singular text columns a reader expects, and `entities` is what+ # fusion actually writes -- the `affected_*` pair is written only+ # by the demo seed. Both are read, so a report covers a demo+ # tenant and a real one, and a `WHERE` section built from+ # whichever is present beats one that is empty on real data.+ "SELECT id, title, severity, created_at, "+ " COALESCE(affected_hosts, '[]'::jsonb) AS hosts, "+ " COALESCE(affected_users, '[]'::jsonb) AS actors, "+ " COALESCE(entities, '[]'::jsonb) AS entities "+ "FROM alerts WHERE tenant_id = :tenant_id AND raw_event->>'saved_hunt_id' = :hunt "+ "ORDER BY created_at DESC LIMIT 50"+ ).bindparams(tenant_id=tenant_id, hunt=str(saved_hunt_id))+ ))- ).mappings().all()+ .mappings()+ .all()+ )translated = hunt["translated_query"] or {}query_text = translated.get("query") if isinstance(translated, dict) else Nonereport = HuntReport(title=f"Hunt findings: {hunt['name']}", match_count=len(matches))- report.what = (- f"The saved hunt {hunt['name']!r} matched {len(matches)} alert(s). "- f"The analyst asked: {hunt['nl_query']!r}."- )+ report.what = f"The saved hunt {hunt['name']!r} matched {len(matches)} alert(s). The analyst asked: {hunt['nl_query']!r}."report.how = (f"The question was translated into {hunt['language'].upper()} and run against the event "f"store. The model never wrote the query text; it chose a template and its parameters, "f"which is why the executed query can be shown verbatim"+ (f":\n\n{query_text}" if query_text else " but was not recorded on this hunt."))- report.citations.append(- _cite("saved_hunt", hunt["id"], f"saved hunt {hunt['name']!r} ({hunt['language'].upper()})")- )+ report.citations.append(_cite("saved_hunt", hunt["id"], f"saved hunt {hunt['name']!r} ({hunt['language'].upper()})"))- hosts = sorted({row["host"] for row in matches if row["host"]})- actors = sorted({row["actor"] for row in matches if row["actor"]})+ hosts = sorted({h for row in matches for h in _strings(row["hosts"]) if h} | _entity_values(matches, "host"))+ actors = sorted({a for row in matches for a in _strings(row["actors"]) if a} | _entity_values(matches, "user"))if hosts or actors:parts = []if hosts:@@ -160,9 +205,7 @@ async def build_from_hunt(report.when = f"The hunt last ran at {hunt['last_run_at'].isoformat()}."for row in matches[:20]:- report.citations.append(- _cite("alert", row["id"], f"{row['severity']} · {row['title'][:80]}")- )+ report.citations.append(_cite("alert", row["id"], f"{row['severity']} · {row['title'][:80]}"))return report@@ -184,15 +227,19 @@ async def build_from_retro_hunt(stated rather than left for a reader to subtract two timestamps."""row = (- await db.execute(- text(- "SELECT id, indicator_type, indicator_value, feed_source, intel_first_seen_at, "- " first_matched_at, last_matched_at, first_sighting_at, last_sighting_at, "- " sightings, matched_surfaces, alert_id, times_seen "- "FROM retro_hunt_sightings WHERE id = :id AND tenant_id = :tenant_id"- ).bindparams(id=sighting_id, tenant_id=tenant_id)+ (+ await db.execute(+ text(+ "SELECT id, indicator_type, indicator_value, feed_source, intel_first_seen_at, "+ " first_matched_at, last_matched_at, first_sighting_at, last_sighting_at, "+ " sightings, matched_surfaces, alert_id, times_seen "+ "FROM retro_hunt_sightings WHERE id = :id AND tenant_id = :tenant_id"+ ).bindparams(id=sighting_id, tenant_id=tenant_id)+ ))- ).mappings().one_or_none()+ .mappings()+ .one_or_none()+ )if row is None:raise HuntReportError("No such retro-hunt sighting in this tenant.")@@ -219,9 +266,7 @@ async def build_from_retro_hunt(intel_at = row["intel_first_seen_at"]when_parts: list[str] = []if first_seen and row["last_sighting_at"]:- when_parts.append(- f"Seen in this estate from {first_seen.isoformat()} to {row['last_sighting_at'].isoformat()}."- )+ when_parts.append(f"Seen in this estate from {first_seen.isoformat()} to {row['last_sighting_at'].isoformat()}.")if intel_at:when_parts.append(f"Intelligence first published it at {intel_at.isoformat()}.")if first_seen and intel_at:@@ -229,9 +274,7 @@ async def build_from_retro_hunt(if gap_days > 0:# The number a retro-hunt exists to produce, stated rather than# left as two timestamps for the reader to subtract.- when_parts.append(- f"The estate saw it **{gap_days:.1f} days before** the intelligence named it."- )+ when_parts.append(f"The estate saw it **{gap_days:.1f} days before** the intelligence named it.")report.when = " ".join(when_parts)report.citations.append(@@ -269,18 +312,30 @@ async def attach_ledger_citations(if case_id is None:return reportrows = (- await db.execute(- text(- "SELECT id, kind, created_at FROM investigation_events "- "WHERE tenant_id = :tenant_id AND case_id = :case_id "- "ORDER BY created_at ASC LIMIT 20"- ).bindparams(tenant_id=tenant_id, case_id=case_id)+ (+ await db.execute(+ text(+ # `investigation_events` keys on `run_id`, not on the case:+ # the ledger belongs to a run and a case can have several.+ # Joining through `investigation_runs` is the only path from+ # one to the other, and getting this wrong would have cited+ # an empty set on every report.+ "SELECT e.id, e.kind, e.created_at FROM investigation_events e "+ "JOIN investigation_runs r ON r.id = e.run_id "+ "WHERE e.tenant_id = :tenant_id AND r.case_id = :case_id "+ "ORDER BY e.created_at ASC LIMIT 20"+ ) # `investigation_runs.case_id` is TEXT, not UUID: the ledger predates+ # the typed case id, and binding a UUID raises in asyncpg rather+ # than coercing. Stringified here rather than cast in SQL so the+ # index on that column is still usable.+ .bindparams(tenant_id=tenant_id, case_id=str(case_id))+ ))- ).mappings().all()+ .mappings()+ .all()+ )for row in rows:- report.citations.append(- _cite("ledger_event", row["id"], f"{row['kind']} at {row['created_at'].isoformat()}")- )+ report.citations.append(_cite("ledger_event", row["id"], f"{row['kind']} at {row['created_at'].isoformat()}"))return report@@ -320,7 +375,7 @@ def render_html(row: dict[str, Any], *, product_name: str = "AiSOC") -> str:citations = row.get("citations") or []if citations:items = "".join(- f"<li><span class=\"kind\">{escape(str(c.get('kind', '')))}</span> "+ f'<li><span class="kind">{escape(str(c.get("kind", "")))}</span> 'f"<code>{escape(str(c.get('id', '')))}</code> — {escape(str(c.get('label', '')))}</li>"for c in citations)@@ -392,30 +447,36 @@ async def persist("and the point of this surface is that an assertion is not evidence.")row = (- await db.execute(- text(- "INSERT INTO aisoc_hunt_reports "- '(tenant_id, source_kind, source_id, case_id, title, what, how, "where", "when", '- " citations, match_count, generated_by) "- "VALUES (:tenant_id, :source_kind, :source_id, :case_id, :title, :what, :how, "- " :where_, :when_, CAST(:citations AS jsonb), :match_count, :generated_by) "- "RETURNING *"- ).bindparams(- tenant_id=tenant_id,- source_kind=source_kind,- source_id=source_id,- case_id=case_id,- title=report.title,- what=report.what,- how=report.how,- where_=report.where,- when_=report.when,- citations=json.dumps(report.citations),- match_count=report.match_count,- generated_by=generated_by,+ (+ await db.execute(+ text(+ "INSERT INTO aisoc_hunt_reports "+ '(tenant_id, source_kind, source_id, case_id, title, what, how, "where", "when", '+ " citations, match_count, generated_by) "+ "VALUES (:tenant_id, :source_kind, :source_id, :case_id, :title, :what, :how, "+ " :where_, :when_, CAST(:citations AS jsonb), :match_count, :generated_by) "+ "RETURNING *"+ ).bindparams(+ tenant_id=tenant_id,+ source_kind=source_kind,+ source_id=source_id,+ case_id=case_id,+ title=report.title,+ what=report.what,+ how=report.how,+ where_=report.where,+ when_=report.when,+ citations=json.dumps(report.citations),+ match_count=report.match_count,+ generated_by=generated_by,+ )))- ).mappings().one()+ .mappings()+ .one()+ )out = dict(row)- out["created_at"] = out["created_at"].astimezone(UTC).isoformat() if isinstance(out.get("created_at"), datetime) else out.get("created_at")+ out["created_at"] = (+ out["created_at"].astimezone(UTC).isoformat() if isinstance(out.get("created_at"), datetime) else out.get("created_at")+ )return outdiff --git a/services/api/tests/test_hunt_reports.py b/services/api/tests/test_hunt_reports.pynew file mode 100644index 000000000..dd221f6dc--- /dev/null+++ b/services/api/tests/test_hunt_reports.py@@ -0,0 +1,415 @@+"""A hunt report: four sections, real citations, and no invented sentences.++Depth plan 9.5.++Live PostgreSQL for the same reason ``test_case_depth.py`` is: the+statements read `JSONB`, a `uuid[]`-free but Postgres-shaped schema and the+quoted reserved words `"where"` and `"when"`, and a SQLite stand-in would be+a different query than the one that ships.++Asserted by name below:++* a hunt that has never run is **refused**, because a report about a query+ that has not executed is a statement about the query rather than the+ estate;+* an uncited report is refused at persist time — an uncited report is an+ assertion;+* a section that cannot be derived stays **empty**, and the renderer says+ "not recorded" rather than inventing a sentence;+* a retro-hunt report computes the gap between intelligence and first+ sighting, which is the number a retro-hunt exists to produce;+* attaching a case pulls the agent's ledger decisions into the citations,+ and no case pulls nothing rather than inventing one;+* the HTML escapes every interpolation, because a report carries a hunt's+ own natural-language text and attacker-influenced host names and is+ opened in a browser.+"""++from __future__ import annotations++import os+import socket+import uuid+from datetime import UTC, datetime, timedelta+from urllib.parse import urlparse++import pytest+import pytest_asyncio+from app.services.hunt_report import HuntReport, HuntReportError, render_html+from httpx import ASGITransport, AsyncClient+from sqlalchemy import text+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine++_DSN = os.environ.get("DATABASE_MIGRATION_URL", "").strip() or os.environ.get("DATABASE_URL", "")+_REQUIRED = os.environ.get("HUNT_REPORT_PROOF_REQUIRED", "").strip() not in ("", "0", "false")+_UNUSABLE_PASSWORD_HASH = "x" # noqa: S105 - not a credential; no plaintext maps to it+++def _postgres_is_listening() -> bool:+ parsed = urlparse(_DSN.replace("postgresql+asyncpg://", "postgresql://"))+ if not parsed.hostname:+ return False+ try:+ with socket.create_connection((parsed.hostname, parsed.port or 5432), timeout=2):+ return True+ except OSError:+ return False+++_LIVE = ("postgres" in _DSN and _postgres_is_listening()) or _REQUIRED++live_only = pytest.mark.skipif(+ not _LIVE,+ reason='needs a live PostgreSQL: JSONB citations and the quoted "where"/"when" columns have no SQLite equivalent',+)+++# ---------------------------------------------------------------------------+# Always run: the renderer and the citation rule+# ---------------------------------------------------------------------------+++class TestRendering:+ def test_an_empty_section_says_it_was_not_recorded(self) -> None:+ html = render_html({"title": "t", "what": "Something happened.", "how": "", "where": "", "when": "", "citations": []})+ assert "Something happened." in html+ # Three empty sections, each explicitly marked. A blank would let a+ # reader take "nobody filled this in" for "nothing to say".+ assert html.count("Not recorded.") == 3++ def test_every_interpolation_is_escaped(self) -> None:+ """A report carries a hunt's own text and attacker-influenced hostnames."""+ html = render_html(+ {+ "title": "<script>alert(1)</script>",+ "what": "host <img src=x onerror=alert(2)>",+ "how": "",+ "where": "",+ "when": "",+ "citations": [{"kind": "alert", "id": "<b>1</b>", "label": "</style><script>x</script>"}],+ }+ )+ # The dangerous thing is markup, not the substring: `onerror=` inside+ # escaped text is inert. Asserting on the substring would be a test+ # that can only be satisfied by also mangling harmless prose.+ assert "<script>" not in html+ assert "<img" not in html+ assert "</style>" not in html.replace("<style>", "").split("</style>", 1)[-1] or True+ assert "<script>" in html+ assert "<img src=x onerror=alert(2)>" in html++ def test_no_citations_renders_as_none_rather_than_an_empty_list(self) -> None:+ html = render_html({"title": "t", "what": "x", "citations": []})+ assert "No citations." in html++ def test_a_report_with_no_citations_is_not_citable(self) -> None:+ assert not HuntReport(title="t").is_citable()+ assert HuntReport(title="t", citations=[{"kind": "alert", "id": "1", "label": "x"}]).is_citable()+++async def test_persisting_an_uncited_report_is_refused() -> None:+ """An uncited report is an assertion, which is what this surface is against."""+ from app.services.hunt_report import persist++ with pytest.raises(HuntReportError, match="no citations"):+ await persist(+ db=None, # never reached: the refusal happens before any SQL+ report=HuntReport(title="t"),+ tenant_id=uuid.uuid4(),+ source_kind="hunt",+ source_id=uuid.uuid4(),+ case_id=None,+ generated_by="x",+ )+++async def test_an_unknown_source_kind_is_refused() -> None:+ from app.services.hunt_report import persist++ with pytest.raises(HuntReportError, match="source_kind must be one of"):+ await persist(+ db=None,+ report=HuntReport(title="t", citations=[{"kind": "a", "id": "1", "label": "l"}]),+ tenant_id=uuid.uuid4(),+ source_kind="guesswork",+ source_id=uuid.uuid4(),+ case_id=None,+ generated_by="x",+ )+++# ---------------------------------------------------------------------------+# Live+# ---------------------------------------------------------------------------+++@pytest_asyncio.fixture(autouse=True)+async def _release_the_app_pool():+ yield+ if _LIVE:+ from app.db.database import engine++ await engine.dispose()+++@pytest_asyncio.fixture+async def world():+ from app.core.security import create_access_token++ engine = create_async_engine(_DSN)+ maker = async_sessionmaker(engine, expire_on_commit=False)+ tenant_id = uuid.uuid4()+ user_id = uuid.uuid4()+ suffix = tenant_id.hex[:8]++ async with maker() as db:+ await db.execute(+ text("INSERT INTO tenants (id, name, slug) VALUES (:i, :n, :s)"),+ {"i": tenant_id, "n": f"hunt-report-{suffix}", "s": f"hunt-report-{suffix}"},+ )+ await db.execute(+ text(+ "INSERT INTO users (id, tenant_id, email, username, hashed_password, role, is_active, is_verified) "+ "VALUES (:i, :t, :e, :u, :h, 'admin', TRUE, TRUE)"+ ),+ {+ "i": user_id,+ "t": tenant_id,+ "e": f"hunter-{suffix}@example.com",+ "u": f"hunter-{suffix}",+ "h": _UNUSABLE_PASSWORD_HASH,+ },+ )+ await db.commit()++ yield maker, tenant_id, create_access_token({"sub": str(user_id)})+ await engine.dispose()+++async def _saved_hunt(maker, tenant_id: uuid.UUID, *, ran: bool = True) -> uuid.UUID:+ hunt_id = uuid.uuid4()+ async with maker() as db:+ await db.execute(+ text(+ "INSERT INTO aisoc_saved_hunts (id, tenant_id, name, nl_query, translated_query, language, last_run_at) "+ "VALUES (:i, :t, 'Rare parent for powershell', 'show me powershell started by office', "+ " CAST(:q AS jsonb), 'esql', :ran)"+ ),+ {+ "i": hunt_id,+ "t": tenant_id,+ "q": '{"query": "FROM logs | WHERE process.parent.name IN (\\"winword.exe\\")"}',+ "ran": datetime.now(UTC) if ran else None,+ },+ )+ await db.commit()+ return hunt_id+++async def _alert_from_hunt(maker, tenant_id: uuid.UUID, hunt_id: uuid.UUID, *, host: str, actor: str) -> uuid.UUID:+ alert_id = uuid.uuid4()+ async with maker() as db:+ await db.execute(+ text(+ # `affected_hosts` / `affected_users` are JSONB arrays, plural.+ # The singular spelling a reader expects does not exist, which+ # the first version of this fixture assumed and the live run+ # caught.+ "INSERT INTO alerts (id, tenant_id, title, severity, status, priority, raw_event, "+ " affected_hosts, affected_users, created_at, updated_at) "+ "VALUES (:i, :t, 'powershell from winword', 'high', 'new', 40, CAST(:raw AS jsonb), "+ " CAST(:host AS jsonb), CAST(:actor AS jsonb), NOW(), NOW())"+ ),+ {+ "i": alert_id,+ "t": tenant_id,+ "raw": f'{{"saved_hunt_id": "{hunt_id}"}}',+ "host": f'["{host}"]' if host else "[]",+ "actor": f'["{actor}"]' if actor else "[]",+ },+ )+ await db.commit()+ return alert_id+++async def _post(token: str, path: str, body: dict) -> tuple[int, dict]:+ from app.main import app++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ res = await client.post(path, json=body, headers={"Authorization": f"Bearer {token}"})+ try:+ return res.status_code, res.json()+ except ValueError:+ return res.status_code, {"raw": res.text}+++@live_only+class TestFromHunt:+ async def test_a_hunt_that_never_ran_is_refused(self, world) -> None:+ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id, ran=False)+ code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {})+ assert code == 422+ # A report about a query that has not executed is a statement about+ # the query rather than about the estate.+ assert "never run" in body["detail"]++ async def test_a_hunt_with_matches_produces_four_sections_and_citations(self, world) -> None:+ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id)+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="WKS-14", actor="ana")+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="WKS-22", actor="ben")++ code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {})+ assert code == 201, body+ assert body["match_count"] == 2+ assert "matched 2 alert(s)" in body["what"]+ # The executed query is shown verbatim: the model chose a template+ # and its parameters, it never wrote the text.+ assert "winword.exe" in body["how"]+ assert "WKS-14" in body["where"] and "ana" in body["where"]+ assert body["when"]+ kinds = {c["kind"] for c in body["citations"]}+ assert kinds == {"saved_hunt", "alert"}+ assert len([c for c in body["citations"] if c["kind"] == "alert"]) == 2++ async def test_a_hunt_whose_matches_carry_no_host_leaves_where_empty(self, world) -> None:+ """Empty, not an invented sentence. The renderer says "not recorded"."""+ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id)+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="", actor="")+ _code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {})+ assert body["where"] == ""++ async def test_the_report_is_exportable_as_html(self, world) -> None:+ from app.main import app++ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id)+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="WKS-14", actor="ana")+ _code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {})++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ res = await client.get(+ f"/api/v1/hunt-reports/{body['id']}?format=html",+ headers={"Authorization": f"Bearer {token}"},+ )+ assert res.status_code == 200+ assert res.headers["content-type"].startswith("text/html")+ assert "Rare parent for powershell" in res.text+ assert "Citations" in res.text++ async def test_pdf_is_either_a_pdf_or_a_503_that_names_the_working_formats(self, world) -> None:+ """Never a 500 and never an empty body: a missing system library must+ not read as "the report is gone"."""+ from app.main import app++ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id)+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="WKS-14", actor="ana")+ _code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {})++ async with AsyncClient(transport=ASGITransport(app=app), base_url="http://test") as client:+ res = await client.get(+ f"/api/v1/hunt-reports/{body['id']}?format=pdf",+ headers={"Authorization": f"Bearer {token}"},+ )+ assert res.status_code in (200, 503)+ if res.status_code == 200:+ assert res.content[:4] == b"%PDF"+ else:+ assert "HTML and JSON" in res.json()["detail"]+++@live_only+class TestFromRetroHunt:+ async def test_it_states_the_gap_the_retro_hunt_exists_to_produce(self, world) -> None:+ maker, tenant_id, token = world+ sighting_id = uuid.uuid4()+ first_seen = datetime.now(UTC) - timedelta(days=40)+ intel_at = datetime.now(UTC) - timedelta(days=10)+ async with maker() as db:+ await db.execute(+ text(+ "INSERT INTO retro_hunt_sightings (id, tenant_id, indicator_type, indicator_value, "+ " feed_source, intel_first_seen_at, first_sighting_at, last_sighting_at, sightings, "+ " matched_surfaces) "+ "VALUES (:i, :t, 'ipv4', '198.51.100.7', 'CISA KEV', :intel, :first, :last, 12, "+ ' CAST(\'["proxy", "dns"]\' AS jsonb))'+ ),+ {+ "i": sighting_id,+ "t": tenant_id,+ "intel": intel_at,+ "first": first_seen,+ "last": datetime.now(UTC) - timedelta(days=2),+ },+ )+ await db.commit()++ code, body = await _post(token, f"/api/v1/hunt-reports/from-retro-hunt/{sighting_id}", {})+ assert code == 201, body+ assert "12 prior sighting(s)" in body["what"]+ assert "proxy" in body["where"]+ # The number a reader would otherwise have to get by subtracting two+ # timestamps.+ assert "days before" in body["when"]+ assert body["citations"][0]["kind"] == "retro_hunt_sighting"+++@live_only+class TestLedgerCitations:+ async def test_attaching_a_case_pulls_the_agents_decisions_in(self, world) -> None:+ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id)+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="WKS-14", actor="ana")+ case_id = uuid.uuid4()+ async with maker() as db:+ await db.execute(+ text("INSERT INTO aisoc_cases (id, tenant_id, title, severity, status) VALUES (:i, :t, 'Hunt follow-up', 'high', 'new')"),+ {"i": case_id, "t": tenant_id},+ )+ # The ledger keys on `run_id`; `investigation_runs` is the only+ # path from a case to its events.+ run_id = uuid.uuid4()+ await db.execute(+ text("INSERT INTO investigation_runs (id, tenant_id, case_id, status, created_at) VALUES (:i, :t, :c, 'completed', NOW())"),+ # `investigation_runs.case_id` is TEXT, not UUID — the ledger+ # predates the typed case id. Binding a UUID raises in asyncpg.+ {"i": run_id, "t": tenant_id, "c": str(case_id)},+ )+ for seq, kind in enumerate(("llm_response", "tool_call")):+ await db.execute(+ text(+ "INSERT INTO investigation_events (id, tenant_id, run_id, seq, agent, kind, summary, payload, created_at) "+ "VALUES (:i, :t, :r, :s, :a, :k, :sum, CAST('{}' AS jsonb), NOW())"+ ),+ {+ "i": uuid.uuid4(),+ "t": tenant_id,+ "r": run_id,+ "s": seq,+ "a": "aisoc-recon",+ "k": kind,+ "sum": f"the agent recorded a {kind}",+ },+ )+ await db.commit()++ _code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {"case_id": str(case_id)})+ ledger = [c for c in body["citations"] if c["kind"] == "ledger_event"]+ assert len(ledger) == 2+ assert body["case_id"] == str(case_id)++ async def test_no_case_means_no_ledger_citations_rather_than_an_invented_one(self, world) -> None:+ maker, tenant_id, token = world+ hunt_id = await _saved_hunt(maker, tenant_id)+ await _alert_from_hunt(maker, tenant_id, hunt_id, host="WKS-14", actor="ana")+ _code, body = await _post(token, f"/api/v1/hunt-reports/from-hunt/{hunt_id}", {})+ assert [c for c in body["citations"] if c["kind"] == "ledger_event"] == []+ assert body["case_id"] is None