Skip to content

armgit / AiSOC

Public Imported from GitHub
0

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.

Asset criticality orders the investigation queue (#1576)

Beenu Arora7db3de5c9c7a
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index ed20a01b4..99b4844f1 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -105,7 +105,7 @@ jobs:
set -euo pipefail
spine_paths='services/ingest/ services/fusion/ services/realtime/ docker-compose.yml scripts/integration/ .github/workflows/integration.yml'
- migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py .github/workflows/integration.yml'
+ migration_paths='services/api/migrations/ services/api/app/scripts/run_migrations.py services/ueba/alembic/ services/api/tests/test_mssp_portfolio_isolation.py services/api/tests/test_alert_queue_priority_live.py services/api/app/services/alert_queue.py tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py .github/workflows/integration.yml'
# backup_crypt.py was missing from the old filter, and it is where
# every byte of the AES-256-GCM implementation lives — so a change
# to the encryption itself did not run the gate that proves the
@@ -780,6 +780,16 @@ jobs:
MSSP_ISOLATION_REQUIRED: '1'
run: pip install --quiet pytest pytest-asyncio && python -m pytest tests/test_mssp_portfolio_isolation.py -v --tb=short
+ # Asset criticality orders the queue: the lower(name)/IP-overlap match,
+ # the exploited-and-unremediated KEV filter and the tenant predicate on
+ # both resolver queries are schema facts only this job can check. The
+ # negative control removes the resolver and asserts the order collapses.
+ - name: Queue priority resolves the tenant's asset inventory (live Postgres)
+ working-directory: services/api
+ env:
+ MSSP_ISOLATION_REQUIRED: '1'
+ run: python -m pytest tests/test_alert_queue_priority_live.py -v --tb=short
+
# 060_rls_coverage.sql takes RLS from 31 of 95 tenant-scoped tables to
# every one of them bar a documented exclusion. A migration that adds 49
# policies is worth what the evidence that they filter is worth, so the
diff --git a/CHANGELOG.md b/CHANGELOG.md
index d5f7768ef..4cb6ec019 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,18 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Asset criticality orders the investigation queue.** The priority scorer
+ (severity as base, asset criticality / exploited-vulnerability / internet
+ exposure as bounded multipliers) existed with zero callers, so two alerts
+ of equal severity — one on a domain controller, one on a meeting-room
+ display — arrived in the order they were raised. `build_queue` now
+ resolves each page against the tenant's own `assets` inventory in two
+ batched queries (hostname/FQDN/IP-overlap match; `is_exploited AND NOT
+ remediated` as the KEV signal) and orders within (bucket, SLA) by the
+ score. Every row carries `priority_score` and a factor-by-factor
+ `priority_basis`; no inventory means severity alone, and the basis says
+ so. Proven on live Postgres with a negative control that removes the
+ resolver and watches the order collapse.
- **An opt-in ack-clock escalation bridge** (`services/escalations`, compose
profile `escalations`; externally contributed). The native outbound-webhook
subsystem is complete but its `enqueue_event` has no production callers, so
diff --git a/ROADMAP.md b/ROADMAP.md
index 9b43582e2..ec0f127e5 100644
--- a/ROADMAP.md
+++ b/ROADMAP.md
@@ -45,7 +45,7 @@ A proof-first, security-first program to make every README claim gate-backed, cl
- **Phase D (breadth):** D1 eight connectors (QRadar/Exabeam/Securonix/Devo/Netskope/Windows-Sysmon/Zeek-Suricata/syslog-CEF) · D2 AI/LLM-usage audit connector + `llm-*` detections + hot/cold lake tiering · D3 live-vendor mock-server smoke.
- **Phase E (prove it):** E1 CI-gated benchmark scoreboard tied to a deterministic live-agent MITRE-accuracy run.
-The claim-to-gate matrix stands at **324 rows — 319 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
+The claim-to-gate matrix stands at **325 rows — 320 GATED / 5 PARTIAL / 0 NO GATE**. Five rows are PARTIAL, each naming what closes it: "Cloud-native collection" until a capture recorded from a live Event Hub replaces the fixture synthesised from the Avro specification; "the retention window a tenant chooses is the one the lake honours" until a live ClickHouse test watches a row survive past the old 90-day boundary; "the AI estate is discovered on the endpoint" until a containerised osquery runs the shipped pack end to end; and "a reported phishing message can be purged across its recipients" until a maintainer-supplied Microsoft 365 or Google Workspace tenant lets the documented request shapes be exercised for real; and "every automatic closure of a production alert is checked against the current policy, grant and stop controls" until the live suite that proves it against real Postgres has been observed to pass on `main` rather than only in the pull request that added it. "SSO completes a sign-in" closed the way the programme requires — by building the gate it named: `sso-live.yml` stands up a containerised Keycloak and both legs have been observed to pass. Every other product claim is backed by a failing test, none is a named deferral either, and the ratchet (`MAX_NO_GATE=0`) forbids any regression. Every PARTIAL row was closed by building the gate it named, never by relabelling. Count the table rows with `python3 scripts/check_claim_gate_matrix.py` rather than trusting a figure quoted in prose — this line has gone stale before. The six lettered deferrals are scoped in [`docs/audit/DEFERRED_SUBPHASES.md`](docs/audit/DEFERRED_SUBPHASES.md).
## v4.0 — Shipped
diff --git a/apps/docs/docs/compliance/evidence-pack.md b/apps/docs/docs/compliance/evidence-pack.md
index 9a0979cbb..06ed99084 100644
--- a/apps/docs/docs/compliance/evidence-pack.md
+++ b/apps/docs/docs/compliance/evidence-pack.md
@@ -33,7 +33,7 @@ and says so.
| Prompt-injection resistance | Three adversarial corpora: 32 payloads scanned in isolation and 71 incident pairs whose payloads are placed in attacker-controllable fields, both against a clean twin with a recall floor and a false-positive ceiling, plus 34 held-out pairs authored after the guard was frozen and carrying no floor at all, on which the guard measures 7.1% | `services/agents/tests/adversarial/` |
| Claim-to-gate traceability | Every product claim mapped to the CI job that fails when it stops being true | `docs/audit/CLAIM_TO_GATE_MATRIX.md` |
-The last row is the one worth reading first. It is the honest index: 319 rows
+The last row is the one worth reading first. It is the honest index: 320 rows
`GATED`, 5 `PARTIAL`, and a ratchet that refuses to let a row sit at
`NO GATE`. Re-read the figure from the table rather than from here — a count
copied into prose goes stale in silence, which is why
diff --git a/apps/docs/docs/console/queue.md b/apps/docs/docs/console/queue.md
index 9c1c25a2a..7d15a9114 100644
--- a/apps/docs/docs/console/queue.md
+++ b/apps/docs/docs/console/queue.md
@@ -8,6 +8,19 @@ description: The /queue workbench — an opinionated, single-page feed answering
`/queue` is the page a Tier-1 analyst lives on. It exists to answer one question — *"what should I work on next?"* — and it answers it the same way an experienced shift-lead would: alerts already assigned to you first, then critical and high alerts no one has claimed, all of it ordered by SLA due time so the closest-to-breach work surfaces first. Low-priority unassigned alerts are deliberately excluded; those are triaged in bulk on `/alerts`.
+Within the same bucket and SLA position, **asset criticality decides**: each
+page of rows is matched against your imported asset inventory (hostname, FQDN
+or IP), and two alerts of equal severity sort by what they landed on — a
+domain controller carrying an exploited vulnerability outranks a meeting-room
+kiosk. Severity is the base and context is a bounded multiplier, so inventory
+can reorder alerts of similar severity and can never invert a severity gap.
+Every row carries `priority_score` and a factor-by-factor `priority_basis`,
+because an ordering you cannot interrogate is one you stop trusting; on a
+tenant with no asset inventory the basis says "severity alone", honestly.
+One stated bound: the refinement applies within a page — the SQL's
+severity-rank order remains the pagination key, so a tie that straddles a
+page boundary is ordered by severity rank, not asset context.
+
This page documents the bucket model, the SLA timer, the action set, and the API surface that powers the workbench.
## Where the workbench sits
diff --git a/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 786aa1e57..d8e4bd0f2 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -110,6 +110,7 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| Entity-graph reads are scoped to the querying tenant | `apps/docs/docs/architecture/graph-schema.md` | `ci.yml :: api tests` (`test_graph_tenant_isolation.py` — asserts `tenant_id` is actually bound to the driver, and that every node of every blast-radius path is scoped; `tenant_id IS NULL` is not accepted anywhere) | full | GATED | - |
| Analysts can hunt the events AiSOC itself ingested | README (hunt surface) | `ci.yml :: api tests` (`test_lake_hunt.py` — the translator IR compiles to parameterised ClickHouse SQL with the tenant predicate generated rather than rewritten in; no question text reaches the SQL string) | full | GATED | - |
| Business-context rules authored in the console affect triage | `apps/docs/docs/console/` (business context) | `ci.yml` agents tests (`test_business_context_per_tenant.py` — rules resolve per tenant from Postgres, one tenant's suppression cannot affect another, and an outage serves last-known rules rather than silently un-suppressing) | core | GATED | - |
+| The queue orders equal-severity alerts by the asset they landed on | `apps/docs/docs/console/queue.md` (asset criticality) | `integration.yml` migrations job (`test_alert_queue_priority_live.py` — a critical asset with an exploited vulnerability outranks a low-criticality one at equal severity and SLA on live Postgres; the negative control removes the resolver and the scores collapse to a tie; another tenant's inventory is invisible; no inventory scores severity alone with the basis saying so) + `ci.yml` api job (`test_alert_queue.py` — projection carries `priority_score`/`priority_basis`, severity-alone defaults pinned) | core | GATED | The refinement orders within a page; the SQL severity-rank order remains the pagination key, stated in the queue doc |
| Seeded sample data never renders as a tenant's real state | Standing honesty rule (synthetic vs real) | `ci.yml :: python-lint` (`check_mock_data_gated.py` — fails the build on a `fallbackData` receiving sample data un-wrapped, on sample data assigned to state with no demo-mode check, and on a module-scope array of named entities carrying measurements in a component with no demo gate; the reviewed-exception list is checked in both directions so a stale exemption fails) + `tests/test_mock_data_gate.py` | core | GATED | the first two patterns needed a `MOCK_`/`DEMO_` name *and* a setter or `fallbackData`, so a fabricated table written inline under an ordinary name in a component that never fetched matched nothing — `MSSPDashboardView` and `TeamAnalyticsView` both shipped under a green gate until the third pattern was added; the check remains shape-based and cannot prove a view is honest |
| No fabricated value is reachable, and no component decides for itself that it is a demo | Standing honesty rule (synthetic vs real) | `ci.yml :: python-lint` (`check_demo_state_gated.py` — every read of a fabricated symbol must have a gate *in scope*, so a ternary, a factory call, or a constant assembled out of a mock all fail; and a `demoMode`-style local `useState` fails outright) + `tests/test_demo_state_gate.py` | core | GATED | the shape gate above accepts a file that mentions `demoFallback` anywhere — `SLADashboard.tsx` had it on line 446 and an ungated `isValidMetrics ? rawMetrics : MOCK_SLA_METRICS` on line 457, so 847 alerts and a 42.5m MTTR rendered on first paint and on error; this gate is scope-based rather than shape-based but still cannot prove a view is honest |
| Published executable-detection count matches what the engine loads | `docs/detections/truth-table.md` | `validate-detections.yml` (`detection_truth_table.py --check` now derives `executable` from `detection_ruleset.json` membership rather than file path and body keys; the old heuristic published 947 while the engine loaded 825, counted 77 Sigma rules with no evaluator, and would have certified a bulk un-quarantine as a no-op) | core | GATED | - |
@@ -335,8 +336,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 324
-- GATED: 319
+- Total: 325
+- GATED: 320
- PARTIAL: 5
- NO GATE: 0
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index 4c4a0cc17..567ad13cc 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -36470,6 +36470,14 @@ components:
- mine
- unassigned
title: Bucket
+ priority_score:
+ type: integer
+ title: Priority Score
+ default: 0
+ priority_basis:
+ additionalProperties: true
+ type: object
+ title: Priority Basis
type: object
required:
- id
diff --git a/services/api/app/services/alert_queue.py b/services/api/app/services/alert_queue.py
index 89bee0527..6806828f9 100644
--- a/services/api/app/services/alert_queue.py
+++ b/services/api/app/services/alert_queue.py
@@ -38,6 +38,7 @@ from sqlalchemy import and_, case, func, literal, or_, select, update
from sqlalchemy.ext.asyncio import AsyncSession
from app.models.alert import Alert
+from app.models.asset import Asset, AssetVulnerability
from app.models.sla import TenantSLAConfig
from app.services import sla_events
from app.services.alert_priority import AssetContext, IdentityContext, score_alert_priority
@@ -148,6 +149,18 @@ class QueueItem(BaseModel):
bucket: Literal["mine", "unassigned"]
+ # Context-aware ordering (gap-closure wave 11, wired by the
+ # business-context plan). ``priority_score`` is what the row sorts by
+ # within its (bucket, SLA) position: severity as the base, asset
+ # criticality / KEV / internet exposure as bounded multipliers, resolved
+ # from the tenant's own ``assets`` inventory. Distinct from ``priority``
+ # above, which is the vendor-reported integer carried off the alert row.
+ # ``priority_basis`` is the factor-by-factor rationale — an ordering a
+ # person cannot interrogate is one they stop trusting. On a tenant with
+ # no asset inventory the score is severity alone and the basis says so.
+ priority_score: int = 0
+ priority_basis: dict[str, Any] = Field(default_factory=dict)
+
class QueueResponse(BaseModel):
"""Paginated queue response.
@@ -311,6 +324,110 @@ def first_action(alert: Alert) -> QueueAction | None:
# ─── Queue assembly ─────────────────────────────────────────────────────
+async def resolve_asset_contexts(
+ db: AsyncSession,
+ tenant_id: uuid.UUID,
+ alerts: list[Alert],
+) -> dict[uuid.UUID, AssetContext]:
+ """Match a page of alerts to the tenant's asset inventory, batched.
+
+ Two queries for the whole page, never one per row: one against
+ ``assets`` on lowered hostname/FQDN or IP overlap, one against
+ ``asset_vulnerabilities`` for open exploited findings (the KEV
+ signal) on the assets that matched.
+
+ An alert matching several assets takes the highest-criticality one —
+ failing toward attention, because the queue's job is "what should I
+ look at first" and the costlier mistake is burying a domain
+ controller under a kiosk. An alert matching nothing gets no entry,
+ and the caller scores it on severity alone; that is the honest
+ day-one state of a deployment with no CMDB import.
+ """
+ host_by_alert: dict[uuid.UUID, set[str]] = {}
+ ip_by_alert: dict[uuid.UUID, set[str]] = {}
+ for alert in alerts:
+ hosts = {h.strip().lower() for h in (alert.affected_hosts or []) if isinstance(h, str) and h.strip()}
+ ips = {i.strip() for i in (alert.affected_ips or []) if isinstance(i, str) and i.strip()}
+ if hosts:
+ host_by_alert[alert.id] = hosts
+ if ips:
+ ip_by_alert[alert.id] = ips
+
+ all_hosts = sorted(set().union(*host_by_alert.values())) if host_by_alert else []
+ all_ips = sorted(set().union(*ip_by_alert.values())) if ip_by_alert else []
+ if not all_hosts and not all_ips:
+ return {}
+
+ match_clauses = []
+ if all_hosts:
+ match_clauses.append(func.lower(Asset.name).in_(all_hosts))
+ match_clauses.append(func.lower(Asset.fqdn).in_(all_hosts))
+ if all_ips:
+ match_clauses.append(Asset.ip_addresses.overlap(all_ips))
+
+ asset_rows = (
+ (
+ await db.execute(
+ select(Asset).where(
+ Asset.tenant_id == tenant_id,
+ or_(*match_clauses),
+ )
+ )
+ )
+ .scalars()
+ .all()
+ )
+ if not asset_rows:
+ return {}
+
+ # Open exploited vulnerabilities per matched asset — the KEV signal.
+ # `remediated_at IS NULL` because a fixed finding is history, not risk.
+ exploited_counts: dict[uuid.UUID, int] = {}
+ vuln_rows = (
+ await db.execute(
+ select(AssetVulnerability.asset_id, func.count())
+ .where(
+ AssetVulnerability.tenant_id == tenant_id,
+ AssetVulnerability.asset_id.in_([a.id for a in asset_rows]),
+ AssetVulnerability.is_exploited.is_(True),
+ AssetVulnerability.remediated_at.is_(None),
+ )
+ .group_by(AssetVulnerability.asset_id)
+ )
+ ).all()
+ for asset_id, count in vuln_rows:
+ exploited_counts[asset_id] = int(count)
+
+ crit_rank = {"critical": 4, "high": 3, "medium": 2, "low": 1, "none": 0}
+
+ def _context_of(asset: Asset) -> AssetContext:
+ tags = {t.strip().lower() for t in (asset.tags or []) if isinstance(t, str)}
+ meta = asset.asset_metadata if isinstance(asset.asset_metadata, dict) else {}
+ exploited = exploited_counts.get(asset.id, 0)
+ return AssetContext(
+ asset_id=str(asset.id),
+ criticality=str(asset.criticality or "medium").lower(),
+ has_kev_vulnerability=exploited > 0,
+ exploitable_vuln_count=exploited,
+ internet_facing=("internet-facing" in tags) or bool(meta.get("internet_facing")),
+ )
+
+ out: dict[uuid.UUID, AssetContext] = {}
+ for alert in alerts:
+ hosts = host_by_alert.get(alert.id, set())
+ ips = ip_by_alert.get(alert.id, set())
+ candidates = [
+ a
+ for a in asset_rows
+ if (a.name or "").lower() in hosts or (a.fqdn or "").lower() in hosts or (ips and set(a.ip_addresses or []) & ips)
+ ]
+ if not candidates:
+ continue
+ best = max(candidates, key=lambda a: crit_rank.get(str(a.criticality or "").lower(), 0))
+ out[alert.id] = _context_of(best)
+ return out
+
+
def queue_priority(alert: Any, *, asset: Any = None, identity: Any = None) -> int:
"""The score this alert sorts by.
@@ -421,7 +538,19 @@ async def build_queue(
)
).all()
- items: list[QueueItem] = []
+ # Asset criticality orders the page. `score_alert_priority` existed with
+ # zero callers — two alerts of equal severity, one on a domain controller
+ # and one on a meeting-room display, arrived in whatever order they were
+ # raised. The contexts are resolved in two batched queries for the page;
+ # the re-sort below refines order *within* the page only: the SQL's
+ # (bucket, sla, severity) order remains the pagination key, so an alert's
+ # page is unchanged and the distortion is bounded to (bucket, sla)-ties
+ # that straddle a page boundary — stated in the queue doc rather than
+ # hidden.
+ page_alerts = [row[0] for row in rows]
+ asset_contexts = await resolve_asset_contexts(db, tenant_id, page_alerts)
+
+ scored: list[tuple[int, datetime, int, QueueItem]] = []
for row in rows:
alert: Alert = row[0]
bucket_idx: int = int(row[1])
@@ -435,29 +564,39 @@ async def build_queue(
first_seen = first_seen.replace(tzinfo=UTC)
age = int((now - first_seen).total_seconds())
- items.append(
- QueueItem(
- id=alert.id,
- tenant_id=alert.tenant_id,
- title=alert.title,
- severity=alert.severity,
- status=alert.status,
- priority=alert.priority,
- category=alert.category,
- connector_type=alert.connector_type,
- assigned_to_id=alert.assigned_to_id,
- case_id=alert.case_id,
- first_seen=first_seen,
- sla_due_at=sla_due_at,
- sla_remaining_seconds=remaining,
- sla_breached=remaining < 0,
- age_seconds=max(0, age),
- asset=first_asset(alert),
- suggested_action=first_action(alert),
- bucket="mine" if bucket_idx == 0 else "unassigned",
- )
+ priority_result = score_alert_priority(
+ severity=str(alert.severity or "medium"),
+ asset=asset_contexts.get(alert.id),
+ identity=None,
)
+ item = QueueItem(
+ id=alert.id,
+ tenant_id=alert.tenant_id,
+ title=alert.title,
+ severity=alert.severity,
+ status=alert.status,
+ priority=alert.priority,
+ category=alert.category,
+ connector_type=alert.connector_type,
+ assigned_to_id=alert.assigned_to_id,
+ case_id=alert.case_id,
+ first_seen=first_seen,
+ sla_due_at=sla_due_at,
+ sla_remaining_seconds=remaining,
+ sla_breached=remaining < 0,
+ age_seconds=max(0, age),
+ asset=first_asset(alert),
+ suggested_action=first_action(alert),
+ bucket="mine" if bucket_idx == 0 else "unassigned",
+ priority_score=priority_result.score,
+ priority_basis=priority_result.as_dict(),
+ )
+ scored.append((bucket_idx, sla_due_at, priority_result.score, item))
+
+ scored.sort(key=lambda entry: (entry[0], entry[1], -entry[2]))
+ items: list[QueueItem] = [entry[3] for entry in scored]
+
pages = (total + page_size - 1) // page_size if total else 0
return QueueResponse(
items=items,
diff --git a/services/api/tests/test_alert_queue.py b/services/api/tests/test_alert_queue.py
index 5dc09374c..56d579596 100644
--- a/services/api/tests/test_alert_queue.py
+++ b/services/api/tests/test_alert_queue.py
@@ -508,13 +508,20 @@ class TestBuildQueue:
rows: list[tuple[Any, int, datetime]] | None = None,
tenant_overrides: list[Any] | None = None,
) -> MagicMock:
- """Wire a session with the queue's 4-call execute pattern.
+ """Wire a session with the queue's execute pattern.
Call order inside ``build_queue``:
1) ``load_sla_targets`` → ``scalars().all()`` on tenant SLA config
2) ``mine_count`` → ``scalar_one()``
3) ``unassigned_count`` → ``scalar_one()``
4) main projection query → ``.all()`` of row tuples
+ 5) asset match (only when a page alert carries hosts/ips)
+ → ``scalars().all()``; empty here, so the vulnerability
+ query never fires and priority falls back to severity
+ alone. The asset-aware ordering itself is exercised
+ against real Postgres in
+ ``test_alert_queue_priority_live.py`` — a mock that
+ answered the array-overlap match would prove nothing.
"""
db = MagicMock()
db.execute = AsyncMock(
@@ -523,6 +530,7 @@ class TestBuildQueue:
_scalar_one_result(mine_count),
_scalar_one_result(unassigned_count),
_rows_all_result(rows or []),
+ _scalars_all_result([]),
]
)
return db
@@ -703,6 +711,11 @@ class TestBuildQueue:
assert item.sla_breached is False
# Countdown is in the future, so > 0.
assert item.sla_remaining_seconds > 0
+ # No asset inventory in this harness, so priority is severity alone
+ # (critical base 900) and the basis says exactly that.
+ assert item.priority_score == 900
+ assert item.priority_basis["base"] == 900
+ assert item.priority_basis["rationale"] == []
# Age is positive (first_seen was 10 minutes ago).
assert item.age_seconds >= 0
# Asset chip pulls host first.
diff --git a/services/api/tests/test_alert_queue_priority_live.py b/services/api/tests/test_alert_queue_priority_live.py
new file mode 100644
index 000000000..1e46118d2
--- /dev/null
+++ b/services/api/tests/test_alert_queue_priority_live.py
@@ -0,0 +1,180 @@
+"""Asset criticality orders the queue — proven against real Postgres.
+
+`score_alert_priority` existed with zero callers: two alerts of equal
+severity — one on a domain controller, one on a meeting-room display —
+arrived in the order they were raised, and an analyst worked out which was
+which by reading the hostname. The ordering now resolves the tenant's own
+``assets`` inventory (name/FQDN/IP-overlap match, exploited-vulnerability
+KEV signal) in two batched queries per page.
+
+Live because the properties under test are schema facts a mock would
+invent: the ``lower(name)``/``ip_addresses &&`` match, the
+``is_exploited AND remediated_at IS NULL`` filter, and the tenant predicate
+on both queries. The negative control monkeypatches the resolver away and
+asserts the order collapses back to insertion order — proving the sort
+actually consumes the resolution.
+
+Skips without a database rather than passing without one.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from datetime import UTC, datetime
+
+import pytest
+import pytest_asyncio
+from app.models.alert import Alert
+from app.models.asset import Asset, AssetVulnerability
+from app.services import alert_queue as queue_module
+from app.services.alert_queue import build_queue
+from sqlalchemy import text
+from sqlalchemy.ext.asyncio import async_sessionmaker, create_async_engine
+
+DSN = os.environ.get("DATABASE_URL", "")
+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")
+
+TENANT = uuid.UUID("0e700000-0000-0000-0000-0000000000d1")
+OTHER_TENANT = uuid.UUID("0e700000-0000-0000-0000-0000000000d2")
+USER = uuid.UUID("0e700000-0000-0000-0000-0000000000d3")
+
+# One shared timestamp: identical first_seen means identical SLA due, so the
+# (bucket, sla) keys tie and the priority score is the deciding key.
+NOW = datetime(2026, 10, 30, 12, 0, 0, tzinfo=UTC)
+
+
+@pytest_asyncio.fixture
+async def db():
+ if "postgres" not in DSN and not REQUIRED:
+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")
+ engine = create_async_engine(DSN)
+ try:
+ async with engine.connect() as probe:
+ await probe.execute(text("SELECT 1"))
+ except Exception as exc:
+ await engine.dispose()
+ if REQUIRED:
+ pytest.fail(f"MSSP_ISOLATION_REQUIRED is set and no database answered at DATABASE_URL: {type(exc).__name__}: {exc}")
+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")
+
+ factory = async_sessionmaker(engine, expire_on_commit=False)
+ async with factory() as session:
+ for tid, slug in ((TENANT, "queue-prio-a"), (OTHER_TENANT, "queue-prio-b")):
+ await session.execute(
+ text("INSERT INTO tenants (id, name, slug) VALUES (:id, :name, :slug) ON CONFLICT (id) DO NOTHING"),
+ {"id": tid, "name": f"Queue prio {slug}", "slug": slug},
+ )
+ await session.commit()
+ yield session
+ await session.rollback()
+ for table in ("asset_vulnerabilities", "assets", "alerts"):
+ await session.execute(
+ text(f"DELETE FROM {table} WHERE tenant_id IN (:a, :b)"), # noqa: S608 — fixed table names
+ {"a": TENANT, "b": OTHER_TENANT},
+ )
+ await session.commit()
+ await engine.dispose()
+
+
+def _alert(tenant: uuid.UUID, title: str, host: str) -> Alert:
+ return Alert(
+ id=uuid.uuid4(),
+ tenant_id=tenant,
+ title=title,
+ severity="high",
+ status="new",
+ event_time=NOW,
+ first_seen=NOW,
+ last_seen=NOW,
+ affected_hosts=[host],
+ )
+
+
+def _asset(tenant: uuid.UUID, name: str, criticality: str) -> Asset:
+ return Asset(id=uuid.uuid4(), tenant_id=tenant, name=name, criticality=criticality)
+
+
+async def _seed_estate(db) -> tuple[Alert, Alert]:
+ """Kiosk alert inserted FIRST so insertion order argues against the DC."""
+ dc = _asset(TENANT, "prod-dc-01", "critical")
+ kiosk = _asset(TENANT, "kiosk-7", "low")
+ db.add_all([dc, kiosk])
+ await db.flush()
+ db.add(
+ AssetVulnerability(
+ id=uuid.uuid4(),
+ tenant_id=TENANT,
+ asset_id=dc.id,
+ title="KEV-listed RCE",
+ severity="critical",
+ is_exploited=True,
+ source="scanner",
+ )
+ )
+ kiosk_alert = _alert(TENANT, "Suspicious PowerShell on kiosk", "kiosk-7")
+ dc_alert = _alert(TENANT, "Suspicious PowerShell on DC", "prod-dc-01")
+ db.add_all([kiosk_alert, dc_alert])
+ await db.commit()
+ return dc_alert, kiosk_alert
+
+
+async def test_the_domain_controller_outranks_the_kiosk(db) -> None:
+ dc_alert, kiosk_alert = await _seed_estate(db)
+
+ resp = await build_queue(db, tenant_id=TENANT, user_id=USER, owner="unassigned")
+ order = [item.id for item in resp.items]
+ assert order.index(dc_alert.id) < order.index(kiosk_alert.id), (
+ "equal severity, equal SLA — the critical asset with an exploited vulnerability must sort first"
+ )
+
+ dc_item = next(i for i in resp.items if i.id == dc_alert.id)
+ kiosk_item = next(i for i in resp.items if i.id == kiosk_alert.id)
+ assert dc_item.priority_score > kiosk_item.priority_score
+ reasons = " | ".join(r["reason"] for r in dc_item.priority_basis["rationale"])
+ assert "critical" in reasons
+ assert "exploited" in reasons.lower() or "KEV" in reasons
+
+
+async def test_negative_control_without_resolution_order_collapses(db, monkeypatch) -> None:
+ """Remove the resolver and the DC loses its rank — the sort provably
+ consumes the asset resolution rather than something correlated."""
+ dc_alert, kiosk_alert = await _seed_estate(db)
+
+ async def _nothing(*_a, **_k):
+ return {}
+
+ monkeypatch.setattr(queue_module, "resolve_asset_contexts", _nothing)
+ resp = await build_queue(db, tenant_id=TENANT, user_id=USER, owner="unassigned")
+ dc_item = next(i for i in resp.items if i.id == dc_alert.id)
+ kiosk_item = next(i for i in resp.items if i.id == kiosk_alert.id)
+ assert dc_item.priority_score == kiosk_item.priority_score, "severity alone: the scores must tie"
+
+
+async def test_another_tenants_inventory_is_invisible(db) -> None:
+ """Tenant B owns a critical asset named like tenant A's kiosk. It must not
+ raise A's kiosk alert — the resolver is tenant-scoped on both queries."""
+ db.add(_asset(OTHER_TENANT, "kiosk-7", "critical"))
+ kiosk_alert = _alert(TENANT, "Suspicious PowerShell on kiosk", "kiosk-7")
+ db.add(kiosk_alert)
+ await db.commit()
+
+ resp = await build_queue(db, tenant_id=TENANT, user_id=USER, owner="unassigned")
+ item = next(i for i in resp.items if i.id == kiosk_alert.id)
+ assert item.priority_basis["rationale"] == [], "no same-tenant asset matched; severity alone"
+
+
+async def test_no_inventory_scores_severity_alone(db) -> None:
+ alert = _alert(TENANT, "Alert on unknown host", "never-imported-host")
+ db.add(alert)
+ await db.commit()
+
+ resp = await build_queue(db, tenant_id=TENANT, user_id=USER, owner="unassigned")
+ item = next(i for i in resp.items if i.id == alert.id)
+ assert item.priority_score == 600 # high base, no multipliers
+ assert item.priority_basis["base"] == 600
+ assert item.priority_basis["rationale"] == []