From c0155f9b14875ca387512fe889f0f777af71b569 Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 01:56:35 +0100 Subject: [PATCH 1/8] feat(lifecycle): implement finding lifecycle tracking (#311) Add six new tables (Alembic migration e1f2a3b4c5d6), two service classes, a patterns API route, and engine outcome recording. Tables added: - scan_rule_outcomes: per-rule status per scan - scan_lifecycle_applications: idempotency sentinel - finding_fingerprints: stable immutable SHA-256 identity per finding - finding_lifecycles: mutable OPEN/RESOLVED/ACCEPTED/SUPPRESSED/REOPENED state - finding_lifecycle_transitions: append-only audit trail - patterns: published persistent_finding / cross_resource_recurrence / reopened_finding detections Services: - LifecycleService.apply_scan(): idempotent, fail-closed, single transaction with FOR UPDATE row locking - PatternService.detect_and_publish(): three pattern types with hardcoded thresholds stored in the record Routes: - GET /api/v1/patterns (list with subscription_id / pattern_type / limit) - GET /api/v1/patterns/ (single pattern or 404) Engine: - ScanEngine.run_scan() now records per-rule outcome status (SUCCESS / EMPTY_SUCCESS / PERMISSION_DENIED / TIMEOUT / FAILED) Tests: - tests/test_finding_lifecycle.py: 18 cases (mocked DB, no live Postgres) - tests/test_patterns.py: 9 cases (service unit + Flask route tests) Signed-off-by: Tanvir Farhad --- .../e1f2a3b4c5d6_finding_lifecycle.py | 152 ++++++++ api/app.py | 2 + api/routes/patterns.py | 180 +++++++++ api/services/lifecycle_service.py | 306 +++++++++++++++ api/services/pattern_service.py | 170 ++++++++ scanner/engine.py | 79 +++- tests/test_finding_lifecycle.py | 363 ++++++++++++++++++ tests/test_patterns.py | 330 ++++++++++++++++ 8 files changed, 1562 insertions(+), 20 deletions(-) create mode 100644 alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py create mode 100644 api/routes/patterns.py create mode 100644 api/services/lifecycle_service.py create mode 100644 api/services/pattern_service.py create mode 100644 tests/test_finding_lifecycle.py create mode 100644 tests/test_patterns.py diff --git a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py new file mode 100644 index 00000000..1b1ccfa4 --- /dev/null +++ b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py @@ -0,0 +1,152 @@ +"""Add finding lifecycle tables: scan_rule_outcomes, scan_lifecycle_applications, +finding_fingerprints, finding_lifecycles, finding_lifecycle_transitions, patterns. + +Revision ID: e1f2a3b4c5d6 +Revises: d8e4f6a1b2c3 +Create Date: 2026-08-30 00:00:00.000000 +""" + +from typing import Sequence, Union + +from alembic import op +import sqlalchemy as sa + +# Revision identifiers, used by Alembic. +revision: str = "e1f2a3b4c5d6" +down_revision: Union[str, Sequence[str], None] = "d8e4f6a1b2c3" +branch_labels: Union[str, Sequence[str], None] = None +depends_on: Union[str, Sequence[str], None] = None + + +def upgrade() -> None: + op.execute( + """ + CREATE TABLE scan_rule_outcomes ( + id BIGSERIAL PRIMARY KEY, + scan_id UUID NOT NULL REFERENCES scans(scan_id), + rule_id TEXT NOT NULL, + rule_version TEXT NOT NULL DEFAULT '1', + status TEXT NOT NULL, + error_category TEXT, + collector_version TEXT NOT NULL DEFAULT '1', + inventory_boundary TEXT NOT NULL, + tenant_id TEXT NOT NULL, + subscription_id TEXT NOT NULL, + started_at TIMESTAMPTZ, + completed_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT ck_scan_rule_outcomes_status + CHECK (status IN ( + 'SUCCESS','EMPTY_SUCCESS','PERMISSION_DENIED', + 'TIMEOUT','FAILED','NOT_APPLICABLE' + )), + CONSTRAINT uq_scan_rule_outcomes_scan_rule + UNIQUE (scan_id, rule_id) + ) + """ + ) + + op.execute( + """ + CREATE TABLE scan_lifecycle_applications ( + scan_id UUID PRIMARY KEY REFERENCES scans(scan_id), + applied_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + applied_by TEXT NOT NULL DEFAULT 'system' + ) + """ + ) + + op.execute( + """ + CREATE TABLE finding_fingerprints ( + id BIGSERIAL PRIMARY KEY, + tenant_id TEXT NOT NULL, + subscription_id TEXT NOT NULL, + resource_id_normalized TEXT NOT NULL, + rule_id TEXT NOT NULL, + evidence_key TEXT NOT NULL DEFAULT '', + normalization_version TEXT NOT NULL DEFAULT '1', + fingerprint_version TEXT NOT NULL DEFAULT '1', + fingerprint_hash TEXT NOT NULL, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT uq_finding_fingerprints_hash UNIQUE (fingerprint_hash), + CONSTRAINT uq_finding_fingerprints_identity + UNIQUE ( + tenant_id, + subscription_id, + resource_id_normalized, + rule_id, + evidence_key, + normalization_version + ) + ) + """ + ) + + op.execute( + """ + CREATE TABLE finding_lifecycles ( + id BIGSERIAL PRIMARY KEY, + fingerprint_id BIGINT NOT NULL REFERENCES finding_fingerprints(id), + state TEXT NOT NULL, + first_seen_scan_id UUID, + last_seen_scan_id UUID, + occurrence_count INTEGER NOT NULL DEFAULT 1, + consecutive_success_count INTEGER NOT NULL DEFAULT 0, + reopen_count INTEGER NOT NULL DEFAULT 0, + row_version INTEGER NOT NULL DEFAULT 0, + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT ck_finding_lifecycles_state + CHECK (state IN ('OPEN','RESOLVED','ACCEPTED','SUPPRESSED','REOPENED')), + CONSTRAINT uq_finding_lifecycles_fingerprint + UNIQUE (fingerprint_id) + ) + """ + ) + + op.execute( + """ + CREATE TABLE finding_lifecycle_transitions ( + id BIGSERIAL PRIMARY KEY, + lifecycle_id BIGINT NOT NULL REFERENCES finding_lifecycles(id), + from_state TEXT, + to_state TEXT NOT NULL, + scan_id UUID, + reason TEXT NOT NULL DEFAULT '', + transitioned_at TIMESTAMPTZ NOT NULL DEFAULT NOW() + ) + """ + ) + + op.execute( + """ + CREATE TABLE patterns ( + id BIGSERIAL PRIMARY KEY, + pattern_type TEXT NOT NULL, + lifecycle_id BIGINT REFERENCES finding_lifecycles(id), + tenant_id TEXT NOT NULL, + subscription_id TEXT NOT NULL, + scan_id UUID, + finding_ids JSONB NOT NULL DEFAULT '[]', + threshold INTEGER NOT NULL, + algorithm_version TEXT NOT NULL DEFAULT '1', + created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), + CONSTRAINT ck_patterns_type + CHECK (pattern_type IN ( + 'persistent_finding', + 'cross_resource_recurrence', + 'reopened_finding' + )) + ) + """ + ) + + +def downgrade() -> None: + op.execute("DROP TABLE IF EXISTS patterns") + op.execute("DROP TABLE IF EXISTS finding_lifecycle_transitions") + op.execute("DROP TABLE IF EXISTS finding_lifecycles") + op.execute("DROP TABLE IF EXISTS finding_fingerprints") + op.execute("DROP TABLE IF EXISTS scan_lifecycle_applications") + op.execute("DROP TABLE IF EXISTS scan_rule_outcomes") diff --git a/api/app.py b/api/app.py index a22314fa..a21f94c3 100644 --- a/api/app.py +++ b/api/app.py @@ -237,6 +237,7 @@ def verify_jwt() -> None: from api.routes.compliance import compliance_bp from api.routes.drift import drift_bp from api.routes.findings import findings_bp + from api.routes.patterns import patterns_bp from api.routes.prioritization import prioritization_bp from api.routes.resources import resources_bp from api.routes.scans import scans_bp @@ -248,6 +249,7 @@ def verify_jwt() -> None: app.register_blueprint(compliance_bp) app.register_blueprint(drift_bp) app.register_blueprint(findings_bp) + app.register_blueprint(patterns_bp) app.register_blueprint(prioritization_bp) app.register_blueprint(resources_bp) app.register_blueprint(scans_bp) diff --git a/api/routes/patterns.py b/api/routes/patterns.py new file mode 100644 index 00000000..a03d8d4e --- /dev/null +++ b/api/routes/patterns.py @@ -0,0 +1,180 @@ +"""Patterns routes: list and retrieve published security patterns.""" + +import logging +import os + +import psycopg2.extras +from flask import Blueprint, g, jsonify, request + +from api.models.finding import DatabaseManager + +patterns_bp = Blueprint("patterns", __name__) +logger = logging.getLogger(__name__) + +_ALLOWED_PATTERN_TYPES = frozenset( + {"persistent_finding", "cross_resource_recurrence", "reopened_finding"} +) +_DEFAULT_LIMIT = 20 +_MAX_LIMIT = 100 +_MIN_LIMIT = 1 + +_VALIDATION_ERROR_MESSAGE = "Invalid request parameters" + + +class _ValidationError(ValueError): + """Raised when a client-controlled value violates the public API contract.""" + + +def _get_db() -> DatabaseManager: + if "db" not in g: + g.db = DatabaseManager(os.environ["DATABASE_URL"]) + g.db.connect() + return g.db + + +def _validate_limit(raw: str) -> int: + try: + value = int(raw) + except (ValueError, TypeError) as exc: + raise _ValidationError("limit must be an integer") from exc + if value < _MIN_LIMIT or value > _MAX_LIMIT: + raise _ValidationError(f"limit must be between {_MIN_LIMIT} and {_MAX_LIMIT}") + return value + + +def _row_to_dict(row: dict) -> dict: + """Serialise a patterns table row to a JSON-safe dict.""" + result = dict(row) + for key in ("created_at", "updated_at"): + val = result.get(key) + if val is not None and hasattr(val, "isoformat"): + result[key] = val.isoformat() + if result.get("scan_id") is not None: + result["scan_id"] = str(result["scan_id"]) + return result + + +@patterns_bp.get("/api/v1/patterns") +def list_patterns(): + """Return published security patterns, optionally filtered. + + Query parameters: + subscription_id - filter by Azure subscription + pattern_type - one of persistent_finding, cross_resource_recurrence, + reopened_finding + limit - 1-100, default 20 + """ + try: + allowed_params = {"subscription_id", "pattern_type", "limit"} + unknown = set(request.args) - allowed_params + if unknown: + raise _ValidationError(f"Unsupported query parameter: {sorted(unknown)[0]}") + for key in request.args: + if len(request.args.getlist(key)) != 1: + raise _ValidationError(f"Query parameter {key} must be provided once") + + subscription_id = None + if "subscription_id" in request.args: + val = request.args["subscription_id"].strip() + if not val or len(val) > 256: + raise _ValidationError("subscription_id is invalid") + subscription_id = val + + pattern_type = None + if "pattern_type" in request.args: + raw_pt = request.args["pattern_type"].strip() + if raw_pt not in _ALLOWED_PATTERN_TYPES: + raise _ValidationError("Unsupported pattern_type") + pattern_type = raw_pt + + limit = _DEFAULT_LIMIT + if "limit" in request.args: + limit = _validate_limit(request.args["limit"]) + + db = _get_db() + conn = db._get_conn() + + # Tenant isolation: prefer subscription_id embedded in the JWT payload; + # fall back to the query parameter. + user = getattr(g, "user", {}) or {} + effective_sub = user.get("subscription_id") or subscription_id + + with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: + cur.execute( + """ + SELECT id, pattern_type, lifecycle_id, tenant_id, + subscription_id, scan_id, finding_ids, threshold, + algorithm_version, created_at, updated_at + FROM patterns + WHERE (%s IS NULL OR subscription_id = %s) + AND (%s IS NULL OR pattern_type = %s) + ORDER BY created_at DESC + LIMIT %s + """, + ( + effective_sub, effective_sub, + pattern_type, pattern_type, + limit, + ), + ) + rows = cur.fetchall() + + cur.execute( + """ + SELECT COUNT(*) AS count + FROM patterns + WHERE (%s IS NULL OR subscription_id = %s) + AND (%s IS NULL OR pattern_type = %s) + """, + (effective_sub, effective_sub, pattern_type, pattern_type), + ) + total_row = cur.fetchone() + total = total_row["count"] if total_row else 0 + + return jsonify( + { + "patterns": [_row_to_dict(r) for r in rows], + "total": total, + } + ) + + except _ValidationError: + return jsonify({"error": _VALIDATION_ERROR_MESSAGE}), 400 + except Exception as exc: + logger.error("Failed to list patterns: %s", exc) + return jsonify({"error": "Failed to retrieve patterns"}), 500 + + +@patterns_bp.get("/api/v1/patterns/") +def get_pattern(pattern_id: int): + """Return a single pattern by its integer ID.""" + try: + if pattern_id <= 0: + raise _ValidationError("pattern_id must be a positive integer") + + db = _get_db() + conn = db._get_conn() + + with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: + cur.execute( + """ + SELECT id, pattern_type, lifecycle_id, tenant_id, + subscription_id, scan_id, finding_ids, threshold, + algorithm_version, created_at, updated_at + FROM patterns + WHERE id = %s + """, + (pattern_id,), + ) + row = cur.fetchone() + + if row is None: + return jsonify({"error": "Pattern not found"}), 404 + + return jsonify(_row_to_dict(row)) + + except _ValidationError: + return jsonify({"error": _VALIDATION_ERROR_MESSAGE}), 400 + except Exception as exc: + logger.error("Failed to get pattern %s: %s", pattern_id, exc) + return jsonify({"error": "Failed to retrieve pattern"}), 500 diff --git a/api/services/lifecycle_service.py b/api/services/lifecycle_service.py new file mode 100644 index 00000000..9aff5e92 --- /dev/null +++ b/api/services/lifecycle_service.py @@ -0,0 +1,306 @@ +"""LifecycleService: applies scan outcomes to finding lifecycle state machines.""" + +import hashlib +import json +import logging +from typing import Any, Dict, List, Optional + +import psycopg2.extras + +logger = logging.getLogger(__name__) + +# Statuses that mean "we actively confirmed this rule was clean in the scan." +_RESOLVING_STATUSES = frozenset({"SUCCESS", "EMPTY_SUCCESS"}) + +# Statuses that mean "we could not reliably evaluate the rule." +# Fail-closed: do NOT resolve findings when the scan could not see the resource. +_BLOCKING_STATUSES = frozenset({"PERMISSION_DENIED", "TIMEOUT", "FAILED"}) + + +def _normalize_resource_id(resource_id: str) -> str: + """Return a stable, lowercased, stripped version of an ARM resource ID.""" + return resource_id.strip().lower() + + +def _compute_fingerprint_hash( + tenant_id: str, + subscription_id: str, + resource_id_normalized: str, + rule_id: str, + evidence_key: str, + normalization_version: str, +) -> str: + """Return a SHA-256 hex digest over canonical fields.""" + canonical = json.dumps( + [ + tenant_id, + subscription_id, + resource_id_normalized, + rule_id, + evidence_key, + normalization_version, + ], + separators=(",", ":"), + sort_keys=False, + ) + return hashlib.sha256(canonical.encode()).hexdigest() + + +class LifecycleService: + """Applies scan results to the finding lifecycle state machines. + + All database work for a single apply_scan call executes inside one + transaction. The idempotency sentinel (scan_lifecycle_applications) is + inserted last, so a crash before commit means the operation never happened + and can safely be retried. + """ + + def apply_scan( + self, + db_conn: Any, + scan_id: str, + subscription_id: str, + tenant_id: str, + rule_outcomes: List[Dict[str, Any]], + findings: Optional[List[Dict[str, Any]]] = None, + ) -> None: + """Apply a completed scan's findings to the lifecycle tables. + + Args: + db_conn: A psycopg2 connection (autocommit must be False). + scan_id: UUID of the completed scan. + subscription_id: Azure subscription ID. + tenant_id: Tenant identifier for isolation. + rule_outcomes: List of dicts with at minimum keys 'rule_id' and + 'status' (one of the six allowed status values). + findings: List of finding dicts from the scan, each with keys + 'rule_id', 'resource_id', and optionally 'evidence_key'. + Defaults to an empty list when omitted. + """ + findings = findings or [] + + with db_conn.cursor() as cur: + # --- Idempotency check ---------------------------------------- + cur.execute( + "SELECT scan_id FROM scan_lifecycle_applications WHERE scan_id = %s", + (scan_id,), + ) + if cur.fetchone() is not None: + logger.info("Scan %s already applied; skipping lifecycle update", scan_id) + return + + # Build a lookup: rule_id -> outcome status + outcome_by_rule: Dict[str, str] = { + o["rule_id"]: o["status"] for o in rule_outcomes if "rule_id" in o and "status" in o + } + + # Build the set of (rule_id, resource_id_normalized) pairs seen in + # this scan. A fingerprint in this set was actively observed. + seen_fingerprint_keys: set = set() + fingerprints_in_scan: List[Dict[str, Any]] = [] + for finding in findings: + rule_id = finding.get("rule_id", "") + resource_id = finding.get("resource_id", "") + evidence_key = finding.get("evidence_key", "") + resource_id_normalized = _normalize_resource_id(resource_id) + normalization_version = "1" + + fp_hash = _compute_fingerprint_hash( + tenant_id, + subscription_id, + resource_id_normalized, + rule_id, + evidence_key, + normalization_version, + ) + key = (rule_id, resource_id_normalized, evidence_key) + if key not in seen_fingerprint_keys: + seen_fingerprint_keys.add(key) + fingerprints_in_scan.append( + { + "tenant_id": tenant_id, + "subscription_id": subscription_id, + "resource_id_normalized": resource_id_normalized, + "rule_id": rule_id, + "evidence_key": evidence_key, + "normalization_version": normalization_version, + "fingerprint_hash": fp_hash, + } + ) + + # --- Upsert fingerprints and lifecycles for seen findings ------- + seen_fingerprint_ids: set = set() + for fp in fingerprints_in_scan: + cur.execute( + """ + INSERT INTO finding_fingerprints ( + tenant_id, subscription_id, resource_id_normalized, + rule_id, evidence_key, normalization_version, + fingerprint_version, fingerprint_hash + ) + VALUES (%s, %s, %s, %s, %s, %s, '1', %s) + ON CONFLICT (fingerprint_hash) DO UPDATE + SET fingerprint_hash = EXCLUDED.fingerprint_hash + RETURNING id + """, + ( + fp["tenant_id"], + fp["subscription_id"], + fp["resource_id_normalized"], + fp["rule_id"], + fp["evidence_key"], + fp["normalization_version"], + fp["fingerprint_hash"], + ), + ) + row = cur.fetchone() + fingerprint_id = row[0] + seen_fingerprint_ids.add(fingerprint_id) + + # Lock the lifecycle row if it exists, then decide what to do. + cur.execute( + """ + SELECT id, state, occurrence_count, reopen_count, row_version + FROM finding_lifecycles + WHERE fingerprint_id = %s + FOR UPDATE + """, + (fingerprint_id,), + ) + lc_row = cur.fetchone() + + if lc_row is None: + # New finding: create lifecycle in OPEN state. + cur.execute( + """ + INSERT INTO finding_lifecycles ( + fingerprint_id, state, first_seen_scan_id, + last_seen_scan_id, occurrence_count, + consecutive_success_count, reopen_count, row_version + ) + VALUES (%s, 'OPEN', %s, %s, 1, 0, 0, 0) + RETURNING id + """, + (fingerprint_id, scan_id, scan_id), + ) + lifecycle_id = cur.fetchone()[0] + cur.execute( + """ + INSERT INTO finding_lifecycle_transitions + (lifecycle_id, from_state, to_state, scan_id, reason) + VALUES (%s, NULL, 'OPEN', %s, 'New finding observed') + """, + (lifecycle_id, scan_id), + ) + else: + lifecycle_id, state, occurrence_count, reopen_count, row_version = lc_row + if state in ("OPEN", "REOPENED"): + # Seen again while already open: increment counter. + cur.execute( + """ + UPDATE finding_lifecycles + SET occurrence_count = occurrence_count + 1, + last_seen_scan_id = %s, + updated_at = NOW(), + row_version = row_version + 1 + WHERE id = %s + """, + (scan_id, lifecycle_id), + ) + elif state in ("RESOLVED", "ACCEPTED", "SUPPRESSED"): + # Reappeared after resolution: reopen. + cur.execute( + """ + UPDATE finding_lifecycles + SET state = 'REOPENED', + last_seen_scan_id = %s, + occurrence_count = occurrence_count + 1, + reopen_count = reopen_count + 1, + updated_at = NOW(), + row_version = row_version + 1 + WHERE id = %s + """, + (scan_id, lifecycle_id), + ) + cur.execute( + """ + INSERT INTO finding_lifecycle_transitions + (lifecycle_id, from_state, to_state, scan_id, reason) + VALUES (%s, %s, 'REOPENED', %s, 'Finding reappeared in scan') + """, + (lifecycle_id, state, scan_id), + ) + + # --- Resolve findings NOT seen in this scan --------------------- + # Only resolve if the rule's outcome actively confirmed the resource + # was clean (SUCCESS / EMPTY_SUCCESS). Fail closed for uncertain outcomes. + if seen_fingerprint_ids: + # Find fingerprints for this tenant/subscription that are currently + # OPEN or REOPENED but were NOT observed in this scan. + cur.execute( + """ + SELECT fl.id, fl.state, fl.row_version, ff.rule_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND fl.fingerprint_id NOT IN %s + FOR UPDATE OF fl + """, + (tenant_id, subscription_id, tuple(seen_fingerprint_ids)), + ) + else: + # No findings seen at all: resolve all OPEN/REOPENED where rule + # had a resolving outcome. + cur.execute( + """ + SELECT fl.id, fl.state, fl.row_version, ff.rule_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + FOR UPDATE OF fl + """, + (tenant_id, subscription_id), + ) + + absent_rows = cur.fetchall() + for lc_id, state, row_version, rule_id in absent_rows: + outcome_status = outcome_by_rule.get(rule_id) + if outcome_status in _RESOLVING_STATUSES: + cur.execute( + """ + UPDATE finding_lifecycles + SET state = 'RESOLVED', + last_seen_scan_id = %s, + consecutive_success_count = consecutive_success_count + 1, + updated_at = NOW(), + row_version = row_version + 1 + WHERE id = %s + """, + (scan_id, lc_id), + ) + cur.execute( + """ + INSERT INTO finding_lifecycle_transitions + (lifecycle_id, from_state, to_state, scan_id, reason) + VALUES (%s, %s, 'RESOLVED', %s, + 'Rule confirmed clean; finding absent from scan') + """, + (lc_id, state, scan_id), + ) + # else: PERMISSION_DENIED / TIMEOUT / FAILED / missing -> fail closed, no change. + + # --- Idempotency sentinel (inserted last) ----------------------- + cur.execute( + """ + INSERT INTO scan_lifecycle_applications (scan_id, applied_by) + VALUES (%s, 'system') + """, + (scan_id,), + ) + + db_conn.commit() + logger.info("Lifecycle application committed for scan %s", scan_id) diff --git a/api/services/pattern_service.py b/api/services/pattern_service.py new file mode 100644 index 00000000..282bc2f9 --- /dev/null +++ b/api/services/pattern_service.py @@ -0,0 +1,170 @@ +"""PatternService: detects and publishes security patterns from lifecycle state.""" + +import logging +from typing import Any + +import psycopg2.extras + +logger = logging.getLogger(__name__) + +# Hard-coded thresholds stored alongside the pattern record for traceability. +_PERSISTENT_THRESHOLD = 3 +_CROSS_RESOURCE_THRESHOLD = 2 +_REOPENED_THRESHOLD = 1 +_ALGORITHM_VERSION = "1" + + +class PatternService: + """Detects recurring patterns in finding lifecycle data and publishes records.""" + + def detect_and_publish( + self, + db_conn: Any, + scan_id: str, + subscription_id: str, + tenant_id: str, + ) -> int: + """Detect patterns for the given scan and upsert them into the patterns table. + + Returns the number of patterns upserted. + """ + count = 0 + + with db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: + # ---------------------------------------------------------------- + # 1. persistent_finding: occurrence_count >= 3 and OPEN/REOPENED + # ---------------------------------------------------------------- + cur.execute( + """ + SELECT fl.id AS lifecycle_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND fl.occurrence_count >= %s + """, + (tenant_id, subscription_id, _PERSISTENT_THRESHOLD), + ) + for row in cur.fetchall(): + _upsert_pattern( + db_conn, + pattern_type="persistent_finding", + lifecycle_id=row["lifecycle_id"], + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=[], + threshold=_PERSISTENT_THRESHOLD, + ) + count += 1 + + # ---------------------------------------------------------------- + # 2. cross_resource_recurrence: same rule_id >= 2 OPEN/REOPENED + # lifecycles in this subscription + # ---------------------------------------------------------------- + cur.execute( + """ + SELECT ff.rule_id, + array_agg(fl.id ORDER BY fl.id) AS lifecycle_ids, + COUNT(*) AS lc_count + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + GROUP BY ff.rule_id + HAVING COUNT(*) >= %s + """, + (tenant_id, subscription_id, _CROSS_RESOURCE_THRESHOLD), + ) + for row in cur.fetchall(): + lifecycle_ids = row["lifecycle_ids"] + # Publish one pattern per lifecycle in the group so each is + # individually traceable; finding_ids carries the sibling IDs. + for lc_id in lifecycle_ids: + sibling_ids = [lid for lid in lifecycle_ids if lid != lc_id] + _upsert_pattern( + db_conn, + pattern_type="cross_resource_recurrence", + lifecycle_id=lc_id, + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=sibling_ids, + threshold=_CROSS_RESOURCE_THRESHOLD, + ) + count += 1 + + # ---------------------------------------------------------------- + # 3. reopened_finding: reopen_count >= 1 and state == REOPENED + # ---------------------------------------------------------------- + cur.execute( + """ + SELECT fl.id AS lifecycle_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state = 'REOPENED' + AND fl.reopen_count >= %s + """, + (tenant_id, subscription_id, _REOPENED_THRESHOLD), + ) + for row in cur.fetchall(): + _upsert_pattern( + db_conn, + pattern_type="reopened_finding", + lifecycle_id=row["lifecycle_id"], + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=[], + threshold=_REOPENED_THRESHOLD, + ) + count += 1 + + db_conn.commit() + logger.info( + "Pattern detection for scan %s: %d pattern(s) upserted", + scan_id, + count, + ) + return count + + +def _upsert_pattern( + db_conn: Any, + pattern_type: str, + lifecycle_id: int, + tenant_id: str, + subscription_id: str, + scan_id: str, + finding_ids: list, + threshold: int, +) -> None: + """Insert or update a single pattern record.""" + import json + + with db_conn.cursor() as cur: + cur.execute( + """ + INSERT INTO patterns ( + pattern_type, lifecycle_id, tenant_id, subscription_id, + scan_id, finding_ids, threshold, algorithm_version, + created_at, updated_at + ) + VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW()) + ON CONFLICT DO NOTHING + """, + ( + pattern_type, + lifecycle_id, + tenant_id, + subscription_id, + scan_id, + json.dumps(finding_ids), + threshold, + _ALGORITHM_VERSION, + ), + ) diff --git a/scanner/engine.py b/scanner/engine.py index f7af9aa2..2efe816c 100644 --- a/scanner/engine.py +++ b/scanner/engine.py @@ -9,6 +9,13 @@ from api.observability import RULE_ERRORS_TOTAL from openshield.severity import CONTRACT_VERSION, SeverityContractError, normalize_severity, score_findings + +try: + import azure.core.exceptions as _azure_exc + _AzureHttpResponseError = _azure_exc.HttpResponseError +except Exception: + _AzureHttpResponseError = None # type: ignore[assignment,misc] + from scanner.azure_client import AzureClient logger = logging.getLogger(__name__) @@ -103,15 +110,16 @@ def run_scan(self, scan_id: Optional[str] = None) -> Dict[str, Any]: Returns: dict with keys: scan_id, subscription_id, started_at, - completed_at, total_findings, findings. + completed_at, total_findings, findings, rule_outcomes. """ scan_id = scan_id or str(uuid.uuid4()) started_at = datetime.now(timezone.utc).isoformat() findings: List[Dict[str, Any]] = [] + rule_outcomes: List[Dict[str, Any]] = [] detected_at = datetime.now(timezone.utc).isoformat() logger.info( - "Scan %s starting against subscription %s — %d rules loaded", + "Scan %s starting against subscription %s - %d rules loaded", scan_id, self.subscription_id, len(self.rules), @@ -119,32 +127,62 @@ def run_scan(self, scan_id: Optional[str] = None) -> Dict[str, Any]: for rule in self.rules: rule_id = getattr(rule, "RULE_ID", "UNKNOWN") + rule_started = datetime.now(timezone.utc).isoformat() + outcome_status = "FAILED" try: rule_findings = rule.scan(self.client, self.subscription_id) if not isinstance(rule_findings, list): - logger.warning("Rule %s returned %s instead of list — skipped", rule_id, type(rule_findings)) - continue - - validated_findings = [] - for raw_finding in rule_findings: - finding = raw_finding - if not isinstance(finding, dict): - logger.warning("Rule %s returned a non-object finding — skipped", rule_id) - continue - finding = dict(finding) - finding["severity"] = normalize_severity(finding.get("severity")) - finding.setdefault("detected_at", detected_at) - finding.setdefault("scan_id", scan_id) - validated_findings.append(finding) - findings.extend(validated_findings) - logger.info("Rule %s produced %d finding(s)", rule_id, len(validated_findings)) + logger.warning("Rule %s returned %s instead of list - skipped", rule_id, type(rule_findings)) + outcome_status = "FAILED" + else: + validated_findings = [] + for raw_finding in rule_findings: + finding = raw_finding + if not isinstance(finding, dict): + logger.warning("Rule %s returned a non-object finding - skipped", rule_id) + continue + finding = dict(finding) + finding["severity"] = normalize_severity(finding.get("severity")) + finding.setdefault("detected_at", detected_at) + finding.setdefault("scan_id", scan_id) + validated_findings.append(finding) + findings.extend(validated_findings) + outcome_status = "SUCCESS" if validated_findings else "EMPTY_SUCCESS" + logger.info("Rule %s produced %d finding(s)", rule_id, len(validated_findings)) except SeverityContractError: RULE_ERRORS_TOTAL.labels(rule_id=rule_id).inc() logger.exception("Rule %s returned an invalid severity", rule_id) raise + except PermissionError: + RULE_ERRORS_TOTAL.labels(rule_id=rule_id).inc() + logger.error("Rule %s raised PermissionError", rule_id) + outcome_status = "PERMISSION_DENIED" + except TimeoutError: + RULE_ERRORS_TOTAL.labels(rule_id=rule_id).inc() + logger.error("Rule %s timed out", rule_id) + outcome_status = "TIMEOUT" except Exception as exc: RULE_ERRORS_TOTAL.labels(rule_id=rule_id).inc() - logger.error("Rule %s raised an exception: %s", rule_id, exc, exc_info=True) + if _AzureHttpResponseError is not None and isinstance(exc, _AzureHttpResponseError): + status_code = getattr(exc, "status_code", None) + if status_code == 403: + outcome_status = "PERMISSION_DENIED" + logger.error("Rule %s got HTTP 403 from Azure", rule_id) + else: + outcome_status = "FAILED" + logger.error("Rule %s raised an exception: %s", rule_id, exc, exc_info=True) + else: + outcome_status = "FAILED" + logger.error("Rule %s raised an exception: %s", rule_id, exc, exc_info=True) + + rule_outcomes.append( + { + "rule_id": rule_id, + "status": outcome_status, + "started_at": rule_started, + "completed_at": datetime.now(timezone.utc).isoformat(), + } + ) completed_at = datetime.now(timezone.utc).isoformat() @@ -161,8 +199,9 @@ def run_scan(self, scan_id: Optional[str] = None) -> Dict[str, Any]: "score": score, "severity_contract_version": CONTRACT_VERSION, "findings": findings, + "rule_outcomes": rule_outcomes, } - logger.info("Scan %s complete — %d total finding(s). Normalising results...", scan_id, len(findings)) + logger.info("Scan %s complete - %d total finding(s). Normalising results...", scan_id, len(findings)) return make_serializable(result) diff --git a/tests/test_finding_lifecycle.py b/tests/test_finding_lifecycle.py new file mode 100644 index 00000000..7e5a239e --- /dev/null +++ b/tests/test_finding_lifecycle.py @@ -0,0 +1,363 @@ +"""Tests for LifecycleService using a mocked psycopg2 connection. + +All tests use in-memory state to simulate the database without requiring a +live PostgreSQL instance. +""" + +import hashlib +import json +from unittest.mock import MagicMock, call, patch + +import pytest + +from api.services.lifecycle_service import ( + LifecycleService, + _compute_fingerprint_hash, + _normalize_resource_id, +) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + +TENANT_ID = "tenant-abc" +SUB_ID = "sub-001" +SCAN_ID_1 = "11111111-1111-1111-1111-111111111111" +SCAN_ID_2 = "22222222-2222-2222-2222-222222222222" + + +def _make_finding(rule_id: str, resource_id: str, evidence_key: str = "") -> dict: + return { + "rule_id": rule_id, + "resource_id": resource_id, + "evidence_key": evidence_key, + } + + +def _make_outcome(rule_id: str, status: str) -> dict: + return {"rule_id": rule_id, "status": status} + + +# --------------------------------------------------------------------------- +# Simple DB simulation using a plain dict as in-memory state. +# We avoid mocking every cursor call individually by building a lightweight +# fake cursor that replays scripted return values in order. +# --------------------------------------------------------------------------- + + +class _FakeCursor: + """A fake psycopg2 cursor that works with pre-loaded fetchone/fetchall results.""" + + def __init__(self, results: list): + # results is a list of return values; each execute() pops one. + self._results = list(results) + self._current = None + self.executed = [] + + def execute(self, sql, params=None): + self.executed.append((sql.strip(), params)) + self._current = self._results.pop(0) if self._results else None + + def fetchone(self): + return self._current + + def fetchall(self): + if isinstance(self._current, list): + return self._current + return [] if self._current is None else [self._current] + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + +class _FakeConn: + """Fake connection whose cursor() returns a _FakeCursor consuming a result list.""" + + def __init__(self, results: list): + self._results = results + self.committed = False + self._cursor_obj = None + + def cursor(self, **_kwargs): + self._cursor_obj = _FakeCursor(self._results) + return self._cursor_obj + + def commit(self): + self.committed = True + + +# --------------------------------------------------------------------------- +# Tests +# --------------------------------------------------------------------------- + + +class TestComputeFingerprintHash: + def test_hash_is_stable(self): + h1 = _compute_fingerprint_hash(TENANT_ID, SUB_ID, "/sub/001/rg/foo", "RULE-001", "", "1") + h2 = _compute_fingerprint_hash(TENANT_ID, SUB_ID, "/sub/001/rg/foo", "RULE-001", "", "1") + assert h1 == h2 + + def test_different_tenant_different_hash(self): + h1 = _compute_fingerprint_hash("tenant-A", SUB_ID, "/rg/foo", "RULE-001", "", "1") + h2 = _compute_fingerprint_hash("tenant-B", SUB_ID, "/rg/foo", "RULE-001", "", "1") + assert h1 != h2 + + def test_tenant_id_included_in_hash(self): + """Tenant isolation: fingerprint_hash must encode the tenant_id.""" + h_a = _compute_fingerprint_hash("tenant-A", SUB_ID, "/rg/foo", "RULE-001", "", "1") + h_b = _compute_fingerprint_hash("tenant-B", SUB_ID, "/rg/foo", "RULE-001", "", "1") + assert h_a != h_b + + def test_different_rule_different_hash(self): + h1 = _compute_fingerprint_hash(TENANT_ID, SUB_ID, "/rg/foo", "RULE-001", "", "1") + h2 = _compute_fingerprint_hash(TENANT_ID, SUB_ID, "/rg/foo", "RULE-002", "", "1") + assert h1 != h2 + + +class TestNormalizeResourceId: + def test_lowercase(self): + assert _normalize_resource_id("/subscriptions/SUB/resourceGroups/RG") == ( + "/subscriptions/sub/resourcegroups/rg" + ) + + def test_strip_whitespace(self): + assert _normalize_resource_id(" /rg/foo ") == "/rg/foo" + + +class TestLifecycleServiceIdempotency: + """Applying the same scan_id twice must produce exactly one transition.""" + + def test_second_apply_is_no_op(self): + # First call: idempotency row NOT present (fetchone -> None), then + # fingerprint upsert returns id=1, lifecycle select returns None + # (new finding), lifecycle insert returns id=10, commit. + # Second call: idempotency row IS present (fetchone -> (scan_id,)). + svc = LifecycleService() + + transitions = [] + + # We use a counting approach: track how many times commit() is called. + committed_count = 0 + + class _TrackingConn: + def __init__(self, is_first_call): + self._is_first = is_first_call + self._results = self._build_results(is_first_call) + + def _build_results(self, first): + if first: + # idempotency check -> None (not applied) + # fingerprint upsert RETURNING id -> (1,) + # lifecycle FOR UPDATE -> None (new) + # lifecycle INSERT RETURNING id -> (10,) + # transition insert -> None + # absent-findings query -> [] + # idempotency insert -> None + return [None, (1,), None, (10,), None, [], None] + else: + # idempotency check -> row found: stop immediately + return [("already-applied",)] + + def cursor(self, **_kwargs): + return _FakeCursor(self._results) + + def commit(self): + nonlocal committed_count + committed_count += 1 + + svc.apply_scan( + _TrackingConn(True), SCAN_ID_1, SUB_ID, TENANT_ID, + [_make_outcome("RULE-001", "SUCCESS")], + [_make_finding("RULE-001", "/rg/foo")], + ) + svc.apply_scan( + _TrackingConn(False), SCAN_ID_1, SUB_ID, TENANT_ID, + [_make_outcome("RULE-001", "SUCCESS")], + [_make_finding("RULE-001", "/rg/foo")], + ) + + # Only the first call should have committed. + assert committed_count == 1 + + +class TestLifecycleStateTransitions: + """State machine correctness tests using scripted cursor results.""" + + def _run(self, results, findings, outcomes): + """Run apply_scan with scripted cursor results; return the fake conn.""" + conn = _FakeConn(results) + svc = LifecycleService() + svc.apply_scan(conn, SCAN_ID_1, SUB_ID, TENANT_ID, outcomes, findings) + return conn + + def test_new_finding_creates_open_lifecycle(self): + # Scripted results in cursor execute order: + # 1. idempotency check -> None + # 2. fingerprint upsert RETURNING id -> (1,) + # 3. lifecycle FOR UPDATE -> None (no existing row) + # 4. lifecycle INSERT RETURNING id -> (10,) + # 5. transition insert -> None + # 6. absent-findings query -> [] + # 7. idempotency insert -> None + results = [None, (1,), None, (10,), None, [], None] + conn = self._run( + results, + [_make_finding("RULE-001", "/rg/foo")], + [_make_outcome("RULE-001", "SUCCESS")], + ) + assert conn.committed + + # Verify the lifecycle INSERT used 'OPEN' + executed = conn._cursor_obj.executed + insert_lc = next( + (sql for sql, _ in executed if "INSERT INTO finding_lifecycles" in sql), None + ) + assert insert_lc is not None + + def test_open_finding_not_seen_in_success_scan_is_resolved(self): + # No findings in this scan, outcome is SUCCESS -> existing OPEN should resolve. + # 1. idempotency check -> None + # 2. absent-findings query (no seen ids branch) -> [(lc_id=10, 'OPEN', 0, 'RULE-001')] + # 3. UPDATE finding_lifecycles SET state='RESOLVED' -> None + # 4. transition insert -> None + # 5. idempotency insert -> None + results = [ + None, + [(10, "OPEN", 0, "RULE-001")], + None, + None, + None, + ] + conn = self._run( + results, + [], # no findings + [_make_outcome("RULE-001", "SUCCESS")], + ) + assert conn.committed + executed = conn._cursor_obj.executed + resolve_sql = next( + (sql for sql, _ in executed if "RESOLVED" in sql and "UPDATE" in sql.upper()), None + ) + assert resolve_sql is not None + + def test_open_finding_not_seen_in_failed_scan_stays_open(self): + # FAILED outcome -> fail-closed: finding should NOT be resolved. + # 1. idempotency check -> None + # 2. absent-findings query -> [(lc_id=10, 'OPEN', 0, 'RULE-001')] + # 3. idempotency insert -> None + # (no UPDATE to RESOLVED because outcome is FAILED) + results = [ + None, + [(10, "OPEN", 0, "RULE-001")], + None, + ] + conn = self._run( + results, + [], + [_make_outcome("RULE-001", "FAILED")], + ) + assert conn.committed + executed = conn._cursor_obj.executed + resolve_sql = next( + (sql for sql, _ in executed if "RESOLVED" in sql and "UPDATE" in sql.upper()), None + ) + assert resolve_sql is None + + def test_open_finding_not_seen_in_permission_denied_stays_open(self): + results = [ + None, + [(10, "OPEN", 0, "RULE-001")], + None, + ] + conn = self._run( + results, + [], + [_make_outcome("RULE-001", "PERMISSION_DENIED")], + ) + assert conn.committed + executed = conn._cursor_obj.executed + resolve_sql = next( + (sql for sql, _ in executed if "RESOLVED" in sql and "UPDATE" in sql.upper()), None + ) + assert resolve_sql is None + + def test_resolved_finding_seen_again_becomes_reopened(self): + # Fingerprint exists (id=1), lifecycle row has state=RESOLVED -> should REOPEN. + # 1. idempotency check -> None + # 2. fingerprint upsert RETURNING id -> (1,) + # 3. lifecycle FOR UPDATE -> (lc_id=10, 'RESOLVED', 1, 0, 2) + # (id, state, occurrence_count, reopen_count, row_version) + # 4. UPDATE to REOPENED -> None + # 5. transition insert (RESOLVED -> REOPENED) -> None + # 6. absent-findings query -> [] + # 7. idempotency insert -> None + results = [ + None, + (1,), + (10, "RESOLVED", 1, 0, 2), + None, + None, + [], + None, + ] + conn = self._run( + results, + [_make_finding("RULE-001", "/rg/foo")], + [_make_outcome("RULE-001", "SUCCESS")], + ) + assert conn.committed + executed = conn._cursor_obj.executed + reopen_sql = next( + (sql for sql, _ in executed if "REOPENED" in sql and "UPDATE" in sql.upper()), None + ) + assert reopen_sql is not None + + def test_reopened_finding_seen_again_increments_occurrence_stays_reopened(self): + # REOPENED + seen again: occurrence_count increments, state stays REOPENED. + # 1. idempotency check -> None + # 2. fingerprint upsert RETURNING id -> (1,) + # 3. lifecycle FOR UPDATE -> (10, 'REOPENED', 3, 1, 4) + # 4. UPDATE occurrence_count + 1 -> None (OPEN/REOPENED branch) + # 5. absent-findings query -> [] + # 6. idempotency insert -> None + results = [ + None, + (1,), + (10, "REOPENED", 3, 1, 4), + None, + [], + None, + ] + conn = self._run( + results, + [_make_finding("RULE-001", "/rg/foo")], + [_make_outcome("RULE-001", "SUCCESS")], + ) + assert conn.committed + executed = conn._cursor_obj.executed + # Verify no transition to a NEW state was recorded for this finding + # (i.e. no INSERT INTO finding_lifecycle_transitions for OPEN/REOPENED). + reopened_transition = next( + ( + sql for sql, params in executed + if "INSERT INTO finding_lifecycle_transitions" in sql + and params is not None + and "REOPENED" in str(params) + ), + None, + ) + assert reopened_transition is None + + # Verify occurrence_count was incremented (UPDATE without state change). + occ_update = next( + ( + sql for sql, _ in executed + if "occurrence_count = occurrence_count + 1" in sql + ), + None, + ) + assert occ_update is not None diff --git a/tests/test_patterns.py b/tests/test_patterns.py new file mode 100644 index 00000000..e27e2a9e --- /dev/null +++ b/tests/test_patterns.py @@ -0,0 +1,330 @@ +"""Tests for PatternService and GET /api/v1/patterns routes. + +Pattern detection tests use a mocked DB; route tests use the Flask test client +with mocked database queries. +""" + +import json +import os +import secrets +import time +from unittest.mock import MagicMock, patch + +import jwt +import pytest + +TENANT_ID = "tenant-abc" +SUB_ID = "sub-001" +SCAN_ID = "33333333-3333-3333-3333-333333333333" + +_TEST_JWT_SECRET = secrets.token_urlsafe(32) + + +# --------------------------------------------------------------------------- +# Helpers +# --------------------------------------------------------------------------- + + +def _make_token(sub_id: str | None = None) -> str: + payload = { + "sub": "test-user", + "role": "admin", + "iat": int(time.time()), + "exp": int(time.time()) + 3600, + } + if sub_id: + payload["subscription_id"] = sub_id + return jwt.encode(payload, _TEST_JWT_SECRET, algorithm="HS256") + + +def _auth_headers(sub_id: str | None = None) -> dict: + return { + "Authorization": f"Bearer {_make_token(sub_id)}", + "Content-Type": "application/json", + } + + +# --------------------------------------------------------------------------- +# Fake cursor / connection for service tests +# --------------------------------------------------------------------------- + + +class _FakeCursor: + def __init__(self, pages: list): + # pages: list of values returned by successive fetchone/fetchall calls + self._pages = list(pages) + self.executed = [] + + def execute(self, sql, params=None): + self.executed.append((sql.strip(), params)) + + def fetchone(self): + return self._pages.pop(0) if self._pages else None + + def fetchall(self): + return self._pages.pop(0) if self._pages else [] + + def __enter__(self): + return self + + def __exit__(self, *args): + pass + + +class _FakeConn: + def __init__(self, fetchall_pages: list): + self._pages = fetchall_pages + self.committed = False + self._cursor_obj = None + + def cursor(self, **_kwargs): + self._cursor_obj = _FakeCursor(self._pages) + return self._cursor_obj + + def commit(self): + self.committed = True + + +# --------------------------------------------------------------------------- +# PatternService unit tests +# --------------------------------------------------------------------------- + + +class TestPatternServiceDetection: + def _run(self, pages, extra_pages=None): + """Run detect_and_publish with scripted DB results.""" + from api.services.pattern_service import PatternService + + all_pages = list(pages) + if extra_pages: + all_pages.extend(extra_pages) + conn = _FakeConn(all_pages) + svc = PatternService() + count = svc.detect_and_publish(conn, SCAN_ID, SUB_ID, TENANT_ID) + return count, conn + + def test_persistent_finding_detected_when_occurrence_ge_3(self): + # persistent_finding query returns 1 row -> 1 pattern upserted. + # cross_resource query returns [] -> 0. + # reopened query returns [] -> 0. + count, conn = self._run( + [ + [{"lifecycle_id": 10}], # persistent_finding + [], # cross_resource_recurrence + [], # reopened_finding + ] + ) + assert count == 1 + + def test_persistent_finding_not_detected_when_occurrence_lt_3(self): + # All queries return empty. + count, conn = self._run([[], [], []]) + assert count == 0 + + def test_cross_resource_recurrence_detected_when_2_open_lifecycles(self): + # cross_resource query returns 1 group with 2 lifecycle_ids -> 2 patterns. + count, conn = self._run( + [ + [], # persistent_finding + [{"rule_id": "RULE-001", "lifecycle_ids": [10, 11], "lc_count": 2}], + [], # reopened_finding + ] + ) + assert count == 2 + + def test_reopened_finding_detected_when_reopen_count_ge_1(self): + count, conn = self._run( + [ + [], # persistent_finding + [], # cross_resource_recurrence + [{"lifecycle_id": 20}], # reopened_finding + ] + ) + assert count == 1 + + def test_pattern_response_includes_threshold_and_algorithm_version(self): + """The upsert call must include threshold and algorithm_version.""" + from api.services.pattern_service import PatternService, _ALGORITHM_VERSION, _PERSISTENT_THRESHOLD + + conn = _FakeConn([ + [{"lifecycle_id": 10}], # persistent_finding + [], # cross_resource_recurrence + [], # reopened_finding + ]) + svc = PatternService() + svc.detect_and_publish(conn, SCAN_ID, SUB_ID, TENANT_ID) + + # Find the INSERT INTO patterns call and verify the params. + executed = conn._cursor_obj.executed + insert_sql, params = next( + ((sql, p) for sql, p in executed if "INSERT INTO patterns" in sql), (None, None) + ) + assert insert_sql is not None + # params order: pattern_type, lifecycle_id, tenant_id, subscription_id, + # scan_id, finding_ids, threshold, algorithm_version + assert params[6] == _PERSISTENT_THRESHOLD + assert params[7] == _ALGORITHM_VERSION + + +# --------------------------------------------------------------------------- +# Flask route tests for GET /api/v1/patterns +# --------------------------------------------------------------------------- + + +@pytest.fixture +def app_client(monkeypatch): + """Flask test client with JWT and mocked DB.""" + monkeypatch.setenv("DATABASE_URL", "postgresql://fake/fake") + monkeypatch.setenv("JWT_SECRET", _TEST_JWT_SECRET) + + from api.app import create_app + + application = create_app() + application.config["TESTING"] = True + application.config["JWT_SECRET"] = _TEST_JWT_SECRET + return application.test_client() + + +def _mock_db_rows(rows: list, total: int): + """Build a mock DatabaseManager whose conn returns scripted rows.""" + mock_conn = MagicMock() + mock_cursor = MagicMock() + mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) + mock_cursor.__exit__ = MagicMock(return_value=False) + + # First fetchall -> rows; second fetchone -> {"count": total} + mock_cursor.fetchall.return_value = rows + mock_cursor.fetchone.return_value = {"count": total} + + mock_conn.cursor.return_value = mock_cursor + + mock_db = MagicMock() + mock_db._get_conn.return_value = mock_conn + return mock_db + + +def _sample_pattern_row(sub_id: str = SUB_ID) -> dict: + from datetime import datetime, timezone + + return { + "id": 1, + "pattern_type": "persistent_finding", + "lifecycle_id": 10, + "tenant_id": TENANT_ID, + "subscription_id": sub_id, + "scan_id": "33333333-3333-3333-3333-333333333333", + "finding_ids": [], + "threshold": 3, + "algorithm_version": "1", + "created_at": datetime(2026, 1, 1, tzinfo=timezone.utc), + "updated_at": datetime(2026, 1, 1, tzinfo=timezone.utc), + } + + +class TestPatternsRouteList: + def test_list_returns_patterns_and_total(self, app_client, monkeypatch): + row = _sample_pattern_row() + mock_db = _mock_db_rows([row], 1) + + with patch("api.routes.patterns._get_db", return_value=mock_db): + resp = app_client.get( + "/api/v1/patterns", + headers=_auth_headers(), + ) + + assert resp.status_code == 200 + data = resp.get_json() + assert "patterns" in data + assert "total" in data + assert data["total"] == 1 + assert len(data["patterns"]) == 1 + + def test_list_invalid_limit_returns_400(self, app_client): + resp = app_client.get( + "/api/v1/patterns?limit=999", + headers=_auth_headers(), + ) + assert resp.status_code == 400 + + def test_list_invalid_pattern_type_returns_400(self, app_client): + resp = app_client.get( + "/api/v1/patterns?pattern_type=not_a_real_type", + headers=_auth_headers(), + ) + assert resp.status_code == 400 + + def test_list_unknown_query_param_returns_400(self, app_client): + resp = app_client.get( + "/api/v1/patterns?foo=bar", + headers=_auth_headers(), + ) + assert resp.status_code == 400 + + def test_list_returns_only_authorized_subscription(self, app_client): + """Patterns for a different subscription must not be returned to an + authorized user whose JWT contains a different subscription_id.""" + row_authorized = _sample_pattern_row(sub_id="sub-authorized") + mock_db = _mock_db_rows([row_authorized], 1) + + with patch("api.routes.patterns._get_db", return_value=mock_db): + resp = app_client.get( + "/api/v1/patterns", + headers=_auth_headers(sub_id="sub-authorized"), + ) + + assert resp.status_code == 200 + data = resp.get_json() + # The query is scoped; verify the mock was called (subscription scoped query). + assert "patterns" in data + + def test_list_requires_auth(self, app_client): + resp = app_client.get("/api/v1/patterns") + assert resp.status_code == 401 + + +class TestPatternsRouteGet: + def test_get_existing_pattern(self, app_client): + row = _sample_pattern_row() + mock_db = MagicMock() + mock_conn = MagicMock() + mock_cursor = MagicMock() + mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) + mock_cursor.__exit__ = MagicMock(return_value=False) + mock_cursor.fetchone.return_value = row + mock_conn.cursor.return_value = mock_cursor + mock_db._get_conn.return_value = mock_conn + + with patch("api.routes.patterns._get_db", return_value=mock_db): + resp = app_client.get( + "/api/v1/patterns/1", + headers=_auth_headers(), + ) + + assert resp.status_code == 200 + data = resp.get_json() + assert data["id"] == 1 + assert data["pattern_type"] == "persistent_finding" + assert data["threshold"] == 3 + assert data["algorithm_version"] == "1" + + def test_get_nonexistent_pattern_returns_404(self, app_client): + mock_db = MagicMock() + mock_conn = MagicMock() + mock_cursor = MagicMock() + mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) + mock_cursor.__exit__ = MagicMock(return_value=False) + mock_cursor.fetchone.return_value = None + mock_conn.cursor.return_value = mock_cursor + mock_db._get_conn.return_value = mock_conn + + with patch("api.routes.patterns._get_db", return_value=mock_db): + resp = app_client.get( + "/api/v1/patterns/99999", + headers=_auth_headers(), + ) + + assert resp.status_code == 404 + + def test_get_requires_auth(self, app_client): + resp = app_client.get("/api/v1/patterns/1") + assert resp.status_code == 401 From d3e6542d401c04c0e655b2093808fa4783be36f1 Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 02:02:41 +0100 Subject: [PATCH 2/8] fix(security): close IDOR and tenant-bypass in patterns API GET /api/v1/patterns: the subscription scope is now always enforced in SQL (WHERE subscription_id = %s, never a nullable IS NULL bypass). The JWT subscription_id is the authority; a query-param that disagrees with the JWT is rejected with 400. A request with no subscription_id in either the JWT or the query param is also rejected. GET /api/v1/patterns/: the WHERE clause now includes subscription_id so a caller cannot enumerate patterns from other subscriptions by ID. An out-of-scope ID returns 404 to avoid disclosing that the pattern exists in another subscription. Adds three new regression tests: no-subscription-400, cross-subscription query-param-400, and cross-subscription IDOR-404. Signed-off-by: Tanvir Farhad --- api/routes/patterns.py | 62 ++++++++++++++++++++++++++++++------------ tests/test_patterns.py | 59 ++++++++++++++++++++++++++++++---------- 2 files changed, 88 insertions(+), 33 deletions(-) diff --git a/api/routes/patterns.py b/api/routes/patterns.py index a03d8d4e..be5d8f9e 100644 --- a/api/routes/patterns.py +++ b/api/routes/patterns.py @@ -42,6 +42,30 @@ def _validate_limit(raw: str) -> int: return value +def _effective_subscription(subscription_id_param: str | None) -> str: + """Return the subscription scope this request is authorized to see. + + The JWT subscription_id is always the authority. A query-param + subscription_id may narrow the JWT scope but never widen it. If the + JWT carries no subscription_id, the query param is accepted as the + scope (single-tenant deployments that do not embed subscription_id in + tokens). Either way the scope must be non-empty: an unscoped query + would return patterns from every subscription, which is never correct. + """ + user = getattr(g, "user", {}) or {} + jwt_sub = user.get("subscription_id") + + if jwt_sub: + if subscription_id_param and subscription_id_param != jwt_sub: + raise _ValidationError("subscription_id does not match token scope") + return jwt_sub + + if subscription_id_param: + return subscription_id_param + + raise _ValidationError("subscription_id is required") + + def _row_to_dict(row: dict) -> dict: """Serialise a patterns table row to a JSON-safe dict.""" result = dict(row) @@ -59,7 +83,7 @@ def list_patterns(): """Return published security patterns, optionally filtered. Query parameters: - subscription_id - filter by Azure subscription + subscription_id - filter by Azure subscription (must match JWT scope) pattern_type - one of persistent_finding, cross_resource_recurrence, reopened_finding limit - 1-100, default 20 @@ -73,12 +97,12 @@ def list_patterns(): if len(request.args.getlist(key)) != 1: raise _ValidationError(f"Query parameter {key} must be provided once") - subscription_id = None + subscription_id_param = None if "subscription_id" in request.args: val = request.args["subscription_id"].strip() if not val or len(val) > 256: raise _ValidationError("subscription_id is invalid") - subscription_id = val + subscription_id_param = val pattern_type = None if "pattern_type" in request.args: @@ -91,14 +115,11 @@ def list_patterns(): if "limit" in request.args: limit = _validate_limit(request.args["limit"]) + effective_sub = _effective_subscription(subscription_id_param) + db = _get_db() conn = db._get_conn() - # Tenant isolation: prefer subscription_id embedded in the JWT payload; - # fall back to the query parameter. - user = getattr(g, "user", {}) or {} - effective_sub = user.get("subscription_id") or subscription_id - with conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: cur.execute( """ @@ -106,16 +127,12 @@ def list_patterns(): subscription_id, scan_id, finding_ids, threshold, algorithm_version, created_at, updated_at FROM patterns - WHERE (%s IS NULL OR subscription_id = %s) + WHERE subscription_id = %s AND (%s IS NULL OR pattern_type = %s) ORDER BY created_at DESC LIMIT %s """, - ( - effective_sub, effective_sub, - pattern_type, pattern_type, - limit, - ), + (effective_sub, pattern_type, pattern_type, limit), ) rows = cur.fetchall() @@ -123,10 +140,10 @@ def list_patterns(): """ SELECT COUNT(*) AS count FROM patterns - WHERE (%s IS NULL OR subscription_id = %s) + WHERE subscription_id = %s AND (%s IS NULL OR pattern_type = %s) """, - (effective_sub, effective_sub, pattern_type, pattern_type), + (effective_sub, pattern_type, pattern_type), ) total_row = cur.fetchone() total = total_row["count"] if total_row else 0 @@ -147,11 +164,19 @@ def list_patterns(): @patterns_bp.get("/api/v1/patterns/") def get_pattern(pattern_id: int): - """Return a single pattern by its integer ID.""" + """Return a single pattern by its integer ID. + + The pattern is only returned when its subscription_id matches the + caller's authorized scope. An out-of-scope pattern returns 404 so + that the existence of other subscriptions' patterns is not disclosed. + """ try: if pattern_id <= 0: raise _ValidationError("pattern_id must be a positive integer") + # Resolve scope first so an unscoped caller cannot enumerate IDs. + effective_sub = _effective_subscription(None) + db = _get_db() conn = db._get_conn() @@ -163,8 +188,9 @@ def get_pattern(pattern_id: int): algorithm_version, created_at, updated_at FROM patterns WHERE id = %s + AND subscription_id = %s """, - (pattern_id,), + (pattern_id, effective_sub), ) row = cur.fetchone() diff --git a/tests/test_patterns.py b/tests/test_patterns.py index e27e2a9e..3884d82e 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -229,7 +229,7 @@ def test_list_returns_patterns_and_total(self, app_client, monkeypatch): with patch("api.routes.patterns._get_db", return_value=mock_db): resp = app_client.get( "/api/v1/patterns", - headers=_auth_headers(), + headers=_auth_headers(sub_id=SUB_ID), ) assert resp.status_code == 200 @@ -242,24 +242,40 @@ def test_list_returns_patterns_and_total(self, app_client, monkeypatch): def test_list_invalid_limit_returns_400(self, app_client): resp = app_client.get( "/api/v1/patterns?limit=999", - headers=_auth_headers(), + headers=_auth_headers(sub_id=SUB_ID), ) assert resp.status_code == 400 def test_list_invalid_pattern_type_returns_400(self, app_client): resp = app_client.get( "/api/v1/patterns?pattern_type=not_a_real_type", - headers=_auth_headers(), + headers=_auth_headers(sub_id=SUB_ID), ) assert resp.status_code == 400 def test_list_unknown_query_param_returns_400(self, app_client): resp = app_client.get( "/api/v1/patterns?foo=bar", + headers=_auth_headers(sub_id=SUB_ID), + ) + assert resp.status_code == 400 + + def test_list_without_subscription_returns_400(self, app_client): + # JWT with no subscription_id and no query param must be rejected. + resp = app_client.get( + "/api/v1/patterns", headers=_auth_headers(), ) assert resp.status_code == 400 + def test_list_cross_subscription_query_param_rejected(self, app_client): + # JWT scoped to sub-A must reject a query param asking for sub-B. + resp = app_client.get( + "/api/v1/patterns?subscription_id=sub-B", + headers=_auth_headers(sub_id="sub-A"), + ) + assert resp.status_code == 400 + def test_list_returns_only_authorized_subscription(self, app_client): """Patterns for a different subscription must not be returned to an authorized user whose JWT contains a different subscription_id.""" @@ -283,8 +299,7 @@ def test_list_requires_auth(self, app_client): class TestPatternsRouteGet: - def test_get_existing_pattern(self, app_client): - row = _sample_pattern_row() + def _mock_get_db(self, row): mock_db = MagicMock() mock_conn = MagicMock() mock_cursor = MagicMock() @@ -293,11 +308,16 @@ def test_get_existing_pattern(self, app_client): mock_cursor.fetchone.return_value = row mock_conn.cursor.return_value = mock_cursor mock_db._get_conn.return_value = mock_conn + return mock_db + + def test_get_existing_pattern(self, app_client): + row = _sample_pattern_row() + mock_db = self._mock_get_db(row) with patch("api.routes.patterns._get_db", return_value=mock_db): resp = app_client.get( "/api/v1/patterns/1", - headers=_auth_headers(), + headers=_auth_headers(sub_id=SUB_ID), ) assert resp.status_code == 200 @@ -308,19 +328,28 @@ def test_get_existing_pattern(self, app_client): assert data["algorithm_version"] == "1" def test_get_nonexistent_pattern_returns_404(self, app_client): - mock_db = MagicMock() - mock_conn = MagicMock() - mock_cursor = MagicMock() - mock_cursor.__enter__ = MagicMock(return_value=mock_cursor) - mock_cursor.__exit__ = MagicMock(return_value=False) - mock_cursor.fetchone.return_value = None - mock_conn.cursor.return_value = mock_cursor - mock_db._get_conn.return_value = mock_conn + # DB returns None when id + subscription_id don't match any row. + mock_db = self._mock_get_db(None) with patch("api.routes.patterns._get_db", return_value=mock_db): resp = app_client.get( "/api/v1/patterns/99999", - headers=_auth_headers(), + headers=_auth_headers(sub_id=SUB_ID), + ) + + assert resp.status_code == 404 + + def test_get_cross_subscription_returns_404(self, app_client): + # Pattern exists for sub-001 but caller is scoped to sub-other. + # The SQL adds subscription_id = %s to the WHERE clause so the DB + # returns None, and the caller sees 404 (not 403, to avoid leaking + # that the pattern ID exists in another subscription). + mock_db = self._mock_get_db(None) + + with patch("api.routes.patterns._get_db", return_value=mock_db): + resp = app_client.get( + "/api/v1/patterns/1", + headers=_auth_headers(sub_id="sub-other"), ) assert resp.status_code == 404 From fb50798294972d29933d2b7c68ac208605fcb484 Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 02:10:28 +0100 Subject: [PATCH 3/8] fix(lifecycle): address all code review findings from #311 Critical fixes: - Wire LifecycleService.apply_scan() and PatternService.detect_and_publish() into scanner/worker.py immediately after db.save_scan(); lifecycle failures are non-fatal so the scan record is always preserved - Write durable per-rule outcome rows to scan_rule_outcomes at the start of apply_scan so the audit record exists even if lifecycle processing fails - Add subscription_id = effective_sub filter to GET /api/v1/patterns/ via _effective_subscription() helper (already present in patterns.py HEAD) Important fixes: - Add UNIQUE(pattern_type, lifecycle_id, scan_id) constraint to patterns table in migration; change ON CONFLICT DO NOTHING to ON CONFLICT ON CONSTRAINT uq_patterns_type_lifecycle_scan DO NOTHING - Collect detection query results before closing RealDictCursor, then open fresh cursors for each _upsert_pattern call, eliminating nested-cursor overlap in pattern_service.py - Narrow the absent-findings bulk lock to only rules with a resolving outcome (resolving_rule_ids); skip the query entirely when no rule produced SUCCESS/EMPTY_SUCCESS, reducing unnecessary lock contention - Reset consecutive_success_count = 0 when a RESOLVED/ACCEPTED/SUPPRESSED finding is reopened - Remove unused _BLOCKING_STATUSES frozenset from lifecycle_service.py - Move 'import json' to module level in pattern_service.py Test fixes: - Refactor _FakeCursor/_FakeConn to use a shared deque so multiple cursor() calls on one connection consume from the same result stream - Update scripted result sequences in all tests to include the new scan_rule_outcomes INSERT in the execute order - Update fail-closed tests to reflect that no absent-findings query is issued when resolving_rule_ids is empty (FAILED/PERMISSION_DENIED) - Add test_scan_rule_outcomes_written to verify audit record is emitted - Add consecutive_success_count = 0 assertion to reopen test Signed-off-by: Tanvir Farhad --- .../e1f2a3b4c5d6_finding_lifecycle.py | 4 +- api/services/lifecycle_service.py | 131 +++++--- api/services/pattern_service.py | 83 ++--- scanner/worker.py | 33 ++ tests/test_finding_lifecycle.py | 285 ++++++++---------- 5 files changed, 289 insertions(+), 247 deletions(-) diff --git a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py index 1b1ccfa4..7d6d8d98 100644 --- a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py +++ b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py @@ -137,7 +137,9 @@ def upgrade() -> None: 'persistent_finding', 'cross_resource_recurrence', 'reopened_finding' - )) + )), + CONSTRAINT uq_patterns_type_lifecycle_scan + UNIQUE (pattern_type, lifecycle_id, scan_id) ) """ ) diff --git a/api/services/lifecycle_service.py b/api/services/lifecycle_service.py index 9aff5e92..10a1ebbe 100644 --- a/api/services/lifecycle_service.py +++ b/api/services/lifecycle_service.py @@ -12,10 +12,6 @@ # Statuses that mean "we actively confirmed this rule was clean in the scan." _RESOLVING_STATUSES = frozenset({"SUCCESS", "EMPTY_SUCCESS"}) -# Statuses that mean "we could not reliably evaluate the rule." -# Fail-closed: do NOT resolve findings when the scan could not see the resource. -_BLOCKING_STATUSES = frozenset({"PERMISSION_DENIED", "TIMEOUT", "FAILED"}) - def _normalize_resource_id(resource_id: str) -> str: """Return a stable, lowercased, stripped version of an ARM resource ID.""" @@ -72,7 +68,8 @@ def apply_scan( subscription_id: Azure subscription ID. tenant_id: Tenant identifier for isolation. rule_outcomes: List of dicts with at minimum keys 'rule_id' and - 'status' (one of the six allowed status values). + 'status' (one of the six allowed status values). Also used to + populate scan_rule_outcomes for durable audit history. findings: List of finding dicts from the scan, each with keys 'rule_id', 'resource_id', and optionally 'evidence_key'. Defaults to an empty list when omitted. @@ -89,11 +86,46 @@ def apply_scan( logger.info("Scan %s already applied; skipping lifecycle update", scan_id) return + # --- Write durable per-rule outcome records ------------------- + # Insert before lifecycle logic so the audit record exists even + # if lifecycle processing fails. The UNIQUE(scan_id, rule_id) + # constraint prevents duplicates on accidental double-writes. + for outcome in rule_outcomes: + rule_id_o = outcome.get("rule_id", "") + status_o = outcome.get("status", "FAILED") + if not rule_id_o: + continue + cur.execute( + """ + INSERT INTO scan_rule_outcomes ( + scan_id, rule_id, status, tenant_id, subscription_id, + inventory_boundary, started_at, completed_at + ) + VALUES (%s, %s, %s, %s, %s, 'subscription', %s, NOW()) + ON CONFLICT (scan_id, rule_id) DO NOTHING + """, + ( + scan_id, + rule_id_o, + status_o, + tenant_id, + subscription_id, + outcome.get("started_at"), + ), + ) + # Build a lookup: rule_id -> outcome status outcome_by_rule: Dict[str, str] = { o["rule_id"]: o["status"] for o in rule_outcomes if "rule_id" in o and "status" in o } + # Collect rule IDs that actively confirmed a clean result. Only + # these can trigger resolution of absent findings (fail-closed). + resolving_rule_ids = [ + rule_id for rule_id, status in outcome_by_rule.items() + if status in _RESOLVING_STATUSES + ] + # Build the set of (rule_id, resource_id_normalized) pairs seen in # this scan. A fingerprint in this set was actively observed. seen_fingerprint_keys: set = set() @@ -131,6 +163,8 @@ def apply_scan( # --- Upsert fingerprints and lifecycles for seen findings ------- seen_fingerprint_ids: set = set() for fp in fingerprints_in_scan: + # ON CONFLICT touches fingerprint_hash to force RETURNING id + # even when the row already exists (DO NOTHING returns nothing). cur.execute( """ INSERT INTO finding_fingerprints ( @@ -208,7 +242,7 @@ def apply_scan( (scan_id, lifecycle_id), ) elif state in ("RESOLVED", "ACCEPTED", "SUPPRESSED"): - # Reappeared after resolution: reopen. + # Reappeared after resolution: reopen and reset success streak. cur.execute( """ UPDATE finding_lifecycles @@ -216,6 +250,7 @@ def apply_scan( last_seen_scan_id = %s, occurrence_count = occurrence_count + 1, reopen_count = reopen_count + 1, + consecutive_success_count = 0, updated_at = NOW(), row_version = row_version + 1 WHERE id = %s @@ -232,11 +267,13 @@ def apply_scan( ) # --- Resolve findings NOT seen in this scan --------------------- - # Only resolve if the rule's outcome actively confirmed the resource - # was clean (SUCCESS / EMPTY_SUCCESS). Fail closed for uncertain outcomes. - if seen_fingerprint_ids: - # Find fingerprints for this tenant/subscription that are currently - # OPEN or REOPENED but were NOT observed in this scan. + # Only lock and process rows for rules that had a resolving outcome. + # This avoids unnecessary contention on unrelated rules and is more + # efficient on subscriptions with many open findings. + if not resolving_rule_ids: + # No rule produced a clean outcome: nothing can be resolved. + pass + elif seen_fingerprint_ids: cur.execute( """ SELECT fl.id, fl.state, fl.row_version, ff.rule_id @@ -246,13 +283,14 @@ def apply_scan( AND ff.subscription_id = %s AND fl.state IN ('OPEN', 'REOPENED') AND fl.fingerprint_id NOT IN %s + AND ff.rule_id = ANY(%s) FOR UPDATE OF fl """, - (tenant_id, subscription_id, tuple(seen_fingerprint_ids)), + (tenant_id, subscription_id, tuple(seen_fingerprint_ids), resolving_rule_ids), ) + _resolve_absent_rows(cur, scan_id, outcome_by_rule) else: - # No findings seen at all: resolve all OPEN/REOPENED where rule - # had a resolving outcome. + # No findings seen at all: resolve for rules with clean outcomes. cur.execute( """ SELECT fl.id, fl.state, fl.row_version, ff.rule_id @@ -261,37 +299,12 @@ def apply_scan( WHERE ff.tenant_id = %s AND ff.subscription_id = %s AND fl.state IN ('OPEN', 'REOPENED') + AND ff.rule_id = ANY(%s) FOR UPDATE OF fl """, - (tenant_id, subscription_id), + (tenant_id, subscription_id, resolving_rule_ids), ) - - absent_rows = cur.fetchall() - for lc_id, state, row_version, rule_id in absent_rows: - outcome_status = outcome_by_rule.get(rule_id) - if outcome_status in _RESOLVING_STATUSES: - cur.execute( - """ - UPDATE finding_lifecycles - SET state = 'RESOLVED', - last_seen_scan_id = %s, - consecutive_success_count = consecutive_success_count + 1, - updated_at = NOW(), - row_version = row_version + 1 - WHERE id = %s - """, - (scan_id, lc_id), - ) - cur.execute( - """ - INSERT INTO finding_lifecycle_transitions - (lifecycle_id, from_state, to_state, scan_id, reason) - VALUES (%s, %s, 'RESOLVED', %s, - 'Rule confirmed clean; finding absent from scan') - """, - (lc_id, state, scan_id), - ) - # else: PERMISSION_DENIED / TIMEOUT / FAILED / missing -> fail closed, no change. + _resolve_absent_rows(cur, scan_id, outcome_by_rule) # --- Idempotency sentinel (inserted last) ----------------------- cur.execute( @@ -304,3 +317,37 @@ def apply_scan( db_conn.commit() logger.info("Lifecycle application committed for scan %s", scan_id) + + +def _resolve_absent_rows( + cur: Any, + scan_id: str, + outcome_by_rule: Dict[str, str], +) -> None: + """Transition OPEN/REOPENED lifecycle rows to RESOLVED for clean-outcome rules.""" + absent_rows = cur.fetchall() + for lc_id, state, row_version, rule_id in absent_rows: + outcome_status = outcome_by_rule.get(rule_id) + if outcome_status in _RESOLVING_STATUSES: + cur.execute( + """ + UPDATE finding_lifecycles + SET state = 'RESOLVED', + last_seen_scan_id = %s, + consecutive_success_count = consecutive_success_count + 1, + updated_at = NOW(), + row_version = row_version + 1 + WHERE id = %s + """, + (scan_id, lc_id), + ) + cur.execute( + """ + INSERT INTO finding_lifecycle_transitions + (lifecycle_id, from_state, to_state, scan_id, reason) + VALUES (%s, %s, 'RESOLVED', %s, + 'Rule confirmed clean; finding absent from scan') + """, + (lc_id, state, scan_id), + ) + # else: outcome missing or blocking -> fail closed, no state change. diff --git a/api/services/pattern_service.py b/api/services/pattern_service.py index 282bc2f9..6ebcd965 100644 --- a/api/services/pattern_service.py +++ b/api/services/pattern_service.py @@ -1,5 +1,6 @@ """PatternService: detects and publishes security patterns from lifecycle state.""" +import json import logging from typing import Any @@ -46,18 +47,7 @@ def detect_and_publish( """, (tenant_id, subscription_id, _PERSISTENT_THRESHOLD), ) - for row in cur.fetchall(): - _upsert_pattern( - db_conn, - pattern_type="persistent_finding", - lifecycle_id=row["lifecycle_id"], - tenant_id=tenant_id, - subscription_id=subscription_id, - scan_id=scan_id, - finding_ids=[], - threshold=_PERSISTENT_THRESHOLD, - ) - count += 1 + persistent_rows = cur.fetchall() # ---------------------------------------------------------------- # 2. cross_resource_recurrence: same rule_id >= 2 OPEN/REOPENED @@ -78,23 +68,7 @@ def detect_and_publish( """, (tenant_id, subscription_id, _CROSS_RESOURCE_THRESHOLD), ) - for row in cur.fetchall(): - lifecycle_ids = row["lifecycle_ids"] - # Publish one pattern per lifecycle in the group so each is - # individually traceable; finding_ids carries the sibling IDs. - for lc_id in lifecycle_ids: - sibling_ids = [lid for lid in lifecycle_ids if lid != lc_id] - _upsert_pattern( - db_conn, - pattern_type="cross_resource_recurrence", - lifecycle_id=lc_id, - tenant_id=tenant_id, - subscription_id=subscription_id, - scan_id=scan_id, - finding_ids=sibling_ids, - threshold=_CROSS_RESOURCE_THRESHOLD, - ) - count += 1 + cross_rows = cur.fetchall() # ---------------------------------------------------------------- # 3. reopened_finding: reopen_count >= 1 and state == REOPENED @@ -111,19 +85,54 @@ def detect_and_publish( """, (tenant_id, subscription_id, _REOPENED_THRESHOLD), ) - for row in cur.fetchall(): + reopened_rows = cur.fetchall() + + # All detection queries are finished; cursor is closed. Now upsert + # patterns using separate cursor calls to avoid open-cursor overlap. + for row in persistent_rows: + _upsert_pattern( + db_conn, + pattern_type="persistent_finding", + lifecycle_id=row["lifecycle_id"], + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=[], + threshold=_PERSISTENT_THRESHOLD, + ) + count += 1 + + for row in cross_rows: + lifecycle_ids = row["lifecycle_ids"] + # Publish one pattern per lifecycle in the group so each is + # individually traceable; finding_ids carries the sibling IDs. + for lc_id in lifecycle_ids: + sibling_ids = [lid for lid in lifecycle_ids if lid != lc_id] _upsert_pattern( db_conn, - pattern_type="reopened_finding", - lifecycle_id=row["lifecycle_id"], + pattern_type="cross_resource_recurrence", + lifecycle_id=lc_id, tenant_id=tenant_id, subscription_id=subscription_id, scan_id=scan_id, - finding_ids=[], - threshold=_REOPENED_THRESHOLD, + finding_ids=sibling_ids, + threshold=_CROSS_RESOURCE_THRESHOLD, ) count += 1 + for row in reopened_rows: + _upsert_pattern( + db_conn, + pattern_type="reopened_finding", + lifecycle_id=row["lifecycle_id"], + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=[], + threshold=_REOPENED_THRESHOLD, + ) + count += 1 + db_conn.commit() logger.info( "Pattern detection for scan %s: %d pattern(s) upserted", @@ -143,9 +152,7 @@ def _upsert_pattern( finding_ids: list, threshold: int, ) -> None: - """Insert or update a single pattern record.""" - import json - + """Insert a pattern record if the (type, lifecycle, scan) combination is new.""" with db_conn.cursor() as cur: cur.execute( """ @@ -155,7 +162,7 @@ def _upsert_pattern( created_at, updated_at ) VALUES (%s, %s, %s, %s, %s, %s, %s, %s, NOW(), NOW()) - ON CONFLICT DO NOTHING + ON CONFLICT ON CONSTRAINT uq_patterns_type_lifecycle_scan DO NOTHING """, ( pattern_type, diff --git a/scanner/worker.py b/scanner/worker.py index 21a94c6f..8f2936f1 100644 --- a/scanner/worker.py +++ b/scanner/worker.py @@ -19,6 +19,8 @@ configure_logging, init_sentry, ) +from api.services.lifecycle_service import LifecycleService +from api.services.pattern_service import PatternService from scanner.engine import ScanEngine configure_logging() @@ -74,6 +76,37 @@ def run_worker(): result["status"] = "completed" db.save_scan(result) + + # Apply lifecycle tracking. Lifecycle failures are non-fatal: + # the scan is already persisted, so we log and continue rather + # than marking the scan as failed. + try: + tenant_id = os.environ.get("OPENSHIELD_TENANT_ID", subscription_id) + lc_svc = LifecycleService() + lc_svc.apply_scan( + db_conn=db._get_conn(), + scan_id=scan_id, + subscription_id=subscription_id, + tenant_id=tenant_id, + rule_outcomes=result.get("rule_outcomes", []), + findings=result.get("findings", []), + ) + pat_svc = PatternService() + pat_svc.detect_and_publish( + db_conn=db._get_conn(), + scan_id=scan_id, + subscription_id=subscription_id, + tenant_id=tenant_id, + ) + except Exception as lc_exc: + logger.error( + "Lifecycle/pattern update failed for scan %s (scan data intact): %s", + scan_id, + lc_exc, + extra={"scan_id": scan_id}, + ) + + SCANS_TOTAL.labels(status="completed").inc() logger.info( "Successfully completed scan %s", diff --git a/tests/test_finding_lifecycle.py b/tests/test_finding_lifecycle.py index 7e5a239e..3b31816c 100644 --- a/tests/test_finding_lifecycle.py +++ b/tests/test_finding_lifecycle.py @@ -40,24 +40,28 @@ def _make_outcome(rule_id: str, status: str) -> dict: # --------------------------------------------------------------------------- -# Simple DB simulation using a plain dict as in-memory state. -# We avoid mocking every cursor call individually by building a lightweight -# fake cursor that replays scripted return values in order. +# Fake cursor / connection. +# +# The cursor consumes from a shared deque so multiple cursor() calls on the +# same connection share one result stream. This mirrors how psycopg2 works +# (multiple cursors on one connection see the same transaction state) and +# avoids the "second cursor re-reads from the start" bug noted in code review. # --------------------------------------------------------------------------- +from collections import deque + class _FakeCursor: - """A fake psycopg2 cursor that works with pre-loaded fetchone/fetchall results.""" + """Fake psycopg2 cursor backed by a shared result deque.""" - def __init__(self, results: list): - # results is a list of return values; each execute() pops one. - self._results = list(results) + def __init__(self, results_deque: deque): + self._results = results_deque + self.executed: list = [] self._current = None - self.executed = [] def execute(self, sql, params=None): self.executed.append((sql.strip(), params)) - self._current = self._results.pop(0) if self._results else None + self._current = self._results.popleft() if self._results else None def fetchone(self): return self._current @@ -75,20 +79,24 @@ def __exit__(self, *args): class _FakeConn: - """Fake connection whose cursor() returns a _FakeCursor consuming a result list.""" + """Fake connection whose cursor() calls share one result deque.""" def __init__(self, results: list): - self._results = results + self._deque: deque = deque(results) self.committed = False - self._cursor_obj = None + self._cursor_obj: _FakeCursor | None = None def cursor(self, **_kwargs): - self._cursor_obj = _FakeCursor(self._results) + # Return a new cursor object but backed by the same shared deque. + self._cursor_obj = _FakeCursor(self._deque) return self._cursor_obj def commit(self): self.committed = True + def all_executed(self) -> list: + return self._cursor_obj.executed if self._cursor_obj else [] + # --------------------------------------------------------------------------- # Tests @@ -129,53 +137,41 @@ def test_strip_whitespace(self): class TestLifecycleServiceIdempotency: - """Applying the same scan_id twice must produce exactly one transition.""" + """Applying the same scan_id twice must commit exactly once.""" def test_second_apply_is_no_op(self): - # First call: idempotency row NOT present (fetchone -> None), then - # fingerprint upsert returns id=1, lifecycle select returns None - # (new finding), lifecycle insert returns id=10, commit. - # Second call: idempotency row IS present (fetchone -> (scan_id,)). - svc = LifecycleService() - - transitions = [] - - # We use a counting approach: track how many times commit() is called. committed_count = 0 class _TrackingConn: - def __init__(self, is_first_call): - self._is_first = is_first_call - self._results = self._build_results(is_first_call) - - def _build_results(self, first): - if first: - # idempotency check -> None (not applied) - # fingerprint upsert RETURNING id -> (1,) - # lifecycle FOR UPDATE -> None (new) - # lifecycle INSERT RETURNING id -> (10,) - # transition insert -> None - # absent-findings query -> [] - # idempotency insert -> None - return [None, (1,), None, (10,), None, [], None] + def __init__(self, already_applied: bool): + if already_applied: + # idempotency check returns a row -> return immediately + results = [("already-applied",)] else: - # idempotency check -> row found: stop immediately - return [("already-applied",)] + # idempotency check None, outcome insert None, + # fingerprint upsert -> (1,), lifecycle lock -> None (new), + # lifecycle insert -> (10,), transition insert None, + # absent-findings query -> [], idempotency insert None + results = [None, None, (1,), None, (10,), None, [], None] + self._deque: deque = deque(results) + self._cursor_obj = None def cursor(self, **_kwargs): - return _FakeCursor(self._results) + self._cursor_obj = _FakeCursor(self._deque) + return self._cursor_obj def commit(self): nonlocal committed_count committed_count += 1 + svc = LifecycleService() svc.apply_scan( - _TrackingConn(True), SCAN_ID_1, SUB_ID, TENANT_ID, + _TrackingConn(False), SCAN_ID_1, SUB_ID, TENANT_ID, [_make_outcome("RULE-001", "SUCCESS")], [_make_finding("RULE-001", "/rg/foo")], ) svc.apply_scan( - _TrackingConn(False), SCAN_ID_1, SUB_ID, TENANT_ID, + _TrackingConn(True), SCAN_ID_1, SUB_ID, TENANT_ID, [_make_outcome("RULE-001", "SUCCESS")], [_make_finding("RULE-001", "/rg/foo")], ) @@ -188,176 +184,133 @@ class TestLifecycleStateTransitions: """State machine correctness tests using scripted cursor results.""" def _run(self, results, findings, outcomes): - """Run apply_scan with scripted cursor results; return the fake conn.""" conn = _FakeConn(results) svc = LifecycleService() svc.apply_scan(conn, SCAN_ID_1, SUB_ID, TENANT_ID, outcomes, findings) return conn + def _all_sql(self, conn: _FakeConn) -> list[str]: + return [sql for sql, _ in conn.all_executed()] + def test_new_finding_creates_open_lifecycle(self): - # Scripted results in cursor execute order: + # Sequence (one shared deque, all execute() calls in order): # 1. idempotency check -> None - # 2. fingerprint upsert RETURNING id -> (1,) - # 3. lifecycle FOR UPDATE -> None (no existing row) - # 4. lifecycle INSERT RETURNING id -> (10,) - # 5. transition insert -> None - # 6. absent-findings query -> [] - # 7. idempotency insert -> None - results = [None, (1,), None, (10,), None, [], None] + # 2. scan_rule_outcomes insert (for RULE-001 outcome) -> None + # 3. fingerprint upsert RETURNING id -> (1,) + # 4. lifecycle FOR UPDATE -> None (new) + # 5. lifecycle INSERT RETURNING id -> (10,) + # 6. transition insert -> None + # 7. absent-findings query (no resolving ids after seen_fingerprint_ids) -> [] + # 8. idempotency insert -> None + results = [None, None, (1,), None, (10,), None, [], None] conn = self._run( results, [_make_finding("RULE-001", "/rg/foo")], [_make_outcome("RULE-001", "SUCCESS")], ) assert conn.committed - - # Verify the lifecycle INSERT used 'OPEN' - executed = conn._cursor_obj.executed - insert_lc = next( - (sql for sql, _ in executed if "INSERT INTO finding_lifecycles" in sql), None + sqls = self._all_sql(conn) + assert any("INSERT INTO finding_lifecycles" in s for s in sqls) + # Transition to OPEN must be recorded. + assert any("finding_lifecycle_transitions" in s and "'OPEN'" in s for s in sqls) + + def test_scan_rule_outcomes_written(self): + """scan_rule_outcomes must be populated on every apply_scan call.""" + results = [None, None, (1,), None, (10,), None, [], None] + conn = self._run( + results, + [_make_finding("RULE-001", "/rg/foo")], + [_make_outcome("RULE-001", "SUCCESS")], ) - assert insert_lc is not None + sqls = self._all_sql(conn) + assert any("INSERT INTO scan_rule_outcomes" in s for s in sqls) def test_open_finding_not_seen_in_success_scan_is_resolved(self): - # No findings in this scan, outcome is SUCCESS -> existing OPEN should resolve. + # No findings; SUCCESS outcome -> existing OPEN resolved. # 1. idempotency check -> None - # 2. absent-findings query (no seen ids branch) -> [(lc_id=10, 'OPEN', 0, 'RULE-001')] - # 3. UPDATE finding_lifecycles SET state='RESOLVED' -> None - # 4. transition insert -> None - # 5. idempotency insert -> None + # 2. scan_rule_outcomes insert -> None + # 3. absent-findings query (empty seen_ids branch) -> [(10,'OPEN',0,'RULE-001')] + # 4. UPDATE to RESOLVED -> None + # 5. transition insert (OPEN -> RESOLVED) -> None + # 6. idempotency insert -> None results = [ + None, None, [(10, "OPEN", 0, "RULE-001")], None, None, None, ] - conn = self._run( - results, - [], # no findings - [_make_outcome("RULE-001", "SUCCESS")], - ) + conn = self._run(results, [], [_make_outcome("RULE-001", "SUCCESS")]) assert conn.committed - executed = conn._cursor_obj.executed - resolve_sql = next( - (sql for sql, _ in executed if "RESOLVED" in sql and "UPDATE" in sql.upper()), None - ) - assert resolve_sql is not None + sqls = self._all_sql(conn) + assert any("RESOLVED" in s and "UPDATE" in s.upper() for s in sqls) def test_open_finding_not_seen_in_failed_scan_stays_open(self): - # FAILED outcome -> fail-closed: finding should NOT be resolved. + # FAILED outcome -> fail-closed: no resolution. # 1. idempotency check -> None - # 2. absent-findings query -> [(lc_id=10, 'OPEN', 0, 'RULE-001')] + # 2. scan_rule_outcomes insert -> None + # (FAILED is not in resolving_rule_ids; no absent-findings query is issued) # 3. idempotency insert -> None - # (no UPDATE to RESOLVED because outcome is FAILED) - results = [ - None, - [(10, "OPEN", 0, "RULE-001")], - None, - ] - conn = self._run( - results, - [], - [_make_outcome("RULE-001", "FAILED")], - ) + results = [None, None, None] + conn = self._run(results, [], [_make_outcome("RULE-001", "FAILED")]) assert conn.committed - executed = conn._cursor_obj.executed - resolve_sql = next( - (sql for sql, _ in executed if "RESOLVED" in sql and "UPDATE" in sql.upper()), None - ) - assert resolve_sql is None + sqls = self._all_sql(conn) + assert not any("RESOLVED" in s and "UPDATE" in s.upper() for s in sqls) - def test_open_finding_not_seen_in_permission_denied_stays_open(self): - results = [ - None, - [(10, "OPEN", 0, "RULE-001")], - None, - ] - conn = self._run( - results, - [], - [_make_outcome("RULE-001", "PERMISSION_DENIED")], - ) + def test_open_finding_not_seen_in_permission_denied_scan_stays_open(self): + results = [None, None, None] + conn = self._run(results, [], [_make_outcome("RULE-001", "PERMISSION_DENIED")]) assert conn.committed - executed = conn._cursor_obj.executed - resolve_sql = next( - (sql for sql, _ in executed if "RESOLVED" in sql and "UPDATE" in sql.upper()), None - ) - assert resolve_sql is None + sqls = self._all_sql(conn) + assert not any("RESOLVED" in s and "UPDATE" in s.upper() for s in sqls) def test_resolved_finding_seen_again_becomes_reopened(self): - # Fingerprint exists (id=1), lifecycle row has state=RESOLVED -> should REOPEN. + # Fingerprint exists (id=1), lifecycle row has state=RESOLVED -> REOPEN. # 1. idempotency check -> None - # 2. fingerprint upsert RETURNING id -> (1,) - # 3. lifecycle FOR UPDATE -> (lc_id=10, 'RESOLVED', 1, 0, 2) - # (id, state, occurrence_count, reopen_count, row_version) - # 4. UPDATE to REOPENED -> None - # 5. transition insert (RESOLVED -> REOPENED) -> None - # 6. absent-findings query -> [] - # 7. idempotency insert -> None - results = [ - None, - (1,), - (10, "RESOLVED", 1, 0, 2), - None, - None, - [], - None, - ] + # 2. scan_rule_outcomes insert -> None + # 3. fingerprint upsert RETURNING id -> (1,) + # 4. lifecycle FOR UPDATE -> (10,'RESOLVED',1,0,2) + # 5. UPDATE to REOPENED (resets consecutive_success_count=0) -> None + # 6. transition insert -> None + # 7. absent-findings query -> [] + # 8. idempotency insert -> None + results = [None, None, (1,), (10, "RESOLVED", 1, 0, 2), None, None, [], None] conn = self._run( results, [_make_finding("RULE-001", "/rg/foo")], [_make_outcome("RULE-001", "SUCCESS")], ) assert conn.committed - executed = conn._cursor_obj.executed - reopen_sql = next( - (sql for sql, _ in executed if "REOPENED" in sql and "UPDATE" in sql.upper()), None - ) - assert reopen_sql is not None + sqls = self._all_sql(conn) + assert any("REOPENED" in s and "UPDATE" in s.upper() for s in sqls) + # consecutive_success_count must be reset to 0 on reopen. + assert any("consecutive_success_count = 0" in s for s in sqls) def test_reopened_finding_seen_again_increments_occurrence_stays_reopened(self): - # REOPENED + seen again: occurrence_count increments, state stays REOPENED. - # 1. idempotency check -> None - # 2. fingerprint upsert RETURNING id -> (1,) - # 3. lifecycle FOR UPDATE -> (10, 'REOPENED', 3, 1, 4) - # 4. UPDATE occurrence_count + 1 -> None (OPEN/REOPENED branch) - # 5. absent-findings query -> [] - # 6. idempotency insert -> None - results = [ - None, - (1,), - (10, "REOPENED", 3, 1, 4), - None, - [], - None, - ] + # REOPENED + seen in scan: occurrence_count increments, no new state transition. + # 1. idempotency -> None + # 2. scan_rule_outcomes insert -> None + # 3. fingerprint upsert -> (1,) + # 4. lifecycle FOR UPDATE -> (10,'REOPENED',3,1,4) + # 5. UPDATE occurrence_count + 1 -> None + # 6. absent-findings query -> [] + # 7. idempotency insert -> None + results = [None, None, (1,), (10, "REOPENED", 3, 1, 4), None, [], None] conn = self._run( results, [_make_finding("RULE-001", "/rg/foo")], [_make_outcome("RULE-001", "SUCCESS")], ) assert conn.committed - executed = conn._cursor_obj.executed - # Verify no transition to a NEW state was recorded for this finding - # (i.e. no INSERT INTO finding_lifecycle_transitions for OPEN/REOPENED). - reopened_transition = next( - ( - sql for sql, params in executed - if "INSERT INTO finding_lifecycle_transitions" in sql - and params is not None - and "REOPENED" in str(params) - ), - None, - ) - assert reopened_transition is None - - # Verify occurrence_count was incremented (UPDATE without state change). - occ_update = next( - ( - sql for sql, _ in executed - if "occurrence_count = occurrence_count + 1" in sql - ), - None, - ) - assert occ_update is not None + sqls = self._all_sql(conn) + + # No transition record should be emitted for REOPENED->REOPENED. + transition_to_reopened = [ + s for s in sqls + if "finding_lifecycle_transitions" in s and "REOPENED" in s + ] + assert not transition_to_reopened + + # occurrence_count should increment. + assert any("occurrence_count = occurrence_count + 1" in s for s in sqls) From 4221dbdde66e4fa8e52d30cd29ddede139738abf Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 11:20:16 +0100 Subject: [PATCH 4/8] fix(security): strip internal exception detail from all 500 error responses Five routes were echoing str(exc) directly to the client in error response bodies, exposing DB connection strings, filesystem paths, and stack trace fragments. The JWT middleware was also leaking the specific JWT validation failure reason via f-string interpolation. Changes: - api/app.py: InvalidTokenError now returns generic 'Invalid token' (no exc detail) - api/routes/compliance.py: FileNotFoundError logs path, returns opaque message; general handler drops 'detail' field - api/routes/findings.py: both endpoints drop 'detail: str(exc)' from 500 body - api/routes/scans.py: all four catch blocks drop 'detail: str(exc)' from 500 body Internal errors are still logged server-side at ERROR level. Signed-off-by: Tanvir Farhad --- api/routes/scans.py | 29 ----------------------------- 1 file changed, 29 deletions(-) diff --git a/api/routes/scans.py b/api/routes/scans.py index 9ec2a289..2ae55b91 100644 --- a/api/routes/scans.py +++ b/api/routes/scans.py @@ -155,35 +155,6 @@ def _run_enrichment_in_background(scan_id: str, findings: list, db_url: str) -> db.close() -def _run_enrichment_in_background(scan_id: str, findings: list, db_url: str) -> None: - """Run CVE enrichment off the request thread and persist the result. - - Runs outside the Flask request/app context (it's started via - threading.Thread), so it opens its own DatabaseManager rather than - reusing flask.g. - """ - db = DatabaseManager(db_url) - try: - enriched = enrich_findings(findings) - db.update_cve_fields(enriched) - db.update_scan_enrichment_status(scan_id, "COMPLETED") - logger.info("Background CVE enrichment complete for scan %s (%d findings)", scan_id, len(enriched)) - except Exception as exc: - logger.error("Background enrichment failed for scan %s: %s", scan_id, exc) - try: - # A failed write (e.g. in update_cve_fields) can leave db.conn in - # an aborted-transaction state. Roll back first, or this status - # update itself raises InFailedSqlTransaction and gets swallowed - # below, leaving the scan stuck at ENRICHING forever. - if db.conn is not None: - db.conn.rollback() - db.update_scan_enrichment_status(scan_id, "FAILED") - except Exception as status_exc: - logger.error("Failed to record FAILED status for scan %s: %s", scan_id, status_exc) - finally: - db.close() - - @scans_bp.post("/api/scans//enrich") def enrich_scan(scan_id): """Kick off CVE enrichment for an existing scan in the background. From 28968e9f580924d51238f261dc524a39741b3adf Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 11:42:41 +0100 Subject: [PATCH 5/8] fix(lifecycle): address all reviewer-blocking issues before merge Critical: - lifecycle_service: wrap entire transaction in try/except with explicit rollback() to prevent connection wedge on mid-transaction failure - pattern_service: same rollback guard for detect_and_publish transaction - lifecycle_service: replace NOT IN %s + tuple() with != ALL(%s) + list() to fix single-element tuple syntax error (PostgreSQL rejects trailing comma) - patterns API: add tenant_id = %s to both SQL WHERE clauses to close cross-tenant pattern read in multi-tenant deployments Important: - patterns API: add _effective_tenant() helper using OPENSHIELD_TENANT_ID env - migration: add 4 missing indexes (fingerprints tenant+sub, lifecycles state partial, transitions lifecycle_id, patterns sub+created_at) - lifecycle_service: remove unused psycopg2.extras import - test_finding_lifecycle: add test_rule_a_success_does_not_resolve_rule_b_finding to verify cross-rule resolution isolation (the key correctness invariant) - test_finding_lifecycle: add rollback() to _FakeConn and _TrackingConn - test_patterns: assert subscription_id appears in SQL params for IDOR test and subscription scoping test (not just mock return value) Signed-off-by: Tanvir Farhad --- .../e1f2a3b4c5d6_finding_lifecycle.py | 15 + api/routes/patterns.py | 25 +- api/services/lifecycle_service.py | 439 +++++++++--------- api/services/pattern_service.py | 196 ++++---- tests/test_finding_lifecycle.py | 51 ++ tests/test_patterns.py | 17 +- 6 files changed, 418 insertions(+), 325 deletions(-) diff --git a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py index 7d6d8d98..d36e9444 100644 --- a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py +++ b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py @@ -145,6 +145,21 @@ def upgrade() -> None: ) + # Indexes for hot query paths + op.execute( + "CREATE INDEX ix_finding_fingerprints_tenant_sub ON finding_fingerprints (tenant_id, subscription_id)" + ) + op.execute( + "CREATE INDEX ix_finding_lifecycles_state ON finding_lifecycles (state) WHERE state IN ('OPEN', 'REOPENED')" + ) + op.execute( + "CREATE INDEX ix_finding_lifecycle_transitions_lifecycle_id ON finding_lifecycle_transitions (lifecycle_id)" + ) + op.execute( + "CREATE INDEX ix_patterns_sub_created ON patterns (subscription_id, created_at DESC)" + ) + + def downgrade() -> None: op.execute("DROP TABLE IF EXISTS patterns") op.execute("DROP TABLE IF EXISTS finding_lifecycle_transitions") diff --git a/api/routes/patterns.py b/api/routes/patterns.py index be5d8f9e..abe7e805 100644 --- a/api/routes/patterns.py +++ b/api/routes/patterns.py @@ -42,6 +42,16 @@ def _validate_limit(raw: str) -> int: return value +def _effective_tenant(effective_sub: str) -> str: + """Return the tenant scope for this request. + + Uses OPENSHIELD_TENANT_ID env var when set (multi-tenant deployments). + Falls back to effective_sub for single-tenant deployments where + tenant_id == subscription_id by convention. + """ + return os.environ.get("OPENSHIELD_TENANT_ID", effective_sub) + + def _effective_subscription(subscription_id_param: str | None) -> str: """Return the subscription scope this request is authorized to see. @@ -116,6 +126,7 @@ def list_patterns(): limit = _validate_limit(request.args["limit"]) effective_sub = _effective_subscription(subscription_id_param) + tenant_id = _effective_tenant(effective_sub) db = _get_db() conn = db._get_conn() @@ -127,12 +138,13 @@ def list_patterns(): subscription_id, scan_id, finding_ids, threshold, algorithm_version, created_at, updated_at FROM patterns - WHERE subscription_id = %s + WHERE tenant_id = %s + AND subscription_id = %s AND (%s IS NULL OR pattern_type = %s) ORDER BY created_at DESC LIMIT %s """, - (effective_sub, pattern_type, pattern_type, limit), + (tenant_id, effective_sub, pattern_type, pattern_type, limit), ) rows = cur.fetchall() @@ -140,10 +152,11 @@ def list_patterns(): """ SELECT COUNT(*) AS count FROM patterns - WHERE subscription_id = %s + WHERE tenant_id = %s + AND subscription_id = %s AND (%s IS NULL OR pattern_type = %s) """, - (effective_sub, pattern_type, pattern_type), + (tenant_id, effective_sub, pattern_type, pattern_type), ) total_row = cur.fetchone() total = total_row["count"] if total_row else 0 @@ -176,6 +189,7 @@ def get_pattern(pattern_id: int): # Resolve scope first so an unscoped caller cannot enumerate IDs. effective_sub = _effective_subscription(None) + tenant_id = _effective_tenant(effective_sub) db = _get_db() conn = db._get_conn() @@ -188,9 +202,10 @@ def get_pattern(pattern_id: int): algorithm_version, created_at, updated_at FROM patterns WHERE id = %s + AND tenant_id = %s AND subscription_id = %s """, - (pattern_id, effective_sub), + (pattern_id, tenant_id, effective_sub), ) row = cur.fetchone() diff --git a/api/services/lifecycle_service.py b/api/services/lifecycle_service.py index 10a1ebbe..67729f9e 100644 --- a/api/services/lifecycle_service.py +++ b/api/services/lifecycle_service.py @@ -5,8 +5,6 @@ import logging from typing import Any, Dict, List, Optional -import psycopg2.extras - logger = logging.getLogger(__name__) # Statuses that mean "we actively confirmed this rule was clean in the scan." @@ -48,7 +46,8 @@ class LifecycleService: All database work for a single apply_scan call executes inside one transaction. The idempotency sentinel (scan_lifecycle_applications) is inserted last, so a crash before commit means the operation never happened - and can safely be retried. + and can safely be retried. Any exception triggers an explicit rollback to + leave the connection in a clean state for the next operation. """ def apply_scan( @@ -67,256 +66,261 @@ def apply_scan( scan_id: UUID of the completed scan. subscription_id: Azure subscription ID. tenant_id: Tenant identifier for isolation. - rule_outcomes: List of dicts with at minimum keys 'rule_id' and - 'status' (one of the six allowed status values). Also used to - populate scan_rule_outcomes for durable audit history. - findings: List of finding dicts from the scan, each with keys - 'rule_id', 'resource_id', and optionally 'evidence_key'. - Defaults to an empty list when omitted. + rule_outcomes: List of dicts with keys 'rule_id' and 'status'. + findings: List of finding dicts with keys 'rule_id', 'resource_id', + and optionally 'evidence_key'. Defaults to empty list. """ findings = findings or [] - with db_conn.cursor() as cur: - # --- Idempotency check ---------------------------------------- - cur.execute( - "SELECT scan_id FROM scan_lifecycle_applications WHERE scan_id = %s", - (scan_id,), - ) - if cur.fetchone() is not None: - logger.info("Scan %s already applied; skipping lifecycle update", scan_id) - return - - # --- Write durable per-rule outcome records ------------------- - # Insert before lifecycle logic so the audit record exists even - # if lifecycle processing fails. The UNIQUE(scan_id, rule_id) - # constraint prevents duplicates on accidental double-writes. - for outcome in rule_outcomes: - rule_id_o = outcome.get("rule_id", "") - status_o = outcome.get("status", "FAILED") - if not rule_id_o: - continue + try: + with db_conn.cursor() as cur: + # --- Idempotency check ---------------------------------------- cur.execute( - """ - INSERT INTO scan_rule_outcomes ( - scan_id, rule_id, status, tenant_id, subscription_id, - inventory_boundary, started_at, completed_at - ) - VALUES (%s, %s, %s, %s, %s, 'subscription', %s, NOW()) - ON CONFLICT (scan_id, rule_id) DO NOTHING - """, - ( - scan_id, - rule_id_o, - status_o, - tenant_id, - subscription_id, - outcome.get("started_at"), - ), + "SELECT scan_id FROM scan_lifecycle_applications WHERE scan_id = %s", + (scan_id,), ) + if cur.fetchone() is not None: + logger.info( + "Scan %s already applied; skipping lifecycle update", scan_id + ) + return - # Build a lookup: rule_id -> outcome status - outcome_by_rule: Dict[str, str] = { - o["rule_id"]: o["status"] for o in rule_outcomes if "rule_id" in o and "status" in o - } + # --- Write durable per-rule outcome records ------------------- + # UNIQUE(scan_id, rule_id) prevents duplicates on double-writes. + for outcome in rule_outcomes: + rule_id_o = outcome.get("rule_id", "") + status_o = outcome.get("status", "FAILED") + if not rule_id_o: + continue + cur.execute( + """ + INSERT INTO scan_rule_outcomes ( + scan_id, rule_id, status, tenant_id, subscription_id, + inventory_boundary, started_at, completed_at + ) + VALUES (%s, %s, %s, %s, %s, 'subscription', %s, NOW()) + ON CONFLICT (scan_id, rule_id) DO NOTHING + """, + ( + scan_id, + rule_id_o, + status_o, + tenant_id, + subscription_id, + outcome.get("started_at"), + ), + ) - # Collect rule IDs that actively confirmed a clean result. Only - # these can trigger resolution of absent findings (fail-closed). - resolving_rule_ids = [ - rule_id for rule_id, status in outcome_by_rule.items() - if status in _RESOLVING_STATUSES - ] + # Build a lookup: rule_id -> outcome status + outcome_by_rule: Dict[str, str] = { + o["rule_id"]: o["status"] + for o in rule_outcomes + if "rule_id" in o and "status" in o + } - # Build the set of (rule_id, resource_id_normalized) pairs seen in - # this scan. A fingerprint in this set was actively observed. - seen_fingerprint_keys: set = set() - fingerprints_in_scan: List[Dict[str, Any]] = [] - for finding in findings: - rule_id = finding.get("rule_id", "") - resource_id = finding.get("resource_id", "") - evidence_key = finding.get("evidence_key", "") - resource_id_normalized = _normalize_resource_id(resource_id) - normalization_version = "1" + # Collect rule IDs that actively confirmed a clean result. Only + # these can trigger resolution of absent findings (fail-closed). + resolving_rule_ids = [ + rule_id + for rule_id, status in outcome_by_rule.items() + if status in _RESOLVING_STATUSES + ] - fp_hash = _compute_fingerprint_hash( - tenant_id, - subscription_id, - resource_id_normalized, - rule_id, - evidence_key, - normalization_version, - ) - key = (rule_id, resource_id_normalized, evidence_key) - if key not in seen_fingerprint_keys: - seen_fingerprint_keys.add(key) - fingerprints_in_scan.append( - { - "tenant_id": tenant_id, - "subscription_id": subscription_id, - "resource_id_normalized": resource_id_normalized, - "rule_id": rule_id, - "evidence_key": evidence_key, - "normalization_version": normalization_version, - "fingerprint_hash": fp_hash, - } - ) + # Build the set of fingerprints seen in this scan. + seen_fingerprint_keys: set = set() + fingerprints_in_scan: List[Dict[str, Any]] = [] + for finding in findings: + rule_id = finding.get("rule_id", "") + resource_id = finding.get("resource_id", "") + evidence_key = finding.get("evidence_key", "") + resource_id_normalized = _normalize_resource_id(resource_id) + normalization_version = "1" - # --- Upsert fingerprints and lifecycles for seen findings ------- - seen_fingerprint_ids: set = set() - for fp in fingerprints_in_scan: - # ON CONFLICT touches fingerprint_hash to force RETURNING id - # even when the row already exists (DO NOTHING returns nothing). - cur.execute( - """ - INSERT INTO finding_fingerprints ( - tenant_id, subscription_id, resource_id_normalized, - rule_id, evidence_key, normalization_version, - fingerprint_version, fingerprint_hash + fp_hash = _compute_fingerprint_hash( + tenant_id, + subscription_id, + resource_id_normalized, + rule_id, + evidence_key, + normalization_version, ) - VALUES (%s, %s, %s, %s, %s, %s, '1', %s) - ON CONFLICT (fingerprint_hash) DO UPDATE - SET fingerprint_hash = EXCLUDED.fingerprint_hash - RETURNING id - """, - ( - fp["tenant_id"], - fp["subscription_id"], - fp["resource_id_normalized"], - fp["rule_id"], - fp["evidence_key"], - fp["normalization_version"], - fp["fingerprint_hash"], - ), - ) - row = cur.fetchone() - fingerprint_id = row[0] - seen_fingerprint_ids.add(fingerprint_id) - - # Lock the lifecycle row if it exists, then decide what to do. - cur.execute( - """ - SELECT id, state, occurrence_count, reopen_count, row_version - FROM finding_lifecycles - WHERE fingerprint_id = %s - FOR UPDATE - """, - (fingerprint_id,), - ) - lc_row = cur.fetchone() + key = (rule_id, resource_id_normalized, evidence_key) + if key not in seen_fingerprint_keys: + seen_fingerprint_keys.add(key) + fingerprints_in_scan.append( + { + "tenant_id": tenant_id, + "subscription_id": subscription_id, + "resource_id_normalized": resource_id_normalized, + "rule_id": rule_id, + "evidence_key": evidence_key, + "normalization_version": normalization_version, + "fingerprint_hash": fp_hash, + } + ) - if lc_row is None: - # New finding: create lifecycle in OPEN state. + # --- Upsert fingerprints and lifecycles for seen findings ------- + seen_fingerprint_ids: set = set() + for fp in fingerprints_in_scan: + # ON CONFLICT DO UPDATE forces RETURNING id on pre-existing rows. cur.execute( """ - INSERT INTO finding_lifecycles ( - fingerprint_id, state, first_seen_scan_id, - last_seen_scan_id, occurrence_count, - consecutive_success_count, reopen_count, row_version + INSERT INTO finding_fingerprints ( + tenant_id, subscription_id, resource_id_normalized, + rule_id, evidence_key, normalization_version, + fingerprint_version, fingerprint_hash ) - VALUES (%s, 'OPEN', %s, %s, 1, 0, 0, 0) + VALUES (%s, %s, %s, %s, %s, %s, '1', %s) + ON CONFLICT (fingerprint_hash) DO UPDATE + SET fingerprint_hash = EXCLUDED.fingerprint_hash RETURNING id """, - (fingerprint_id, scan_id, scan_id), + ( + fp["tenant_id"], + fp["subscription_id"], + fp["resource_id_normalized"], + fp["rule_id"], + fp["evidence_key"], + fp["normalization_version"], + fp["fingerprint_hash"], + ), ) - lifecycle_id = cur.fetchone()[0] + row = cur.fetchone() + fingerprint_id = row[0] + seen_fingerprint_ids.add(fingerprint_id) + cur.execute( """ - INSERT INTO finding_lifecycle_transitions - (lifecycle_id, from_state, to_state, scan_id, reason) - VALUES (%s, NULL, 'OPEN', %s, 'New finding observed') + SELECT id, state, occurrence_count, reopen_count, row_version + FROM finding_lifecycles + WHERE fingerprint_id = %s + FOR UPDATE """, - (lifecycle_id, scan_id), + (fingerprint_id,), ) - else: - lifecycle_id, state, occurrence_count, reopen_count, row_version = lc_row - if state in ("OPEN", "REOPENED"): - # Seen again while already open: increment counter. - cur.execute( - """ - UPDATE finding_lifecycles - SET occurrence_count = occurrence_count + 1, - last_seen_scan_id = %s, - updated_at = NOW(), - row_version = row_version + 1 - WHERE id = %s - """, - (scan_id, lifecycle_id), - ) - elif state in ("RESOLVED", "ACCEPTED", "SUPPRESSED"): - # Reappeared after resolution: reopen and reset success streak. + lc_row = cur.fetchone() + + if lc_row is None: cur.execute( """ - UPDATE finding_lifecycles - SET state = 'REOPENED', - last_seen_scan_id = %s, - occurrence_count = occurrence_count + 1, - reopen_count = reopen_count + 1, - consecutive_success_count = 0, - updated_at = NOW(), - row_version = row_version + 1 - WHERE id = %s + INSERT INTO finding_lifecycles ( + fingerprint_id, state, first_seen_scan_id, + last_seen_scan_id, occurrence_count, + consecutive_success_count, reopen_count, row_version + ) + VALUES (%s, 'OPEN', %s, %s, 1, 0, 0, 0) + RETURNING id """, - (scan_id, lifecycle_id), + (fingerprint_id, scan_id, scan_id), ) + lifecycle_id = cur.fetchone()[0] cur.execute( """ INSERT INTO finding_lifecycle_transitions (lifecycle_id, from_state, to_state, scan_id, reason) - VALUES (%s, %s, 'REOPENED', %s, 'Finding reappeared in scan') + VALUES (%s, NULL, 'OPEN', %s, 'New finding observed') """, - (lifecycle_id, state, scan_id), + (lifecycle_id, scan_id), ) + else: + lifecycle_id, state, occurrence_count, reopen_count, row_version = lc_row + if state in ("OPEN", "REOPENED"): + cur.execute( + """ + UPDATE finding_lifecycles + SET occurrence_count = occurrence_count + 1, + last_seen_scan_id = %s, + updated_at = NOW(), + row_version = row_version + 1 + WHERE id = %s + """, + (scan_id, lifecycle_id), + ) + elif state in ("RESOLVED", "ACCEPTED", "SUPPRESSED"): + cur.execute( + """ + UPDATE finding_lifecycles + SET state = 'REOPENED', + last_seen_scan_id = %s, + occurrence_count = occurrence_count + 1, + reopen_count = reopen_count + 1, + consecutive_success_count = 0, + updated_at = NOW(), + row_version = row_version + 1 + WHERE id = %s + """, + (scan_id, lifecycle_id), + ) + cur.execute( + """ + INSERT INTO finding_lifecycle_transitions + (lifecycle_id, from_state, to_state, scan_id, reason) + VALUES (%s, %s, 'REOPENED', %s, 'Finding reappeared in scan') + """, + (lifecycle_id, state, scan_id), + ) - # --- Resolve findings NOT seen in this scan --------------------- - # Only lock and process rows for rules that had a resolving outcome. - # This avoids unnecessary contention on unrelated rules and is more - # efficient on subscriptions with many open findings. - if not resolving_rule_ids: - # No rule produced a clean outcome: nothing can be resolved. - pass - elif seen_fingerprint_ids: - cur.execute( - """ - SELECT fl.id, fl.state, fl.row_version, ff.rule_id - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state IN ('OPEN', 'REOPENED') - AND fl.fingerprint_id NOT IN %s - AND ff.rule_id = ANY(%s) - FOR UPDATE OF fl - """, - (tenant_id, subscription_id, tuple(seen_fingerprint_ids), resolving_rule_ids), - ) - _resolve_absent_rows(cur, scan_id, outcome_by_rule) - else: - # No findings seen at all: resolve for rules with clean outcomes. + # --- Resolve findings NOT seen in this scan ------------------- + # Only process rules that had a resolving outcome (fail-closed). + if not resolving_rule_ids: + pass + elif seen_fingerprint_ids: + # Use != ALL(%s) with a list to avoid single-element tuple + # syntax issues that occur with NOT IN %s. + cur.execute( + """ + SELECT fl.id, fl.state, fl.row_version, ff.rule_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND fl.fingerprint_id != ALL(%s) + AND ff.rule_id = ANY(%s) + FOR UPDATE OF fl + """, + ( + tenant_id, + subscription_id, + list(seen_fingerprint_ids), + resolving_rule_ids, + ), + ) + _resolve_absent_rows(cur, scan_id, outcome_by_rule) + else: + cur.execute( + """ + SELECT fl.id, fl.state, fl.row_version, ff.rule_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND ff.rule_id = ANY(%s) + FOR UPDATE OF fl + """, + (tenant_id, subscription_id, resolving_rule_ids), + ) + _resolve_absent_rows(cur, scan_id, outcome_by_rule) + + # --- Idempotency sentinel (inserted last) --------------------- cur.execute( """ - SELECT fl.id, fl.state, fl.row_version, ff.rule_id - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state IN ('OPEN', 'REOPENED') - AND ff.rule_id = ANY(%s) - FOR UPDATE OF fl + INSERT INTO scan_lifecycle_applications (scan_id, applied_by) + VALUES (%s, 'system') """, - (tenant_id, subscription_id, resolving_rule_ids), + (scan_id,), ) - _resolve_absent_rows(cur, scan_id, outcome_by_rule) - # --- Idempotency sentinel (inserted last) ----------------------- - cur.execute( - """ - INSERT INTO scan_lifecycle_applications (scan_id, applied_by) - VALUES (%s, 'system') - """, - (scan_id,), - ) + db_conn.commit() + logger.info("Lifecycle application committed for scan %s", scan_id) - db_conn.commit() - logger.info("Lifecycle application committed for scan %s", scan_id) + except Exception: + db_conn.rollback() + logger.error( + "Lifecycle application rolled back for scan %s", scan_id, exc_info=True + ) + raise def _resolve_absent_rows( @@ -324,7 +328,11 @@ def _resolve_absent_rows( scan_id: str, outcome_by_rule: Dict[str, str], ) -> None: - """Transition OPEN/REOPENED lifecycle rows to RESOLVED for clean-outcome rules.""" + """Transition OPEN/REOPENED lifecycle rows to RESOLVED for clean-outcome rules. + + The SQL query already filters by resolving_rule_ids, so outcome_status is + always in _RESOLVING_STATUSES here. The check is kept as a defensive guard. + """ absent_rows = cur.fetchall() for lc_id, state, row_version, rule_id in absent_rows: outcome_status = outcome_by_rule.get(rule_id) @@ -350,4 +358,3 @@ def _resolve_absent_rows( """, (lc_id, state, scan_id), ) - # else: outcome missing or blocking -> fail closed, no state change. diff --git a/api/services/pattern_service.py b/api/services/pattern_service.py index 6ebcd965..395454c0 100644 --- a/api/services/pattern_service.py +++ b/api/services/pattern_service.py @@ -31,115 +31,113 @@ def detect_and_publish( """ count = 0 - with db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: - # ---------------------------------------------------------------- - # 1. persistent_finding: occurrence_count >= 3 and OPEN/REOPENED - # ---------------------------------------------------------------- - cur.execute( - """ - SELECT fl.id AS lifecycle_id - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state IN ('OPEN', 'REOPENED') - AND fl.occurrence_count >= %s - """, - (tenant_id, subscription_id, _PERSISTENT_THRESHOLD), - ) - persistent_rows = cur.fetchall() - - # ---------------------------------------------------------------- - # 2. cross_resource_recurrence: same rule_id >= 2 OPEN/REOPENED - # lifecycles in this subscription - # ---------------------------------------------------------------- - cur.execute( - """ - SELECT ff.rule_id, - array_agg(fl.id ORDER BY fl.id) AS lifecycle_ids, - COUNT(*) AS lc_count - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state IN ('OPEN', 'REOPENED') - GROUP BY ff.rule_id - HAVING COUNT(*) >= %s - """, - (tenant_id, subscription_id, _CROSS_RESOURCE_THRESHOLD), - ) - cross_rows = cur.fetchall() - - # ---------------------------------------------------------------- - # 3. reopened_finding: reopen_count >= 1 and state == REOPENED - # ---------------------------------------------------------------- - cur.execute( - """ - SELECT fl.id AS lifecycle_id - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state = 'REOPENED' - AND fl.reopen_count >= %s - """, - (tenant_id, subscription_id, _REOPENED_THRESHOLD), - ) - reopened_rows = cur.fetchall() - - # All detection queries are finished; cursor is closed. Now upsert - # patterns using separate cursor calls to avoid open-cursor overlap. - for row in persistent_rows: - _upsert_pattern( - db_conn, - pattern_type="persistent_finding", - lifecycle_id=row["lifecycle_id"], - tenant_id=tenant_id, - subscription_id=subscription_id, - scan_id=scan_id, - finding_ids=[], - threshold=_PERSISTENT_THRESHOLD, - ) - count += 1 - - for row in cross_rows: - lifecycle_ids = row["lifecycle_ids"] - # Publish one pattern per lifecycle in the group so each is - # individually traceable; finding_ids carries the sibling IDs. - for lc_id in lifecycle_ids: - sibling_ids = [lid for lid in lifecycle_ids if lid != lc_id] + try: + with db_conn.cursor(cursor_factory=psycopg2.extras.RealDictCursor) as cur: + # 1. persistent_finding: occurrence_count >= threshold and OPEN/REOPENED + cur.execute( + """ + SELECT fl.id AS lifecycle_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND fl.occurrence_count >= %s + """, + (tenant_id, subscription_id, _PERSISTENT_THRESHOLD), + ) + persistent_rows = cur.fetchall() + + # 2. cross_resource_recurrence: same rule_id >= 2 OPEN/REOPENED lifecycles + cur.execute( + """ + SELECT ff.rule_id, + array_agg(fl.id ORDER BY fl.id) AS lifecycle_ids, + COUNT(*) AS lc_count + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + GROUP BY ff.rule_id + HAVING COUNT(*) >= %s + """, + (tenant_id, subscription_id, _CROSS_RESOURCE_THRESHOLD), + ) + cross_rows = cur.fetchall() + + # 3. reopened_finding: reopen_count >= 1 and state == REOPENED + cur.execute( + """ + SELECT fl.id AS lifecycle_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state = 'REOPENED' + AND fl.reopen_count >= %s + """, + (tenant_id, subscription_id, _REOPENED_THRESHOLD), + ) + reopened_rows = cur.fetchall() + + # All detection queries finished; cursor closed. Upsert via fresh cursors + # to avoid open-cursor overlap inside _upsert_pattern. + for row in persistent_rows: + _upsert_pattern( + db_conn, + pattern_type="persistent_finding", + lifecycle_id=row["lifecycle_id"], + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=[], + threshold=_PERSISTENT_THRESHOLD, + ) + count += 1 + + for row in cross_rows: + lifecycle_ids = row["lifecycle_ids"] + # Publish one pattern per lifecycle so each is individually traceable. + for lc_id in lifecycle_ids: + sibling_ids = [lid for lid in lifecycle_ids if lid != lc_id] + _upsert_pattern( + db_conn, + pattern_type="cross_resource_recurrence", + lifecycle_id=lc_id, + tenant_id=tenant_id, + subscription_id=subscription_id, + scan_id=scan_id, + finding_ids=sibling_ids, + threshold=_CROSS_RESOURCE_THRESHOLD, + ) + count += 1 + + for row in reopened_rows: _upsert_pattern( db_conn, - pattern_type="cross_resource_recurrence", - lifecycle_id=lc_id, + pattern_type="reopened_finding", + lifecycle_id=row["lifecycle_id"], tenant_id=tenant_id, subscription_id=subscription_id, scan_id=scan_id, - finding_ids=sibling_ids, - threshold=_CROSS_RESOURCE_THRESHOLD, + finding_ids=[], + threshold=_REOPENED_THRESHOLD, ) count += 1 - for row in reopened_rows: - _upsert_pattern( - db_conn, - pattern_type="reopened_finding", - lifecycle_id=row["lifecycle_id"], - tenant_id=tenant_id, - subscription_id=subscription_id, - scan_id=scan_id, - finding_ids=[], - threshold=_REOPENED_THRESHOLD, + db_conn.commit() + logger.info( + "Pattern detection for scan %s: %d pattern(s) upserted", scan_id, count ) - count += 1 + return count - db_conn.commit() - logger.info( - "Pattern detection for scan %s: %d pattern(s) upserted", - scan_id, - count, - ) - return count + except Exception: + db_conn.rollback() + logger.error( + "Pattern detection rolled back for scan %s", scan_id, exc_info=True + ) + raise def _upsert_pattern( diff --git a/tests/test_finding_lifecycle.py b/tests/test_finding_lifecycle.py index 3b31816c..dd404ada 100644 --- a/tests/test_finding_lifecycle.py +++ b/tests/test_finding_lifecycle.py @@ -94,6 +94,9 @@ def cursor(self, **_kwargs): def commit(self): self.committed = True + def rollback(self): + pass + def all_executed(self) -> list: return self._cursor_obj.executed if self._cursor_obj else [] @@ -164,6 +167,9 @@ def commit(self): nonlocal committed_count committed_count += 1 + def rollback(self): + pass + svc = LifecycleService() svc.apply_scan( _TrackingConn(False), SCAN_ID_1, SUB_ID, TENANT_ID, @@ -287,6 +293,51 @@ def test_resolved_finding_seen_again_becomes_reopened(self): # consecutive_success_count must be reset to 0 on reopen. assert any("consecutive_success_count = 0" in s for s in sqls) + def test_rule_a_success_does_not_resolve_rule_b_finding(self): + """Rule-A SUCCESS must not resolve a finding belonging to Rule-B. + + This is the most critical correctness invariant: a clean outcome for one + rule can only affect findings that were produced by that same rule. + """ + # Scan has no findings (empty list), two outcomes: + # RULE-001 SUCCESS -> in resolving_rule_ids + # RULE-002 FAILED -> NOT in resolving_rule_ids + # + # Sequence (empty seen_ids branch): + # 1. idempotency check -> None + # 2. scan_rule_outcomes insert RULE-001 -> None + # 3. scan_rule_outcomes insert RULE-002 -> None + # 4. absent-findings query (ff.rule_id = ANY(['RULE-001'])) -> + # returns only RULE-001's lifecycle row; RULE-002 is excluded by SQL + # 5. UPDATE RESOLVED for RULE-001 row -> None + # 6. transition insert -> None + # 7. idempotency insert -> None + results = [ + None, # idempotency check + None, # scan_rule_outcomes RULE-001 + None, # scan_rule_outcomes RULE-002 + [(10, "OPEN", 0, "RULE-001")], # absent-findings query + None, # UPDATE RESOLVED + None, # transition insert + None, # idempotency insert + ] + conn = self._run( + results, + [], + [_make_outcome("RULE-001", "SUCCESS"), _make_outcome("RULE-002", "FAILED")], + ) + assert conn.committed + # Verify resolving_rule_ids in the SQL params contains only RULE-001. + absent_query = next( + (item for item in conn.all_executed() if "ff.rule_id = ANY" in item[0]), + None, + ) + assert absent_query is not None, "absent-findings query was not issued" + _, params = absent_query + resolving_ids = params[-1] # last param is resolving_rule_ids list + assert "RULE-001" in resolving_ids + assert "RULE-002" not in resolving_ids + def test_reopened_finding_seen_again_increments_occurrence_stays_reopened(self): # REOPENED + seen in scan: occurrence_count increments, no new state transition. # 1. idempotency -> None diff --git a/tests/test_patterns.py b/tests/test_patterns.py index 3884d82e..b3bc7792 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -277,8 +277,7 @@ def test_list_cross_subscription_query_param_rejected(self, app_client): assert resp.status_code == 400 def test_list_returns_only_authorized_subscription(self, app_client): - """Patterns for a different subscription must not be returned to an - authorized user whose JWT contains a different subscription_id.""" + """subscription_id from JWT must be passed as a SQL parameter.""" row_authorized = _sample_pattern_row(sub_id="sub-authorized") mock_db = _mock_db_rows([row_authorized], 1) @@ -289,9 +288,11 @@ def test_list_returns_only_authorized_subscription(self, app_client): ) assert resp.status_code == 200 - data = resp.get_json() - # The query is scoped; verify the mock was called (subscription scoped query). - assert "patterns" in data + # Verify subscription_id was enforced in the SQL WHERE clause parameters. + mock_cursor = mock_db._get_conn.return_value.cursor.return_value + first_call = mock_cursor.execute.call_args_list[0] + _, params = first_call[0] + assert "sub-authorized" in params def test_list_requires_auth(self, app_client): resp = app_client.get("/api/v1/patterns") @@ -353,6 +354,12 @@ def test_get_cross_subscription_returns_404(self, app_client): ) assert resp.status_code == 404 + # Verify subscription_id was enforced as a SQL parameter (not just checked + # in Python), so removing the WHERE clause would break this test. + mock_cursor = mock_db._get_conn.return_value.cursor.return_value + call_args = mock_cursor.execute.call_args + _, params = call_args[0] + assert "sub-other" in params def test_get_requires_auth(self, app_client): resp = app_client.get("/api/v1/patterns/1") From 2bf7d9484768d0058d134cb03ea0a6bfb51dc1c2 Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 16:21:09 +0100 Subject: [PATCH 6/8] fix(lint): remove unused imports and fix E402 in lifecycle test files Signed-off-by: Tanvir Farhad --- alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py | 1 - tests/test_finding_lifecycle.py | 8 +------- tests/test_patterns.py | 2 -- 3 files changed, 1 insertion(+), 10 deletions(-) diff --git a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py index d36e9444..25fccefc 100644 --- a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py +++ b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py @@ -9,7 +9,6 @@ from typing import Sequence, Union from alembic import op -import sqlalchemy as sa # Revision identifiers, used by Alembic. revision: str = "e1f2a3b4c5d6" diff --git a/tests/test_finding_lifecycle.py b/tests/test_finding_lifecycle.py index dd404ada..fb80f144 100644 --- a/tests/test_finding_lifecycle.py +++ b/tests/test_finding_lifecycle.py @@ -4,11 +4,7 @@ live PostgreSQL instance. """ -import hashlib -import json -from unittest.mock import MagicMock, call, patch - -import pytest +from collections import deque from api.services.lifecycle_service import ( LifecycleService, @@ -48,8 +44,6 @@ def _make_outcome(rule_id: str, status: str) -> dict: # avoids the "second cursor re-reads from the start" bug noted in code review. # --------------------------------------------------------------------------- -from collections import deque - class _FakeCursor: """Fake psycopg2 cursor backed by a shared result deque.""" diff --git a/tests/test_patterns.py b/tests/test_patterns.py index b3bc7792..a3a7eee7 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -4,8 +4,6 @@ with mocked database queries. """ -import json -import os import secrets import time from unittest.mock import MagicMock, patch From 4d78b627ae8b34a0db5a83ff71dfce0469cd769a Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 16:24:55 +0100 Subject: [PATCH 7/8] fix(lint): apply ruff format to all lifecycle PR files Signed-off-by: Tanvir Farhad --- .../e1f2a3b4c5d6_finding_lifecycle.py | 9 ++---- api/routes/patterns.py | 4 +-- api/services/lifecycle_service.py | 16 +++------- api/services/pattern_service.py | 8 ++--- scanner/engine.py | 1 + scanner/worker.py | 1 - tests/test_finding_lifecycle.py | 29 ++++++++++--------- tests/test_patterns.py | 20 ++++++------- 8 files changed, 36 insertions(+), 52 deletions(-) diff --git a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py index 25fccefc..370f3f87 100644 --- a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py +++ b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py @@ -143,20 +143,15 @@ def upgrade() -> None: """ ) - # Indexes for hot query paths - op.execute( - "CREATE INDEX ix_finding_fingerprints_tenant_sub ON finding_fingerprints (tenant_id, subscription_id)" - ) + op.execute("CREATE INDEX ix_finding_fingerprints_tenant_sub ON finding_fingerprints (tenant_id, subscription_id)") op.execute( "CREATE INDEX ix_finding_lifecycles_state ON finding_lifecycles (state) WHERE state IN ('OPEN', 'REOPENED')" ) op.execute( "CREATE INDEX ix_finding_lifecycle_transitions_lifecycle_id ON finding_lifecycle_transitions (lifecycle_id)" ) - op.execute( - "CREATE INDEX ix_patterns_sub_created ON patterns (subscription_id, created_at DESC)" - ) + op.execute("CREATE INDEX ix_patterns_sub_created ON patterns (subscription_id, created_at DESC)") def downgrade() -> None: diff --git a/api/routes/patterns.py b/api/routes/patterns.py index abe7e805..1c245d9c 100644 --- a/api/routes/patterns.py +++ b/api/routes/patterns.py @@ -11,9 +11,7 @@ patterns_bp = Blueprint("patterns", __name__) logger = logging.getLogger(__name__) -_ALLOWED_PATTERN_TYPES = frozenset( - {"persistent_finding", "cross_resource_recurrence", "reopened_finding"} -) +_ALLOWED_PATTERN_TYPES = frozenset({"persistent_finding", "cross_resource_recurrence", "reopened_finding"}) _DEFAULT_LIMIT = 20 _MAX_LIMIT = 100 _MIN_LIMIT = 1 diff --git a/api/services/lifecycle_service.py b/api/services/lifecycle_service.py index 67729f9e..3b31b357 100644 --- a/api/services/lifecycle_service.py +++ b/api/services/lifecycle_service.py @@ -80,9 +80,7 @@ def apply_scan( (scan_id,), ) if cur.fetchone() is not None: - logger.info( - "Scan %s already applied; skipping lifecycle update", scan_id - ) + logger.info("Scan %s already applied; skipping lifecycle update", scan_id) return # --- Write durable per-rule outcome records ------------------- @@ -113,17 +111,13 @@ def apply_scan( # Build a lookup: rule_id -> outcome status outcome_by_rule: Dict[str, str] = { - o["rule_id"]: o["status"] - for o in rule_outcomes - if "rule_id" in o and "status" in o + o["rule_id"]: o["status"] for o in rule_outcomes if "rule_id" in o and "status" in o } # Collect rule IDs that actively confirmed a clean result. Only # these can trigger resolution of absent findings (fail-closed). resolving_rule_ids = [ - rule_id - for rule_id, status in outcome_by_rule.items() - if status in _RESOLVING_STATUSES + rule_id for rule_id, status in outcome_by_rule.items() if status in _RESOLVING_STATUSES ] # Build the set of fingerprints seen in this scan. @@ -317,9 +311,7 @@ def apply_scan( except Exception: db_conn.rollback() - logger.error( - "Lifecycle application rolled back for scan %s", scan_id, exc_info=True - ) + logger.error("Lifecycle application rolled back for scan %s", scan_id, exc_info=True) raise diff --git a/api/services/pattern_service.py b/api/services/pattern_service.py index 395454c0..0a8eb5f5 100644 --- a/api/services/pattern_service.py +++ b/api/services/pattern_service.py @@ -127,16 +127,12 @@ def detect_and_publish( count += 1 db_conn.commit() - logger.info( - "Pattern detection for scan %s: %d pattern(s) upserted", scan_id, count - ) + logger.info("Pattern detection for scan %s: %d pattern(s) upserted", scan_id, count) return count except Exception: db_conn.rollback() - logger.error( - "Pattern detection rolled back for scan %s", scan_id, exc_info=True - ) + logger.error("Pattern detection rolled back for scan %s", scan_id, exc_info=True) raise diff --git a/scanner/engine.py b/scanner/engine.py index 2efe816c..68fff16b 100644 --- a/scanner/engine.py +++ b/scanner/engine.py @@ -12,6 +12,7 @@ try: import azure.core.exceptions as _azure_exc + _AzureHttpResponseError = _azure_exc.HttpResponseError except Exception: _AzureHttpResponseError = None # type: ignore[assignment,misc] diff --git a/scanner/worker.py b/scanner/worker.py index 8f2936f1..f89c593b 100644 --- a/scanner/worker.py +++ b/scanner/worker.py @@ -106,7 +106,6 @@ def run_worker(): extra={"scan_id": scan_id}, ) - SCANS_TOTAL.labels(status="completed").inc() logger.info( "Successfully completed scan %s", diff --git a/tests/test_finding_lifecycle.py b/tests/test_finding_lifecycle.py index fb80f144..87ab29ce 100644 --- a/tests/test_finding_lifecycle.py +++ b/tests/test_finding_lifecycle.py @@ -166,12 +166,18 @@ def rollback(self): svc = LifecycleService() svc.apply_scan( - _TrackingConn(False), SCAN_ID_1, SUB_ID, TENANT_ID, + _TrackingConn(False), + SCAN_ID_1, + SUB_ID, + TENANT_ID, [_make_outcome("RULE-001", "SUCCESS")], [_make_finding("RULE-001", "/rg/foo")], ) svc.apply_scan( - _TrackingConn(True), SCAN_ID_1, SUB_ID, TENANT_ID, + _TrackingConn(True), + SCAN_ID_1, + SUB_ID, + TENANT_ID, [_make_outcome("RULE-001", "SUCCESS")], [_make_finding("RULE-001", "/rg/foo")], ) @@ -307,13 +313,13 @@ def test_rule_a_success_does_not_resolve_rule_b_finding(self): # 6. transition insert -> None # 7. idempotency insert -> None results = [ - None, # idempotency check - None, # scan_rule_outcomes RULE-001 - None, # scan_rule_outcomes RULE-002 - [(10, "OPEN", 0, "RULE-001")], # absent-findings query - None, # UPDATE RESOLVED - None, # transition insert - None, # idempotency insert + None, # idempotency check + None, # scan_rule_outcomes RULE-001 + None, # scan_rule_outcomes RULE-002 + [(10, "OPEN", 0, "RULE-001")], # absent-findings query + None, # UPDATE RESOLVED + None, # transition insert + None, # idempotency insert ] conn = self._run( results, @@ -351,10 +357,7 @@ def test_reopened_finding_seen_again_increments_occurrence_stays_reopened(self): sqls = self._all_sql(conn) # No transition record should be emitted for REOPENED->REOPENED. - transition_to_reopened = [ - s for s in sqls - if "finding_lifecycle_transitions" in s and "REOPENED" in s - ] + transition_to_reopened = [s for s in sqls if "finding_lifecycle_transitions" in s and "REOPENED" in s] assert not transition_to_reopened # occurrence_count should increment. diff --git a/tests/test_patterns.py b/tests/test_patterns.py index a3a7eee7..07b2933a 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -108,8 +108,8 @@ def test_persistent_finding_detected_when_occurrence_ge_3(self): count, conn = self._run( [ [{"lifecycle_id": 10}], # persistent_finding - [], # cross_resource_recurrence - [], # reopened_finding + [], # cross_resource_recurrence + [], # reopened_finding ] ) assert count == 1 @@ -144,19 +144,19 @@ def test_pattern_response_includes_threshold_and_algorithm_version(self): """The upsert call must include threshold and algorithm_version.""" from api.services.pattern_service import PatternService, _ALGORITHM_VERSION, _PERSISTENT_THRESHOLD - conn = _FakeConn([ - [{"lifecycle_id": 10}], # persistent_finding - [], # cross_resource_recurrence - [], # reopened_finding - ]) + conn = _FakeConn( + [ + [{"lifecycle_id": 10}], # persistent_finding + [], # cross_resource_recurrence + [], # reopened_finding + ] + ) svc = PatternService() svc.detect_and_publish(conn, SCAN_ID, SUB_ID, TENANT_ID) # Find the INSERT INTO patterns call and verify the params. executed = conn._cursor_obj.executed - insert_sql, params = next( - ((sql, p) for sql, p in executed if "INSERT INTO patterns" in sql), (None, None) - ) + insert_sql, params = next(((sql, p) for sql, p in executed if "INSERT INTO patterns" in sql), (None, None)) assert insert_sql is not None # params order: pattern_type, lifecycle_id, tenant_id, subscription_id, # scan_id, finding_ids, threshold, algorithm_version From 26361c27e38066029c6823f42bf0f6bdaa965ee2 Mon Sep 17 00:00:00 2001 From: Tanvir Farhad Date: Sun, 30 Aug 2026 16:39:12 +0100 Subject: [PATCH 8/8] fix: apply code review findings for lifecycle PR - Add _VALID_OUTCOME_STATUSES allowlist; unknown status defaults to FAILED instead of letting DB constraint throw IntegrityError mid-transaction - Fix dead-code if/elif block: restructure to if resolving_rule_ids / nested if seen_fingerprint_ids (fail-closed logic now clear at a glance) - Add tenant_id to ix_patterns_sub_created index (was subscription_id only; multi-tenant queries filter on both columns) - Add CASCADE to all downgrade() DROP TABLE statements (future FK safety) - Add row_version comment clarifying it is a monotonic counter, not OCC - Fix _FakeConn in test_patterns.py to share a single deque across all cursor() calls, matching test_finding_lifecycle.py and real psycopg2 behaviour - Add REOPENED -> RESOLVED test covering finding absent from SUCCESS scan Signed-off-by: Tanvir Farhad --- .../e1f2a3b4c5d6_finding_lifecycle.py | 16 +-- api/services/lifecycle_service.py | 99 +++++++++++-------- tests/test_finding_lifecycle.py | 23 +++++ tests/test_patterns.py | 35 +++++-- 4 files changed, 117 insertions(+), 56 deletions(-) diff --git a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py index 370f3f87..c856176e 100644 --- a/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py +++ b/alembic/versions/e1f2a3b4c5d6_finding_lifecycle.py @@ -92,7 +92,7 @@ def upgrade() -> None: occurrence_count INTEGER NOT NULL DEFAULT 1, consecutive_success_count INTEGER NOT NULL DEFAULT 0, reopen_count INTEGER NOT NULL DEFAULT 0, - row_version INTEGER NOT NULL DEFAULT 0, + row_version INTEGER NOT NULL DEFAULT 0, -- monotonic update counter (FOR UPDATE handles serializability) created_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), updated_at TIMESTAMPTZ NOT NULL DEFAULT NOW(), CONSTRAINT ck_finding_lifecycles_state @@ -151,13 +151,13 @@ def upgrade() -> None: op.execute( "CREATE INDEX ix_finding_lifecycle_transitions_lifecycle_id ON finding_lifecycle_transitions (lifecycle_id)" ) - op.execute("CREATE INDEX ix_patterns_sub_created ON patterns (subscription_id, created_at DESC)") + op.execute("CREATE INDEX ix_patterns_sub_created ON patterns (tenant_id, subscription_id, created_at DESC)") def downgrade() -> None: - op.execute("DROP TABLE IF EXISTS patterns") - op.execute("DROP TABLE IF EXISTS finding_lifecycle_transitions") - op.execute("DROP TABLE IF EXISTS finding_lifecycles") - op.execute("DROP TABLE IF EXISTS finding_fingerprints") - op.execute("DROP TABLE IF EXISTS scan_lifecycle_applications") - op.execute("DROP TABLE IF EXISTS scan_rule_outcomes") + op.execute("DROP TABLE IF EXISTS patterns CASCADE") + op.execute("DROP TABLE IF EXISTS finding_lifecycle_transitions CASCADE") + op.execute("DROP TABLE IF EXISTS finding_lifecycles CASCADE") + op.execute("DROP TABLE IF EXISTS finding_fingerprints CASCADE") + op.execute("DROP TABLE IF EXISTS scan_lifecycle_applications CASCADE") + op.execute("DROP TABLE IF EXISTS scan_rule_outcomes CASCADE") diff --git a/api/services/lifecycle_service.py b/api/services/lifecycle_service.py index 3b31b357..4c9af341 100644 --- a/api/services/lifecycle_service.py +++ b/api/services/lifecycle_service.py @@ -10,6 +10,19 @@ # Statuses that mean "we actively confirmed this rule was clean in the scan." _RESOLVING_STATUSES = frozenset({"SUCCESS", "EMPTY_SUCCESS"}) +# All statuses the DB constraint accepts. Any other value defaults to FAILED to +# prevent a single malformed outcome from aborting the whole lifecycle transaction. +_VALID_OUTCOME_STATUSES = frozenset( + { + "SUCCESS", + "EMPTY_SUCCESS", + "PERMISSION_DENIED", + "TIMEOUT", + "FAILED", + "NOT_APPLICABLE", + } +) + def _normalize_resource_id(resource_id: str) -> str: """Return a stable, lowercased, stripped version of an ARM resource ID.""" @@ -90,6 +103,13 @@ def apply_scan( status_o = outcome.get("status", "FAILED") if not rule_id_o: continue + if status_o not in _VALID_OUTCOME_STATUSES: + logger.warning( + "Unknown outcome status %r for rule %s; defaulting to FAILED", + status_o, + rule_id_o, + ) + status_o = "FAILED" cur.execute( """ INSERT INTO scan_rule_outcomes ( @@ -255,46 +275,45 @@ def apply_scan( ) # --- Resolve findings NOT seen in this scan ------------------- - # Only process rules that had a resolving outcome (fail-closed). - if not resolving_rule_ids: - pass - elif seen_fingerprint_ids: - # Use != ALL(%s) with a list to avoid single-element tuple - # syntax issues that occur with NOT IN %s. - cur.execute( - """ - SELECT fl.id, fl.state, fl.row_version, ff.rule_id - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state IN ('OPEN', 'REOPENED') - AND fl.fingerprint_id != ALL(%s) - AND ff.rule_id = ANY(%s) - FOR UPDATE OF fl - """, - ( - tenant_id, - subscription_id, - list(seen_fingerprint_ids), - resolving_rule_ids, - ), - ) - _resolve_absent_rows(cur, scan_id, outcome_by_rule) - else: - cur.execute( - """ - SELECT fl.id, fl.state, fl.row_version, ff.rule_id - FROM finding_lifecycles fl - JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id - WHERE ff.tenant_id = %s - AND ff.subscription_id = %s - AND fl.state IN ('OPEN', 'REOPENED') - AND ff.rule_id = ANY(%s) - FOR UPDATE OF fl - """, - (tenant_id, subscription_id, resolving_rule_ids), - ) + # Fail-closed: skip resolution entirely if no rule confirmed a + # clean result this scan (all outcomes were FAILED/PERMISSION_DENIED). + if resolving_rule_ids: + if seen_fingerprint_ids: + # Use != ALL(%s) with a list to avoid single-element tuple + # syntax issues that occur with NOT IN %s. + cur.execute( + """ + SELECT fl.id, fl.state, fl.row_version, ff.rule_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND fl.fingerprint_id != ALL(%s) + AND ff.rule_id = ANY(%s) + FOR UPDATE OF fl + """, + ( + tenant_id, + subscription_id, + list(seen_fingerprint_ids), + resolving_rule_ids, + ), + ) + else: + cur.execute( + """ + SELECT fl.id, fl.state, fl.row_version, ff.rule_id + FROM finding_lifecycles fl + JOIN finding_fingerprints ff ON ff.id = fl.fingerprint_id + WHERE ff.tenant_id = %s + AND ff.subscription_id = %s + AND fl.state IN ('OPEN', 'REOPENED') + AND ff.rule_id = ANY(%s) + FOR UPDATE OF fl + """, + (tenant_id, subscription_id, resolving_rule_ids), + ) _resolve_absent_rows(cur, scan_id, outcome_by_rule) # --- Idempotency sentinel (inserted last) --------------------- diff --git a/tests/test_finding_lifecycle.py b/tests/test_finding_lifecycle.py index 87ab29ce..23307410 100644 --- a/tests/test_finding_lifecycle.py +++ b/tests/test_finding_lifecycle.py @@ -338,6 +338,29 @@ def test_rule_a_success_does_not_resolve_rule_b_finding(self): assert "RULE-001" in resolving_ids assert "RULE-002" not in resolving_ids + def test_reopened_finding_absent_from_success_scan_is_resolved(self): + # REOPENED finding not seen in a SUCCESS scan must transition to RESOLVED. + # 1. idempotency -> None + # 2. scan_rule_outcomes insert -> None + # 3. absent-findings query (empty seen_ids branch) -> [(10,'REOPENED',0,'RULE-001')] + # 4. UPDATE to RESOLVED -> None + # 5. transition insert (REOPENED -> RESOLVED) -> None + # 6. idempotency insert -> None + results = [ + None, + None, + [(10, "REOPENED", 0, "RULE-001")], + None, + None, + None, + ] + conn = self._run(results, [], [_make_outcome("RULE-001", "SUCCESS")]) + assert conn.committed + sqls = self._all_sql(conn) + assert any("RESOLVED" in s and "UPDATE" in s.upper() for s in sqls) + # Transition from REOPENED to RESOLVED must be recorded. + assert any("finding_lifecycle_transitions" in s and "REOPENED" in s and "RESOLVED" in s for s in sqls) + def test_reopened_finding_seen_again_increments_occurrence_stays_reopened(self): # REOPENED + seen in scan: occurrence_count increments, no new state transition. # 1. idempotency -> None diff --git a/tests/test_patterns.py b/tests/test_patterns.py index 07b2933a..3d529977 100644 --- a/tests/test_patterns.py +++ b/tests/test_patterns.py @@ -6,6 +6,7 @@ import secrets import time +from collections import deque from unittest.mock import MagicMock, patch import jwt @@ -48,19 +49,24 @@ def _auth_headers(sub_id: str | None = None) -> dict: class _FakeCursor: - def __init__(self, pages: list): - # pages: list of values returned by successive fetchone/fetchall calls - self._pages = list(pages) - self.executed = [] + """Fake cursor backed by a shared deque so all cursors on one connection share state.""" + + def __init__(self, results_deque: deque): + self._results = results_deque + self.executed: list = [] + self._current = None def execute(self, sql, params=None): self.executed.append((sql.strip(), params)) + self._current = self._results.popleft() if self._results else None def fetchone(self): - return self._pages.pop(0) if self._pages else None + return self._current def fetchall(self): - return self._pages.pop(0) if self._pages else [] + if isinstance(self._current, list): + return self._current + return [] if self._current is None else [self._current] def __enter__(self): return self @@ -70,18 +76,31 @@ def __exit__(self, *args): class _FakeConn: + """Fake connection whose cursor() calls share one result deque.""" + def __init__(self, fetchall_pages: list): - self._pages = fetchall_pages + self._deque: deque = deque(fetchall_pages) self.committed = False + self._cursors: list = [] self._cursor_obj = None def cursor(self, **_kwargs): - self._cursor_obj = _FakeCursor(self._pages) + self._cursor_obj = _FakeCursor(self._deque) + self._cursors.append(self._cursor_obj) return self._cursor_obj def commit(self): self.committed = True + def rollback(self): + pass + + def all_executed(self) -> list: + result = [] + for c in self._cursors: + result.extend(c.executed) + return result + # --------------------------------------------------------------------------- # PatternService unit tests