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 reaches fusion confidence and action approval, tighten-only (#1578)

Beenu Aroradf369dfda5d2
diff --git a/.github/workflows/integration.yml b/.github/workflows/integration.yml
index e1770020d..ba434e1db 100644
--- a/.github/workflows/integration.yml
+++ b/.github/workflows/integration.yml
@@ -105,6 +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 services/fusion/tests/test_asset_context_live.py services/fusion/app/services/asset_context.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 tests/isolation/test_postgres_rls.py tests/isolation/test_mssp_rls_live.py scripts/check_runtime_db_role.py services/api/tests/test_alert_rail_business_context_live.py services/api/app/services/alert_rail.py services/agents/tests/test_business_context_tenant_rules_live.py services/agents/app/workers/business_context.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
@@ -781,6 +782,17 @@ jobs:
MSSP_ISOLATION_REQUIRED: '1'
run: pip install --quiet pytest pytest-asyncio && python -m pytest tests/test_mssp_portfolio_isolation.py -v --tb=short
+ # Fusion's fuse-time asset-context resolver: the name/FQDN/IP match,
+ # the highest-criticality tie-break and the tenant predicate are schema
+ # facts a fake pool would invent. The file's import closure is kept
+ # deliberately tiny (pydantic + pydantic-settings + structlog + asyncpg,
+ # the last two because fusion's conftest imports app.core.config) so this job can run
+ # it without fusion's full dependency set.
+ - name: Fusion asset-context resolver matches real inventory (live Postgres)
+ working-directory: services/fusion
+ env:
+ MSSP_ISOLATION_REQUIRED: '1'
+ run: pip install --quiet pydantic pydantic-settings structlog && python -m pytest tests/test_asset_context_live.py -v --tb=short
# The Investigation Rail's business-context leg joins
# investigation_events through investigation_runs (case_id TEXT = alert
# id) — schema facts only this job can check, including that another
diff --git a/CHANGELOG.md b/CHANGELOG.md
index 7fd7721c2..cff3ae636 100644
--- a/CHANGELOG.md
+++ b/CHANGELOG.md
@@ -9,6 +9,23 @@ and this project adheres to [Semantic Versioning](https://semver.org/spec/v2.0.0
### Added
+- **Asset criticality reaches fusion confidence and action approval —
+ tighten-only.** Fusion stamps what each alert landed on at fuse time
+ (`enrichments["asset_context"]`, resolved from the tenant's own `assets`
+ inventory by name/FQDN/IP with the highest criticality winning) and the
+ confidence scorer gains a bounded `asset_criticality` factor (weight 0.06,
+ weights rebalanced to keep summing to 1.0) — an absent stamp contributes
+ exactly 0.0 and the rationale row says `unknown (no inventory match)`
+ rather than being omitted, because "we do not know what this host is" is a
+ fact an analyst needs. On the response side, `evaluate_contract` grades a
+ verb one impact rank higher when the target asset is critical/high in the
+ tenant's inventory — never lower, with two deliberate non-raises:
+ READ_ONLY stays READ_ONLY (a read against a domain controller is still a
+ read) and SEVERE never becomes IRREVERSIBLE (context can demand a human,
+ it cannot make an undoable action undoable). The positive control is the
+ point: unknown criticality grades every verb identically, so a deployment
+ with no CMDB loses nothing. Both approval doors thread the resolution;
+ the console's vendored copy stays byte-identical.
- **Business context reaches the triage model, and impact statements must
cite it.** The business-context applier's result used to die in the
worker's local variable: a tenant `set_severity` mutated the alert
diff --git a/ROADMAP.md b/ROADMAP.md
index e0e615880..e5c815046 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 **327 rows — 322 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 **329 rows — 324 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 df455ca9f..7dc8562e0 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: 322 rows
+The last row is the one worth reading first. It is the honest index: 324 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/docs/audit/CLAIM_TO_GATE_MATRIX.md b/docs/audit/CLAIM_TO_GATE_MATRIX.md
index 0446a61ac..957982ab9 100644
--- a/docs/audit/CLAIM_TO_GATE_MATRIX.md
+++ b/docs/audit/CLAIM_TO_GATE_MATRIX.md
@@ -109,6 +109,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
| A verdict is not auto-closed on reasoning the evidence does not support | README (groundedness axis) | `ci.yml` agents tests (`test_groundedness_gate.py` — an auto-closing verdict citing an indicator absent from the alert is demoted to `needs_review` at runtime, with confidence lowered to match) | core | GATED | - |
| 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 | - |
+| Fusion confidence weighs what the alert landed on | `services/fusion/app/services/confidence.py` (factor table) | `ci.yml` fusion job (`test_confidence.py` — the `asset_criticality` factor is in the complete-rationale pin, weights still sum to 1.0, a critical asset raises the score, low pulls it down bounded at weight 0.06, and an absent stamp renders contribution exactly 0.0 with the row SAYING `unknown (no inventory match)` rather than being omitted; `test_asset_context.py` — the engine stamps before the scorer reads and a resolver failure leaves the honest unknown) + `integration.yml` migrations job (`test_asset_context_live.py` — the resolver's real SQL on live Postgres: name/FQDN/IP match, highest-criticality tie-break, tenant-scoped) | core | GATED | - |
+| A critical asset tightens action approval and can never loosen it | `services/actions/app/live_actions/approval_rules.py` (`evaluate_contract`) | `ci.yml` actions job (`test_asset_criticality_tightens.py` — critical/high raises one impact rank with the reason naming it; READ_ONLY never raises (a read on a DC is still a read); SEVERE never becomes IRREVERSIBLE; a 135-case sweep asserts the requirement is never less restrictive; and the POSITIVE control: unknown criticality grades every verb identically, so a deployment with no CMDB loses nothing) + `test_approval_doors_agree.py` (both doors still one grading) + `ci.yml :: python-lint` (`sync_vendored_action_contracts.py --check` keeps the console's vendored copy byte-identical) | core | 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) + `integration.yml` migrations job (`test_business_context_tenant_rules_live.py` — the worker's own asyncpg read path against the real `aisoc_business_context_rule_sets` row: saved rule applies, other tenant gets nothing, disabled set applies nothing) | core | GATED | - |
| The triage model is told what business-context rules did, and an impact statement must cite the rules that fired | `apps/docs/docs/console/triage-context.md` (business impact) | `ci.yml` agents job (`test_triage_business_context_prompt.py` — the preamble names the rules and the severity mutation; the `business_impact` instruction is injected only when context exists, never into the registry-pinned system prompt; an element citing a rule that did not fire — including the no-context fabrication case — is dropped and counted, asserted through the real `run_auto_triage` with only the model stubbed; rule ids are an injection-scanned channel) + `test_business_context_hotpath.py` (matched rules reach the state the agent reads and the `persist_auto_triage` kwargs, recorded independently) | core | GATED | - |
| The Investigation Rail shows which business rules fired and the cited impact | `apps/docs/docs/console/triage-context.md` (rail section) | `integration.yml` migrations job (`test_alert_rail_business_context_live.py` — the envelope leg reads real ledger rows through the `investigation_runs` join on live Postgres, another tenant's event is invisible, and no event means `None`, not zero) + `ci.yml` web vitest (`BusinessContextSection.test.tsx` — renders the rules, mutation and cited impact; renders nothing at all when no rule fired, asserted at first paint) | core | GATED | - |
@@ -338,8 +340,8 @@ Statuses: `GATED` (a CI job fails when the claim stops being true) · `PARTIAL`
## Summary
-- Total: 327
-- GATED: 322
+- Total: 329
+- GATED: 324
- PARTIAL: 5
- NO GATE: 0
diff --git a/services/actions/app/live_actions/approval_rules.py b/services/actions/app/live_actions/approval_rules.py
index a37c71ea1..ad4395695 100644
--- a/services/actions/app/live_actions/approval_rules.py
+++ b/services/actions/app/live_actions/approval_rules.py
@@ -344,11 +344,24 @@ def evaluate(
)
+#: The one-rank impact raise a critical/high asset applies. READ_ONLY and
+#: SEVERE are deliberately absent — see ``evaluate_contract``'s docstring —
+#: and IRREVERSIBLE cannot be raised further by construction.
+_IMPACT_RAISE_ONE_RANK: dict[ActionImpact, ActionImpact] = {
+ ActionImpact.LOW: ActionImpact.MODERATE,
+ ActionImpact.MODERATE: ActionImpact.HIGH,
+ ActionImpact.HIGH: ActionImpact.SEVERE,
+}
+
+_ASSET_TIGHTEN_CRITICALITIES = frozenset({"critical", "high"})
+
+
def evaluate_contract(
*,
contract: _Contract,
confidence: float | None,
tier: str,
+ asset_criticality: str | None = None,
) -> ApprovalDecision:
"""Grade a capability contract. **The one place a door may decide.**
@@ -374,10 +387,44 @@ def evaluate_contract(
``services/actions/tests/test_approval_doors_agree.py`` sweeps both live
doors over every capability, tier and confidence band to catch it if one
does.
+
+ ``asset_criticality`` (business-context plan, PR-3) is the criticality of
+ the asset the action would touch, resolved from the tenant's own
+ inventory by the door that has it. **Tighten-only**: a ``critical`` or
+ ``high`` asset grades the verb at one impact rank higher, and nothing
+ here can ever lower a requirement. Unknown — no inventory, no match,
+ ``None`` — grades exactly as before, so a deployment with no CMDB keeps
+ every verb it had (the positive control in
+ ``test_asset_criticality_tightens.py``). Two deliberate non-raises:
+ ``READ_ONLY`` stays ``READ_ONLY``, because a read against a domain
+ controller is still a read and queueing pure reads is the regression the
+ doors-agree work exists to prevent; and ``SEVERE`` stays ``SEVERE``,
+ because ``IRREVERSIBLE`` is a factual property of the verb — context can
+ demand a human, it cannot make an undoable action undoable.
"""
- return evaluate(
- impact=contract.impact,
+ graded_impact = contract.impact
+ criticality = (asset_criticality or "").strip().lower()
+ if criticality in _ASSET_TIGHTEN_CRITICALITIES:
+ raised = _IMPACT_RAISE_ONE_RANK.get(contract.impact)
+ if raised is not None:
+ graded_impact = raised
+
+ decision = evaluate(
+ impact=graded_impact,
declared_approval=contract.approval,
confidence=confidence,
tier=tier,
)
+ if graded_impact is not contract.impact:
+ return ApprovalDecision(
+ requirement=decision.requirement,
+ reason=(
+ f"{decision.reason} Impact graded {graded_impact.value} rather than the declared "
+ f"{contract.impact.value}: the target asset's criticality is {criticality} in the "
+ "tenant's own inventory, and asset context may raise a requirement, never lower it."
+ ),
+ impact=decision.impact,
+ confidence=decision.confidence,
+ tier=decision.tier,
+ )
+ return decision
diff --git a/services/actions/app/live_actions/dispatcher.py b/services/actions/app/live_actions/dispatcher.py
index 28ce323bd..981e8755b 100644
--- a/services/actions/app/live_actions/dispatcher.py
+++ b/services/actions/app/live_actions/dispatcher.py
@@ -44,6 +44,7 @@ import structlog
from app.models.action import ActionRequest, ActionType
from app.services.approval_matrix import evaluate_contract
+from app.services.asset_lookup import asset_criticality_for_target
from app.services.autonomy_safety import (
_BLAST_ORDER,
ACTION_BLAST_RADIUS,
@@ -134,6 +135,10 @@ async def _govern(request: LiveActionRequest, action_type: ActionType) -> Autono
requested_by=request.requested_by,
)
policy = await resolve_tenant_policy(request.tenant_id)
+ # What is this action about to touch? Resolved once per dispatch from the
+ # tenant's own inventory; None (no CMDB, no match, outage) grades exactly
+ # as before. Tighten-only by construction in evaluate_contract.
+ target_criticality = await asset_criticality_for_target(request.tenant_id, request.target)
# A tenant override is a deliberate, explicit instruction for one action
# type, so it outranks the tier ladder in both directions.
@@ -162,6 +167,7 @@ async def _govern(request: LiveActionRequest, action_type: ActionType) -> Autono
f"action type '{action_type.value}' is force-auto by tenant policy",
),
tier_label="L4",
+ asset_criticality=target_criticality,
)
# Gap-closure Phase 2.3. A tenant that has run this verb's alert classes in
@@ -208,6 +214,7 @@ async def _govern(request: LiveActionRequest, action_type: ActionType) -> Autono
request,
decision,
tier_label=_tier_label(effective_tier),
+ asset_criticality=target_criticality,
)
@@ -260,7 +267,12 @@ async def _govern_by_contract_alone(request: LiveActionRequest) -> AutonomyDecis
f"contract ({contract.impact.value} impact) under tier {policy.tier.name}"
),
)
- return _apply_capability_contract(request, baseline, tier_label=_tier_label(policy.tier))
+ return _apply_capability_contract(
+ request,
+ baseline,
+ tier_label=_tier_label(policy.tier),
+ asset_criticality=await asset_criticality_for_target(request.tenant_id, request.target),
+ )
def _apply_capability_contract(
@@ -268,6 +280,7 @@ def _apply_capability_contract(
decision: AutonomyDecision,
*,
tier_label: str,
+ asset_criticality: str | None = None,
) -> AutonomyDecision:
"""Raise the autonomy verdict to whatever the capability contract demands.
@@ -311,6 +324,7 @@ def _apply_capability_contract(
contract=contract,
confidence=request.confidence,
tier=tier_label,
+ asset_criticality=asset_criticality,
)
if verdict.is_blocked:
diff --git a/services/actions/app/services/approval_gate.py b/services/actions/app/services/approval_gate.py
index e98260586..5e2a9d1e2 100644
--- a/services/actions/app/services/approval_gate.py
+++ b/services/actions/app/services/approval_gate.py
@@ -46,6 +46,7 @@ from app.live_actions.capability_contracts import contract_for_action_type
from app.live_actions.contract import ApprovalRequirement
from app.models.action import ActionRequest, ActionStatus, BlastRadius
from app.services.approval_matrix import DEFAULT_TIER, evaluate_contract
+from app.services.asset_lookup import asset_criticality_for_target
logger = structlog.get_logger()
@@ -143,6 +144,7 @@ async def apply_matrix(
contract=contract,
confidence=request.confidence,
tier=await _resolve_tier(request.tenant_id),
+ asset_criticality=await asset_criticality_for_target(request.tenant_id, request.target),
)
if decision.is_blocked:
diff --git a/services/actions/app/services/asset_lookup.py b/services/actions/app/services/asset_lookup.py
new file mode 100644
index 000000000..bb5a79b06
--- /dev/null
+++ b/services/actions/app/services/asset_lookup.py
@@ -0,0 +1,87 @@
+"""What is the action about to touch? — target → asset criticality.
+
+The approval matrix's asset modifier (``evaluate_contract``'s
+``asset_criticality``) is tighten-only, and this module is where the value
+comes from: the action's ``target`` (a hostname, FQDN or IP, which is what
+every containment verb names) matched against the tenant's own ``assets``
+inventory — the same table the console import writes and the queue resolver
+reads.
+
+Fail-soft by construction: no DSN, no match, a slow query or an outage is a
+``None``, and ``None`` grades exactly as before — a deployment with no CMDB
+keeps every verb it had. Highest criticality wins on multiple matches,
+failing toward attention. A small TTL cache bounds the cost on the dispatch
+hot path; inventories change on human timescales.
+"""
+
+from __future__ import annotations
+
+import time
+from typing import Any
+
+import structlog
+
+from app.services.tenant_policy import resolve_dsn
+
+logger = structlog.get_logger()
+
+_CACHE_TTL_SECONDS = 300.0
+_QUERY_TIMEOUT_SECONDS = 3.0
+_CRITICALITY_RANK = {"critical": 4, "high": 3, "medium": 2, "low": 1, "none": 0}
+
+_cache: dict[tuple[str, str], tuple[float, str | None]] = {}
+
+
+def _clear_cache() -> None:
+ """Tests only."""
+ _cache.clear()
+
+
+async def asset_criticality_for_target(tenant_id: Any, target: str | None) -> str | None:
+ """The target asset's criticality in this tenant's inventory, or ``None``.
+
+ ``target`` is matched as a lowered hostname/FQDN and as an IP — the
+ caller does not have to know which it holds, because a containment
+ request frequently doesn't either.
+ """
+ value = (target or "").strip().lower()
+ if not value or tenant_id is None:
+ return None
+ dsn = resolve_dsn()
+ if not dsn:
+ return None
+
+ key = (str(tenant_id), value)
+ now = time.monotonic()
+ cached = _cache.get(key)
+ if cached is not None and now - cached[0] < _CACHE_TTL_SECONDS:
+ return cached[1]
+
+ result: str | None = None
+ try:
+ import asyncpg # noqa: PLC0415 — optional at import time
+
+ conn = await asyncpg.connect(dsn, timeout=_QUERY_TIMEOUT_SECONDS)
+ try:
+ rows = await conn.fetch(
+ """
+ SELECT criticality
+ FROM assets
+ WHERE tenant_id = CAST($1 AS uuid)
+ AND (lower(name) = $2 OR lower(fqdn) = $2 OR $2 = ANY(ip_addresses))
+ """,
+ str(tenant_id),
+ value,
+ timeout=_QUERY_TIMEOUT_SECONDS,
+ )
+ finally:
+ await conn.close()
+ if rows:
+ best = max(rows, key=lambda r: _CRITICALITY_RANK.get(str(r["criticality"] or "").lower(), 0))
+ result = str(best["criticality"] or "").lower() or None
+ except Exception as exc: # noqa: BLE001 — inventory must never block dispatch
+ logger.debug("asset_lookup.unresolved", error=str(exc))
+ return None
+
+ _cache[key] = (now, result)
+ return result
diff --git a/services/actions/tests/test_asset_criticality_tightens.py b/services/actions/tests/test_asset_criticality_tightens.py
new file mode 100644
index 000000000..758667416
--- /dev/null
+++ b/services/actions/tests/test_asset_criticality_tightens.py
@@ -0,0 +1,109 @@
+"""The asset modifier tightens approval and can never loosen it.
+
+`evaluate_contract` grades a verb at one impact rank higher when the target
+asset's criticality is critical/high. Four properties, each its own test
+class, and the **positive control is the point**: a fail-closed safety
+control that is stuck closed reads as working caution, so the control that
+matters most asserts an *unknown* criticality keeps every verb exactly as it
+was — a deployment with no CMDB must lose nothing.
+"""
+
+from __future__ import annotations
+
+from dataclasses import dataclass
+
+import pytest
+from app.live_actions.approval_rules import ApprovalRequirement, evaluate_contract
+from app.live_actions.contract import ActionImpact
+
+
+@dataclass(frozen=True)
+class _Contract:
+ impact: ActionImpact
+ approval: ApprovalRequirement
+
+
+def _grade(impact: ActionImpact, *, criticality: str | None, confidence: float = 0.99, tier: str = "L4"):
+ return evaluate_contract(
+ contract=_Contract(impact=impact, approval=ApprovalRequirement.AUTOMATIC),
+ confidence=confidence,
+ tier=tier,
+ asset_criticality=criticality,
+ )
+
+
+class TestPositiveControl:
+ """Unknown keeps the verb — the control that catches stuck-closed."""
+
+ @pytest.mark.parametrize("criticality", [None, "", "medium", "low", "none", "weird-value"])
+ @pytest.mark.parametrize("impact", list(ActionImpact))
+ def test_non_tightening_criticality_grades_identically(self, impact: ActionImpact, criticality: str | None) -> None:
+ with_ctx = _grade(impact, criticality=criticality)
+ without = _grade(impact, criticality=None)
+ assert with_ctx.requirement == without.requirement
+ assert with_ctx.impact == without.impact
+
+
+class TestTighten:
+ def test_a_critical_asset_raises_one_rank(self) -> None:
+ plain = _grade(ActionImpact.MODERATE, criticality=None)
+ tightened = _grade(ActionImpact.MODERATE, criticality="critical")
+ assert tightened.impact == ActionImpact.HIGH
+ assert plain.impact == ActionImpact.MODERATE
+ assert "asset's criticality is critical" in tightened.reason
+
+ def test_high_impact_on_a_critical_asset_grades_severe(self) -> None:
+ # SEVERE is in NEVER_AUTONOMOUS territory for autonomy purposes:
+ # the raise must move the requirement in the restrictive direction.
+ plain = _grade(ActionImpact.HIGH, criticality="critical")
+ assert plain.impact == ActionImpact.SEVERE
+
+ @pytest.mark.parametrize("criticality", ["critical", "high", "CRITICAL", " High "])
+ def test_both_tiers_and_any_casing_tighten(self, criticality: str) -> None:
+ assert _grade(ActionImpact.LOW, criticality=criticality).impact == ActionImpact.MODERATE
+
+
+class TestDeliberateNonRaises:
+ def test_read_only_is_never_raised(self) -> None:
+ """A read against a domain controller is still a read. Queueing pure
+ reads is the regression the doors-agree work exists to prevent."""
+ graded = _grade(ActionImpact.READ_ONLY, criticality="critical")
+ assert graded.impact == ActionImpact.READ_ONLY
+ assert graded.requirement == _grade(ActionImpact.READ_ONLY, criticality=None).requirement
+
+ def test_severe_is_not_raised_to_irreversible(self) -> None:
+ """Irreversibility is a factual property of the verb: context can
+ demand a human, it cannot make an undoable action undoable — and
+ PROHIBITED would forbid rather than tighten."""
+ graded = _grade(ActionImpact.SEVERE, criticality="critical")
+ assert graded.impact == ActionImpact.SEVERE
+ assert graded.requirement != ApprovalRequirement.PROHIBITED
+
+
+class TestTightenOnlyInvariant:
+ """Sweep: with context, the requirement is never less restrictive."""
+
+ _ORDER = {
+ ApprovalRequirement.AUTOMATIC: 0,
+ ApprovalRequirement.ANALYST: 1,
+ ApprovalRequirement.MANDATORY_HUMAN: 2,
+ ApprovalRequirement.PROHIBITED: 3,
+ }
+
+ @pytest.mark.parametrize("impact", list(ActionImpact))
+ @pytest.mark.parametrize("criticality", ["critical", "high", "medium", "low", None])
+ @pytest.mark.parametrize("confidence", [0.2, 0.8, 0.99])
+ @pytest.mark.parametrize("tier", ["L0", "L2", "L4"])
+ def test_never_less_restrictive(self, impact: ActionImpact, criticality: str | None, confidence: float, tier: str) -> None:
+ base = evaluate_contract(
+ contract=_Contract(impact=impact, approval=ApprovalRequirement.AUTOMATIC),
+ confidence=confidence,
+ tier=tier,
+ )
+ with_ctx = evaluate_contract(
+ contract=_Contract(impact=impact, approval=ApprovalRequirement.AUTOMATIC),
+ confidence=confidence,
+ tier=tier,
+ asset_criticality=criticality,
+ )
+ assert self._ORDER[with_ctx.requirement] >= self._ORDER[base.requirement]
diff --git a/services/api/app/_vendor/action_contracts/approval_rules.py b/services/api/app/_vendor/action_contracts/approval_rules.py
index a37c71ea1..ad4395695 100644
--- a/services/api/app/_vendor/action_contracts/approval_rules.py
+++ b/services/api/app/_vendor/action_contracts/approval_rules.py
@@ -344,11 +344,24 @@ def evaluate(
)
+#: The one-rank impact raise a critical/high asset applies. READ_ONLY and
+#: SEVERE are deliberately absent — see ``evaluate_contract``'s docstring —
+#: and IRREVERSIBLE cannot be raised further by construction.
+_IMPACT_RAISE_ONE_RANK: dict[ActionImpact, ActionImpact] = {
+ ActionImpact.LOW: ActionImpact.MODERATE,
+ ActionImpact.MODERATE: ActionImpact.HIGH,
+ ActionImpact.HIGH: ActionImpact.SEVERE,
+}
+
+_ASSET_TIGHTEN_CRITICALITIES = frozenset({"critical", "high"})
+
+
def evaluate_contract(
*,
contract: _Contract,
confidence: float | None,
tier: str,
+ asset_criticality: str | None = None,
) -> ApprovalDecision:
"""Grade a capability contract. **The one place a door may decide.**
@@ -374,10 +387,44 @@ def evaluate_contract(
``services/actions/tests/test_approval_doors_agree.py`` sweeps both live
doors over every capability, tier and confidence band to catch it if one
does.
+
+ ``asset_criticality`` (business-context plan, PR-3) is the criticality of
+ the asset the action would touch, resolved from the tenant's own
+ inventory by the door that has it. **Tighten-only**: a ``critical`` or
+ ``high`` asset grades the verb at one impact rank higher, and nothing
+ here can ever lower a requirement. Unknown — no inventory, no match,
+ ``None`` — grades exactly as before, so a deployment with no CMDB keeps
+ every verb it had (the positive control in
+ ``test_asset_criticality_tightens.py``). Two deliberate non-raises:
+ ``READ_ONLY`` stays ``READ_ONLY``, because a read against a domain
+ controller is still a read and queueing pure reads is the regression the
+ doors-agree work exists to prevent; and ``SEVERE`` stays ``SEVERE``,
+ because ``IRREVERSIBLE`` is a factual property of the verb — context can
+ demand a human, it cannot make an undoable action undoable.
"""
- return evaluate(
- impact=contract.impact,
+ graded_impact = contract.impact
+ criticality = (asset_criticality or "").strip().lower()
+ if criticality in _ASSET_TIGHTEN_CRITICALITIES:
+ raised = _IMPACT_RAISE_ONE_RANK.get(contract.impact)
+ if raised is not None:
+ graded_impact = raised
+
+ decision = evaluate(
+ impact=graded_impact,
declared_approval=contract.approval,
confidence=confidence,
tier=tier,
)
+ if graded_impact is not contract.impact:
+ return ApprovalDecision(
+ requirement=decision.requirement,
+ reason=(
+ f"{decision.reason} Impact graded {graded_impact.value} rather than the declared "
+ f"{contract.impact.value}: the target asset's criticality is {criticality} in the "
+ "tenant's own inventory, and asset context may raise a requirement, never lower it."
+ ),
+ impact=decision.impact,
+ confidence=decision.confidence,
+ tier=decision.tier,
+ )
+ return decision
diff --git a/services/fusion/app/main.py b/services/fusion/app/main.py
index b07c0d85e..bcebef080 100644
--- a/services/fusion/app/main.py
+++ b/services/fusion/app/main.py
@@ -16,6 +16,7 @@ from app.services.ai_asset_recorder import AiAssetRecorder
from app.services.alert_enricher import AlertEnricher
from app.services.alert_outbox import AlertNotificationOutbox
from app.services.alert_sink import AlertSink
+from app.services.asset_context import AssetContextResolver
from app.services.attack_chain_grouper import AttackChainGrouper
from app.services.baselines import BaselineStore
from app.services.confidence import ConfidenceScorer
@@ -104,6 +105,11 @@ async def lifespan(app: FastAPI):
memory_provider = (
MemoryPriorProvider() if os.getenv("AISOC_FUSION_MEMORY_NUDGE", "1").strip().lower() not in {"0", "false", "no", "off"} else None
)
+ # Business-context plan PR-3 — fuse-time asset-context stamp. Same
+ # Postgres this service already connects to (the assets table the console
+ # import writes); unset DATABASE_URL leaves the scorer's factor honestly
+ # reading "unknown (no inventory match)".
+ asset_resolver = AssetContextResolver(settings.database_url) if settings.database_url else None
engine = FusionEngine(
dedup,
correlator,
@@ -112,6 +118,7 @@ async def lifespan(app: FastAPI):
ueba_cache=ueba_cache,
chain_grouper=chain_grouper,
enricher=enricher,
+ asset_resolver=asset_resolver,
memory_provider=memory_provider,
)
# Phase 3.1 — fused alerts land in the Postgres alert store so the spine
diff --git a/services/fusion/app/services/asset_context.py b/services/fusion/app/services/asset_context.py
new file mode 100644
index 000000000..1c8d16a87
--- /dev/null
+++ b/services/fusion/app/services/asset_context.py
@@ -0,0 +1,125 @@
+"""Fuse-time asset-context stamp — what did this alert land on?
+
+The confidence scorer's ``asset_criticality`` factor reads
+``fused.enrichments["asset_context"]``; this module is the only writer. It
+resolves the alert's hostname/IP against the tenant's own ``assets``
+inventory (the table the console's asset import and the CMDB connectors
+write) at fuse time, the same slot the TI enrichment uses — the scorer stays
+a pure projection and never opens a connection.
+
+Honesty and robustness, same contract as the TI enricher one file over:
+
+* **Unknown is unknown.** No inventory, no match, no database — the stamp is
+ absent and the scorer's factor row reads "unknown (no inventory match)"
+ with a contribution of exactly zero. Absence of a CMDB row is not evidence
+ in either direction.
+* **Fail-soft.** A missing DSN, a connection error or a slow query is a
+ ``None`` and a warning — asset context never blocks or crashes fusion.
+* **Bounded.** One indexed query per (tenant, host/ip) with a small TTL
+ cache, because fusion sits on the hot path and the inventory changes on
+ human timescales.
+"""
+
+from __future__ import annotations
+
+import os
+import time
+from typing import Any
+
+import structlog
+
+from app.models.alert import RawAlert
+
+logger = structlog.get_logger()
+
+_CACHE_TTL_SECONDS = 300.0
+_QUERY_TIMEOUT_SECONDS = 2.0
+
+_CRITICALITY_RANK = {"critical": 4, "high": 3, "medium": 2, "low": 1, "none": 0}
+
+
+def _asyncpg_dsn(url: str) -> str:
+ """Strip the SQLAlchemy driver suffix — asyncpg wants plain postgresql://."""
+ return url.replace("postgresql+asyncpg://", "postgresql://", 1)
+
+
+class AssetContextResolver:
+ """Resolve an alert's host/IP to the tenant's asset criticality."""
+
+ def __init__(self, database_url: str | None = None) -> None:
+ url = (database_url or os.getenv("DATABASE_URL") or "").strip()
+ self._dsn = _asyncpg_dsn(url) if url else ""
+ self._pool: Any = None
+ self._cache: dict[tuple[str, str], tuple[float, dict[str, Any] | None]] = {}
+
+ @property
+ def configured(self) -> bool:
+ return bool(self._dsn)
+
+ async def _ensure_pool(self) -> Any:
+ if self._pool is None:
+ import asyncpg # noqa: PLC0415 — optional at import time
+
+ self._pool = await asyncpg.create_pool(self._dsn, min_size=0, max_size=2, timeout=_QUERY_TIMEOUT_SECONDS)
+ return self._pool
+
+ async def close(self) -> None:
+ if self._pool is not None:
+ await self._pool.close()
+ self._pool = None
+
+ async def resolve(self, alert: RawAlert) -> dict[str, Any] | None:
+ """``{"criticality": ..., "matched": <asset name>}`` or ``None``.
+
+ Matches on lowered name/FQDN or IP membership; several matches take
+ the highest criticality, failing toward attention. The cache key is
+ the pivot value, so two alerts on one host inside the TTL cost one
+ query.
+ """
+ if not self._dsn:
+ return None
+ host = (alert.hostname or "").strip().lower()
+ ip = (alert.src_ip or "").strip()
+ pivot = host or ip
+ if not pivot:
+ return None
+
+ key = (str(alert.tenant_id), pivot)
+ now = time.monotonic()
+ cached = self._cache.get(key)
+ if cached is not None and now - cached[0] < _CACHE_TTL_SECONDS:
+ return cached[1]
+
+ try:
+ pool = await self._ensure_pool()
+ # Empty-string guards rather than NUL sentinels: Postgres refuses
+ # a 0x00 byte in a text parameter outright, and '' would otherwise
+ # match an asset with an empty name.
+ rows = await pool.fetch(
+ """
+ SELECT name, criticality
+ FROM assets
+ WHERE tenant_id = $1
+ AND (
+ ($2 <> '' AND (lower(name) = $2 OR lower(fqdn) = $2))
+ OR ($3 <> '' AND $3 = ANY(ip_addresses))
+ )
+ """,
+ alert.tenant_id,
+ host,
+ ip,
+ timeout=_QUERY_TIMEOUT_SECONDS,
+ )
+ except Exception as exc: # noqa: BLE001 — never block fusion on inventory
+ logger.warning("asset_context.resolve_failed", error=str(exc))
+ return None
+
+ result: dict[str, Any] | None = None
+ if rows:
+ best = max(rows, key=lambda r: _CRITICALITY_RANK.get(str(r["criticality"] or "").lower(), 0))
+ result = {
+ "criticality": str(best["criticality"] or "medium").lower(),
+ "matched": str(best["name"] or ""),
+ }
+ self._cache[key] = (now, result)
+ return result
diff --git a/services/fusion/app/services/confidence.py b/services/fusion/app/services/confidence.py
index 2e94cc239..af907bb0c 100644
--- a/services/fusion/app/services/confidence.py
+++ b/services/fusion/app/services/confidence.py
@@ -27,13 +27,14 @@ Factors and weights
================== ====== ==========================================
factor w signal
================== ====== ==========================================
-severity 0.20 alert severity (critical / high / med / low)
-ml_anomaly 0.18 IsolationForest anomaly_score (0–1)
-ml_priority 0.18 LightGBM priority_score (0–1)
+severity 0.18 alert severity (critical / high / med / low)
+ml_anomaly 0.17 IsolationForest anomaly_score (0–1)
+ml_priority 0.17 LightGBM priority_score (0–1)
mitre_coverage 0.14 number of mapped MITRE techniques
-threat_intel 0.16 enrichment hits (TI feed match)
+threat_intel 0.15 enrichment hits (TI feed match)
upstream_risk 0.08 raw_alert.risk_score (0–1, vendor-provided)
-ioc_density 0.06 distinct populated IOC fields
+ioc_density 0.05 distinct populated IOC fields
+asset_criticality 0.06 tenant asset inventory (fuse-time stamp)
================== ====== ==========================================
Sum of weights = 1.0. The factor list is *also* what's persisted on the
@@ -68,13 +69,26 @@ HIGH_THRESHOLD = 0.70
LOW_THRESHOLD = 0.40
# Factor weights — keep summing to 1.0 if you tweak.
-WEIGHT_SEVERITY = 0.20
-WEIGHT_ML_ANOMALY = 0.18
-WEIGHT_ML_PRIORITY = 0.18
+WEIGHT_SEVERITY = 0.18
+WEIGHT_ML_ANOMALY = 0.17
+WEIGHT_ML_PRIORITY = 0.17
WEIGHT_MITRE = 0.14
-WEIGHT_THREAT_INTEL = 0.16
+WEIGHT_THREAT_INTEL = 0.15
WEIGHT_UPSTREAM_RISK = 0.08
-WEIGHT_IOC_DENSITY = 0.06
+WEIGHT_IOC_DENSITY = 0.05
+WEIGHT_ASSET_CRITICALITY = 0.06
+
+# What the asset the alert landed on contributes. Unknown — no inventory, no
+# match — is exactly 0.0: the absence of a CMDB row is not evidence in either
+# direction, and the factor row says "unknown" rather than being omitted,
+# because "we do not know what this host is" is a fact an analyst needs.
+_ASSET_CRITICALITY_CONTRIBUTION = {
+ "critical": 1.0,
+ "high": 0.5,
+ "medium": 0.0,
+ "low": -0.3,
+ "none": -0.5,
+}
_SEVERITY_CONTRIBUTION = {
AlertSeverity.CRITICAL: 1.0,
@@ -279,7 +293,23 @@ class ConfidenceScorer:
)
)
- # 8. Institutional memory nudge (Wave 1) — a bounded ±MEMORY_CAP
+ # 8. Asset criticality (business-context plan, PR-3). Read from the
+ # fuse-time stamp (`enrichments["asset_context"]`), never queried
+ # here — the scorer stays a pure projection.
+ asset_ctx = (fused.enrichments or {}).get("asset_context")
+ criticality = str(asset_ctx.get("criticality", "")).lower() if isinstance(asset_ctx, dict) else ""
+ asset_contribution = _ASSET_CRITICALITY_CONTRIBUTION.get(criticality, 0.0)
+ rationale.append(
+ ConfidenceFactor(
+ factor="asset_criticality",
+ label="Asset criticality",
+ value=(criticality or "unknown (no inventory match)"),
+ contribution=asset_contribution,
+ weight=WEIGHT_ASSET_CRITICALITY,
+ )
+ )
+
+ # 9. Institutional memory nudge (Wave 1) — a bounded ±MEMORY_CAP
# adjustment from the distilled per-signature prior. A signature the
# analysts have repeatedly corrected to benign pulls new alerts of that
# signature down; one repeatedly confirmed nudges up. Unknown
diff --git a/services/fusion/app/services/fusion_engine.py b/services/fusion/app/services/fusion_engine.py
index a1606a9c2..ce40a9832 100644
--- a/services/fusion/app/services/fusion_engine.py
+++ b/services/fusion/app/services/fusion_engine.py
@@ -125,6 +125,7 @@ class FusionEngine:
ueba_cache: UebaSignalCache | None = None,
chain_grouper: AttackChainGrouper | None = None,
enricher: AlertEnricher | None = None,
+ asset_resolver: Any = None,
memory_provider: Any = None,
) -> None:
self._dedup = deduplicator
@@ -141,6 +142,10 @@ class FusionEngine:
self._chain_grouper = chain_grouper
# Wave 1 — fuse-time TI/vuln enrichment (optional; None = no enrichment).
self._enricher = enricher
+ # Business-context plan PR-3 — fuse-time asset-context stamp for the
+ # scorer's asset_criticality factor (optional; None = factor reads
+ # "unknown"). `app.services.asset_context.AssetContextResolver`.
+ self._asset_resolver = asset_resolver
# Confidence + explainability is intrinsic to a fused alert — every
# alert leaves the engine with a high/med/low label and an evidence
# chain. The scorer is pure / stateless so we instantiate a default.
@@ -209,6 +214,19 @@ class FusionEngine:
except Exception as exc:
logger.warning("fuse_enrichment_failed", error=str(exc))
+ # --- Step 2.6: Asset context (business-context plan, PR-3) ---
+ # Stamp what the alert landed on BEFORE the scorer reads it, same
+ # contract as the TI stamp above: the scorer stays a pure projection,
+ # and a resolver miss/outage leaves the honest "unknown (no inventory
+ # match)" factor in place.
+ if self._asset_resolver is not None:
+ try:
+ asset_ctx = await self._asset_resolver.resolve(alert)
+ if asset_ctx:
+ fused.enrichments["asset_context"] = asset_ctx
+ except Exception as exc:
+ logger.warning("fuse_asset_context_failed", error=str(exc))
+
# --- Step 3: ML scoring ---
try:
fused = await self._ml_scorer.score(fused)
diff --git a/services/fusion/tests/test_asset_context.py b/services/fusion/tests/test_asset_context.py
new file mode 100644
index 000000000..8ef764b74
--- /dev/null
+++ b/services/fusion/tests/test_asset_context.py
@@ -0,0 +1,110 @@
+"""The asset-context stamp: engine wiring + the resolver's real SQL.
+
+Two halves, two kinds of evidence:
+
+* The **engine** half uses a fake resolver, which is honest here because the
+ property under test is the wiring — the stamp lands on
+ ``fused.enrichments`` before the scorer reads it, and a resolver failure
+ leaves the "unknown" factor in place rather than failing the alert.
+* The **resolver** half runs its real SQL against live Postgres (the same
+ ``assets`` table the console import writes), because the name/FQDN/IP match
+ and the tenant predicate are schema facts a fake pool would invent. Skips
+ without a database rather than passing without one; runs in
+ ``integration.yml``'s migrations job.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from typing import Any
+
+import pytest
+from app.models.alert import AlertSeverity, RawAlert
+from app.services.fusion_engine import FusionEngine
+
+DSN = (os.environ.get("DATABASE_URL", "") or "").replace("postgresql+asyncpg://", "postgresql://")
+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")
+
+TENANT = uuid.UUID("0e700000-0000-0000-0000-0000000000e1")
+OTHER = uuid.UUID("0e700000-0000-0000-0000-0000000000e2")
+
+
+def _alert(**over: Any) -> RawAlert:
+ base: dict[str, Any] = {
+ "tenant_id": TENANT,
+ "source": "edr",
+ "title": "Suspicious PowerShell",
+ "severity": AlertSeverity.HIGH,
+ "hostname": "prod-dc-01",
+ }
+ base.update(over)
+ return RawAlert(**base)
+
+
+class _NullDedup:
+ async def is_duplicate(self, _alert): # noqa: ANN001, ANN202
+ return False, None
+
+ async def register(self, _alert): # noqa: ANN001, ANN202
+ return None
+
+
+class _NullCorrelator:
+ async def correlate(self, alert): # noqa: ANN001, ANN202
+ from app.models.alert import IncidentSummary
+
+ return False, IncidentSummary(id=uuid.uuid4(), tenant_id=alert.tenant_id, title="t", severity=alert.severity)
+
+
+# ─── Engine wiring (fake resolver — the property is the wiring) ──────────────
+
+
+class _FixedResolver:
+ def __init__(self, result: dict[str, Any] | None = None, *, boom: bool = False) -> None:
+ self._result = result
+ self._boom = boom
+
+ async def resolve(self, _alert): # noqa: ANN001, ANN202
+ if self._boom:
+ raise RuntimeError("inventory store down")
+ return self._result
+
+
+async def test_the_stamp_lands_before_the_scorer_reads_it() -> None:
+ engine = FusionEngine(
+ _NullDedup(), # type: ignore[arg-type] # duck-typed double; the wiring is under test
+ _NullCorrelator(), # type: ignore[arg-type]
+ asset_resolver=_FixedResolver({"criticality": "critical", "matched": "prod-dc-01"}),
+ )
+ fused = await engine.process(_alert())
+ assert fused.enrichments["asset_context"] == {"criticality": "critical", "matched": "prod-dc-01"}
+ factor = next(f for f in fused.confidence_rationale if f.factor == "asset_criticality")
+ assert factor.value == "critical"
+ assert factor.contribution == 1.0
+
+
+async def test_a_resolver_failure_leaves_the_honest_unknown() -> None:
+ engine = FusionEngine(
+ _NullDedup(), # type: ignore[arg-type] # duck-typed double; the wiring is under test
+ _NullCorrelator(), # type: ignore[arg-type]
+ asset_resolver=_FixedResolver(boom=True),
+ )
+ fused = await engine.process(_alert())
+ assert "asset_context" not in fused.enrichments
+ factor = next(f for f in fused.confidence_rationale if f.factor == "asset_criticality")
+ assert factor.value == "unknown (no inventory match)"
+ assert factor.contribution == 0.0
+
+
+async def test_no_resolver_configured_is_the_same_unknown() -> None:
+ engine = FusionEngine(
+ _NullDedup(), # type: ignore[arg-type] # duck-typed double; the wiring is under test
+ _NullCorrelator(), # type: ignore[arg-type]
+ )
+ fused = await engine.process(_alert())
+ factor = next(f for f in fused.confidence_rationale if f.factor == "asset_criticality")
+ assert factor.value == "unknown (no inventory match)"
diff --git a/services/fusion/tests/test_asset_context_live.py b/services/fusion/tests/test_asset_context_live.py
new file mode 100644
index 000000000..30a89c099
--- /dev/null
+++ b/services/fusion/tests/test_asset_context_live.py
@@ -0,0 +1,121 @@
+"""The asset-context resolver's real SQL, against live Postgres.
+
+Split from ``test_asset_context.py`` (the engine-wiring half, which runs in
+the offline fusion job) so this file's import closure stays tiny — pydantic,
+structlog, asyncpg — and ``integration.yml``'s migrations job can run it
+without fusion's full dependency set. The name/FQDN/IP match, the
+highest-criticality tie-break and the tenant predicate are schema facts a
+fake pool would invent.
+
+Skips without a database rather than passing without one.
+"""
+
+from __future__ import annotations
+
+import os
+import uuid
+from typing import Any
+
+import pytest
+import pytest_asyncio
+from app.models.alert import AlertSeverity, RawAlert
+from app.services.asset_context import AssetContextResolver
+
+DSN = (os.environ.get("DATABASE_URL", "") or "").replace("postgresql+asyncpg://", "postgresql://")
+REQUIRED = os.environ.get("MSSP_ISOLATION_REQUIRED", "").strip() not in ("", "0", "false")
+
+TENANT = uuid.UUID("0e700000-0000-0000-0000-0000000000e1")
+OTHER = uuid.UUID("0e700000-0000-0000-0000-0000000000e2")
+
+
+def _alert(**over: Any) -> RawAlert:
+ base: dict[str, Any] = {
+ "tenant_id": TENANT,
+ "source": "edr",
+ "title": "Suspicious PowerShell",
+ "severity": AlertSeverity.HIGH,
+ "hostname": "prod-dc-01",
+ }
+ base.update(over)
+ return RawAlert(**base)
+
+
+@pytest_asyncio.fixture
+async def seeded_pg():
+ if "postgres" not in DSN and not REQUIRED:
+ pytest.skip("needs a live Postgres with the migration chain applied (integration.yml)")
+ try:
+ import asyncpg
+
+ conn = await asyncpg.connect(DSN, timeout=5.0)
+ except Exception as exc:
+ if REQUIRED:
+ pytest.fail(f"MSSP_ISOLATION_REQUIRED is set and no database answered: {type(exc).__name__}: {exc}")
+ pytest.skip(f"no database at DATABASE_URL ({type(exc).__name__}) — runs in integration.yml")
+
+ try:
+ for tid, slug in ((TENANT, "asset-ctx-a"), (OTHER, "asset-ctx-b")):
+ await conn.execute(
+ "INSERT INTO tenants (id, name, slug) VALUES ($1, $2, $3) ON CONFLICT (id) DO NOTHING",
+ tid,
+ f"Asset ctx {slug}",
+ slug,
+ )
+ await conn.execute("DELETE FROM assets WHERE tenant_id IN ($1, $2)", TENANT, OTHER)
+ await conn.execute(
+ """
+ INSERT INTO assets (id, tenant_id, name, fqdn, ip_addresses, criticality)
+ VALUES
+ ($1, $3, 'prod-dc-01', 'prod-dc-01.corp.example', ARRAY['10.0.0.5'], 'critical'),
+ ($2, $3, 'prod-dc-01-replica', NULL, ARRAY['10.0.0.5'], 'low'),
+ ($4, $5, 'prod-dc-01', NULL, NULL, 'low')
+ """,
+ uuid.uuid4(),
+ uuid.uuid4(),
+ TENANT,
+ uuid.uuid4(),
+ OTHER,
+ )
+ yield conn
+ await conn.execute("DELETE FROM assets WHERE tenant_id IN ($1, $2)", TENANT, OTHER)
+ finally:
+ await conn.close()
+
+
+async def test_resolver_matches_name_fqdn_and_ip_live(seeded_pg) -> None:
+ resolver = AssetContextResolver(DSN)
+ try:
+ by_name = await resolver.resolve(_alert(hostname="PROD-DC-01"))
+ assert by_name == {"criticality": "critical", "matched": "prod-dc-01"}
+
+ by_fqdn = await resolver.resolve(_alert(hostname="prod-dc-01.corp.example"))
+ assert by_fqdn is not None and by_fqdn["criticality"] == "critical"
+
+ # IP matches two assets (critical + low): highest criticality wins,
+ # failing toward attention.
+ by_ip = await resolver.resolve(_alert(hostname=None, src_ip="10.0.0.5"))
+ assert by_ip is not None and by_ip["criticality"] == "critical"
+ finally:
+ await resolver.close()
+
+
+async def test_resolver_is_tenant_scoped_live(seeded_pg) -> None:
+ """Tenant B owns an identically-named asset; tenant A's alert must not
+ see it — and vice versa, B's own alert resolves B's low-criticality row."""
+ resolver = AssetContextResolver(DSN)
+ try:
+ theirs = await resolver.resolve(_alert(tenant_id=OTHER, hostname="prod-dc-01"))
+ assert theirs == {"criticality": "low", "matched": "prod-dc-01"}
+ finally:
+ await resolver.close()
+
+
+async def test_resolver_unknown_host_is_none_live(seeded_pg) -> None:
+ resolver = AssetContextResolver(DSN)
+ try:
+ assert await resolver.resolve(_alert(hostname="never-imported")) is None
+ finally:
+ await resolver.close()
diff --git a/services/fusion/tests/test_confidence.py b/services/fusion/tests/test_confidence.py
index 396702750..84a26efa8 100644
--- a/services/fusion/tests/test_confidence.py
+++ b/services/fusion/tests/test_confidence.py
@@ -106,6 +106,7 @@ def test_score_attaches_complete_rationale(scorer: ConfidenceScorer) -> None:
"threat_intel",
"upstream_risk",
"ioc_density",
+ "asset_criticality",
}
@@ -327,3 +328,39 @@ def test_score_clamped_to_unit_interval(scorer: ConfidenceScorer) -> None:
)
scored = scorer.score(extreme)
assert 0.0 <= scored.confidence_score <= 1.0
+
+
+# ─── Asset criticality (business-context plan, PR-3) ─────────────────────────
+
+
+def test_asset_criticality_reads_the_fuse_time_stamp(scorer: ConfidenceScorer) -> None:
+ """A critical asset pushes the score up; the factor names the match."""
+ fused = _fused(_alert())
+ fused.enrichments["asset_context"] = {"criticality": "critical", "matched": "prod-dc-01"}
+ scored = scorer.score(fused)
+ factor = next(f for f in scored.confidence_rationale if f.factor == "asset_criticality")
+ assert factor.contribution == 1.0
+ assert factor.value == "critical"
+
+ baseline = scorer.score(_fused(_alert()))
+ assert scored.confidence_score > baseline.confidence_score
+
+
+def test_no_inventory_match_is_unknown_not_zero_evidence(scorer: ConfidenceScorer) -> None:
+ """Absent stamp: contribution exactly 0.0 and the row SAYS unknown —
+ "we do not know what this host is" is a fact an analyst needs, so the
+ factor is rendered rather than omitted."""
+ scored = scorer.score(_fused(_alert()))
+ factor = next(f for f in scored.confidence_rationale if f.factor == "asset_criticality")
+ assert factor.contribution == 0.0
+ assert factor.value == "unknown (no inventory match)"
+
+
+def test_low_criticality_pulls_down_but_is_bounded(scorer: ConfidenceScorer) -> None:
+ fused = _fused(_alert())
+ fused.enrichments["asset_context"] = {"criticality": "low", "matched": "kiosk-7"}
+ scored = scorer.score(fused)
+ factor = next(f for f in scored.confidence_rationale if f.factor == "asset_criticality")
+ assert factor.contribution == -0.3
+ # Bounded: weight 0.06, so the full swing is ±0.03 on the score.
+ assert factor.weight == 0.06