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.

feat(cve): patch-window policy — bulk-close, vuln inventory, grouped promotion (rebased onto #1183) (#1201)

alexmateescu7e57a0b7e6a0
diff --git a/.security/allowlist.yml b/.security/allowlist.yml
index 345ef4f06..4df64c843 100644
--- a/.security/allowlist.yml
+++ b/.security/allowlist.yml
@@ -191,8 +191,24 @@ ceilings:
# disabled). That is exactly one `error` finding, and both the error
# and total counts dropped by exactly one on this branch, so the delta
# is the removed call and not the scanner. Lowering locks it in.
- total: 103
- error: 38
+ #
+ # 103/38 -> 105/40. Two `avoid-sqlalchemy-text` findings, both on
+ # `services/api/app/services/alert_bulk_close.py`, where the bulk-close
+ # snapshot interpolates a backup *table name* into `text()`.
+ #
+ # Counted rather than suppressed, per the note above: a ceiling counts a
+ # finding, a suppression hides it. And the finding is real as a pattern
+ # even though it is not exploitable here — a table name cannot be a bind
+ # parameter in SQL, so interpolation is the only way to name one. The
+ # value is generated as `uuid.uuid4().hex` and then re-checked against an
+ # anchored `_BACKUP_TABLE_RE` that admits nothing but
+ # `aisoc_bulk_close_backup.bulk_close_backup_<32 hex>`, with a raise if it
+ # does not match, so no caller-supplied string reaches the statement.
+ #
+ # If the snapshot is ever reshaped to write into one fixed table keyed by
+ # a run id, both findings go away and this ceiling should come back down.
+ total: 105
+ error: 40
measured_with: "1.86.0"
checkov:
failed: 219
diff --git a/DEPTH_PROGRESS.md b/DEPTH_PROGRESS.md
index 983101b45..0ab1d16fe 100644
--- a/DEPTH_PROGRESS.md
+++ b/DEPTH_PROGRESS.md
@@ -278,67 +278,6 @@ Instead, every selector field, `group-by` and `distinct_by` is checked
against the emitted-field namespace with **no ceiling**, which caught three
invented fields on the first run of the gate.
-### D9 -- Five of the 45 "unreachable" rules were never unreachable
-
-`scripts/check_detection_fields.py` carries its own copy of the matcher's
-operator suffixes, under a comment saying it mirrors
-`detection_matcher.OPERATORS`. It did not. `neq` had been added to the
-matcher and not to the gate, so `approver_role_neq: "codeowner"` — which the
-engine reads correctly as `approver_role` with `!=` — was reported as a rule
-naming a field called `approver_role_neq`. Five rules were counted against
-the ratchet for a defect that had already been fixed.
-
-The same comparison in the other direction found a worse one: the gate
-listed `not_startswith_any` and `not_endswith`, which the **matcher** did not
-implement. Three shipped rules use `path_not_startswith_any`, so the matcher
-read the whole string as a field name and all three could never fire — while
-the gate, stripping a suffix nothing implemented, reported them reachable.
-Both operators are now implemented in the vendored matcher and the canonical
-one, the fixture synthesiser knows them, and
-`test_the_gate_and_the_matcher_agree_on_every_operator` compares the two
-lists in both directions.
-
-### D10 -- 18 rules are retired rather than fixed, and why each one is
-
-The plan says of one family: "build them where cheap, otherwise quarantine
-with a reason". Applied to all three families, that leaves 18 rules that need
-work belonging to another item, recorded individually in
-`scripts/enrichment_decisions.py`:
-
-| kind | n | needs |
-|---|---|---|
-| `needs-connector-field` | 9 | a field the vendor has and no connector surfaces — depth plan 2.2 |
-| `needs-external-source` | 6 | a registry, a credential report or a factor record — 2.5 and beyond |
-| `needs-inventory` | 3 | an inventory this platform does not hold (DC machine accounts, privileged OAuth scopes) |
-
-`scripts/check_enrichment_decisions.py` is what stops this being a way to
-move the ratchet: it fails if a retired rule's fields are all resolvable.
-Proved by retiring a working rule and watching it fail.
-
-The line that mattered most was refusing a plausible substitute.
-`domain_age_days` wants a domain's registration age from a registry; the
-first-seen store could have answered "when this deployment first saw it" and
-the number would have looked right in a diff. It would also have fired the
-rule on most of the internet. Five such age-of-a-thing fields are named in a
-test that forbids the first-seen store from ever growing them.
-
-### D11 -- Identity privilege reads a table a tenant must populate
-
-The `*_priv` booleans resolve from `identity_nodes.privilege_tier >= 2`, the
-column migration 018 created for the question. The table's only writer is
-`POST /api/v1/identity-graph/nodes`, so a tenant that has imported no
-directory gets **no key at all** and those 18 rules stay silent — they are
-reachable "when the tenant has identity data", the same standard this gate
-already applies to a vendor-payload field. That is weaker than "reachable on
-any deployment" and is stated rather than glossed. Depth plan 2.5's posture
-collectors are what will populate it automatically.
-
-Four booleans in the same family are deliberately **not** computed —
-`scope_priv`, `act_as_user_priv`, `gpo_link_priv` and `account_is_dc` — and
-are among the 18 above. Each has no subject field any source emits, and
-guessing a subject would produce a boolean that is confidently wrong rather
-than absent.
-
## Phase 1: Verdict quality you can publish
- [x] **1.1** Balanced, labelled verdict corpus
@@ -366,11 +305,6 @@ than absent.
refused with a reason. `MAX_UNREACHABLE` 119 → 45.
- [x] **3.2** Ordered sequences and Sigma correlations — the windowed engine
stages ordered and unordered sequences; all four translatable Sigma
- correlation types compile. Windowed corpus 68 → 72. See D7 and D8.
- correlation types compile. See D7 and D8.
-- [x] **3.3** Enrichment inputs (parity 5.5) — identity privilege and a
- per-tenant first-seen store built; 18 rules retired with a reason.
- `MAX_UNREACHABLE` 45 → 2. See D9–D11.
- [ ] **3.2** Ordered sequences and Sigma correlations
- [ ] **3.3** Enrichment inputs (parity 5.5)
- [ ] **3.4** Behavioural baselines in CORE
diff --git a/apps/docs/docs/connectors/wazuh.md b/apps/docs/docs/connectors/wazuh.md
index 69885ce48..e67a97649 100644
--- a/apps/docs/docs/connectors/wazuh.md
+++ b/apps/docs/docs/connectors/wazuh.md
@@ -140,6 +140,7 @@ connector trusts the indexer's certificate.
| `index_pattern` | Alert Index Pattern | string | no | `wazuh-alerts-*` | Override only if you have re-templated the default Wazuh index naming. |
| `min_rule_level` | Minimum Rule Level | number | no | `7` | Drop alerts with rule.level below this value at ingest. Default 7 keeps low-signal noise out of the lake; lower to 3 for full audit coverage. |
| `verify_tls` | Verify TLS Certificate | boolean | no | `True` | Disable only for self-signed lab clusters. Production deployments must install the CA chain. |
+| `vuln_mode` | Vulnerability Events | select | no | `inventory` | Where vulnerability-detector events go. 'inventory' (default) routes them to the asset vulnerability inventory with patch-window due dates per docs/cve-patch-policy.md; only CVSS>9, KEV, or overdue findings raise alerts. 'alerts' keeps the legacy behaviour of one alert per scan finding. · one of: `inventory`, `alerts` |
:::note Credential handling
`password` is encrypted at rest by the credential vault before the row is written, and decrypted only at poll time. The value is never logged and never returned by the API. See [credential vault](../operations/credentials.md).
diff --git a/docs/connectors/conformance-matrix.md b/docs/connectors/conformance-matrix.md
index 9cc7623d5..9c870a583 100644
--- a/docs/connectors/conformance-matrix.md
+++ b/docs/connectors/conformance-matrix.md
@@ -92,7 +92,7 @@
| trellix_helix | siem | 3 | 1 | 4 | ✅ | ✅ | ✅ |
| trend_vision_one | edr | 2 | 1 | 5 | ✅ | ✅ | ✅ |
| vault | iam | 4 | 1 | 2 | ✅ | ✅ | ✅ |
-| wazuh | siem | 6 | 1 | 4 | ✅ | ✅ | ✅ |
+| wazuh | siem | 7 | 1 | 5 | ✅ | ✅ | ✅ |
| windows_event | edr | 3 | 1 | 3 | ✅ | ✅ | ✅ |
| wiz | cloud | 4 | 1 | 1 | ✅ | ✅ | ✅ |
| zeek_suricata | ndr | 4 | 1 | 2 | ✅ | ✅ | ✅ |
diff --git a/docs/cve-patch-policy.md b/docs/cve-patch-policy.md
new file mode 100644
index 000000000..5d1081d9b
--- /dev/null
+++ b/docs/cve-patch-policy.md
@@ -0,0 +1,79 @@
+# CVE Patch Policy
+
+Status: approved by Alexandru Mateescu (2026-10-06). Implementation tracks the PR sequence at the bottom.
+
+## Problem
+
+An open-source SIEM/HIDS's periodic vulnerability re-scan maps every finding to a new alert.
+A full scan of the four TMC agents produced 3,885 CVE alerts in two hours
+(2026-10-06 06:00–08:00 UTC); the queue stood at 3,902 `new` alerts, of
+which 1,576 were distinct CVEs. `dedup_hash` is keyed per event, so a
+re-scan of an unchanged host re-inserts every finding. The board becomes
+uncloseable and analysts stop trusting it.
+
+## Policy
+
+Vulnerabilities are **tracked findings, not incidents**, with one exception.
+
+1. Servers get patched on the scheduled patch date. Always.
+2. A CVE with CVSS base score **> 9**, listed in CISA KEV, or flagged
+ actively exploited is **urgent**: it must be patched out-of-band and it
+ raises an alert immediately.
+3. Everything else is `scheduled` to the next patch date for the host's
+ environment class. No alert at creation.
+4. A `scheduled` finding whose `patch_due_date` has passed while the scanner
+ still reports it raises exactly one `overdue` alert.
+5. When the scanner stops reporting a finding, the row closes silently
+ (`remediated_at`).
+
+### Patch calendar
+
+| Class | Rule | Next windows |
+|-------|------|--------------|
+| TEST (hostname contains `dev`, `test`, `uat`) | first Wednesday after Patch Tuesday | 2026-10-14, 2026-11-11, 2026-12-09 |
+| PROD (default) | test window + 7 days | 2026-10-21, 2026-11-18, 2026-12-16 |
+
+Patch Tuesday = second Tuesday of the month (the anchor; Linux vendors do
+not publish on a fixed date but distro kernel updates land in the same
+window).
+
+### Data model
+
+- `asset_vulnerabilities` (exists, currently Tenable-only) becomes the home
+ for all scanner findings, keyed `(tenant_id, asset_id, cve_id, source)`;
+ re-polls move `last_found` only. Add `environment_class` derived from the
+ hostname rule above, and `patch_due_date` + `policy_status`
+ (`scheduled|urgent|overdue|remediated`).
+- The `alerts` table receives only: urgent creations (grouped per CVE,
+ hosts as children), overdue promotions (one per CVE+host), and threat-intel
+ re-promotions.
+- Open-source SIEM/HIDS vulnerability events stop creating per-finding alerts once the writer
+ lands; the connector maps them into `asset_vulnerabilities` instead.
+
+### Day-one numbers (2026-10-06 snapshot, live DB)
+
+- 1,576 distinct open CVEs across 4 TMC agents (packages: `linux-aws` kernel).
+- 216 distinct CVEs with CVSS > 9 (500 CVE+host pairs) — urgent list.
+- 1,360 distinct CVEs in the 7–9 band — scheduled, due Oct 14 (test) / Oct 21 (prod).
+- 0 below 7.
+
+The urgent list collapses to one action: patch + reboot the kernel on the
+four hosts.
+
+### Agent prompt (enforcement lives in the pipeline, not here)
+
+Triage agents receive: *"Vulnerability findings follow patch-window policy:
+severity ≤ 9 inside its patch window is scheduled maintenance, not an
+incident — never raise severity on it. Escalate only CVSS > 9, KEV, or
+findings overdue past `patch_due_date`."*
+
+## PR sequence
+
+1. `feat(alerts): POST /api/v1/alerts/bulk-close` — ids or filter spec,
+ `max_count` guard, backup table + audit entries (mirrors the manual
+ Oct-2 bulk close that produced `alerts_bulk_close_backup_20261002`).
+2. `feat(connectors): route open-source HIDS vulnerability findings to asset_vulnerabilities`
+ — per-event alert creation removed; urgent rule applied at write time.
+3. `feat(api): patch_due_date + patch_windows config + overdue promotion job`.
+4. `feat(web): patch backlog view` (CVE → affected hosts roll-up).
+5. `chore(agents): patch-window policy paragraph in triage system prompt`.
diff --git a/docs/openapi.yaml b/docs/openapi.yaml
index dfeb95ada..25afae03c 100644
--- a/docs/openapi.yaml
+++ b/docs/openapi.yaml
@@ -972,6 +972,46 @@ paths:
application/json:
schema:
$ref: '#/components/schemas/HTTPValidationError'
+ /api/v1/alerts/bulk-close:
+ post:
+ tags:
+ - alerts
+ summary: Bulk Close Alerts Endpoint
+ description: "Close many alerts in one call, with a preflight guard and a snapshot.\n\
+ \n* Pass ``alert_ids`` for an explicit set, or filters\n (``statuses``/``severities``/``categories``/``connector_types``/\n\
+ \ ``older_than``) for a class of alerts. A filter without ``older_than``\n\
+ \ only matches still-open rows.\n* **Dry-run for free:** the first call with\
+ \ a ``max_count`` below the\n real match count returns ``409`` carrying ``matched_count``\
+ \ — raise\n ``max_count`` past it to execute. Nothing is written on the 409.\n\
+ * Every affected row is snapshotted into a dedicated backup table\n (returned\
+ \ in the body) before the UPDATE commits.\n* One audit entry covers the batch\
+ \ (with the backup table name so the\n restore target is recorded next to\
+ \ the action).\n\nTypical noise sweep::\n\n POST /api/v1/alerts/bulk-close\n\
+ \ {\"categories\": [\"malware\", \"vulnerability\"],\n \"severities\"\
+ : [\"low\", \"informational\"],\n \"older_than\": \"2026-10-05T00:00:00Z\"\
+ ,\n \"max_count\": 5000, \"comment\": \"quarterly noise sweep\"}"
+ operationId: bulk_close_alerts_endpoint_api_v1_alerts_bulk_close_post
+ requestBody:
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AlertBulkCloseRequest'
+ required: true
+ responses:
+ '200':
+ description: Successful Response
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/AlertBulkCloseResponse'
+ '422':
+ description: Validation Error
+ content:
+ application/json:
+ schema:
+ $ref: '#/components/schemas/HTTPValidationError'
+ security:
+ - HTTPBearer: []
/api/v1/alerts/{alert_id}/explain:
post:
tags:
@@ -19992,6 +20032,100 @@ components:
- threat_intel_age_hours
- checks
title: AirgapStatus
+ AlertBulkCloseRequest:
+ properties:
+ alert_ids:
+ anyOf:
+ - items:
+ type: string
+ format: uuid
+ type: array
+ maxItems: 10000
+ - type: 'null'
+ title: Alert Ids
+ statuses:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ maxItems: 10
+ - type: 'null'
+ title: Statuses
+ severities:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ maxItems: 10
+ - type: 'null'
+ title: Severities
+ categories:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ maxItems: 20
+ - type: 'null'
+ title: Categories
+ connector_types:
+ anyOf:
+ - items:
+ type: string
+ type: array
+ maxItems: 20
+ - type: 'null'
+ title: Connector Types
+ older_than:
+ anyOf:
+ - type: string
+ format: date-time
+ - type: 'null'
+ title: Older Than
+ close_status:
+ type: string
+ enum:
+ - resolved
+ - false_positive
+ - closed
+ title: Close Status
+ default: resolved
+ max_count:
+ type: integer
+ maximum: 10000.0
+ minimum: 1.0
+ title: Max Count
+ default: 500
+ comment:
+ anyOf:
+ - type: string
+ maxLength: 500
+ - type: 'null'
+ title: Comment
+ additionalProperties: false
+ type: object
+ title: AlertBulkCloseRequest
+ description: Ids or filters — never neither, never a wildcard.
+ AlertBulkCloseResponse:
+ properties:
+ matched_count:
+ type: integer
+ title: Matched Count
+ closed_count:
+ type: integer
+ title: Closed Count
+ close_status:
+ type: string
+ title: Close Status
+ backup_table:
+ type: string
+ title: Backup Table
+ type: object
+ required:
+ - matched_count
+ - closed_count
+ - close_status
+ - backup_table
+ title: AlertBulkCloseResponse
AlertDetailResponse:
properties:
id:
diff --git a/scripts/check_raw_sql_columns.py b/scripts/check_raw_sql_columns.py
index 3dec8f8e4..8b23f342e 100644
--- a/scripts/check_raw_sql_columns.py
+++ b/scripts/check_raw_sql_columns.py
@@ -240,6 +240,15 @@ PARSER_ARTEFACTS: dict[tuple[str, str], str] = {
"services/actions/app/live_actions/builtins.py",
"the",
): "Prose in the module docstring, not a statement. The word follows `SELECT` in an English sentence.",
+ (
+ "services/api/app/services/alert_bulk_close.py",
+ "a",
+ ): (
+ "`CREATE TABLE {backup_table} AS SELECT * FROM ({compiled}) AS snapshot_rows`. Both "
+ "placeholders are unresolved in source — the table name is a uuid4 hex and the inner "
+ "SELECT is compiled by SQLAlchemy at call time — so what reaches the parser is a "
+ "fragment and it reads the remains as a one-letter alias. There is no table named `a`."
+ ),
}
#: Tables a statement names that no migration creates and that are not foreign
@@ -272,6 +281,18 @@ DYNAMIC_SQL: dict[tuple[str, str], str] = {
"('aisoc._migrations'), interpolated, and this module creates it. Same reason as "
"`aisoc_schema_migrations` above, one store over."
),
+ (
+ "services/api/app/services/alert_bulk_close.py",
+ "alerts",
+ ): (
+ "The bulk-close undo snapshot. Two statements, both assembled at runtime and "
+ "neither comparable to a migration: the UPDATE's SET clause is built from whichever "
+ "filters the request supplied, and the CREATE TABLE AS names a per-operation backup "
+ "table whose name is a uuid4 hex, wrapping a SELECT that SQLAlchemy compiles. There "
+ "is no column list in the source to compare, and the backup table is created by this "
+ "function rather than by a migration -- which is the point of it. The columns it can "
+ "touch are literals in this module, which is the read a human has to do."
+ ),
(
"services/api/app/api/v1/endpoints/cases.py",
"aisoc_cases",
diff --git a/services/actions/app/live_actions/capabilities.py b/services/actions/app/live_actions/capabilities.py
index b67323417..af5e8a79b 100644
--- a/services/actions/app/live_actions/capabilities.py
+++ b/services/actions/app/live_actions/capabilities.py
@@ -35,6 +35,7 @@ KNOWN_CAPABILITIES: frozenset[str] = frozenset(
"pull_file",
"pull_logs",
"pull_pcap",
+ "pull_vulnerabilities",
# QUERY
"query_logs",
"query_processes",
diff --git a/services/api/app/api/v1/endpoints/alerts.py b/services/api/app/api/v1/endpoints/alerts.py
index 87cd70acd..147822e81 100644
--- a/services/api/app/api/v1/endpoints/alerts.py
+++ b/services/api/app/api/v1/endpoints/alerts.py
@@ -7,7 +7,7 @@ import uuid
from datetime import UTC, datetime
from typing import Annotated, Any, Literal
-from fastapi import APIRouter, Depends, Header, HTTPException, Query, status
+from fastapi import APIRouter, Depends, Header, HTTPException, Query, Request, status
from pydantic import BaseModel, ConfigDict, Field
from sqlalchemy import and_, func, select, update
from sqlalchemy.exc import IntegrityError
@@ -15,6 +15,13 @@ from sqlalchemy.exc import IntegrityError
from app.api.v1.deps import AuthUser, DBSession, require_permission
from app.db.rls import TenantDBSession
from app.models.alert import Alert
+from app.services.alert_bulk_close import (
+ DEFAULT_MAX_COUNT,
+ MAX_BULK_CLOSE_LIMIT,
+ BulkCloseEmpty,
+ BulkCloseOverMatch,
+ bulk_close_alerts,
+)
from app.services.alert_queue import (
AlertAlreadyClaimedError,
AlertNotFoundError,
@@ -28,6 +35,7 @@ from app.services.alert_rail import (
RelatedEntity,
build_rail_envelope,
)
+from app.services.audit import emit_audit
from app.services.event_sanitiser import (
SubmitPayloadTooLarge,
sanitise_event_batch,
@@ -1029,3 +1037,114 @@ async def snooze_alert(
await db.refresh(alert)
return AlertResponse.model_validate(alert)
+
+
+class AlertBulkCloseRequest(BaseModel):
+ """Ids or filters — never neither, never a wildcard."""
+
+ model_config = ConfigDict(extra="forbid")
+
+ alert_ids: list[uuid.UUID] | None = Field(default=None, max_length=MAX_BULK_CLOSE_LIMIT)
+ statuses: list[str] | None = Field(default=None, max_length=10)
+ severities: list[str] | None = Field(default=None, max_length=10)
+ categories: list[str] | None = Field(default=None, max_length=20)
+ connector_types: list[str] | None = Field(default=None, max_length=20)
+ older_than: datetime | None = None
+ close_status: Literal["resolved", "false_positive", "closed"] = "resolved"
+ max_count: int = Field(default=DEFAULT_MAX_COUNT, ge=1, le=MAX_BULK_CLOSE_LIMIT)
+ comment: str | None = Field(default=None, max_length=500)
+
+
+class AlertBulkCloseResponse(BaseModel):
+ matched_count: int
+ closed_count: int
+ close_status: str
+ backup_table: str
+
+
[email protected]("/bulk-close", response_model=AlertBulkCloseResponse)
+async def bulk_close_alerts_endpoint(
+ payload: AlertBulkCloseRequest,
+ request: Request,
+ current_user: Annotated[AuthUser, Depends(require_permission("alerts:write"))],
+ db: DBSession,
+) -> AlertBulkCloseResponse:
+ """Close many alerts in one call, with a preflight guard and a snapshot.
+
+ * Pass ``alert_ids`` for an explicit set, or filters
+ (``statuses``/``severities``/``categories``/``connector_types``/
+ ``older_than``) for a class of alerts. A filter without ``older_than``
+ only matches still-open rows.
+ * **Dry-run for free:** the first call with a ``max_count`` below the
+ real match count returns ``409`` carrying ``matched_count`` — raise
+ ``max_count`` past it to execute. Nothing is written on the 409.
+ * Every affected row is snapshotted into a dedicated backup table
+ (returned in the body) before the UPDATE commits.
+ * One audit entry covers the batch (with the backup table name so the
+ restore target is recorded next to the action).
+
+ Typical noise sweep::
+
+ POST /api/v1/alerts/bulk-close
+ {"categories": ["malware", "vulnerability"],
+ "severities": ["low", "informational"],
+ "older_than": "2026-10-05T00:00:00Z",
+ "max_count": 5000, "comment": "quarterly noise sweep"}
+ """
+ if not payload.alert_ids and not (
+ payload.statuses or payload.severities or payload.categories or payload.connector_types or payload.older_than
+ ):
+ raise HTTPException(
+ status_code=status.HTTP_400_BAD_REQUEST,
+ detail="provide alert_ids or at least one filter (statuses/severities/categories/connector_types/older_than)",
+ )
+
+ try:
+ outcome = await bulk_close_alerts(
+ db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ close_status=payload.close_status,
+ alert_ids=payload.alert_ids,
+ statuses=payload.statuses,
+ severities=payload.severities,
+ categories=payload.categories,
+ connector_types=payload.connector_types,
+ older_than=payload.older_than,
+ max_count=payload.max_count,
+ comment=payload.comment,
+ )
+ except BulkCloseOverMatch as exc:
+ raise HTTPException(
+ status_code=status.HTTP_409_CONFLICT,
+ detail={
+ "error": "over_match",
+ "matched_count": exc.matched,
+ "max_count": exc.max_count,
+ "hint": "raise max_count above matched_count to confirm, or tighten the filter",
+ },
+ ) from exc
+ except BulkCloseEmpty as exc:
+ raise HTTPException(status_code=status.HTTP_404_NOT_FOUND, detail="no alerts matched the given ids/filter") from exc
+
+ await emit_audit(
+ db=db,
+ tenant_id=current_user.tenant_id,
+ actor_id=current_user.user_id,
+ actor_email=getattr(current_user, "email", None),
+ action="alerts:bulk_close",
+ resource="alert",
+ changes={
+ "close_status": outcome["close_status"],
+ "closed_count": outcome["closed_count"],
+ "filters": payload.model_dump(exclude_none=True, exclude={"alert_ids"}),
+ "id_count": len(payload.alert_ids or []),
+ "comment": payload.comment,
+ "backup_table": outcome["backup_table"],
+ },
+ request=request,
+ api_key_prefix=getattr(current_user, "api_key_prefix", None),
+ )
+ await db.commit()
+
+ return AlertBulkCloseResponse(**outcome)
diff --git a/services/api/app/data/connector_catalog_fallback.json b/services/api/app/data/connector_catalog_fallback.json
index d49289fa1..baf86b659 100644
--- a/services/api/app/data/connector_catalog_fallback.json
+++ b/services/api/app/data/connector_catalog_fallback.json
@@ -3525,6 +3525,7 @@
{
"capabilities": [
"pull_alerts",
+ "pull_vulnerabilities",
"query_logs",
"search_siem",
"pivot_host"
@@ -3579,6 +3580,24 @@
"name": "verify_tls",
"required": false,
"type": "boolean"
+ },
+ {
+ "default": "inventory",
+ "help_text": "Where vulnerability-detector events go. 'inventory' (default) routes them to the asset vulnerability inventory with patch-window due dates per docs/cve-patch-policy.md; only CVSS>9, KEV, or overdue findings raise alerts. 'alerts' keeps the legacy behaviour of one alert per scan finding.",
+ "label": "Vulnerability Events",
+ "name": "vuln_mode",
+ "options": [
+ {
+ "label": "Inventory + patch windows (recommended)",
+ "value": "inventory"
+ },
+ {
+ "label": "Alert per finding (legacy)",
+ "value": "alerts"
+ }
+ ],
+ "required": false,
+ "type": "select"
}
]
},
diff --git a/services/api/app/services/alert_bulk_close.py b/services/api/app/services/alert_bulk_close.py
new file mode 100644
index 000000000..fb5ab3756
--- /dev/null
+++ b/services/api/app/services/alert_bulk_close.py
@@ -0,0 +1,258 @@
+"""Bulk alert closure.
+
+The console learned the hard way (see the ``alerts_bulk_close_backup_*``
+relic tables) that closing thousands of noise alerts one PATCH at a time
+is not a workflow, it is a punishment. This module is the sanctioned path:
+one call, explicit id set or filter spec, a preflight count, a snapshot of
+every row it is about to touch, then a single tenant-scoped UPDATE.
+
+Guarantees
+----------
+* **Preflight over-match protection** — the filter is counted before it is
+ applied; a caller who forgets a predicate and matches their entire queue
+ gets ``409`` unless they raised ``max_count`` past the count. The guard
+ is deliberately *interactive*: the 409 body carries the real number, so
+ the retry is one keystroke, not an archaeology dig.
+* **Recoverability** — every affected row's pre-change state is copied into
+ a per-call backup table (``bulk_close_backup_<uuid-hex>``) before the
+ UPDATE runs. Restoring is a ``UPDATE alerts SET ... FROM backup`` join
+ away.
+* **Fail closed on tenancy** — the WHERE clause is built once and reused
+ verbatim by the count, the snapshot SELECT, and the UPDATE, and it always
+ leads with the tenant predicate; there is no code path where an id list
+ escapes the tenant that submitted it.
+"""
+
+from __future__ import annotations
+
+import logging
+import re
+import uuid
+from datetime import UTC, datetime
+from typing import Any
+
+from sqlalchemy import Select, and_, func, select, text, update
+from sqlalchemy.dialects import postgresql
+from sqlalchemy.ext.asyncio import AsyncSession
+
+from app.models.alert import Alert
+
+logger = logging.getLogger(__name__)
+
+#: Hard ceiling on one call's blast radius, independent of ``max_count``.
+#: A caller may lower it, never raise it: bulk close is reversible but a
+#: six-figure UPDATE is still a six-figure lock.
+MAX_BULK_CLOSE_LIMIT = 10_000
+
+#: Backstop below the ceiling: a caller who asks for the full 10k without
+#: ever thinking still has to acknowledge the real matched count first.
+DEFAULT_MAX_COUNT = 500
+
+#: Backup-table names are generated (never user-supplied) but are still
+#: interpolated into DDL, so they go through the same identifier gate.
+# Backup tables live in aisoc_bulk_close_backup (migration 095): aisoc_app
+# deliberately lacks CREATE in public — least privilege, live-caught 500.
+_BACKUP_SCHEMA = "aisoc_bulk_close_backup"
+_BACKUP_TABLE_RE = re.compile(r"^aisoc_bulk_close_backup\.bulk_close_backup_[0-9a-f]{32}$")
+
+#: Log-injection guard (CodeQL py/log-injection): a bulk-close comment is
+#: free text from the request. CR/LF and control bytes would forge extra
+#: log lines (or break JSON handlers downstream); neutralise them and cap
+#: the length before anything reaches the logger.
+_LOG_UNSAFE_RE = re.compile(r"[\r\n\x00-\x1f\x7f]")
+
+
+def _safe_log_text(value: str | None, *, limit: int = 120) -> str:
+ """Single-line, control-char-free rendering of user free text for logs."""
+ if not value:
+ return ""
+ return _LOG_UNSAFE_RE.sub(" ", value)[:limit]
+
+
+#: Statuses an alert may be bulk-closed *to*. ``new``/``investigating`` are
+#: excluded: those are queue states, and bulk-moving work into the queue is
+#: not what this endpoint is for.
+CLOSE_STATUSES = frozenset({"resolved", "false_positive", "closed"})
+
+#: Alert statuses that count as still-open for the preflight count (an
+#: already-closed row must not consume a caller's max_count budget).
+OPEN_STATUSES = ("new", "triaging", "investigating", "in_progress", "escalated", "snoozed")
+
+
+class BulkCloseOverMatch(Exception):
+ """Raised when the filter matched more rows than ``max_count`` allows.
+
+ Carries the actual count so the 409 body can teach the caller exactly
+ what to adjust — never a bare 403 with a mystery number.
+ """
+
+ def __init__(self, matched: int, max_count: int) -> None:
+ self.matched = matched
+ self.max_count = max_count
+ super().__init__(f"bulk close matched {matched} alerts, over max_count={max_count}")
+
+
+class BulkCloseEmpty(Exception):
+ """Nothing matched — surfaced as 404 rather than a silent 200/zero."""
+
+
+def build_bulk_close_predicates(
+ *,
+ tenant_id: uuid.UUID,
+ alert_ids: list[uuid.UUID] | None,
+ statuses: list[str] | None,
+ severities: list[str] | None,
+ categories: list[str] | None,
+ connector_types: list[str] | None,
+ older_than: datetime | None,
+) -> list[Any]:
+ """Compose the WHERE list shared by the count, snapshot, and UPDATE.
+
+ One builder for all three statements is the whole point: a predicate
+ added here lands in every statement at once, so the rows counted,
+ snapshotted, and updated can never drift apart.
+ """
+ preds: list[Any] = [Alert.tenant_id == tenant_id]
+ if alert_ids:
+ preds.append(Alert.id.in_(alert_ids))
+ if statuses:
+ preds.append(Alert.status.in_(statuses))
+ if severities:
+ preds.append(Alert.severity.in_(severities))
+ if categories:
+ preds.append(Alert.category.in_(categories))
+ if connector_types:
+ preds.append(Alert.connector_type.in_(connector_types))
+ if older_than is not None:
+ preds.append(Alert.created_at < older_than)
+ elif not alert_ids:
+ # A pure-filter close must not reach into already closed work:
+ # re-closing closed rows would churn resolved_at and audit noise
+ # for zero operational value. An explicit id list may still re-close
+ # (analysts legitimately re-triage a wrongly-closed alert).
+ preds.append(Alert.status.in_(OPEN_STATUSES))
+ return preds
+
+
+_SNAPSHOT_COLUMNS = (
+ Alert.id,
+ Alert.title,
+ Alert.status,
+ Alert.severity,
+ Alert.priority,
+ Alert.category,
+ Alert.connector_type,
+ Alert.tags,
+ Alert.description,
+ Alert.resolved_at,
+ Alert.updated_at,
+)
+
+
+def _snapshot_select(preds: list[Any]) -> Select[tuple[Any, ...]]:
+ return select(*_SNAPSHOT_COLUMNS).where(and_(*preds))
+
+
+def _snapshot_sql(select_stmt: Select[tuple[Any, ...]], backup_table: str) -> str:
+ """Render the snapshot SELECT into CREATE TABLE ... AS form.
+
+ Compiled with ``literal_binds`` on purpose: the raw DDL string goes to
+ asyncpg through ``text()``, and asyncpg has no pyformat binds — a
+ leftover ``%(name)s`` placeholder from a psycopg2-style compile is a
+ syntax error at the driver (live-caught 2026-10-06: HTTP 500,
+ "syntax error at or near %"). literal_binds keeps the WHERE structure
+ identical to the statement the endpoint counted and the UPDATE reuses,
+ with SQLAlchemy handling all quoting/escaping of the values (which are
+ tenant UUIDs and validated filter strings).
+ """
+ compiled = str(select_stmt.compile(dialect=postgresql.dialect(), compile_kwargs={"literal_binds": True}))
+ # Strip the table qualifier from the projected columns: CREATE TABLE AS
+ # derives column names, and `alerts.id` would name the column "id"
+ # anyway — but PostgreSQL warns on qualified names in CTAS output,
+ # so we emit the unqualified list ourselves.
+ return f"CREATE TABLE {backup_table} AS SELECT * FROM ({compiled}) AS snapshot_rows"
+
+
+async def bulk_close_alerts(
+ db: AsyncSession,
+ *,
+ tenant_id: uuid.UUID,
+ actor_id: uuid.UUID | None,
+ close_status: str,
+ alert_ids: list[uuid.UUID] | None = None,
+ statuses: list[str] | None = None,
+ severities: list[str] | None = None,
+ categories: list[str] | None = None,
+ connector_types: list[str] | None = None,
+ older_than: datetime | None = None,
+ max_count: int = DEFAULT_MAX_COUNT,
+ comment: str | None = None,
+) -> dict[str, Any]:
+ """Snapshot then close every alert matching the id set or filter.
+
+ Returns ``{"backup_table", "closed_count", "matched_count", "close_status"}``.
+ Raises :class:`BulkCloseOverMatch` (409 upstream), :class:`BulkCloseEmpty`
+ (404 upstream), or ``ValueError`` for an invalid close target — all
+ before any row is touched.
+ """
+ if close_status not in CLOSE_STATUSES:
+ raise ValueError(f"close target must be one of {sorted(CLOSE_STATUSES)}")
+ if not alert_ids and not (statuses or severities or categories or connector_types or older_than):
+ # Neither ids nor filters would target the whole queue; refuse rather
+ # than let a forgotten body close everything.
+ raise ValueError("bulk close requires alert_ids or at least one filter")
+
+ max_count = max(1, min(int(max_count), MAX_BULK_CLOSE_LIMIT))
+ preds = build_bulk_close_predicates(
+ tenant_id=tenant_id,
+ alert_ids=alert_ids,
+ statuses=statuses,
+ severities=severities,
+ categories=categories,
+ connector_types=connector_types,
+ older_than=older_than,
+ )
+
+ matched = int((await db.execute(select(func.count()).select_from(Alert).where(and_(*preds)))).scalar_one())
+ if matched == 0:
+ raise BulkCloseEmpty()
+ if matched > max_count:
+ raise BulkCloseOverMatch(matched=matched, max_count=max_count)
+
+ backup_table = f"{_BACKUP_SCHEMA}.bulk_close_backup_{uuid.uuid4().hex}"
+ if not _BACKUP_TABLE_RE.match(backup_table): # pragma: no cover - belt over braces
+ raise RuntimeError("generated backup table name failed identifier validation")
+
+ select_stmt = _snapshot_select(preds)
+
+ await db.execute(text(f"DROP TABLE IF EXISTS {backup_table}"))
+ await db.execute(text(_snapshot_sql(select_stmt, backup_table)))
+
+ now = datetime.now(UTC)
+ updates: dict[str, Any] = {"status": close_status, "updated_at": now}
+ updates["resolved_at"] = now
+ result = await db.execute(update(Alert).where(and_(*preds)).values(**updates))
+ closed = int(result.rowcount or 0)
+ await db.commit()
+
+ # Every interpolated value is neutralised or validated: tenant/actor are
+ # server-side UUIDs, close_status is membership-checked against
+ # CLOSE_STATUSES, backup_table is regex-validated above, comment is free
+ # text and goes through _safe_log_text (CodeQL py/log-injection).
+ logger.info(
+ "alerts.bulk_close tenant=%s actor=%s matched=%d closed=%d target=%s backup=%s comment=%s",
+ tenant_id,
+ actor_id,
+ matched,
+ closed,
+ close_status,
+ backup_table,
+ _safe_log_text(comment),
+ )
+
+ return {
+ "backup_table": backup_table,
+ "matched_count": matched,
+ "closed_count": closed,
+ "close_status": close_status,
+ }
diff --git a/services/api/migrations/099_bulk_close_backup_schema.sql b/services/api/migrations/099_bulk_close_backup_schema.sql
new file mode 100644
index 000000000..e64a6b57d
--- /dev/null
+++ b/services/api/migrations/099_bulk_close_backup_schema.sql
@@ -0,0 +1,24 @@
+-- 095: dedicated schema for bulk-close backup snapshots.
+--
+-- POST /api/v1/alerts/bulk-close snapshots every matched row into a
+-- per-call table (bulk_close_backup_<uuid>) immediately before the
+-- tenant-scoped UPDATE, so any sweep is reversible row-for-row. The
+-- runtime role aisoc_app deliberately has no CREATE in schema public —
+-- that is least-privilege working as intended (live-caught 2026-10-06:
+-- the endpoint 500'd with "permission denied for schema public").
+--
+-- Rather than widen public, grant CREATE on a purpose-built schema the
+-- app can only use for backups. Tables created there are owned by
+-- aisoc_app itself, so read-back and drop need no further grants.
+--
+-- Idempotent: CREATE SCHEMA IF NOT EXISTS + GRANT are re-applable no-ops.
+
+CREATE SCHEMA IF NOT EXISTS aisoc_bulk_close_backup AUTHORIZATION aisoc;
+
+GRANT USAGE, CREATE ON SCHEMA aisoc_bulk_close_backup TO aisoc_app;
+
+-- Anything the operator role creates here stays readable to the app too
+-- (forensic imports), and vice versa the app-owned backups stay readable
+-- to the owner role for manual restores.
+ALTER DEFAULT PRIVILEGES IN SCHEMA aisoc_bulk_close_backup
+ GRANT SELECT ON TABLES TO aisoc_app;
diff --git a/services/api/migrations/100_vuln_patch_windows.sql b/services/api/migrations/100_vuln_patch_windows.sql
new file mode 100644
index 000000000..f139405d8
--- /dev/null
+++ b/services/api/migrations/100_vuln_patch_windows.sql
@@ -0,0 +1,33 @@
+-- PR2 (docs/cve-patch-policy.md): patch-window tracking on the vulnerability
+-- inventory. Additive only — no existing column is touched, so a stack that
+-- rolls back the code keeps running against this schema unchanged.
+--
+-- Semantics:
+-- environment = 'test' | 'prod' bucket assigned at first materialization
+-- from hostname classification (app/patch_calendar.py);
+-- unknown hosts are 'prod' (fail closed toward the stricter
+-- window).
+-- patch_due_date = window due date computed once at first materialization
+-- from first_found; re-polls MUST NOT move it (the due date
+-- is the operational promise, not observed state).
+-- patch_status = 'tracked' -> 'overdue' (due date passed) -> 'promoted'
+-- (an alert exists). 'tracked' is the default so rows
+-- written before the promotion job exists still enter the
+-- lifecycle on the next sweep.
+--
+-- The partial index serves the promotion sweep's hot path
+-- (open rows by tenant + status + due date) without indexing the full
+-- remediated history.
+
+ALTER TABLE asset_vulnerabilities
+ ADD COLUMN IF NOT EXISTS environment text;
+
+ALTER TABLE asset_vulnerabilities
+ ADD COLUMN IF NOT EXISTS patch_due_date date;
+
+ALTER TABLE asset_vulnerabilities
+ ADD COLUMN IF NOT EXISTS patch_status text NOT NULL DEFAULT 'tracked';
+
+CREATE INDEX IF NOT EXISTS ix_asset_vuln_patch_due
+ ON asset_vulnerabilities (tenant_id, patch_status, patch_due_date)
+ WHERE remediated_at IS NULL;
diff --git a/services/api/tests/test_alert_bulk_close.py b/services/api/tests/test_alert_bulk_close.py
new file mode 100644
index 000000000..ee9a35747
--- /dev/null
+++ b/services/api/tests/test_alert_bulk_close.py
@@ -0,0 +1,241 @@
+"""Tests for the bulk-close service (services/api/app/services/alert_bulk_close.py).
+
+Mirrors the alert-queue test convention: pure service layer, mocked
+AsyncSession, no TestClient, no Postgres. The integration tests in CI run
+the same code path against a real database; here we lock the *rules* —
+what refuses to run, and what the executed statements must contain.
+
+The critical assertions are the fail-closed ones:
+* the tenant predicate is present in every statement (count, snapshot,
+ UPDATE) — an escaping tenant filter is the one bug this endpoint is
+ not allowed to have;
+* over-match and empty refuse BEFORE any write is attempted (the mock
+ would raise if the order were flipped);
+* generated backup table names never interpolate attacker input.
+"""
+
+from __future__ import annotations
+
+import uuid
+from datetime import UTC, datetime, timedelta
+from unittest.mock import AsyncMock, MagicMock
+
+import pytest
+from app.services.alert_bulk_close import (
+ DEFAULT_MAX_COUNT,
+ MAX_BULK_CLOSE_LIMIT,
+ BulkCloseEmpty,
+ BulkCloseOverMatch,
+ build_bulk_close_predicates,
+ bulk_close_alerts,
+)
+
+
+def _tenant() -> uuid.UUID:
+ return uuid.uuid4()
+
+
+def _compiled(stmt) -> str:
+ from sqlalchemy.dialects import postgresql
+
+ return str(stmt.compile(dialect=postgresql.dialect(), compile_kwargs={"render_postcompile": True}))
+
+
+def _session(matched: int = 3, snapshot_rows: int = 3) -> AsyncMock:
+ """Mock session whose execute() answers count → matched, then anything."""
+ db = AsyncMock()
+ count_result = MagicMock()
+ count_result.scalar_one.return_value = matched
+ update_result = MagicMock()
+ update_result.rowcount = snapshot_rows
+ db.execute = AsyncMock(side_effect=[count_result, MagicMock(), MagicMock(), update_result])
+ return db
+
+
+class TestPredicateBuilder:
+ def test_tenant_predicate_always_first(self):
+ preds = build_bulk_close_predicates(
+ tenant_id=_tenant(),
+ alert_ids=None,
+ statuses=None,
+ severities=None,
+ categories=None,
+ connector_types=None,
+ older_than=None,
+ )
+ assert "tenant_id" in _compiled(preds[0])
+
+ def test_bare_filter_restricted_to_open_statuses(self):
+ preds = build_bulk_close_predicates(
+ tenant_id=_tenant(),
+ alert_ids=None,
+ statuses=None,
+ severities=["low"],
+ categories=None,
+ connector_types=None,
+ older_than=None,
+ )
+ rendered = " ".join(_compiled(p) for p in preds)
+ assert "status IN" in rendered
+ # IN-collections render as expando binds, so the open-status
+ # guard is checked on the compiled parameters, not SQL text.
+ from app.services.alert_bulk_close import OPEN_STATUSES
+
+ params = {}
+ for pr in preds:
+ params.update(pr.compile().params)
+ flat = [v for val in params.values() for v in (val if isinstance(val, (list, tuple)) else [val])]
+ assert any(str(v) in OPEN_STATUSES for v in flat)
+
+ def test_explicit_ids_may_reclose_closed_rows(self):
+ preds = build_bulk_close_predicates(
+ tenant_id=_tenant(),
+ alert_ids=[uuid.uuid4()],
+ statuses=None,
+ severities=None,
+ categories=None,
+ connector_types=None,
+ older_than=None,
+ )
+ rendered = " ".join(_compiled(p) for p in preds)
+ assert "status IN" not in rendered
+
+
+class TestSnapshotSqlRendering:
+ def test_snapshot_ddl_has_no_pyformat_binds(self):
+ """asyncpg rejects %(name)s placeholders — live-caught 500.
+
+ The snapshot DDL is compiled with literal_binds; a regression to a
+ psycopg2-style compile would reintroduce % binds into text() and
+ blow up at the driver, invisible to mocked-session tests.
+ """
+ from app.services.alert_bulk_close import _snapshot_select, _snapshot_sql
+
+ preds = build_bulk_close_predicates(
+ tenant_id=_tenant(),
+ alert_ids=None,
+ statuses=["new"],
+ severities=["low", "high"],
+ categories=None,
+ connector_types=["scanner"],
+ older_than=None,
+ )
+ ddl = _snapshot_sql(_snapshot_select(preds), "aisoc_bulk_close_backup.bulk_close_backup_deadbeef")
+ assert "%" not in ddl
+ assert "CREATE TABLE aisoc_bulk_close_backup.bulk_close_backup_deadbeef AS SELECT" in ddl
+ assert "tenant_id" in ddl
+
+
+class TestValidationBeforeWrite:
+ @pytest.mark.asyncio
+ async def test_no_ids_no_filter_refused(self):
+ db = _session()
+ with pytest.raises(ValueError, match="requires alert_ids or at least one filter"):
+ await bulk_close_alerts(db, tenant_id=_tenant(), actor_id=None, close_status="resolved")
+ db.execute.assert_not_awaited()
+ db.commit.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_invalid_close_status_refused(self):
+ db = _session()
+ with pytest.raises(ValueError):
+ await bulk_close_alerts(db, tenant_id=_tenant(), actor_id=None, close_status="new", severities=["low"])
+ db.execute.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_over_match_refused_before_any_write(self):
+ db = _session(matched=900)
+ with pytest.raises(BulkCloseOverMatch) as exc_info:
+ await bulk_close_alerts(
+ db,
+ tenant_id=_tenant(),
+ actor_id=None,
+ close_status="resolved",
+ categories=["vulnerability"],
+ )
+ assert exc_info.value.matched == 900
+ assert exc_info.value.max_count == DEFAULT_MAX_COUNT
+ # only the COUNT ran — no DROP/CREATE/UPDATE
+ assert db.execute.await_count == 1
+ db.commit.assert_not_awaited()
+
+ @pytest.mark.asyncio
+ async def test_empty_refused(self):
+ db = _session(matched=0)
+ with pytest.raises(BulkCloseEmpty):
+ await bulk_close_alerts(db, tenant_id=_tenant(), actor_id=None, close_status="resolved", severities=["low"])
+ assert db.execute.await_count == 1
+
+
+class TestHappyPath:
+ @pytest.mark.asyncio
+ async def test_close_writes_snapshot_then_update_with_tenant_scope(self):
+ tenant = _tenant()
+ db = _session(matched=3, snapshot_rows=3)
+ outcome = await bulk_close_alerts(
+ db,
+ tenant_id=tenant,
+ actor_id=uuid.uuid4(),
+ close_status="false_positive",
+ categories=["vulnerability"],
+ connector_types=["scanner"],
+ older_than=datetime.now(UTC) - timedelta(days=1),
+ max_count=5000,
+ comment="kernel backlog suppression",
+ )
+ assert outcome["closed_count"] == 3
+ assert outcome["close_status"] == "false_positive"
+ assert outcome["backup_table"].startswith("aisoc_bulk_close_backup.bulk_close_backup_")
+
+ statements = []
+ for call in db.execute.await_args_list:
+ arg = call.args[0]
+ statements.append(str(arg) if not isinstance(arg, str) else arg)
+ joined = " | ".join(statements)
+
+ # count → snapshot DDL → update, tenant predicate in each of them
+ assert joined.count("tenant_id") >= 3
+ assert "CREATE TABLE aisoc_bulk_close_backup.bulk_close_backup_" in joined
+ assert "UPDATE alerts" in joined
+ assert "DROP TABLE IF EXISTS aisoc_bulk_close_backup.bulk_close_backup_" in joined
+ db.commit.assert_awaited_once()
+
+ @pytest.mark.asyncio
+ async def test_max_count_clamped_to_hard_ceiling(self):
+ tenant = _tenant()
+ db = _session(matched=MAX_BULK_CLOSE_LIMIT + 100)
+ with pytest.raises(BulkCloseOverMatch) as exc_info:
+ await bulk_close_alerts(
+ db,
+ tenant_id=tenant,
+ actor_id=None,
+ close_status="resolved",
+ severities=["low"],
+ max_count=10**9,
+ )
+ assert exc_info.value.max_count == MAX_BULK_CLOSE_LIMIT
+
+ @pytest.mark.asyncio
+ async def test_ids_path_scopes_update_to_ids_and_tenant(self):
+ tenant = _tenant()
+ ids = [uuid.uuid4(), uuid.uuid4()]
+ db = _session(matched=2, snapshot_rows=2)
+ outcome = await bulk_close_alerts(db, tenant_id=tenant, actor_id=None, close_status="closed", alert_ids=ids)
+ assert outcome["closed_count"] == 2
+ update_stmt = str(db.execute.await_args_list[-1].args[0])
+ assert "UPDATE alerts" in update_stmt
+ assert "id IN" in update_stmt and "tenant_id" in update_stmt
+
+
+def test_safe_log_text_neutralises_log_injection() -> None:
+ """CodeQL py/log-injection: CR/LF/control bytes from user comments must
+ never reach the log stream verbatim."""
+ from app.services.alert_bulk_close import _safe_log_text
+
+ evil = "sweep\r\n2026-10-07 FAKE extra log line\x1b[31mred\x1b\x00end"
+ out = _safe_log_text(evil)
+ assert "\r" not in out and "\n" not in out
+ assert "\x1b" not in out and "\x00" not in out
+ assert out.startswith("sweep")
+ assert _safe_log_text("x" * 500) == "x" * 120
+ assert _safe_log_text(None) == ""
diff --git a/services/connectors/app/connectors/base.py b/services/connectors/app/connectors/base.py
index 5022c1f17..197726b9b 100644
--- a/services/connectors/app/connectors/base.py
+++ b/services/connectors/app/connectors/base.py
@@ -70,6 +70,12 @@ class Capability(str, Enum):
PULL_AUDIT = "pull_audit"
PULL_PCAP = "pull_pcap"
PULL_FILE = "pull_file"
+ #: Pull *vulnerability findings* (per-asset CVE state) rather than the
+ #: alert stream. Connectors declaring it must expose
+ #: ``fetch_vulnerability_findings()``, which the scheduler materialises
+ #: into ``asset_vulnerabilities`` (docs/cve-patch-policy.md): scanner
+ #: findings are inventory rows with patch windows, not console alerts.
+ PULL_VULNERABILITIES = "pull_vulnerabilities"
# QUERY — ad-hoc search across the source's index.
QUERY_LOGS = "query_logs"
diff --git a/services/connectors/app/connectors/wazuh.py b/services/connectors/app/connectors/wazuh.py
index 4a89e27ce..dc01ac632 100644
--- a/services/connectors/app/connectors/wazuh.py
+++ b/services/connectors/app/connectors/wazuh.py
@@ -81,6 +81,41 @@ _SEVERITY_BANDS: tuple[tuple[int, str], ...] = (
)
+#: Rule groups the Wazuh vulnerability-detector stamps on its CVE scan
+#: events. A hit in one of these groups is *inventory state* ("host X runs
+#: a package with CVE-Y"), not an incident. docs/cve-patch-policy.md routes
+#: them to ``asset_vulnerabilities`` with a patch due date instead of the
+#: alert queue — a full re-scan of four agents produced ~3,900 alert rows in
+#: one hour on the live stack, which no analyst can triage and which buried
+#: every real detection that landed in the same window.
+_VULN_RULE_GROUPS: tuple[str, ...] = ("vulnerability-detector", "vulnerability")
+
+
+def is_vulnerability_source(source: dict[str, Any]) -> bool:
+ """True if an indexer ``_source`` document is a vulnerability-detector event.
+
+ Two structural markers, in order of authority:
+
+ * ``rule.groups`` contains the detector group — the canonical stamp the
+ stock ``ossec-github``/vulnerability-detection ruleset puts on every
+ scan event.
+ * ``data.vulnerability`` is an object — the payload shape the detector
+ itself writes, which custom rule packs keep even when they re-home the
+ event under a different rule.
+
+ Deliberately *not* a CVE mention in the description: legitimate
+ exploit-attempt detections cite CVEs in their rule descriptions too, and
+ swallowing one of those would hide a real incident. Fail open toward the
+ alert queue, which is where visible-but-noisy beats invisible.
+ """
+ rule = source.get("rule") or {}
+ groups = rule.get("groups")
+ if isinstance(groups, list) and any(g in _VULN_RULE_GROUPS for g in groups):
+ return True
+ data = source.get("data")
+ return isinstance(data, dict) and isinstance(data.get("vulnerability"), dict)
+
+
def _severity_from_level(level: int | float | str | None) -> str:
"""Map a Wazuh rule level (0-15) to an AiSOC severity tier.
@@ -99,6 +134,29 @@ def _severity_from_level(level: int | float | str | None) -> str:
return "info"
+#: Wazuh detector severity strings → AiSOC tiers. The detector uses the
+#: NVD adjectival ladder ("Low", "Medium", "High", "Critical") plus the
+#: odd vendor variants; anything unrecognised conservatively maps to
+#: ``medium`` so an unknown label still lands above ``info`` in the
+#: inventory without screaming critical.
+_DETECTOR_SEVERITY_MAP: dict[str, str] = {
+ "critical": "critical",
+ "severe": "critical", # Wazuh's own word for the top band
+ "high": "high",
+ "medium": "medium",
+ "moderate": "medium",
+ "low": "low",
+ "negligible": "info",
+ "none": "info",
+ "informational": "info",
+}
+
+
+def _severity_from_detector(severity: str | None) -> str:
+ text = (severity or "").strip().lower()
+ return _DETECTOR_SEVERITY_MAP.get(text, "medium")
+
+
class WazuhConnector(BaseConnector):
"""Wazuh — open-source XDR/SIEM.
@@ -119,6 +177,7 @@ class WazuhConnector(BaseConnector):
# response actions belong in a future kinetic plugin.
return (
Capability.PULL_ALERTS,
+ Capability.PULL_VULNERABILITIES,
Capability.QUERY_LOGS,
Capability.SEARCH_SIEM,
Capability.PIVOT_HOST,
@@ -183,6 +242,25 @@ class WazuhConnector(BaseConnector):
default=True,
help_text=("Disable only for self-signed lab clusters. Production deployments must install the CA chain."),
),
+ Field(
+ "vuln_mode",
+ "select",
+ "Vulnerability Events",
+ required=False,
+ default="inventory",
+ help_text=(
+ "Where vulnerability-detector events go. 'inventory' "
+ "(default) routes them to the asset vulnerability "
+ "inventory with patch-window due dates per "
+ "docs/cve-patch-policy.md; only CVSS>9, KEV, or "
+ "overdue findings raise alerts. 'alerts' keeps the "
+ "legacy behaviour of one alert per scan finding."
+ ),
+ options=[
+ {"value": "inventory", "label": "Inventory + patch windows (recommended)"},
+ {"value": "alerts", "label": "Alert per finding (legacy)"},
+ ],
+ ),
],
)
@@ -194,6 +272,7 @@ class WazuhConnector(BaseConnector):
index_pattern: str = "wazuh-alerts-*",
min_rule_level: int = 7,
verify_tls: bool = True,
+ vuln_mode: str = "inventory",
):
# Strip trailing slash so URL composition is predictable.
self._base_url = indexer_url.rstrip("/")
@@ -205,6 +284,13 @@ class WazuhConnector(BaseConnector):
except (TypeError, ValueError):
self._min_rule_level = 7
self._verify_tls = bool(verify_tls)
+ # "inventory" (default): detector events become asset_vulnerabilities
+ # rows, not alerts. "alerts": legacy behaviour, detector events flow
+ # into the alert stream as they always did. Anything unrecognised
+ # collapses to the legacy mode — the operator asked for it by
+ # setting a value we don't honour, and silently switching an
+ # established pipeline is worse than not switching it.
+ self._vuln_mode = vuln_mode if vuln_mode in ("inventory", "alerts") else "alerts"
# ---- helpers ------------------------------------------------------
@@ -255,8 +341,16 @@ class WazuhConnector(BaseConnector):
Pagination is bounded to 1000 hits per poll because anything
larger means the operator should drop the polling interval, not
chase a single huge batch.
+
+ In ``vuln_mode=inventory`` (the default) vulnerability-detector hits
+ are excluded here and returned by
+ :meth:`fetch_vulnerability_findings` instead. Excluding at the
+ source — not via a downstream filter rule — is deliberate: the
+ scheduler's ``filter_rules`` are tenant-controlled and evaluated
+ after normalization, so dropping here is the only place the two
+ streams provably cannot both claim the same event.
"""
- query = {
+ query: dict[str, Any] = {
"size": 1000,
"sort": [{"@timestamp": {"order": "asc"}}],
"query": {
@@ -275,7 +369,89 @@ class WazuhConnector(BaseConnector):
}
},
}
+ if self._vuln_mode == "inventory":
+ # Annotated at the literal rather than indexed through `object`:
+ # without it mypy infers the nested dict's values as `object`,
+ # which is not indexable, and the chained subscript below is
+ # unchecked.
+ query["query"]["bool"]["must_not"] = [
+ {"terms": {"rule.groups": list(_VULN_RULE_GROUPS)}},
+ ]
+
+ hits = await self._search(query)
+ if self._vuln_mode != "inventory":
+ return [self.normalize(hit) for hit in hits if isinstance(hit, dict)]
+ # belt-and-braces: the must_not above misses custom rule packs that
+ # re-home detector events under a different group, so re-check the
+ # document shape itself before anything reaches the alert stream.
+ return [self.normalize(hit) for hit in hits if isinstance(hit, dict) and not is_vulnerability_source(hit.get("_source") or {})]
+
+ async def fetch_vulnerability_findings(self, since_seconds: int = 3600) -> list[dict[str, Any]]:
+ """Pull recent vulnerability-detector events as inventory findings.
+
+ Called by the scheduler's vulnerability-sync gate (it detects this
+ method's presence), which feeds :func:`app.vulnerabilities.sync_findings`
+ → ``asset_vulnerabilities``. One finding per (CVE, host) as the
+ detector reported it; the sync side keys inventory by
+ ``(tenant, asset, cve, source)`` so repeat scans touch ``last_found``
+ instead of multiplying rows.
+
+ The window is wider than the alert poll (1h vs 5min) and bounded by
+ the same 1000-hit page: the detector's own scan interval is hourly,
+ so a narrow window would drop findings between polls if the
+ connector was down, and re-scans are idempotent anyway.
+
+ In ``vuln_mode=alerts`` this returns nothing: that mode puts
+ detector events in the alert stream (legacy behaviour), and the
+ scheduler gate below would otherwise double-write every finding —
+ once as an alert, once as inventory.
+ """
+ if self._vuln_mode != "inventory":
+ return []
+ query = {
+ "size": 1000,
+ "sort": [{"@timestamp": {"order": "asc"}}],
+ "query": {
+ "bool": {
+ "must": [
+ {
+ "range": {
+ "@timestamp": {
+ "gte": f"now-{max(int(since_seconds), 0)}s",
+ "lte": "now",
+ }
+ }
+ },
+ {"term": {"rule.groups": "vulnerability-detector"}},
+ ]
+ }
+ },
+ }
+
+ hits = await self._search(query)
+ findings: list[dict[str, Any]] = []
+ for hit in hits:
+ if not isinstance(hit, dict):
+ continue
+ finding = self.normalize_vulnerability(hit)
+ if finding is not None:
+ findings.append(finding)
+ logger.info(
+ "wazuh.vulnerability_findings",
+ fetched=len(hits),
+ findings=len(findings),
+ window_seconds=since_seconds,
+ )
+ return findings
+ async def _search(self, query: dict[str, Any]) -> list[dict[str, Any]]:
+ """POST an OpenSearch DSL query at the alert index; return raw hits.
+
+ Shared by both fetch paths so auth, error handling and the
+ never-raise contract live once: a failed search returns ``[]`` and
+ logs, because the scheduler's failure recorder must see a fetch
+ return, not an exception escaping into the poll loop.
+ """
try:
async with httpx.AsyncClient(timeout=30.0, verify=self._verify_tls) as client:
resp = await client.post(
@@ -301,8 +477,55 @@ class WazuhConnector(BaseConnector):
logger.warning("wazuh.search_returned_non_json")
return []
- hits = (payload.get("hits") or {}).get("hits") or []
- return [self.normalize(hit) for hit in hits if isinstance(hit, dict)]
+ return (payload.get("hits") or {}).get("hits") or []
+
+ def normalize_vulnerability(self, hit: dict[str, Any]) -> dict[str, Any] | None:
+ """Project a detector hit into the ``sync_findings`` finding shape.
+
+ Returns ``None`` for events without a CVE or a host — the same two
+ fields ``sync_findings`` would skip on — so they are counted here
+ rather than silently dropped downstream.
+ """
+ source = hit.get("_source") or {}
+ data = source.get("data") or {}
+ vuln = data.get("vulnerability") or {}
+ agent = source.get("agent") or {}
+
+ cve = str(vuln.get("cve") or data.get("cve") or "").strip().upper()
+ hostname = agent.get("name") or agent.get("ip")
+ if not cve.startswith("CVE-") or not hostname:
+ return None
+
+ cvss = vuln.get("cvss") or {}
+ # Wazuh nests v3 under cvss.cvss3 and v2 under cvss.cvss (yes,
+ # literally the key "cvss" inside "cvss"). Prefer v3 base score.
+ cvss3 = cvss.get("cvss3") or {}
+ cvss2 = cvss.get("cvss") or {}
+ score = cvss3.get("base_score")
+ if score is None:
+ score = cvss2.get("base_score")
+ try:
+ score = float(score) if score is not None else None
+ except (TypeError, ValueError):
+ score = None
+
+ return {
+ "cve_id": cve,
+ "hostname": hostname,
+ "ip_address": agent.get("ip"),
+ # The detector's own severity ("Severe", "High", ...) is
+ # free-form; sync_findings re-derives nothing, so collapse the
+ # Wazuh text onto our five tiers conservatively.
+ "severity": _severity_from_detector(vuln.get("severity")),
+ "cvss_score": score,
+ "title": (source.get("rule") or {}).get("description") or cve,
+ "source": "wazuh",
+ "external_id": hit.get("_id"),
+ # KEV: the detector reports what it knowsvia the rule hit —
+ # is_exploited stays False here and is owned by the KEV worker
+ # (retro_hunt/kev_exposure.py), which flips it from the CISA
+ # feed. The connector must not invent exploited status.
+ }
def normalize(self, raw: dict[str, Any]) -> dict[str, Any]:
"""Project a Wazuh indexer hit into the AiSOC canonical alert shape.
diff --git a/services/connectors/app/patch_calendar.py b/services/connectors/app/patch_calendar.py
new file mode 100644
index 000000000..3443e09ca
--- /dev/null
+++ b/services/connectors/app/patch_calendar.py
@@ -0,0 +1,118 @@
+"""The org's patch-window calendar — one source of truth for patch due dates.
+
+Codifies ``docs/cve-patch-policy.md``:
+
+* ``patch_tuesday`` — Microsoft Patch Tuesday, the second Tuesday of the
+ month (the Linux advisory window lands on the same day).
+* TEST environment — due the first Wednesday on-or-after Patch Tuesday.
+* PROD environment — due exactly seven days after the TEST window, so
+ every production patch is observed on test hardware first.
+
+Verified against the calendar the policy doc committed with:
+
+ TEST: Oct 14, Nov 11, Dec 9 (2026) PROD: Oct 21, Nov 18, Dec 16 (2026)
+
+Why a module and not a prompt: the policy is enforced by ingest, inventory
+and the promotion worker. An agent prompt can restate the policy; it cannot
+be what computes ``patch_due_date`` (the policy doc's own enforcement
+table). Hostname classification lives here too so every writer buckets hosts
+identically — and it is conservative on purpose: an unknown host is PROD,
+because a missed urgent patch on a production box is the expensive failure,
+while a patch moved a week earlier costs nothing.
+"""
+
+from __future__ import annotations
+
+import calendar
+from datetime import UTC, date, datetime, timedelta
+
+#: Environment buckets the patch windows are defined for.
+ENV_TEST = "test"
+ENV_PROD = "prod"
+
+#: Hostname tokens that mark a host as TEST. Substring match, lowercase.
+#: Everything else — including names we don't recognise — is PROD.
+_TEST_HOSTNAME_TOKENS: tuple[str, ...] = ("dev", "test", "uat", "staging", "stage", "sandbox", "qa")
+
+
+def patch_tuesday(year: int, month: int) -> date:
+ """The second Tuesday of ``year``-``month`` (Microsoft Patch Tuesday).
+
+ ``calendar.monthcalendar`` weeks start Monday, so Tuesday is column 1.
+ The row containing day 8 is by construction the row containing the
+ second Tuesday — every month has exactly one day 8, and the first week
+ holds at most days 1-7.
+ """
+ for week in calendar.monthcalendar(year, month):
+ day = week[calendar.TUESDAY]
+ if day != 0 and day >= 8:
+ return date(year, month, day)
+ # monthcalendar cannot yield no Tuesday; unreachable but explicit.
+ raise ValueError(f"no Tuesday found in {year}-{month}")
+
+
+def test_patch_due_for(found_on: date) -> date:
+ """The TEST window a finding seen on ``found_on`` is due in.
+
+ The window is the first Wednesday on-or-after that month's Patch
+ Tuesday. A finding discovered *after* the window has passed — e.g.
+ scanned into inventory late — is due in the NEXT month's window; we
+ never mint a due date in the past, because an instantly-overdue finding
+ would fire the promotion worker for findings the operators have simply
+ not been scanned yet. A finding discovered ON Patch Tuesday or ON the
+ window Wednesday itself is due that same Wednesday: the window is open.
+ """
+ tuesday = patch_tuesday(found_on.year, found_on.month)
+ wednesday = tuesday + timedelta(days=1)
+ if wednesday < found_on:
+ # The window already closed; roll to the next month (December ->
+ # January carries the year).
+ if found_on.month == 12:
+ return test_patch_due_for(date(found_on.year + 1, 1, 1))
+ return test_patch_due_for(date(found_on.year, found_on.month + 1, 1))
+ return wednesday
+
+
+def prod_patch_due_for(test_due: date) -> date:
+ """PROD window = TEST window + 7 days."""
+ return test_due + timedelta(days=7)
+
+
+def patch_due_for(found_on: datetime | date, environment: str) -> date:
+ """The patch due date for a finding seen on ``found_on`` in ``environment``.
+
+ Accepts aware or naive datetimes; naive is assumed UTC. The date is
+ computed once, at materialization, from the date the scan first reported
+ the finding, so the clock a patch SLA is measured against never moves
+ (mirrors ``first_found`` never being touched by a re-poll).
+ """
+ if isinstance(found_on, datetime):
+ day = found_on.astimezone(UTC).date() if found_on.tzinfo else found_on.date()
+ else:
+ day = found_on
+ env = (environment or ENV_PROD).strip().lower()
+ test_due = test_patch_due_for(day)
+ return test_due if env == ENV_TEST else prod_patch_due_for(test_due)
+
+
+def classify_environment(hostname: str | None) -> str:
+ """Bucket a hostname into ``test`` or ``prod`` for patch-window purposes.
+
+ Fail closed toward PROD: an unrecognised host gets the production window
+ so a real production box can never inherit the test host's extra slack.
+ """
+ if not hostname:
+ return ENV_PROD
+ lowered = hostname.lower()
+ return ENV_TEST if any(token in lowered for token in _TEST_HOSTNAME_TOKENS) else ENV_PROD
+
+
+__all__ = [
+ "ENV_TEST",
+ "ENV_PROD",
+ "patch_tuesday",
+ "test_patch_due_for",
+ "prod_patch_due_for",
+ "patch_due_for",
+ "classify_environment",
+]
diff --git a/services/connectors/app/scheduler.py b/services/connectors/app/scheduler.py
index f5be5bd5f..89625c91e 100644
--- a/services/connectors/app/scheduler.py
+++ b/services/connectors/app/scheduler.py
@@ -49,6 +49,7 @@ Design rationale
from __future__ import annotations
+import json
import logging
import os
import uuid
@@ -76,6 +77,13 @@ from app.pipeline import (
diff_fingerprints,
)
from app.security.credential_vault import CredentialVault, CredentialVaultError, get_vault
+from app.vuln_promotion_sql import (
+ MARK_OVERDUE_SQL,
+ MARK_PROMOTED_SQL,
+ PROMOTE_CANDIDATES_SQL,
+ RESOLVE_REMEDIATED_SQL,
+ UPSERT_ALERT_SQL,
+)
logger = logging.getLogger("aisoc.connectors.scheduler")
@@ -84,6 +92,12 @@ logger = logging.getLogger("aisoc.connectors.scheduler")
# 60s with N connectors, we issue 1 SELECT/min regardless of N.
_DEFAULT_RELOAD_INTERVAL_S = 60.0
+#: Hours between patch-window promotion sweeps. Six hours means an
+#: overdue-vs-due transition is visible to analysts within half a working
+#: day without hammering the inventory table; the windows themselves are
+#: weekly, so this is generous.
+_PROMOTION_INTERVAL_S = 6 * 3600.0
+
# Default poll cadence per connector instance when ``connector_config``
# doesn't override it. Five minutes is the standard SOC poll interval and
# matches every connector's default ``since_seconds=300`` parameter.
@@ -206,6 +220,19 @@ class ConnectorScheduler:
max_instances=1,
coalesce=True,
)
+ # Patch-window promotion (docs/cve-patch-policy.md rule 5): the ONLY
+ # path from asset_vulnerabilities back into the alert queue. Every
+ # 6h it flips due-tracked rows to overdue and raises one grouped
+ # alert per CVE that is overdue, CVSS>9, KEV, or exploited.
+ self._scheduler.add_job(
+ self._promote_overdue_findings,
+ "interval",
+ seconds=_PROMOTION_INTERVAL_S,
+ id="_vuln_promotion_loop",
+ replace_existing=True,
+ max_instances=1,
+ coalesce=True,
+ )
logger.info(
"connector.scheduler.started reload_interval=%ss",
self._reload_interval_s,
@@ -839,6 +866,107 @@ class ConnectorScheduler:
target.connector_type,
)
+ async def _promote_overdue_findings(self) -> None:
+ """Patch-window promotion sweep (docs/cve-patch-policy.md rule 5).
+
+ The single sanctioned path from ``asset_vulnerabilities`` back into
+ ``alerts``. Per enabled tenant, in one transaction:
+
+ 1. flip ``tracked`` rows past their due date to ``overdue``;
+ 2. auto-resolve promoted alerts whose CVE vanished from the open
+ inventory (patch day done);
+ 3. select the candidate CVEs — overdue, CVSS>9, exploited, or
+ KEV-listed — grouped per CVE with host roll-up;
+ 4. upsert one alert per CVE keyed by ``vuln-promo:<cve>`` so the
+ partial unique index makes re-promotion a touch, not a duplicate
+ (this is the "1 CVE on 4 hosts is 1 alert" rule).
+
+ Never raises: a failed sweep logs and waits for the next tick; a
+ promotion bug must not take the connector poll loop with it.
+ """
+ if self._engine is None:
+ return
+ from sqlalchemy import text
+
+ try:
+ async with self._engine.connect() as conn:
+ tenants = (await conn.execute(text("SELECT DISTINCT tenant_id FROM connectors WHERE is_enabled"))).scalars().all()
+ except Exception: # pragma: no cover
+ logger.exception("connector.scheduler.promotion_tenant_enum_failed")
+ return
+
+ for tenant_id in tenants:
+ try:
+ async with self._engine.begin() as conn:
+ # The connector role reads with current_tenant_id() NULL;
+ # bind it per statement so the RLS policies on
+ # asset_vulnerabilities / alerts apply to this tenant.
+ await conn.execute(
+ text("SELECT set_config('aisoc.tenant_id', :tid, true)"),
+ {"tid": str(tenant_id)},
+ )
+ overdue = (await conn.execute(text(MARK_OVERDUE_SQL), {"tenant_id": tenant_id})).rowcount
+ resolved = (await conn.execute(text(RESOLVE_REMEDIATED_SQL), {"tenant_id": tenant_id})).rowcount
+ candidates = (await conn.execute(text(PROMOTE_CANDIDATES_SQL), {"tenant_id": tenant_id})).fetchall()
+
+ promoted = 0
+ for row in candidates:
+ cve = str(row.cve_id)
+ score = float(row.cvss_score) if row.cvss_score is not None else None
+ sev = "critical" if (score is not None and score >= 9.0) or row.is_exploited else "high"
+ hosts = row.affected_hosts or []
+ why = []
+ if row.patch_due_date is not None:
+ why.append(f"patch window closed {row.patch_due_date}")
+ if score is not None and score > 9:
+ why.append(f"CVSS {score}")
+ if row.is_exploited:
+ why.append("actively exploited")
+ await conn.execute(
+ text(UPSERT_ALERT_SQL),
+ {
+ "tenant_id": tenant_id,
+ "title": f"{cve} overdue / urgent on {row.host_count} host(s)",
+ "description": (
+ f"{cve} is open on {row.host_count} asset(s) and meets the "
+ f"patch-policy exception path: {'; '.join(why) or 'KEV-listed'}. "
+ f"Hosts: {', '.join(str(h) for h in hosts[:20])}"
+ ),
+ "severity": sev,
+ "affected_hosts": json.dumps(hosts),
+ "tags": json.dumps(["patch-window", "vulnerability", cve.lower()]),
+ "idempotency_key": f"vuln-promo:{cve.lower()}",
+ "connector_id": None,
+ "raw_event": json.dumps(
+ {
+ "cve": cve,
+ "cvss_score": score,
+ "is_exploited": bool(row.is_exploited),
+ "patch_due_date": str(row.patch_due_date),
+ "host_count": row.host_count,
+ "affected_hosts": hosts,
+ }
+ ),
+ },
+ )
+ await conn.execute(
+ text(MARK_PROMOTED_SQL),
+ {"tenant_id": tenant_id, "cve_id": cve.lower()},
+ )
+ promoted += 1
+
+ if overdue or promoted or resolved:
+ logger.info(
+ "connector.scheduler.vuln_promotion tenant=%s marked_overdue=%d alerts_promoted=%d alerts_resolved=%d",
+ tenant_id,
+ overdue,
+ promoted,
+ resolved,
+ )
+ except Exception:
+ # One tenant's failure must not stop the others' sweep.
+ logger.exception("connector.scheduler.vuln_promotion_failed tenant=%s", tenant_id)
+
async def _record_failure(self, connector_id: uuid.UUID) -> None:
if self._engine is None: # pragma: no cover
return
diff --git a/services/connectors/app/vuln_promotion_sql.py b/services/connectors/app/vuln_promotion_sql.py
new file mode 100644
index 000000000..f286fb766
--- /dev/null
+++ b/services/connectors/app/vuln_promotion_sql.py
@@ -0,0 +1,136 @@
+# SQL for the patch-window promotion job (docs/cve-patch-policy.md rule 5).
+# Kept module-level (not inline in coroutines) so tests can pin the
+# statements and a reviewer can diff the policy in one place. The inventory
+# insert/touch statements live in app.vulnerabilities (sync_findings owns
+# them); this module only owns the tracked->overdue->promoted->resolved
+# lifecycle and the grouped-alert upsert.
+
+from __future__ import annotations
+
+#: Mark a patch window's tracked findings overdue once their due date has
+#: passed. Only ``tracked`` rows flip — ``promoted`` rows already have an
+#: alert, and rows with ``remediated_at`` set are done. Runs inside the
+#: promotion job's transaction so an alert is never created for a row the
+#: same sweep did not mark overdue.
+MARK_OVERDUE_SQL = """
+ UPDATE asset_vulnerabilities
+ SET patch_status = 'overdue'
+ WHERE tenant_id = CAST(:tenant_id AS uuid)
+ AND remediated_at IS NULL
+ AND patch_status = 'tracked'
+ AND patch_due_date IS NOT NULL
+ AND patch_due_date < (NOW() AT TIME ZONE 'UTC')::date
+"""
+
+#: The promotion candidate set: one row per CVE (the CVE is the unit an
+#: analyst tracks; hosts roll up into ``affected_hosts``) that is
+#: open AND (overdue, CVSS>9, KEV-listed, or actively exploited) —
+#: exactly the policy's rule-5 exception path. ``MAX``/``bool_or``
+#: aggregates pick the worst-case representation; the per-CVE grouping is
+#: why 1 CVE on 4 hosts is one alert instead of four.
+#:
+#: KEV join note: ``threat_intel_iocs`` is live-empty on this stack, so
+#: the EXISTS clause contributes nothing today — it is the seam the 093
+#: KEV seed worker feeds when it lands. ``is_exploited`` is the exploited
+#: signal that works right now.
+PROMOTE_CANDIDATES_SQL = """
+ SELECT v.cve_id,
+ MAX(v.cvss_score) AS cvss_score,
+ bool_or(v.is_exploited) AS is_exploited,
+ MIN(v.patch_due_date) AS patch_due_date,
+ jsonb_agg(DISTINCT a.name ORDER BY a.name) AS affected_hosts,
+ count(DISTINCT v.asset_id) AS host_count
+ FROM asset_vulnerabilities v
+ JOIN assets a
+ ON a.tenant_id = v.tenant_id AND a.id = v.asset_id
+ WHERE v.tenant_id = CAST(:tenant_id AS uuid)
+ AND v.remediated_at IS NULL
+ AND (
+ v.patch_status IN ('overdue', 'promoted')
+ OR (v.cvss_score IS NOT NULL AND v.cvss_score > 9)
+ OR v.is_exploited
+ OR EXISTS (
+ SELECT 1 FROM threat_intel_iocs i
+ WHERE i.tenant_id = v.tenant_id
+ AND i.ioc_type = 'cve'
+ AND lower(i.value) = lower(v.cve_id)
+ AND i.is_active
+ AND i.false_positive = false
+ )
+ )
+ GROUP BY v.cve_id
+"""
+
+#: Close a promoted alert when its CVE is remediated: the alert follows the
+#: CVE's open/closed state, so the patch day clears the queue without an
+#: analyst touching 500 windows (policy §Alert lifecycle). Column names are
+#: the live schema (``resolved_at``/``disposition`` — there is no
+#: ``closed_at``/``resolution`` on ``alerts``).
+RESOLVE_REMEDIATED_SQL = """
+ UPDATE alerts al
+ SET status = 'resolved',
+ resolved_at = NOW(),
+ disposition = 'remediated: all assets patched (patch-window policy)'
+ WHERE al.tenant_id = CAST(:tenant_id AS uuid)
+ AND al.status NOT IN ('resolved', 'closed')
+ AND al.idempotency_key LIKE 'vuln-promo:%'
+ AND NOT EXISTS (
+ SELECT 1 FROM asset_vulnerabilities v
+ WHERE v.tenant_id = al.tenant_id
+ AND v.remediated_at IS NULL
+ AND lower(v.cve_id) = split_part(al.idempotency_key, ':', 2)
+ )
+"""
+
+#: One grouped alert per CVE (upsert). The conflict target is the partial
+#: unique index uq_alerts_tenant_idempotency — the same idempotency
+#: discipline the alert sink uses for scanner alerts, so re-promoting an
+#: already-open CVE touches ``last_seen`` instead of minting a duplicate.
+#: ``ON CONFLICT ... DO UPDATE`` bumps metadata only when something
+#: meaningful changed (more hosts, new exploit status), keeping ``status``
+#: sticky: a promoted alert that an analyst moved to ``investigating`` must
+#: not snap back to ``new`` on the next sweep.
+UPSERT_ALERT_SQL = """
+ INSERT INTO alerts (
+ tenant_id, connector_type, category, title, description,
+ severity, status, event_time, first_seen, last_seen,
+ affected_hosts, tags, ocsf_class_uid, idempotency_key,
+ connector_id, raw_event
+ ) VALUES (
+ CAST(:tenant_id AS uuid), 'inventory', 'vulnerability',
+ :title, :description, :severity, 'new', NOW(), NOW(), NOW(),
+ :affected_hosts::jsonb, :tags::jsonb, 2001, :idempotency_key,
+ :connector_id, :raw_event::jsonb
+ )
+ ON CONFLICT (tenant_id, idempotency_key) WHERE idempotency_key IS NOT NULL
+ DO UPDATE SET
+ last_seen = NOW(),
+ affected_hosts = EXCLUDED.affected_hosts,
+ severity = EXCLUDED.severity,
+ description = EXCLUDED.description,
+ tags = EXCLUDED.tags
+"""
+
+#: After a CVE's alert row exists, mark its contributing rows promoted so
+#: the next sweep does not re-count them as fresh candidates.
+MARK_PROMOTED_SQL = """
+ UPDATE asset_vulnerabilities
+ SET patch_status = 'promoted'
+ WHERE tenant_id = CAST(:tenant_id AS uuid)
+ AND remediated_at IS NULL
+ AND lower(cve_id) = :cve_id
+ AND patch_status IN ('tracked', 'overdue')
+"""
+
+
+#: Public surface: the scheduler and tests import these names. Public (not
+#: underscore) because cross-module use of private names is what made an
+#: automated pass report them "unused globals" — the module is the SQL's
+#: only home, and its consumers are in-repo and explicit.
+__all__ = [
+ "MARK_OVERDUE_SQL",
+ "PROMOTE_CANDIDATES_SQL",
+ "RESOLVE_REMEDIATED_SQL",
+ "UPSERT_ALERT_SQL",
+ "MARK_PROMOTED_SQL",
+]
diff --git a/services/connectors/app/vulnerabilities.py b/services/connectors/app/vulnerabilities.py
index 4f51779ec..c07468da3 100644
--- a/services/connectors/app/vulnerabilities.py
+++ b/services/connectors/app/vulnerabilities.py
@@ -33,6 +33,7 @@ we first see this" is the question an exposure window is asked.
from __future__ import annotations
+import pathlib
import uuid
from datetime import UTC, datetime
from typing import Any
@@ -84,11 +85,14 @@ _INSERT_VULN = text(
"""
INSERT INTO asset_vulnerabilities
(id, tenant_id, asset_id, cve_id, title, description, severity,
- is_exploited, source, external_id, first_found, last_found,
- metadata, created_at)
+ cvss_score, is_exploited, source, external_id, first_found,
+ last_found, metadata, created_at,
+ environment, patch_due_date, patch_status)
VALUES (:id, CAST(:tenant_id AS uuid), CAST(:asset_id AS uuid), :cve_id,
- :title, :description, :severity, false, :source, :external_id,
- :now, :now, CAST(:metadata AS jsonb), :now)
+ :title, :description, :severity,
+ :cvss_score, false, :source, :external_id,
+ :now, :now, CAST(:metadata AS jsonb), :now,
+ :environment, :patch_due_date, 'tracked')
"""
)
@@ -202,6 +206,41 @@ async def sync_findings(
await conn.execute(_TOUCH_VULN, {**params, "id": str(existing[0]), "tenant_id": tenant})
touched += 1
else:
+ # Patch-window policy (docs/cve-patch-policy.md): the due
+ # date is minted here, once, from the moment the finding
+ # first enters inventory — never recomputed by a re-poll
+ # (the touch path deliberately omits it). Environment comes
+ # from the hostname classifier; unknown hosts are PROD.
+ try:
+ from app.patch_calendar import classify_environment, patch_due_for
+ except ModuleNotFoundError: # pragma: no cover - import-shape only
+ # The isolation harness loads this module by path under a
+ # private name (both services package as ), so the
+ # sibling package is not on sys.modules here. Load the
+ # calendar off disk the same way the harness does.
+ import importlib.util
+ import sys
+
+ _pc = pathlib.Path(__file__).with_name("patch_calendar.py")
+ _spec = importlib.util.spec_from_file_location("aisoc_patch_calendar", _pc)
+ # `spec_from_file_location` returns None when the path is
+ # not importable, and a spec can carry no loader. Both are
+ # unreachable for a file this package ships, but a bare
+ # `exec_module` on either would raise AttributeError
+ # several frames from the cause — so say what went wrong.
+ if _spec is None or _spec.loader is None:
+ # `from None`: this is a fresh condition, not a
+ # re-raise of the ImportError that put us in this
+ # branch, and chaining the two would suggest the
+ # import error caused it.
+ raise RuntimeError(f"patch calendar is not importable from {_pc}") from None
+ _mod = importlib.util.module_from_spec(_spec)
+ sys.modules[_spec.name] = _mod
+ _spec.loader.exec_module(_mod)
+ classify_environment = _mod.classify_environment
+ patch_due_for = _mod.patch_due_for
+
+ environment = classify_environment(hostname)
await conn.execute(
_INSERT_VULN,
{
@@ -211,9 +250,12 @@ async def sync_findings(
"asset_id": str(asset_id),
"cve_id": cve,
"description": finding.get("title"),
+ "cvss_score": finding.get("cvss_score"),
"source": source,
- "external_id": str(finding.get("plugin_id") or "") or None,
+ "external_id": str(finding.get("plugin_id") or finding.get("external_id") or "") or None,
"metadata": json.dumps({"plugin_id": finding.get("plugin_id")}),
+ "environment": environment,
+ "patch_due_date": patch_due_for(stamp, environment),
},
)
inserted += 1
diff --git a/services/connectors/tests/test_vuln_patch_windows.py b/services/connectors/tests/test_vuln_patch_windows.py
new file mode 100644
index 000000000..4f2730d18
--- /dev/null
+++ b/services/connectors/tests/test_vuln_patch_windows.py
@@ -0,0 +1,231 @@
+"""PR2: vulnerability findings are inventory with patch windows, not alerts.
+
+Covers docs/cve-patch-policy.md end to end at the unit level:
+
+* the calendar math (Patch Tuesday -> TEST Wednesday -> PROD +7d),
+* the Wazuh stream split (detector events leave ``fetch_alerts`` and arrive
+ on ``fetch_vulnerability_findings``),
+* the inventory write (due date minted once, fail-closed environment),
+* the promotion contract (one grouped alert per CVE, exception-path only).
+
+HTTP routing uses ``respx`` exactly like ``test_wazuh_connector.py``.
+"""
+
+from __future__ import annotations
+
+from datetime import UTC, date, datetime
+
+import httpx
+import pytest
+import respx
+from app.connectors.base import Capability
+from app.connectors.wazuh import WazuhConnector, is_vulnerability_source
+from app.patch_calendar import (
+ classify_environment,
+ patch_due_for,
+ patch_tuesday,
+)
+from app.patch_calendar import prod_patch_due_for as _prod_patch_due_for
+from app.patch_calendar import test_patch_due_for as _test_patch_due_for
+
+INDEXER = "https://wazuh.test.local:9200"
+USERNAME = "admin"
+PASSWORD = "wazuh-fake-password"
+
+
+def _detector_hit(cve: str = "CVE-2024-0001", host: str = "prod-tmc-01", cvss=9.8) -> dict:
+ return {
+ "_id": "doc-vuln",
+ "_index": "wazuh-alerts-4.x-2026.10.06",
+ "_source": {
+ "@timestamp": "2026-10-06T06:00:00.000Z",
+ "agent": {"id": "002", "name": host, "ip": "10.0.0.5"},
+ "rule": {
+ "id": "20570",
+ "level": 7,
+ "description": f"{cve} affects linux-aws on {host}",
+ "groups": ["vulnerability-detector", "vulnerability"],
+ },
+ "data": {
+ "vulnerability": {
+ "cve": cve,
+ "severity": "Critical",
+ "cvss": {"cvss3": {"base_score": cvss}},
+ }
+ },
+ },
+ }
+
+
+def _real_alert_hit() -> dict:
+ return {
+ "_id": "doc-alert",
+ "_index": "wazuh-alerts-4.x-2026.10.06",
+ "_source": {
+ "@timestamp": "2026-10-06T06:05:00.000Z",
+ "agent": {"id": "002", "name": "prod-tmc-01", "ip": "10.0.0.5"},
+ "rule": {
+ "id": "100100",
+ "level": 12,
+ "description": "Possible rootkit installation",
+ "groups": ["rootcheck", "intrusion_attempt"],
+ },
+ "data": {"command": "modprobe evil"},
+ },
+ }
+
+
+def _hits_response(hits: list[dict]):
+ return httpx.Response(200, json={"hits": {"hits": hits}})
+
+
+class TestTheCalendar:
+ """The policy doc's concrete dates are the contract."""
+
+ def test_patch_tuesdays_2026(self):
+ assert patch_tuesday(2026, 10) == date(2026, 10, 13)
+ assert patch_tuesday(2026, 11) == date(2026, 11, 10)
+ assert patch_tuesday(2026, 12) == date(2026, 12, 8)
+
+ def test_windows_match_the_policy_doc(self):
+ # TEST: Oct 14, Nov 11, Dec 9 — PROD one week later.
+ assert _test_patch_due_for(date(2026, 10, 1)) == date(2026, 10, 14)
+ assert _test_patch_due_for(date(2026, 11, 1)) == date(2026, 11, 11)
+ assert _test_patch_due_for(date(2026, 12, 1)) == date(2026, 12, 9)
+ assert _prod_patch_due_for(date(2026, 10, 14)) == date(2026, 10, 21)
+ assert _prod_patch_due_for(date(2026, 11, 11)) == date(2026, 11, 18)
+ assert _prod_patch_due_for(date(2026, 12, 9)) == date(2026, 12, 16)
+
+ def test_a_window_never_opens_in_the_past(self):
+ # Found after October's window closed -> due in November's window.
+ assert _test_patch_due_for(date(2026, 10, 20)) == date(2026, 11, 11)
+ # December rolls the year.
+ assert _test_patch_due_for(date(2026, 12, 20)) == date(2027, 1, 13)
+
+ def test_environment_classification_fails_closed(self):
+ assert classify_environment("dev-tmc-01") == "test"
+ assert classify_environment("UAT-app-2") == "test"
+ assert classify_environment("cbs-euw1-tmc-01") == "prod"
+ assert classify_environment("mgi-tmc-02") == "prod"
+ assert classify_environment(None) == "prod"
+
+ def test_due_date_dispatches_by_environment(self):
+ found = datetime(2026, 10, 6, 12, 0, tzinfo=UTC)
+ assert patch_due_for(found, "test") == date(2026, 10, 14)
+ assert patch_due_for(found, "prod") == date(2026, 10, 21)
+ # unknown environment string behaves like prod (fail closed)
+ assert patch_due_for(found, "garbage") == date(2026, 10, 21)
+
+
+class TestTheStreamSplit:
+ def test_wazuh_declares_the_vulnerability_capability(self):
+ assert Capability.PULL_VULNERABILITIES in WazuhConnector.capabilities()
+
+ def test_schema_offers_the_mode_knob(self):
+ schema = WazuhConnector.schema()
+ field = next((f for f in schema.fields if f.name == "vuln_mode"), None)
+ assert field is not None, "operators have no way to see or set the mode"
+ assert field.default == "inventory"
+
+ def test_detector_events_are_recognised(self):
+ assert is_vulnerability_source(_detector_hit()["_source"])
+ assert not is_vulnerability_source(_real_alert_hit()["_source"])
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_detector_events_leave_the_alert_stream(self):
+ route = respx.post(f"{INDEXER}/wazuh-alerts-*/_search").mock(return_value=_hits_response([_detector_hit(), _real_alert_hit()]))
+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)
+ events = await connector.fetch_alerts(since_seconds=300)
+
+ assert route.called
+ # The syscheck alert survives; the detector event does not.
+ assert len(events) == 1
+ assert events[0]["title"] == "Possible rootkit installation"
+ # and the query itself asked the indexer to exclude the group, so
+ # the 1000-hit page cap can't smuggle scan noise back in.
+ body = route.calls.last.request.content.decode()
+ assert "vulnerability-detector" in body
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_legacy_mode_keeps_the_old_behaviour(self):
+ route = respx.post(f"{INDEXER}/wazuh-alerts-*/_search").mock(return_value=_hits_response([_detector_hit(), _real_alert_hit()]))
+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD, vuln_mode="alerts")
+ events = await connector.fetch_alerts(since_seconds=300)
+
+ assert len(events) == 2
+ # ...and the findings path stays empty so nothing double-writes.
+ assert await connector.fetch_vulnerability_findings() == []
+ # the legacy query has no must_not — that's the point of the mode.
+ body = route.calls[0].request.content.decode()
+ assert "must_not" not in body
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_findings_fetch_names_cve_host_and_cvss(self):
+ route = respx.post(f"{INDEXER}/wazuh-alerts-*/_search").mock(
+ return_value=_hits_response([_detector_hit(cve="CVE-2021-44228", host="dev-tmc-01")])
+ )
+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)
+ findings = await connector.fetch_vulnerability_findings()
+
+ assert route.called
+ assert len(findings) == 1
+ f = findings[0]
+ assert f["cve_id"] == "CVE-2021-44228"
+ assert f["hostname"] == "dev-tmc-01"
+ assert f["cvss_score"] == pytest.approx(9.8)
+ assert f["severity"] == "critical"
+ assert f["source"] == "wazuh"
+
+ @pytest.mark.asyncio
+ @respx.mock
+ async def test_anonymous_events_are_skipped_not_guessed(self):
+ hit = _detector_hit()
+ del hit["_source"]["data"]["vulnerability"]["cve"]
+ hit["_source"]["agent"] = {}
+ respx.post(f"{INDEXER}/wazuh-alerts-*/_search").mock(return_value=_hits_response([hit]))
+ connector = WazuhConnector(INDEXER, USERNAME, PASSWORD)
+
+ assert await connector.fetch_vulnerability_findings() == []
+
+
+class TestThePromotionContract:
+ def test_sql_is_fail_closed_and_scoped(self):
+ from app.vuln_promotion_sql import (
+ MARK_OVERDUE_SQL,
+ PROMOTE_CANDIDATES_SQL,
+ UPSERT_ALERT_SQL,
+ )
+
+ for sql in (MARK_OVERDUE_SQL, PROMOTE_CANDIDATES_SQL, UPSERT_ALERT_SQL):
+ assert "tenant_id" in sql, "every statement is tenant-scoped"
+ # The exception path is spelled in the candidate query, not in a
+ # prompt: overdue OR CVSS>9 OR exploited OR KEV.
+ assert "patch_status IN ('overdue', 'promoted')" in PROMOTE_CANDIDATES_SQL
+ assert "cvss_score > 9" in PROMOTE_CANDIDATES_SQL
+ assert "is_exploited" in PROMOTE_CANDIDATES_SQL
+ assert "threat_intel_iocs" in PROMOTE_CANDIDATES_SQL
+ # one grouped alert per CVE via the idempotency key
+ assert "ON CONFLICT (tenant_id, idempotency_key)" in UPSERT_ALERT_SQL
+ assert "GROUP BY v.cve_id" in PROMOTE_CANDIDATES_SQL
+
+ def test_scheduler_registers_the_promotion_job(self):
+ import inspect
+
+ from app.scheduler import ConnectorScheduler
+
+ src = inspect.getsource(ConnectorScheduler)
+ assert "_vuln_promotion_loop" in src
+ assert "_promote_overdue_findings" in src
+
+ def test_inventory_insert_mints_the_window_once(self):
+ from app.vulnerabilities import _INSERT_VULN, _TOUCH_VULN
+
+ ins = str(_INSERT_VULN)
+ assert "patch_due_date" in ins and "environment" in ins and "patch_status" in ins
+ touch = str(_TOUCH_VULN)
+ # A re-poll must never move the promised date or un-overdue a row.
+ assert "patch_due_date" not in touch
+ assert "patch_status" not in touch