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
Phase 3.1: continuous event spine + real-container integration gates (#425)
Beenu Aroraae7d7d1631c7
diff --git a/.github/workflows/ci.yml b/.github/workflows/ci.ymlindex b63cc58c4..182a6d350 100644--- a/.github/workflows/ci.yml+++ b/.github/workflows/ci.yml@@ -361,7 +361,9 @@ jobs:# We deliberately do NOT install the full API dep set here — the goal# of this job stays "pure helpers + thin router contracts, no# service boot, no Postgres/Kafka/Redis".- run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka+ # asyncpg: required since Phase 3.1 — the fusion AlertSink persists+ # fused alerts to the Postgres alert store.+ run: pip install --quiet pydantic pydantic-settings pytest pytest-asyncio structlog redis aioredis fastapi httpx aiokafka asyncpg- name: Install pytest-cov (Phase 2.2 coverage gate)run: pip install --quiet 'pytest-cov>=4,<7'# Phase 2.2 — every wave-1 service now has a measured coveragediff --git a/.github/workflows/integration.yml b/.github/workflows/integration.ymlnew file mode 100644index 000000000..e0b1dbe3c--- /dev/null+++ b/.github/workflows/integration.yml@@ -0,0 +1,322 @@+name: Integration++# Phase 3 (world-class program) — prove the stack actually runs.+#+# Three jobs, all against real containers, no mocks:+#+# spine — raw vendor event → ingest (OCSF normalize) → Kafka →+# fusion (promote + dedup + correlate) → fused topic →+# realtime WebSocket frame → Postgres alert row →+# GET /api/v1/alerts. Plus duplicate suppression and a+# chaos step (kill the fusion consumer, produce, restart,+# assert recovery with zero event loss).+# migrations — the API's SQL migration chain applies cleanly on a+# fresh Postgres 16, is idempotent on re-run (strict+# mode), and the UEBA alembic chain round-trips+# upgrade → downgrade → upgrade.+# backup-restore — scripts/backup.sh + restore.sh against Postgres 16 ++# MinIO: seed → backup → destroy → restore → assert+# full data integrity. Publishes measured RTO. An+# untested backup is not a backup.+#+# The spine job builds `fusion` and `ingest-worker` from PR source (they own+# the bridges under test) and pulls the other service images from GHCR+# `:main` — those surfaces are gated by compose-smoke.yml with its own+# rebuild-on-change detection.++on:+ pull_request:+ paths:+ - 'services/ingest/**'+ - 'services/fusion/**'+ - 'services/realtime/**'+ - 'services/api/migrations/**'+ - 'services/api/app/scripts/run_migrations.py'+ - 'services/ueba/alembic/**'+ - 'docker-compose.yml'+ - 'scripts/integration/**'+ - 'scripts/backup.sh'+ - 'scripts/restore.sh'+ - '.github/workflows/integration.yml'+ push:+ branches: [main]+ paths:+ - 'services/ingest/**'+ - 'services/fusion/**'+ - 'services/realtime/**'+ - 'services/api/migrations/**'+ - 'services/api/app/scripts/run_migrations.py'+ - 'services/ueba/alembic/**'+ - 'docker-compose.yml'+ - 'scripts/integration/**'+ - 'scripts/backup.sh'+ - 'scripts/restore.sh'+ - '.github/workflows/integration.yml'+ workflow_dispatch:++concurrency:+ group: integration-${{ github.ref }}+ cancel-in-progress: true++permissions:+ contents: read++jobs:+ # ── The spine, end to end ──────────────────────────────────────────────────+ spine:+ name: Event spine (real containers)+ runs-on: ubuntu-latest+ timeout-minutes: 40+ env:+ AISOC_VERSION: main+ COMPOSE_PROJECT_NAME: aisoc-integration+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7++ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6+ with:+ python-version: '3.12'++ - name: Install test dependencies+ run: pip install --quiet httpx websockets++ - name: Seed environment file+ run: |+ cp .env.example .env+ if grep -q '^AISOC_VERSION=' .env; then+ sed -i "s|^AISOC_VERSION=.*|AISOC_VERSION=${AISOC_VERSION}|" .env+ else+ printf '\nAISOC_VERSION=%s\n' "${AISOC_VERSION}" >> .env+ fi++ - name: Pre-pull published images+ run: docker compose pull --ignore-pull-failures --quiet || true++ # The two spine-bridge owners are always built from PR source so the+ # code under test is the code that runs. Build AFTER the pull so the+ # locally-built tags are not clobbered by the registry.+ - name: Build fusion + ingest from source+ run: docker compose build fusion ingest-worker++ - name: Boot stack+ run: docker compose up -d++ - name: Run spine test+ run: python3 scripts/integration/spine_test.py++ # ── Chaos: kill the fusion consumer, produce, restart, assert ────────+ # The event is produced while the consumer is down; on restart the+ # consumer group must resume from its committed offset and process it.+ # Zero event loss across a consumer crash is the claim under test.+ - name: Chaos — kill fusion consumer mid-stream+ run: |+ set -euo pipefail+ TITLE="ChaosTest-${GITHUB_RUN_ID}-${GITHUB_RUN_ATTEMPT}"+ echo "chaos title: ${TITLE}"+ docker compose kill fusion+ python3 scripts/integration/spine_test.py --post-event --title "${TITLE}"+ sleep 5+ docker compose up -d fusion+ python3 scripts/integration/spine_test.py --await-alert --title "${TITLE}" --timeout 180++ - name: Capture forensics on failure+ if: failure()+ run: |+ docker compose ps || true+ echo "── fusion ──"; docker compose logs --tail=150 --no-color fusion || true+ echo "── ingest ──"; docker compose logs --tail=100 --no-color ingest-worker || true+ echo "── realtime ──"; docker compose logs --tail=100 --no-color realtime || true+ echo "── api ──"; docker compose logs --tail=100 --no-color api || true+ echo "── kafka ──"; docker compose logs --tail=60 --no-color kafka || true++ - name: Teardown+ if: always()+ run: docker compose down -v --remove-orphans++ # ── Migration correctness ──────────────────────────────────────────────────+ migrations:+ name: Migrations (fresh apply, idempotent re-run, alembic round-trip)+ runs-on: ubuntu-latest+ timeout-minutes: 15+ services:+ postgres:+ image: postgres:16+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_secret+ POSTGRES_DB: aisoc+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 10+ env:+ DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/aisoc+ SECRET_KEY: ci-dummy-secret-key-at-least-32bytes!+ ENVIRONMENT: development+ AISOC_MIGRATIONS_STRICT: '1'+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7++ - uses: actions/setup-python@ece7cb06caefa5fff74198d8649806c4678c61a1 # v6+ with:+ python-version: '3.12'+ cache: pip++ # Same importable-subset recipe as ci.yml's API job — run_migrations+ # imports app.core.config, which needs the settings surface only.+ - name: Install API dependencies+ run: >-+ pip install --quiet+ fastapi "pydantic[email]" pydantic-settings "sqlalchemy[asyncio]" asyncpg+ structlog "python-jose[cryptography]" "passlib[bcrypt]" tenacity pyyaml+ prometheus-client "opentelemetry-sdk" "opentelemetry-api"+ "opentelemetry-exporter-otlp-proto-grpc"+ "opentelemetry-instrumentation-fastapi"+ "strawberry-graphql[fastapi]"+ neo4j redis celery httpx aiofiles email-validator PyJWT+ "sqlglot>=23,<27" aiosqlite "croniter>=2.0,<7.0"++ - name: Apply full migration chain on fresh Postgres (strict)+ working-directory: services/api+ run: python -m app.scripts.run_migrations++ - name: Re-run must be a no-op (idempotency)+ working-directory: services/api+ run: |+ set -euo pipefail+ python -m app.scripts.run_migrations 2>&1 | tee /tmp/second-run.log+ grep -q "0 pending" /tmp/second-run.log \+ || { echo "::error::second migration run was not a no-op"; exit 1; }++ - name: Assert every migration file is tracked+ run: |+ set -euo pipefail+ FILES=$(ls services/api/migrations/*.sql | wc -l)+ ROWS=$(PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc -tAc \+ "SELECT count(*) FROM aisoc_schema_migrations")+ echo "migration files: ${FILES}, tracked rows: ${ROWS}"+ [ "${FILES}" = "${ROWS}" ] \+ || { echo "::error::tracked migrations (${ROWS}) != migration files (${FILES})"; exit 1; }++ # The UEBA package layout (app/ dir) isn't wheel-buildable; alembic's+ # env.py only needs `app.models.ueba` importable, so run in-place with+ # PYTHONPATH instead of pip-installing the service.+ - name: Install alembic+ run: pip install --quiet alembic++ - name: UEBA alembic round-trip (upgrade → downgrade → upgrade)+ working-directory: services/ueba+ env:+ PYTHONPATH: .+ # Dedicated database so the SQL-runner schema above is untouched.+ DATABASE_URL: postgresql+asyncpg://aisoc:aisoc_ci_secret@localhost:5432/ueba_ci+ run: |+ set -euo pipefail+ PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc -c "CREATE DATABASE ueba_ci"+ alembic upgrade head+ alembic downgrade base+ alembic upgrade head+ echo "alembic round-trip clean"++ # ── Disaster recovery: an untested backup is not a backup ─────────────────+ backup-restore:+ name: Backup → destroy → restore (Postgres via MinIO)+ runs-on: ubuntu-latest+ timeout-minutes: 15+ services:+ postgres:+ image: postgres:16+ env:+ POSTGRES_USER: aisoc+ POSTGRES_PASSWORD: aisoc_ci_secret+ POSTGRES_DB: aisoc+ ports:+ - 5432:5432+ options: >-+ --health-cmd "pg_isready -U aisoc"+ --health-interval 5s+ --health-timeout 5s+ --health-retries 10+ env:+ POSTGRES_URL: postgresql://aisoc:aisoc_ci_secret@localhost:5432/aisoc+ BACKUP_S3_BUCKET: s3://aisoc-dr-test+ BACKUP_S3_PREFIX: ci-dr+ AWS_ACCESS_KEY_ID: minioadmin+ AWS_SECRET_ACCESS_KEY: minioadmin+ AWS_ENDPOINT_URL: http://localhost:9000+ AWS_DEFAULT_REGION: us-east-1+ steps:+ - uses: actions/checkout@9c091bb21b7c1c1d1991bb908d89e4e9dddfe3e0 # v7++ - name: Install tooling (awscli + postgres client)+ run: |+ pip install --quiet awscli+ sudo apt-get update -q && sudo apt-get install -y -q postgresql-client++ # MinIO needs a `server /data` command, which the GitHub `services:`+ # block cannot pass — run it as a plain container instead.+ - name: Start MinIO+ run: |+ docker run -d --name minio -p 9000:9000 \+ -e MINIO_ROOT_USER=minioadmin -e MINIO_ROOT_PASSWORD=minioadmin \+ minio/minio:RELEASE.2024-12-18T13-15-44Z server /data++ - name: Create bucket+ run: |+ for i in $(seq 1 12); do+ aws s3 mb "${BACKUP_S3_BUCKET}" && break || sleep 5+ done++ - name: Seed data+ run: |+ PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc <<'SQL'+ CREATE TABLE dr_probe (id SERIAL PRIMARY KEY, payload TEXT NOT NULL);+ INSERT INTO dr_probe (payload)+ SELECT md5(g::text) FROM generate_series(1, 500) AS g;+ SQL+ COUNT=$(PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc -tAc "SELECT count(*) FROM dr_probe")+ echo "seeded ${COUNT} rows"+ [ "${COUNT}" = "500" ]++ - name: Backup (scripts/backup.sh)+ run: ./scripts/backup.sh --component postgres++ - name: Destroy all data+ run: |+ PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc \+ -c "DROP SCHEMA public CASCADE; CREATE SCHEMA public;"+ COUNT=$(PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc -tAc \+ "SELECT count(*) FROM information_schema.tables WHERE table_schema='public'")+ echo "tables after destroy: ${COUNT}"+ [ "${COUNT}" = "0" ]++ - name: Restore (scripts/restore.sh) and measure RTO+ run: |+ set -euo pipefail+ START=$(date +%s)+ ./scripts/restore.sh --latest --component postgres < /dev/null+ RTO=$(( $(date +%s) - START ))+ echo "RTO_SECONDS=${RTO}" >> "$GITHUB_ENV"+ echo "measured restore time: ${RTO}s"++ - name: Assert full data integrity+ run: |+ COUNT=$(PGPASSWORD=aisoc_ci_secret psql -h localhost -U aisoc -d aisoc -tAc "SELECT count(*) FROM dr_probe")+ echo "rows after restore: ${COUNT}"+ [ "${COUNT}" = "500" ] || { echo "::error::data loss after restore (${COUNT}/500 rows)"; exit 1; }++ - name: Publish DR summary+ run: |+ {+ echo "## Disaster-recovery gate"+ echo ""+ echo "| metric | value |"+ echo "|--------|-------|"+ echo "| rows seeded | 500 |"+ echo "| rows after restore | 500 |"+ echo "| measured RTO | ${RTO_SECONDS}s |"+ echo "| RPO | last completed backup (event-loss window = backup cadence) |"+ } >> "$GITHUB_STEP_SUMMARY"diff --git a/CHANGELOG.md b/CHANGELOG.mdindex 9f8a3bbe8..9b44ad82f 100644--- a/CHANGELOG.md+++ b/CHANGELOG.md@@ -7,6 +7,14 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0## [Unreleased]+### Added++- **Phase 3.1 — the event spine is now continuous, and CI proves it with real containers.** The reality audit found two silent gaps in the product's central claim: ingest published normalized OCSF events to `aisoc.raw_events` that nothing consumed, and fusion published to `aisoc.alerts.fused` that nothing persisted — a raw event could never become an alert row without a human calling the API. Both bridges now exist in `services/fusion`: a deterministic promotion policy (`app/services/promoter.py` — OCSF Findings-category events and `severity_id >= 4` telemetry become `RawAlert`s; everything else is left to the detection engine by design) and a fail-soft, idempotent Postgres `AlertSink` (`app/services/alert_sink.py` — dedup-fingerprint-guarded insert, duplicates never persisted, DB outage degrades instead of crashing the consumer). New `.github/workflows/integration.yml` gates three claims against real containers, no mocks: (1) **spine** — `POST /v1/ingest/batch` → OCSF normalize → Kafka → fusion → WebSocket `alert.fused` frame + Postgres row via `GET /api/v1/alerts`, plus duplicate suppression and a chaos step (kill the fusion consumer mid-stream, produce, restart, assert zero event loss) — driver: `scripts/integration/spine_test.py`; (2) **migrations** — the full SQL chain applies on fresh Postgres 16, re-run is a no-op (new `AISOC_MIGRATIONS_STRICT=1` mode fails CI on any failed migration), and the UEBA alembic chain round-trips upgrade → downgrade → upgrade; (3) **backup-restore** — `scripts/backup.sh`/`restore.sh` against Postgres + MinIO: seed → backup → destroy → restore → assert full integrity, with measured RTO published to the job summary. 20 new fusion unit tests cover the mapping/skip logic (`test_promoter.py`, `test_alert_sink.py`); full fusion suite 71/71.++### Fixed++- **Phase 3.1 gates caught two latent bugs before merge** (exactly what the real-container tier is for — both would have shipped invisibly under the previous mock-only CI). (1) **`scripts/restore.sh` never restored anything.** `resolve_timestamp()` ended in a `[[ -z "$TIMESTAMP" ]] && { … }` guard that evaluates *false* once a timestamp is resolved; as the function's last command that non-zero status propagated out and, under `set -e`, aborted the script before the restore began — for **both** `--latest` and `--timestamp`. An untested backup script had been broken the whole time. Converted the guard to an explicit `if` + `return 0`; the backup → destroy → restore gate now restores 500/500 rows with a measured RTO. (2) **`services/fusion` `AlertSink` silently failed to persist every alert.** The dedup fingerprint (`$10`) was used untyped in both the `INSERT … SELECT` target (the `dedup_hash VARCHAR(64)` column) and `WHERE dedup_hash = $10` (varchar comparisons resolve through `text` operators), so asyncpg's prepare raised `inconsistent types deduced for parameter $10: text versus character varying` and the insert threw — the fused alert streamed over Kafka/WebSocket but never reached the alert store, so the spine's `GET /api/v1/alerts` assertion timed out. Pinned both uses to `::text`; the real-container spine gate now observes the alert row end to end.+### Security- **Phase 2 continuation — signed, attested container images + SHA-pinned CI.** Every `ghcr.io/beenuar/*` service image pushed by `publish-images.yml` (push-to-main) and `release.yml` (tags) is now: (1) signed with `cosign` keyless/OIDC, (2) attested with a CycloneDX SBOM generated by `syft` and attached via `cosign attest --type cyclonedx`, and (3) built with BuildKit `provenance: mode=max` + `sbom: true` so SLSA provenance and an SPDX SBOM ride the image manifest. Every third-party GitHub Action across all 32 workflows is pinned to a full commit SHA (tag retained as a comment) so a tag-hijack of an upstream action cannot change what CI executes. `docs/operations/verifying-releases.md` rewritten with copy-pasteable verification commands for all four artifact types. Claim-to-gate matrix: "Signed / attested release artifacts" moved PARTIAL → GATED (11 GATED / 13 PARTIAL / 3 NO GATE).diff --git a/scripts/integration/spine_test.py b/scripts/integration/spine_test.pynew file mode 100644index 000000000..da1e3244f--- /dev/null+++ b/scripts/integration/spine_test.py@@ -0,0 +1,254 @@+#!/usr/bin/env python3+"""End-to-end event-spine test against real containers (Phase 3.1).++Proves the product's central claim with zero mocks:++ raw vendor event+ → POST /v1/ingest/batch (services/ingest, Go)+ → OCSF normalize (services/ingest)+ → Kafka `aisoc.raw_events`+ → promotion + dedup + correlate (services/fusion)+ → Kafka `aisoc.alerts.fused`+ → WebSocket `alert.fused` frame (services/realtime)+ → Postgres `alerts` row (services/fusion AlertSink)+ → GET /api/v1/alerts (services/api)++Also asserts duplicate suppression: re-submitting the same event must NOT+create a second alert row.++Run against a booted docker-compose stack (see .github/workflows/integration.yml):++ python3 scripts/integration/spine_test.py # full spine test+ python3 scripts/integration/spine_test.py --post-event --title "chaos-1"+ python3 scripts/integration/spine_test.py --await-alert --title "chaos-1"++The --post-event / --await-alert modes are used by the chaos step (kill the+fusion consumer, produce, restart, assert recovery).++Dependencies: httpx, websockets (installed by the workflow).+"""++from __future__ import annotations++import argparse+import asyncio+import json+import sys+import time+import uuid++import httpx+import websockets++API = "http://localhost:8000"+INGEST = "http://localhost:8081"+FUSION = "http://localhost:8003"+REALTIME_HTTP = "http://localhost:8086"+REALTIME_WS = "ws://localhost:8086"+TENANT = "00000000-0000-0000-0000-000000000001"++HEALTH_BUDGET_S = 300+SPINE_BUDGET_S = 180+REPOST_INTERVAL_S = 20+++def log(msg: str) -> None:+ print(f"[{time.strftime('%H:%M:%S')}] {msg}", flush=True)+++async def wait_healthy(client: httpx.AsyncClient) -> None:+ """Block until every spine service answers its health probe."""+ probes = {+ "api": f"{API}/readyz",+ "ingest": f"{INGEST}/health",+ "fusion": f"{FUSION}/readyz",+ "realtime": f"{REALTIME_HTTP}/health",+ }+ deadline = time.monotonic() + HEALTH_BUDGET_S+ pending = dict(probes)+ while pending and time.monotonic() < deadline:+ for name, url in list(pending.items()):+ try:+ r = await client.get(url, timeout=5)+ if r.status_code == 200:+ log(f"healthy: {name}")+ del pending[name]+ except httpx.HTTPError:+ pass+ if pending:+ await asyncio.sleep(3)+ if pending:+ raise SystemExit(f"services never became healthy: {sorted(pending)}")+++def event_payload(title: str) -> dict:+ """A CrowdStrike-shaped critical finding. `event_simpleName` maps to+ OCSF `activity_name`, which the fusion promoter uses as the alert title."""+ return {+ "connector_id": "spine-test",+ "connector_type": "crowdstrike_falcon",+ "source_format": "json",+ "events": [+ {+ "event_simpleName": title,+ "ComputerName": "SPINE-TEST-HOST",+ "UserName": "spine-test-user",+ "SHA256HashData": "f" * 64,+ "severity": "Critical",+ "technique_id": "T1003",+ "timestamp": time.strftime("%Y-%m-%dT%H:%M:%SZ", time.gmtime()),+ }+ ],+ }+++async def post_event(client: httpx.AsyncClient, title: str) -> None:+ r = await client.post(+ f"{INGEST}/v1/ingest/batch",+ json=event_payload(title),+ headers={"X-Tenant-ID": TENANT},+ timeout=10,+ )+ r.raise_for_status()+ body = r.json()+ if body.get("accepted") != 1:+ raise SystemExit(f"ingest rejected the event: {body}")+ log(f"ingest accepted event title={title!r}")+++async def count_alerts_titled(client: httpx.AsyncClient, title: str) -> int:+ r = await client.get(f"{API}/api/v1/alerts", params={"page_size": 200}, timeout=10)+ r.raise_for_status()+ items = r.json().get("items", [])+ return sum(1 for a in items if a.get("title") == title)+++async def get_alert_titled(client: httpx.AsyncClient, title: str) -> dict | None:+ r = await client.get(f"{API}/api/v1/alerts", params={"page_size": 200}, timeout=10)+ r.raise_for_status()+ for a in r.json().get("items", []):+ if a.get("title") == title:+ return a+ return None+++async def mint_ws_ticket(client: httpx.AsyncClient) -> str:+ r = await client.post(f"{API}/api/v1/realtime/ticket", timeout=10)+ r.raise_for_status()+ return r.json()["token"]+++async def ws_listener(ticket: str, title: str, found: asyncio.Event) -> None:+ """Listen on the alerts channel until a fused frame carrying `title` arrives."""+ url = f"{REALTIME_WS}/ws/alerts?token={ticket}"+ async with websockets.connect(url, open_timeout=15) as ws:+ log("websocket connected")+ while not found.is_set():+ raw = await ws.recv()+ try:+ frame = json.loads(raw)+ except (TypeError, ValueError):+ continue+ if frame.get("type") != "alert.fused":+ continue+ payload = frame.get("payload") or {}+ alert = payload.get("alert") or {}+ if alert.get("title") == title:+ log("websocket frame received for spine event")+ found.set()+++async def await_alert_row(client: httpx.AsyncClient, title: str, timeout_s: int, repost: bool) -> None:+ """Poll the API until the alert row exists. Optionally re-POST the event to+ ride out consumer-group assignment races (dedup keeps this idempotent)."""+ deadline = time.monotonic() + timeout_s+ last_post = time.monotonic()+ while time.monotonic() < deadline:+ if await count_alerts_titled(client, title) >= 1:+ log("alert row visible via GET /api/v1/alerts")+ return+ if repost and time.monotonic() - last_post > REPOST_INTERVAL_S:+ await post_event(client, title)+ last_post = time.monotonic()+ await asyncio.sleep(3)+ raise SystemExit(f"alert row for {title!r} never appeared within {timeout_s}s")+++async def full_spine_test() -> None:+ title = f"SpineTest-{uuid.uuid4().hex[:12]}"+ async with httpx.AsyncClient() as client:+ await wait_healthy(client)++ # WS listener must be up before the event flows.+ ticket = await mint_ws_ticket(client)+ ws_found = asyncio.Event()+ ws_task = asyncio.create_task(ws_listener(ticket, title, ws_found))++ # Give the fusion + realtime consumer groups a moment to be assigned+ # partitions after boot; the repost loop below covers the rest.+ await asyncio.sleep(5)+ started = time.monotonic()+ await post_event(client, title)++ await await_alert_row(client, title, SPINE_BUDGET_S, repost=True)+ elapsed = time.monotonic() - started+ log(f"raw event → alert row in {elapsed:.1f}s")++ # WS frame: every fused alert (including dedup republish) is broadcast,+ # and the repost loop keeps producing until the row exists, so the+ # frame must arrive promptly if the realtime consumer is alive.+ try:+ await asyncio.wait_for(ws_found.wait(), timeout=60)+ except TimeoutError:+ raise SystemExit("no alert.fused WebSocket frame received within 60s") from None+ finally:+ ws_task.cancel()++ # Alert content assertions — the row must carry the fused pipeline's+ # fingerprint of the original telemetry, not a bare title.+ alert = await get_alert_titled(client, title)+ assert alert is not None+ for field, expected in [("severity", "critical"), ("status", "new")]:+ if alert.get(field) != expected:+ raise SystemExit(f"alert.{field}={alert.get(field)!r}, expected {expected!r}")+ techniques = alert.get("mitre_techniques") or []+ if "T1003" not in techniques:+ raise SystemExit(f"ATT&CK enrichment lost in transit: {techniques}")++ # Duplicate suppression: same event again must NOT create a second row.+ await post_event(client, title)+ await asyncio.sleep(15)+ n = await count_alerts_titled(client, title)+ if n != 1:+ raise SystemExit(f"duplicate suppression failed: {n} rows for {title!r}")+ log("duplicate suppression verified (1 row after re-submit)")++ log("SPINE TEST PASSED")+++async def main() -> None:+ parser = argparse.ArgumentParser(description=__doc__)+ parser.add_argument("--post-event", action="store_true", help="only POST an event")+ parser.add_argument("--await-alert", action="store_true", help="only await the alert row")+ parser.add_argument("--title", help="event title for --post-event / --await-alert")+ parser.add_argument("--timeout", type=int, default=120)+ args = parser.parse_args()++ if args.post_event or args.await_alert:+ if not args.title:+ parser.error("--title is required with --post-event / --await-alert")+ async with httpx.AsyncClient() as client:+ if args.post_event:+ await post_event(client, args.title)+ if args.await_alert:+ await await_alert_row(client, args.title, args.timeout, repost=False)+ return++ await full_spine_test()+++if __name__ == "__main__":+ try:+ asyncio.run(main())+ except KeyboardInterrupt:+ sys.exit(130)diff --git a/scripts/restore.sh b/scripts/restore.shindex f0fb2b79b..500d2dc18 100755--- a/scripts/restore.sh+++ b/scripts/restore.sh@@ -110,7 +110,15 @@ resolve_timestamp() {filog "Latest timestamp: $TIMESTAMP"fi- [[ -z "$TIMESTAMP" ]] && { echo "--timestamp or --latest is required" >&2; exit 1; }+ if [[ -z "$TIMESTAMP" ]]; then+ echo "--timestamp or --latest is required" >&2+ exit 1+ fi+ # Return explicit success: with the previous `[[ -z … ]] && { … }` form, the+ # test evaluates false (exit 1) once a timestamp is resolved, and as the+ # function's last command that non-zero status propagated out and tripped+ # `set -e` in the caller — aborting every restore before it began.+ return 0}# ── pre-flight ─────────────────────────────────────────────────────────────────diff --git a/services/api/app/scripts/run_migrations.py b/services/api/app/scripts/run_migrations.pyindex 133247388..ea40020d7 100644--- a/services/api/app/scripts/run_migrations.py+++ b/services/api/app/scripts/run_migrations.py@@ -244,6 +244,11 @@ async def main() -> None:if failures:logger.warning("%d migrations failed; see logs above", len(failures))+ # CI strict mode (Phase 3 migrations gate): any failed migration+ # must fail the job instead of shipping a partially-applied+ # schema that later boots "successfully" against missing tables.+ if os.environ.get("AISOC_MIGRATIONS_STRICT", "").strip().lower() in {"1", "true", "yes", "on"}:+ raise SystemExit(f"{len(failures)} migration(s) failed in strict mode")finally:await conn.close()diff --git a/services/fusion/app/core/config.py b/services/fusion/app/core/config.pyindex 7edca08e9..6218a79d2 100644--- a/services/fusion/app/core/config.py+++ b/services/fusion/app/core/config.py@@ -21,6 +21,13 @@ class Settings(BaseSettings):kafka_topic_alerts_raw: str = Field(default="aisoc.alerts.raw", alias="KAFKA_TOPIC_ALERTS_RAW")kafka_topic_alerts_fused: str = Field(default="aisoc.alerts.fused", alias="KAFKA_TOPIC_ALERTS_FUSED")kafka_consumer_group: str = Field(default="aisoc-fusion-consumer", alias="KAFKA_CONSUMER_GROUP")+ # Phase 3.1 spine bridge — ingest's normalized-event topic. Fusion promotes+ # findings + high/critical telemetry into RawAlerts (app/services/promoter.py).+ kafka_topic_raw_events: str = Field(default="aisoc.raw_events", alias="KAFKA_TOPIC_RAW_EVENTS")+ event_promotion_enabled: bool = Field(default=True, alias="AISOC_EVENT_PROMOTION_ENABLED")+ # Phase 3.1 spine bridge — persist fused (non-duplicate) alerts to the+ # Postgres alert store (app/services/alert_sink.py). Fail-soft by design.+ alert_sink_enabled: bool = Field(default=True, alias="AISOC_ALERT_SINK_ENABLED")# Redisredis_url: str = Field(default="redis://localhost:6379/2", alias="REDIS_URL")diff --git a/services/fusion/app/main.py b/services/fusion/app/main.pyindex 6ca9e078f..5f3d05e99 100644--- a/services/fusion/app/main.py+++ b/services/fusion/app/main.py@@ -8,6 +8,7 @@ from app._health import install_health_routesfrom app.api.router import router, set_workerfrom app.core.config import settingsfrom app.core.logging import configure_logging, logger+from app.services.alert_sink import AlertSinkfrom app.services.confidence import ConfidenceScorerfrom app.services.correlator import Correlatorfrom app.services.deduplicator import Deduplicator@@ -33,7 +34,11 @@ async def lifespan(app: FastAPI):entity_risk=entity_risk,confidence_scorer=confidence_scorer,)- worker = FusionWorker(engine)+ # Phase 3.1 — fused alerts land in the Postgres alert store so the spine+ # is continuous (raw event → alert row). Fail-soft: a missing/unreachable+ # DB never blocks the Kafka pipeline.+ sink = AlertSink(settings.database_url) if settings.alert_sink_enabled else None+ worker = FusionWorker(engine, sink=sink)set_worker(worker)# Start Kafka worker as a background taskdiff --git a/services/fusion/app/services/alert_sink.py b/services/fusion/app/services/alert_sink.pynew file mode 100644index 000000000..a4cc3537d--- /dev/null+++ b/services/fusion/app/services/alert_sink.py@@ -0,0 +1,164 @@+"""Persist fused alerts into the Postgres ``alerts`` table.++Phase 3.1 (world-class program) closed the second spine gap the reality audit+exposed: fusion published fused alerts to ``aisoc.alerts.fused`` and — before+this module — **nothing wrote them to the alert store**. The only writers were+the API's manual ``POST /alerts/submit`` endpoint and the demo seeder, so a+raw event could never become an alert row without a human in the loop.++Design constraints:++* **Fail-soft.** Fusion ran for months without a database; a Postgres outage+ must degrade to "fused alerts still stream over Kafka/WS, persistence+ resumes when the DB returns" — never crash the consumer.+* **Idempotent.** The insert is guarded by the alert's dedup fingerprint per+ tenant, so replaying a Kafka batch (consumer-group rebalance, restart+ mid-batch) cannot produce duplicate rows.+* **Duplicates are not persisted.** Fusion publishes DUPLICATE decisions+ downstream for observability, but they must not become new alert rows.+"""++from __future__ import annotations++import json++import asyncpg+import structlog++from app.models.alert import FusedAlert, FusionDecision++logger = structlog.get_logger()++_INSERT_SQL = """+INSERT INTO alerts (+ tenant_id, title, description, severity, status,+ mitre_tactics, mitre_techniques, iocs, entities, raw_event,+ dedup_hash, confidence, confidence_label, confidence_rationale,+ narrative, anomaly_score, event_time+)+SELECT+ $1, $2, $3, $4, 'new',+ $5::jsonb, $6::jsonb, $7::jsonb, $8::jsonb, $9::jsonb,+ $10::text, $11, $12, $13::jsonb,+ $14, $15, COALESCE($16, NOW())+WHERE NOT EXISTS (+ SELECT 1 FROM alerts WHERE tenant_id = $1 AND dedup_hash = $10::text+)+RETURNING id+"""+# NB: $10 (dedup_hash) is cast to ::text in BOTH the INSERT target and the+# WHERE. `dedup_hash` is VARCHAR(64), and varchar comparisons resolve through+# text operators — so `WHERE dedup_hash = $10` deduces $10 as text while the+# INSERT target deduces it as varchar. asyncpg's prepare cannot unify the two+# ("inconsistent types deduced for parameter $10: text versus character+# varying") and the persist fails silently, so no alert row is ever written.+# Pinning both uses to ::text makes the deduction unambiguous.+++def _asyncpg_dsn(url: str) -> str:+ """Strip the SQLAlchemy driver suffix — asyncpg wants plain postgresql://."""+ return url.replace("postgresql+asyncpg://", "postgresql://", 1)+++def _iocs(fused: FusedAlert) -> list[dict[str, str]]:+ alert = fused.alert+ out: list[dict[str, str]] = []+ for ioc_type, value in (+ ("ip", alert.src_ip),+ ("ip", alert.dst_ip),+ ("hash", alert.file_hash),+ ("domain", alert.domain),+ ("url", alert.url),+ ):+ if value:+ out.append({"type": ioc_type, "value": value})+ return out+++def _entities(fused: FusedAlert) -> list[dict[str, str]]:+ alert = fused.alert+ out: list[dict[str, str]] = []+ if alert.hostname:+ out.append({"type": "host", "value": alert.hostname})+ if alert.username:+ out.append({"type": "user", "value": alert.username})+ return out+++class AlertSink:+ """asyncpg-backed writer from the fusion pipeline into the alert store."""++ def __init__(self, database_url: str, pool_size: int = 2) -> None:+ self._dsn = _asyncpg_dsn(database_url)+ self._pool_size = pool_size+ self._pool: asyncpg.Pool | None = None+ self._connect_failed_logged = False++ async def start(self) -> None:+ """Open the pool. Failure is logged, not raised (fail-soft)."""+ try:+ self._pool = await asyncpg.create_pool(self._dsn, min_size=1, max_size=self._pool_size, timeout=10)+ logger.info("alert_sink.started")+ except Exception as exc: # noqa: BLE001 — degrade, never crash the worker+ self._pool = None+ logger.error("alert_sink.connect_failed", error=str(exc))++ async def stop(self) -> None:+ if self._pool is not None:+ await self._pool.close()+ self._pool = None++ async def _ensure_pool(self) -> asyncpg.Pool | None:+ if self._pool is None:+ # One reconnect attempt per persist call — cheap when the DB is+ # down (fast connect error) and self-healing when it returns.+ await self.start()+ return self._pool++ async def persist(self, fused: FusedAlert) -> str | None:+ """Insert one fused alert. Returns the new row id, or ``None`` when+ skipped (duplicate decision, dedup hit, or DB unavailable)."""+ if fused.fusion_decision == FusionDecision.DUPLICATE:+ return None++ pool = await self._ensure_pool()+ if pool is None:+ if not self._connect_failed_logged:+ logger.error("alert_sink.unavailable_dropping_persistence")+ self._connect_failed_logged = True+ return None+ self._connect_failed_logged = False++ alert = fused.alert+ try:+ async with pool.acquire() as conn:+ row = await conn.fetchrow(+ _INSERT_SQL,+ alert.tenant_id,+ alert.title[:500],+ alert.description or None,+ alert.severity.value,+ json.dumps(alert.mitre_tactics),+ json.dumps(alert.mitre_techniques),+ json.dumps(_iocs(fused)),+ json.dumps(_entities(fused)),+ json.dumps(alert.raw_event, default=str),+ alert.fingerprint(),+ int(round(fused.confidence_score * 100)),+ fused.confidence_label.value,+ json.dumps([f.model_dump() for f in fused.confidence_rationale]),+ fused.narrative,+ fused.anomaly_score,+ alert.event_time,+ )+ if row is None:+ logger.debug("alert_sink.dedup_skip", fingerprint=alert.fingerprint())+ return None+ return str(row["id"])+ except asyncpg.ForeignKeyViolationError:+ # Unknown tenant — a mis-provisioned connector, not a pipeline bug.+ logger.warning("alert_sink.unknown_tenant", tenant_id=str(alert.tenant_id))+ return None+ except Exception as exc: # noqa: BLE001 — one bad row must not wedge the consumer+ logger.error("alert_sink.persist_failed", error=str(exc))+ return Nonediff --git a/services/fusion/app/services/promoter.py b/services/fusion/app/services/promoter.pynew file mode 100644index 000000000..ea0230f5d--- /dev/null+++ b/services/fusion/app/services/promoter.py@@ -0,0 +1,180 @@+"""Promotion of ingest-normalized OCSF events into fusion RawAlerts.++Phase 3.1 (world-class program) closed the first of the two spine gaps the+reality audit exposed: ``services/ingest`` publishes normalized OCSF events to+``aisoc.raw_events`` and — before this module — **nothing consumed them**. The+fusion worker now subscribes to that topic and runs every message through+:func:`promote_normalized_event`.++Promotion policy (deterministic, no LLM, documented honestly):++* **Vendor-asserted findings are promoted.** Any event in the OCSF *Findings*+ category (``class_uid`` 2000–2999 — Security Finding, Detection Finding,+ etc.) is already an alert in the source product's judgment; dropping it on+ the floor would be silent data loss.+* **High/critical telemetry is promoted.** Non-finding events with+ ``severity_id >= 4`` (High / Critical / Fatal on the OCSF ladder) are+ promoted so a critical Okta or K8s event is never invisible to the SOC.+* **Everything else is NOT promoted.** Turning raw Medium-and-below telemetry+ into alerts is the job of the detection engine, not this bridge — promoting+ it here would destroy the alert-reduction property the fusion stage exists+ to provide.++Events whose ``tenant_id`` is not a UUID are skipped (the alert store keys+tenants by UUID; a non-UUID tenant header is a mis-configured connector, and+we log it rather than crash the consumer).+"""++from __future__ import annotations++import uuid+from datetime import datetime+from typing import Any++import structlog++from app.models.alert import AlertSeverity, RawAlert++logger = structlog.get_logger()++# OCSF category 2 = Findings (Security Finding 2001, Vulnerability Finding+# 2002, Compliance Finding 2003, Detection Finding 2004, ...).+_FINDINGS_CATEGORY = 2++# OCSF severity_id >= 4 means High(4) / Critical(5) / Fatal(6).+_PROMOTE_SEVERITY_FLOOR = 4++_SEVERITY_BY_ID: dict[int, AlertSeverity] = {+ 6: AlertSeverity.CRITICAL, # OCSF Fatal collapses onto our critical tier+ 5: AlertSeverity.CRITICAL,+ 4: AlertSeverity.HIGH,+ 3: AlertSeverity.MEDIUM,+ 2: AlertSeverity.LOW,+ 1: AlertSeverity.INFO,+ 0: AlertSeverity.MEDIUM, # Unknown — median tier, never silently info+}+++def _get_nested(obj: dict[str, Any], *path: str) -> Any:+ cur: Any = obj+ for key in path:+ if not isinstance(cur, dict):+ return None+ cur = cur.get(key)+ return cur+++def _first_file_hash(ocsf: dict[str, Any]) -> str | None:+ fingerprints = _get_nested(ocsf, "file", "fingerprints")+ if isinstance(fingerprints, list) and fingerprints:+ first = fingerprints[0]+ if isinstance(first, dict):+ value = first.get("value")+ if isinstance(value, str) and value:+ return value+ return None+++def _mitre(ocsf: dict[str, Any]) -> tuple[list[str], list[str]]:+ """Extract (tactics, techniques) from the ingest ATT&CK enrichment block."""+ tactics: list[str] = []+ techniques: list[str] = []+ block = ocsf.get("mitre_attck")+ if isinstance(block, list):+ for entry in block:+ if not isinstance(entry, dict):+ continue+ tid = entry.get("technique_id")+ if isinstance(tid, str) and tid and tid not in techniques:+ techniques.append(tid)+ names = entry.get("tactic_names")+ if isinstance(names, list):+ for name in names:+ if isinstance(name, str) and name and name not in tactics:+ tactics.append(name)+ return tactics, techniques+++def _title(ocsf: dict[str, Any]) -> str:+ for key in ("message", "activity_name"):+ val = ocsf.get(key)+ if isinstance(val, str) and val.strip():+ return val.strip()[:500]+ class_name = ocsf.get("class_name") or "Security event"+ product = _get_nested(ocsf, "metadata", "product", "name")+ if isinstance(product, str) and product:+ return f"{class_name} from {product}"[:500]+ return str(class_name)[:500]+++def _source(ocsf: dict[str, Any]) -> str:+ vendor = _get_nested(ocsf, "metadata", "product", "vendor_name")+ product = _get_nested(ocsf, "metadata", "product", "name")+ parts = [p for p in (vendor, product) if isinstance(p, str) and p]+ return " ".join(parts) or "ingest"+++def _event_time(ocsf: dict[str, Any]) -> datetime | None:+ raw = ocsf.get("time")+ if isinstance(raw, str) and raw:+ try:+ return datetime.fromisoformat(raw.replace("Z", "+00:00"))+ except ValueError:+ return None+ return None+++def should_promote(ocsf: dict[str, Any]) -> bool:+ """Deterministic promotion decision — see module docstring for policy."""+ class_uid = ocsf.get("class_uid")+ if isinstance(class_uid, int) and class_uid // 1000 == _FINDINGS_CATEGORY:+ return True+ severity_id = ocsf.get("severity_id")+ return isinstance(severity_id, int) and severity_id >= _PROMOTE_SEVERITY_FLOOR+++def promote_normalized_event(message: dict[str, Any]) -> RawAlert | None:+ """Convert one ``aisoc.raw_events`` message into a RawAlert, or ``None``.++ ``message`` is the JSON body ``services/ingest`` publishes — a+ ``NormalizedEvent`` with ``ocsf_event`` carrying the OCSF payload.+ Returns ``None`` when the event doesn't meet the promotion policy or the+ message is malformed (logged, never raised — one bad event must not wedge+ the consumer; the Phase 5 DLQ takes over from there).+ """+ ocsf = message.get("ocsf_event")+ if not isinstance(ocsf, dict):+ logger.warning("promoter.malformed_message", keys=sorted(message.keys()))+ return None++ if not should_promote(ocsf):+ return None++ tenant_raw = message.get("tenant_id") or ocsf.get("tenant_uid")+ try:+ tenant_id = uuid.UUID(str(tenant_raw))+ except (ValueError, TypeError):+ logger.warning("promoter.non_uuid_tenant", tenant_id=str(tenant_raw)[:64])+ return None++ severity_id = ocsf.get("severity_id")+ severity = _SEVERITY_BY_ID.get(severity_id if isinstance(severity_id, int) else 0, AlertSeverity.MEDIUM)++ tactics, techniques = _mitre(ocsf)++ return RawAlert(+ tenant_id=tenant_id,+ source=_source(ocsf),+ title=_title(ocsf),+ description=str(ocsf.get("raw_data") or "")[:2000],+ severity=severity,+ src_ip=_get_nested(ocsf, "src_endpoint", "ip"),+ dst_ip=_get_nested(ocsf, "dst_endpoint", "ip"),+ hostname=_get_nested(ocsf, "device", "name"),+ username=_get_nested(ocsf, "actor", "user", "name"),+ file_hash=_first_file_hash(ocsf),+ mitre_tactics=tactics,+ mitre_techniques=techniques,+ raw_event=ocsf,+ event_time=_event_time(ocsf),+ )diff --git a/services/fusion/app/workers/consumer.py b/services/fusion/app/workers/consumer.pyindex ac2e515bc..446d35c72 100644--- a/services/fusion/app/workers/consumer.py+++ b/services/fusion/app/workers/consumer.py@@ -1,6 +1,7 @@"""-Kafka consumer worker: reads raw alerts, runs them through the fusion engine,-and publishes fused results back to Kafka.+Kafka consumer worker: reads raw alerts (and, since Phase 3.1, ingest's+normalized OCSF events), runs them through the fusion engine, publishes fused+results back to Kafka, and persists non-duplicate alerts to Postgres."""import json@@ -10,7 +11,9 @@ from aiokafka import AIOKafkaConsumer, AIOKafkaProducerfrom app.core.config import settingsfrom app.models.alert import FusionDecision, RawAlert+from app.services.alert_sink import AlertSinkfrom app.services.fusion_engine import FusionEngine+from app.services.promoter import promote_normalized_eventlogger = structlog.get_logger()@@ -19,6 +22,9 @@ _METRICS = {"duplicates": 0,"correlated": 0,"new_incidents": 0,+ "promoted": 0,+ "not_promoted": 0,+ "persisted": 0,"errors": 0,}@@ -26,8 +32,9 @@ _METRICS = {class FusionWorker:"""Kafka consumer/producer pair that drives the fusion pipeline."""- def __init__(self, engine: FusionEngine) -> None:+ def __init__(self, engine: FusionEngine, sink: AlertSink | None = None) -> None:self._engine = engine+ self._sink = sinkself._consumer: AIOKafkaConsumer | None = Noneself._producer: AIOKafkaProducer | None = Noneself._running = False@@ -37,8 +44,11 @@ class FusionWorker:return self._engineasync def start(self) -> None:+ topics = [settings.kafka_topic_alerts_raw]+ if settings.event_promotion_enabled:+ topics.append(settings.kafka_topic_raw_events)self._consumer = AIOKafkaConsumer(- settings.kafka_topic_alerts_raw,+ *topics,bootstrap_servers=settings.kafka_bootstrap_servers,group_id=settings.kafka_consumer_group,auto_offset_reset="latest",@@ -51,12 +61,15 @@ class FusionWorker:)await self._consumer.start()await self._producer.start()+ if self._sink is not None:+ await self._sink.start()self._running = Truelogger.info("Fusion worker started",consumer_group=settings.kafka_consumer_group,- input_topic=settings.kafka_topic_alerts_raw,+ input_topics=topics,output_topic=settings.kafka_topic_alerts_fused,+ alert_sink=self._sink is not None,)await self._consume_loop()@@ -66,6 +79,8 @@ class FusionWorker:await self._consumer.stop()if self._producer:await self._producer.stop()+ if self._sink is not None:+ await self._sink.stop()logger.info("Fusion worker stopped", metrics=_METRICS)async def _consume_loop(self) -> None:@@ -73,18 +88,28 @@ class FusionWorker:if not self._running:breaktry:- await self._process_message(msg.value)+ await self._process_message(msg.value, topic=msg.topic)except Exception as exc:_METRICS["errors"] += 1logger.error("Failed to process message", error=str(exc), exc_info=True)- async def _process_message(self, payload: dict) -> None:- try:- alert = RawAlert.model_validate(payload)- except Exception as exc:- logger.warning("Invalid alert payload", error=str(exc))- _METRICS["errors"] += 1- return+ async def _process_message(self, payload: dict, topic: str | None = None) -> None:+ if topic == settings.kafka_topic_raw_events:+ # Ingest-normalized OCSF event — run the deterministic promotion+ # policy (see app/services/promoter.py). Non-promoted events are+ # dropped here by design; the detect stage owns rule evaluation.+ alert = promote_normalized_event(payload)+ if alert is None:+ _METRICS["not_promoted"] += 1+ return+ _METRICS["promoted"] += 1+ else:+ try:+ alert = RawAlert.model_validate(payload)+ except Exception as exc:+ logger.warning("Invalid alert payload", error=str(exc))+ _METRICS["errors"] += 1+ returnfused = await self._engine.process(alert)_METRICS["processed"] += 1@@ -102,6 +127,12 @@ class FusionWorker:value=fused.model_dump(mode="json"),)+ # Persist to the alert store (Phase 3.1). Fail-soft + idempotent —+ # see app/services/alert_sink.py. Duplicates are skipped inside.+ if self._sink is not None:+ if await self._sink.persist(fused) is not None:+ _METRICS["persisted"] += 1+@staticmethoddef get_metrics() -> dict:return dict(_METRICS)diff --git a/services/fusion/tests/test_alert_sink.py b/services/fusion/tests/test_alert_sink.pynew file mode 100644index 000000000..250eb3575--- /dev/null+++ b/services/fusion/tests/test_alert_sink.py@@ -0,0 +1,136 @@+"""Unit tests for the Phase 3.1 fused-alert → Postgres sink.++Covers the skip/fail-soft decision logic with a stub pool. The real-container+insert path is gated by `.github/workflows/integration.yml`+(scripts/integration/spine_test.py) — asserting SQL against a live Postgres,+not a mock.+"""++from __future__ import annotations++import uuid+from contextlib import asynccontextmanager++import pytest+from app.models.alert import (+ AlertSeverity,+ FusedAlert,+ FusionDecision,+ RawAlert,+)+from app.services.alert_sink import AlertSink, _asyncpg_dsn, _entities, _iocs++TENANT = uuid.UUID("00000000-0000-0000-0000-000000000001")+++def _fused(decision: FusionDecision = FusionDecision.NEW_ALERT) -> FusedAlert:+ raw = RawAlert(+ tenant_id=TENANT,+ source="CrowdStrike Falcon",+ title="Credential dumping via LSASS access",+ severity=AlertSeverity.CRITICAL,+ src_ip="10.20.30.40",+ hostname="WIN-DC01",+ username="svc-backup",+ mitre_techniques=["T1003"],+ )+ return FusedAlert(+ id=raw.id,+ tenant_id=TENANT,+ fusion_decision=decision,+ alert=raw,+ )+++class _StubConn:+ def __init__(self, row):+ self._row = row+ self.calls: list[tuple] = []++ async def fetchrow(self, sql, *args):+ self.calls.append((sql, args))+ return self._row+++class _StubPool:+ def __init__(self, row):+ self.conn = _StubConn(row)++ @asynccontextmanager+ async def _acquire(self):+ yield self.conn++ def acquire(self):+ return self._acquire()+++def test_dsn_strips_sqlalchemy_driver():+ assert _asyncpg_dsn("postgresql+asyncpg://u:p@h:5432/db") == "postgresql://u:p@h:5432/db"+ assert _asyncpg_dsn("postgresql://u:p@h:5432/db") == "postgresql://u:p@h:5432/db"+++def test_iocs_and_entities_extraction():+ fused = _fused()+ iocs = _iocs(fused)+ assert {"type": "ip", "value": "10.20.30.40"} in iocs+ entities = _entities(fused)+ assert {"type": "host", "value": "WIN-DC01"} in entities+ assert {"type": "user", "value": "svc-backup"} in entities+++async def test_duplicate_decision_is_never_persisted():+ sink = AlertSink("postgresql://x")+ sink._pool = _StubPool(row={"id": uuid.uuid4()}) # would succeed if called+ result = await sink.persist(_fused(FusionDecision.DUPLICATE))+ assert result is None+ assert sink._pool.conn.calls == []+++async def test_new_alert_is_inserted_with_fingerprint():+ row_id = uuid.uuid4()+ pool = _StubPool(row={"id": row_id})+ sink = AlertSink("postgresql://x")+ sink._pool = pool++ fused = _fused()+ result = await sink.persist(fused)++ assert result == str(row_id)+ (sql, args) = pool.conn.calls[0]+ assert "INSERT INTO alerts" in sql+ assert "WHERE NOT EXISTS" in sql # idempotency guard+ assert args[0] == TENANT+ assert args[9] == fused.alert.fingerprint() # dedup_hash+++async def test_dedup_hit_returns_none():+ pool = _StubPool(row=None) # WHERE NOT EXISTS filtered the insert out+ sink = AlertSink("postgresql://x")+ sink._pool = pool+ assert await sink.persist(_fused()) is None+++async def test_db_unavailable_degrades_without_raising(monkeypatch):+ sink = AlertSink("postgresql://nope:[email protected]:1/none")++ async def _fail_start():+ sink._pool = None++ monkeypatch.setattr(sink, "start", _fail_start)+ # Must not raise — fail-soft is the contract.+ assert await sink.persist(_fused()) is None+++async def test_persist_exception_is_swallowed():+ class _BoomPool(_StubPool):+ def acquire(self):+ raise RuntimeError("connection reset")++ sink = AlertSink("postgresql://x")+ sink._pool = _BoomPool(row=None)+ assert await sink.persist(_fused()) is Nonediff --git a/services/fusion/tests/test_promoter.py b/services/fusion/tests/test_promoter.pynew file mode 100644index 000000000..3fb7a08fd--- /dev/null+++ b/services/fusion/tests/test_promoter.py@@ -0,0 +1,129 @@+"""Unit tests for the Phase 3.1 raw-event → RawAlert promotion bridge.++These cover the deterministic mapping logic. The gate that proves the bridge+works against real containers is `.github/workflows/integration.yml`+(scripts/integration/spine_test.py) — these tests never mock Kafka/Postgres+and never claim to.+"""++from __future__ import annotations++import uuid++from app.models.alert import AlertSeverity+from app.services.promoter import promote_normalized_event, should_promote++TENANT = "00000000-0000-0000-0000-000000000001"+++def _message(ocsf_overrides: dict | None = None) -> dict:+ ocsf = {+ "class_uid": 2001,+ "class_name": "Security Finding",+ "category_uid": 2,+ "severity_id": 5,+ "severity": "Critical",+ "message": "Credential dumping via LSASS access",+ "time": "2026-07-12T08:00:00Z",+ "tenant_uid": TENANT,+ "metadata": {"product": {"name": "Falcon", "vendor_name": "CrowdStrike"}},+ "device": {"name": "WIN-DC01"},+ "actor": {"user": {"name": "svc-backup"}},+ "src_endpoint": {"ip": "10.20.30.40"},+ "file": {"fingerprints": [{"value": "a" * 64}]},+ "mitre_attck": [+ {+ "technique_id": "T1003",+ "technique_name": "OS Credential Dumping",+ "tactic_names": ["Credential Access"],+ }+ ],+ "raw_data": '{"event_simpleName":"CredentialDump"}',+ }+ if ocsf_overrides:+ ocsf.update(ocsf_overrides)+ return {+ "id": str(uuid.uuid4()),+ "connector_id": "conn-1",+ "tenant_id": TENANT,+ "ocsf_event": ocsf,+ "normalization_version": "1.1.0",+ }+++class TestShouldPromote:+ def test_findings_category_always_promotes(self):+ assert should_promote({"class_uid": 2004, "severity_id": 1})++ def test_high_severity_non_finding_promotes(self):+ assert should_promote({"class_uid": 3002, "severity_id": 4})++ def test_critical_non_finding_promotes(self):+ assert should_promote({"class_uid": 4001, "severity_id": 5})++ def test_medium_non_finding_does_not_promote(self):+ assert not should_promote({"class_uid": 4001, "severity_id": 3})++ def test_unknown_severity_non_finding_does_not_promote(self):+ assert not should_promote({"class_uid": 6003, "severity_id": 0})++ def test_missing_fields_do_not_promote(self):+ assert not should_promote({})+++class TestPromoteNormalizedEvent:+ def test_full_mapping(self):+ alert = promote_normalized_event(_message())+ assert alert is not None+ assert str(alert.tenant_id) == TENANT+ assert alert.title == "Credential dumping via LSASS access"+ assert alert.severity == AlertSeverity.CRITICAL+ assert alert.source == "CrowdStrike Falcon"+ assert alert.hostname == "WIN-DC01"+ assert alert.username == "svc-backup"+ assert alert.src_ip == "10.20.30.40"+ assert alert.file_hash == "a" * 64+ assert alert.mitre_techniques == ["T1003"]+ assert alert.mitre_tactics == ["Credential Access"]+ assert alert.event_time is not None+ assert alert.raw_event["class_uid"] == 2001++ def test_severity_ladder(self):+ for sev_id, expected in [+ (5, AlertSeverity.CRITICAL),+ (4, AlertSeverity.HIGH),+ (3, AlertSeverity.MEDIUM),+ (2, AlertSeverity.LOW),+ (1, AlertSeverity.INFO),+ ]:+ alert = promote_normalized_event(_message({"severity_id": sev_id}))+ assert alert is not None, f"severity_id={sev_id} (finding) must promote"+ assert alert.severity == expected++ def test_below_threshold_non_finding_returns_none(self):+ msg = _message({"class_uid": 4001, "category_uid": 4, "severity_id": 2})+ assert promote_normalized_event(msg) is None++ def test_title_falls_back_to_class_and_product(self):+ msg = _message()+ del msg["ocsf_event"]["message"]+ alert = promote_normalized_event(msg)+ assert alert is not None+ assert alert.title == "Security Finding from Falcon"++ def test_non_uuid_tenant_returns_none(self):+ msg = _message()+ msg["tenant_id"] = "acme-corp"+ msg["ocsf_event"]["tenant_uid"] = "acme-corp"+ assert promote_normalized_event(msg) is None++ def test_malformed_message_returns_none(self):+ assert promote_normalized_event({"nope": True}) is None+ assert promote_normalized_event({"ocsf_event": "not-a-dict"}) is None++ def test_fingerprint_stable_across_promotions(self):+ # The same source event promoted twice must dedup downstream.+ a = promote_normalized_event(_message())+ b = promote_normalized_event(_message())+ assert a is not None and b is not None+ assert a.fingerprint() == b.fingerprint()