"""Postgres adapter tests against a real, throw-away PostgreSQL server.""" import contextlib from dataclasses import replace from datetime import date, timedelta import psycopg import pytest from psycopg_pool import ConnectionPool from pytest_postgresql import factories from nixray.adapters.postgres.migrate import available_migrations, migrate from nixray.adapters.postgres.read_model import PostgresReadModel from nixray.adapters.postgres.unit_of_work import PostgresUnitOfWorkFactory from nixray.adapters.vulnix.scanner import RecordedVulnixScanner from nixray.application.errors import ScannerError from nixray.application.queries import ExposureFilter, FindingQuery, VulnerabilityQueries from nixray.application.read_models import FindingStatus from nixray.application.scan import RunScan from nixray.application.triage import MarkFalsePositive, ReviewSelection, TriageService from nixray.application.upstream import CheckUpstream from nixray.domain.advice import Basis, ExternalTriage, Outcome, Verdict from nixray.domain.judgement import Applicability, Judgement from nixray.domain.model import ( CveId, CveRecord, DebianStatus, DebianVerdict, DetectedVulnerability, EuvdEntry, ExploitSource, PublicExploit, RecordState, Scope, ) from tests.conftest import FIXTURES, detection, per_scan, report from tests.fakes import FakeClock, FakeScanner, FakeUnitOfWork, InMemoryStore pytestmark = pytest.mark.db postgresql_proc = factories.postgresql_proc() postgresql = factories.postgresql("postgresql_proc") @pytest.fixture def conninfo(postgresql) -> str: dsn = postgresql.info.dsn migrate(dsn, "localhost") return dsn @pytest.fixture def pool(conninfo): with ConnectionPool(conninfo, min_size=1, max_size=4, open=True) as pool: yield pool @pytest.fixture def clock(): return FakeClock() def test_migrations_are_idempotent(conninfo): assert migrate(conninfo, "localhost") == [] with psycopg.connect(conninfo) as conn: names = [r[0] for r in conn.execute("SELECT name FROM schema_migration ORDER BY name")] assert names == [name for name, _ in available_migrations()] def test_recorded_vulnix_scan_roundtrip(pool, clock): run = RunScan( PostgresUnitOfWorkFactory(pool), RecordedVulnixScanner(FIXTURES / "vulnix-scan.json"), clock ) outcome = run.execute() queries = VulnerabilityQueries(PostgresReadModel(pool), clock) dashboard = queries.dashboard() assert dashboard.actionable == outcome.findings == len(outcome.opened) detail = queries.cve_detail("CVE-2024-13278") assert detail.findings[0].package.pname == "Diff" assert detail.derivations[detail.findings[0].id] == ( "/nix/store/0qqc4vmmcww9zs7nnjcgmy8hq8d2y0y7-Diff-1.0.2.drv", ) def _built(d): return DetectedVulnerability(d.cve, d.package, d.derivation_paths, Scope.BUILDTIME) SCENARIO = [ [ detection("CVE-2025-0001", "openssl", "3.0.13", 9.8), detection("CVE-2024-13278", "Diff", "1.0.2", 9.1), ], [ detection("CVE-2025-0001", "openssl", "3.0.14", 9.8), detection("CVE-2024-13278", "Diff", "1.0.2", 9.1), ], [ detection("CVE-2024-13278", "Diff", "1.0.2", 9.1), detection("CVE-2025-0002", "zlib", "1.3", None), ], [_built(detection("CVE-2025-0003", "gcc", "4.6.4", 7.5))], [ detection("CVE-2025-0002", "zlib", "1.3", 4.2), detection("CVE-2025-0003", "gcc", "4.6.4", 7.5), # now part of the system ], ] def _play(uow_factory, read_model, clock): for index, detections in enumerate(SCENARIO): RunScan( uow_factory, FakeScanner(report(*detections, store_path=f"/nix/store/{index}-system")), clock, ).execute() clock.advance(timedelta(hours=1)) # A second host that has zlib only every other scan: its scans must # neither open nor close anything on the first host. web2 = (detection("CVE-2025-0002", "zlib", "1.3", 4.2),) if index % 2 == 0 else () RunScan(uow_factory, FakeScanner(report(*web2)), clock, host="web2").execute() clock.advance(timedelta(hours=10)) if index == 1: TriageService(uow_factory, clock).mark_false_positive( MarkFalsePositive( "CVE-2024-13278", "Diff", None, "Haskell library, not Drupal", "alice" ) ) if index == 0: with uow_factory() as uow: uow.external_triage.save( ExternalTriage( CveId("CVE-2024-13278"), Outcome.REJECTED, Basis.HUMAN, clock.now(), affected=("haskellPackages.Diff",), explanation="not in Nixpkgs", url="https://tracker.example/suggestions/by-id/1", ) ) uow.commit() if index == 2: zlib = [fid for fid, key in _keys(read_model).items() if key.package.pname == "zlib"] TriageService(uow_factory, clock).confirm( ReviewSelection(zlib, "bob", "real, waiting for fix") ) queries = VulnerabilityQueries(read_model, clock) web2 = queries.for_host("web2") return { "queries": queries, "trend": queries.trend(queries.trend_grid(None)), "hosts": queries.hosts(), "web2": [ (str(f.key.package), f.status, f.exposure, len(f.periods), f.confirmation is not None) for f in web2.findings(FindingQuery(statuses=tuple(FindingStatus))).items ], "web2_scans": [(v.new, v.resolved) for v in web2.scans()], "dashboard": queries.dashboard(), "findings": queries.findings( FindingQuery(statuses=tuple(FindingStatus), scopes=tuple(Scope)) ), "exposure": queries.exposure(ExposureFilter.ALL), "scans": queries.scans(), "suppressions": queries.suppressions(), "inbox": queries.review_inbox(), } def _keys(read_model): return {record.id: record.key for record in read_model.findings("localhost")} def _normalise(results): d = results["dashboard"] return { "web2": results["web2"], "web2_scans": results["web2_scans"], "trend": per_scan(results["queries"]), "trend_changes": (results["trend"].new, results["trend"].resolved, results["trend"].failed), "scopes": sorted((str(f.key.package), f.scope) for f in results["findings"].items), "runtime_counts": [v.scan.runtime_count for v in results["scans"]], "counts": ( d.actionable, d.suppressed, d.new_since_previous, d.resolved_since_previous, d.needs_review, ), "inbox": [(str(i.finding.key.package), i.new_in_latest_scan) for i in results["inbox"]], "hints": sorted( (str(f.key.package), f.hint.verdict, f.hint.basis, f.hint.triage.explanation) for f in results["findings"].items if f.hint ), "confirmed": sorted( (str(f.key.package), f.confirmation.created_by, f.confirmation.note) for f in results["findings"].items if f.confirmation ), "findings": sorted( (str(f.key.package), f.key.cve_id.value, f.status, f.exposure) for f in results["findings"].items ), "exposure": sorted( (r.cve.id.value, r.status, r.exposure) for r in results["exposure"].rows ), "scans": [(v.new, v.resolved, v.deployment, v.scan.status) for v in results["scans"]], "suppressions": [ (v.state, v.matches, v.suppression.reason) for v in results["suppressions"] ], } def results_hosts(pool): return VulnerabilityQueries(PostgresReadModel(pool), FakeClock()).hosts() def test_postgres_adapter_behaves_like_the_in_memory_reference(pool): """Contract test: the same scenario yields identical views on both implementations.""" store = InMemoryStore() expected = _normalise(_play(lambda: FakeUnitOfWork(store), store, FakeClock())) actual = _normalise( _play(PostgresUnitOfWorkFactory(pool), PostgresReadModel(pool), FakeClock()) ) assert actual == expected assert results_hosts(pool) == ["localhost", "web2"] # zlib came and went on web2 (opened, closed, opened, closed, opened): 11 h + 11 h # + 10 h so far. bob's confirmation on the first host is about the finding, so it # applies here too. assert expected["web2"] == [("zlib-1.3", FindingStatus.OPEN, timedelta(hours=32), 3, True)] assert expected["web2_scans"] == [(1, 0), (0, 1), (1, 0), (0, 1), (1, 0)] # (runtime, high+critical, build-time) per scan. gcc moved into the runtime # closure in the last scan; with current knowledge it counts as runtime across # its history, like a false-positive mark does. assert expected["trend"] == [(1, 1, 0), (1, 1, 0), (1, 0, 0), (1, 1, 0), (2, 1, 0)] assert ("gcc-4.6.4", Scope.RUNTIME) in expected["scopes"] assert expected["runtime_counts"] == [2, 0, 2, 2, 2] # zlib was confirmed (the confirmation carries over); gcc still needs a decision assert expected["inbox"] == [("gcc-4.6.4", False)] assert expected["confirmed"] == [("zlib-1.3", "bob", "real, waiting for fix")] assert expected["hints"] == [ ("Diff-1.0.2", Verdict.NOT_AFFECTED, Basis.HUMAN, "not in Nixpkgs") ] def test_cve_scores_are_updated(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan( uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3", None))), clock ).execute() clock.advance(timedelta(hours=1)) RunScan( uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3", 8.1))), clock ).execute() (record,) = PostgresReadModel(pool).findings("localhost") assert record.cve.cvss_v3 == 8.1 def test_suppressions_are_append_only(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3"))), clock).execute() rule = TriageService(uow, clock).mark_false_positive( MarkFalsePositive("CVE-2025-0002", None, None, "not relevant on this host", "alice") ) with pool.connection() as conn, pytest.raises(psycopg.errors.RaiseException): conn.execute("DELETE FROM suppression WHERE id = %s", (rule,)) with pool.connection() as conn, pytest.raises(psycopg.errors.RaiseException): conn.execute("UPDATE suppression SET reason = 'rewritten history!' WHERE id = %s", (rule,)) def test_confirmations_are_append_only(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3"))), clock).execute() ids = list(_keys(PostgresReadModel(pool))) TriageService(uow, clock).confirm(ReviewSelection(ids, "alice", "known, fix pending")) (confirmation,) = PostgresReadModel(pool).confirmations() assert (confirmation.pname, confirmation.note) == ("zlib", "known, fix pending") for statement in ("DELETE FROM confirmation", "UPDATE confirmation SET note = 'rewritten'"): with pool.connection() as conn, pytest.raises(psycopg.errors.RaiseException): conn.execute(statement) def test_confirmations_can_be_revoked_once(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3"))), clock).execute() ids = list(_keys(PostgresReadModel(pool))) triage = TriageService(uow, clock) triage.confirm(ReviewSelection(ids, "alice", "first")) triage.confirm(ReviewSelection(ids, "alice", "second")) # supersedes the first queries = VulnerabilityQueries(PostgresReadModel(pool), clock) newest, oldest = queries.cve_detail("CVE-2025-0002").confirmations assert (newest.is_active, oldest.is_active) == (True, False) triage.revoke_confirmation(newest.id, "bob", "confirmed by mistake") assert [i.finding.package.pname for i in queries.review_inbox()] == ["zlib"] with pool.connection() as conn, pytest.raises(psycopg.errors.RaiseException): conn.execute( "UPDATE confirmation SET revoke_reason = 'rewritten reason' WHERE id = %s", (newest.id,), ) with pool.connection() as conn, pytest.raises(psycopg.errors.UniqueViolation): conn.execute( "INSERT INTO confirmation (cve_id, pname, created_by, created_at)" " VALUES ('CVE-2025-0002', 'zlib', 'x', now()), ('CVE-2025-0002', 'zlib', 'y', now())" ) def test_migration_0003_keeps_only_the_newest_duplicate_confirmation(postgresql): dsn = postgresql.info.dsn before, after = available_migrations()[:2], available_migrations()[2:] with psycopg.connect(dsn, autocommit=True) as conn: conn.execute( "CREATE TABLE schema_migration (name text PRIMARY KEY," " applied_at timestamptz NOT NULL DEFAULT now())" ) for name, sql in before: conn.execute(sql.encode()) conn.execute("INSERT INTO schema_migration (name) VALUES (%s)", (name,)) conn.execute( "INSERT INTO cve (id, first_seen_at, updated_at) VALUES ('CVE-2025-0002', now(), now())" ) conn.execute( "INSERT INTO confirmation (cve_id, pname, created_by, created_at) VALUES" " ('CVE-2025-0002', 'zlib', 'old', now() - interval '1 day')," " ('CVE-2025-0002', 'zlib', 'new', now())" ) assert migrate(dsn, "localhost") == [name for name, _ in after] with psycopg.connect(dsn) as conn: rows = conn.execute( "SELECT created_by, revoked_at IS NULL FROM confirmation ORDER BY created_at" ).fetchall() assert rows == [("old", False), ("new", True)] def test_external_triage_is_cached_and_replaced(pool, clock): uow = PostgresUnitOfWorkFactory(pool) first = ExternalTriage( CveId("CVE-2026-6238"), Outcome.PENDING, Basis.AUTOMATIC, clock.now(), affected=("glibc", "musl"), ) with uow() as u: u.external_triage.save(first) u.commit() clock.advance(timedelta(days=1)) second = ExternalTriage( CveId("CVE-2026-6238"), Outcome.CONFIRMED, Basis.HUMAN, clock.now(), affected=("glibc",), excluded=("libc", "iconv"), explanation="published as NIXPKGS-2026-1286", issue="NIXPKGS-2026-1286", url="https://tracker.example/suggestions/by-id/5884", ) with uow() as u: u.external_triage.save(second) u.commit() (stored,) = PostgresReadModel(pool).external_triage() assert stored == second with uow() as u: assert u.external_triage.all() == {CveId("CVE-2026-6238"): second} with pool.connection() as conn, pytest.raises(psycopg.errors.CheckViolation): conn.execute( "INSERT INTO external_triage (cve_id, outcome, basis, url, fetched_at)" " VALUES ('CVE-2026-0001', 'rejected', 'human', 'javascript:alert(1)', now())" ) def test_applying_tracker_advice_in_postgres(pool, clock): uow = PostgresUnitOfWorkFactory(pool) detections = [ detection("CVE-2026-6238", "glibc", "2.42", 6.5), detection("CVE-2026-67456", "warp", "1.0.0", 7.5), ] RunScan(uow, FakeScanner(report(*detections)), clock).execute() with uow() as u: u.external_triage.save( ExternalTriage( CveId("CVE-2026-6238"), Outcome.CONFIRMED, Basis.HUMAN, clock.now(), affected=("glibc",), explanation="published as NIXPKGS-2026-1286", issue="NIXPKGS-2026-1286", ) ) u.external_triage.save( ExternalTriage( CveId("CVE-2026-67456"), Outcome.REJECTED, Basis.HUMAN, clock.now(), explanation="not in Nixpkgs", ) ) u.commit() ids = list(_keys(PostgresReadModel(pool))) assert TriageService(uow, clock).apply_advice(ReviewSelection(ids, "alice")) == 2 read = PostgresReadModel(pool) (confirmation,) = read.confirmations() (suppression,) = read.suppressions() assert confirmation.pname == "glibc" and "NIXPKGS-2026-1286" in confirmation.note assert suppression.scope.pname == "warp" and "not in Nixpkgs" in suppression.reason assert VulnerabilityQueries(read, clock).review_inbox() == [] def test_migration_0005_treats_earlier_observations_as_runtime(postgresql): dsn = postgresql.info.dsn before, after = available_migrations()[:4], available_migrations()[4:] with psycopg.connect(dsn, autocommit=True) as conn: conn.execute( "CREATE TABLE schema_migration (name text PRIMARY KEY," " applied_at timestamptz NOT NULL DEFAULT now())" ) for name, sql in before: conn.execute(sql.encode()) conn.execute("INSERT INTO schema_migration (name) VALUES (%s)", (name,)) conn.execute( "INSERT INTO cve (id, first_seen_at, updated_at)" " VALUES ('CVE-2025-0002', now(), now());" "INSERT INTO package (pname, version) VALUES ('zlib', '1.3');" "INSERT INTO finding (cve_id, package_id) SELECT 'CVE-2025-0002', id FROM package;" "INSERT INTO scan (started_at, finished_at, status, target, finding_count)" " VALUES (now(), now(), 'succeeded', '--system', 1);" "INSERT INTO observation (scan_id, finding_id)" " SELECT s.id, f.id FROM scan s, finding f;" "INSERT INTO exposure_period (finding_id, opened_scan_id, period)" " SELECT f.id, s.id, tstzrange(now(), NULL) FROM scan s, finding f;" ) assert migrate(dsn, "localhost") == [name for name, _ in after] with ConnectionPool(dsn, min_size=1, max_size=1, open=True) as pool: (record,) = PostgresReadModel(pool).findings("localhost") (scan,) = PostgresReadModel(pool).scans("localhost") assert record.scope is Scope.RUNTIME assert scan.runtime_count is None # that scan did not distinguish def test_schema_rejects_overlapping_periods(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3"))), clock).execute() with pool.connection() as conn, pytest.raises(psycopg.errors.ExclusionViolation): conn.execute( "INSERT INTO exposure_period" " (host_id, finding_id, opened_scan_id, closed_scan_id, period)" " SELECT host_id, finding_id, opened_scan_id, opened_scan_id," " tstzrange(lower(period) - interval '1 day', lower(period) + interval '1 hour')" " FROM exposure_period" ) def test_schema_enforces_scan_status_invariants(pool, clock): with pool.connection() as conn, pytest.raises(psycopg.errors.CheckViolation): conn.execute( "INSERT INTO scan (host_id, started_at, target, status, finished_at)" " SELECT id, now(), 'x', 'failed', now() FROM host" ) def test_web_role_records_decisions_but_cannot_rewrite_the_audit_trail(postgresql, clock): dsn = postgresql.info.dsn with psycopg.connect(dsn, autocommit=True) as conn: conn.execute('CREATE ROLE "nixray-web"') migrate(dsn, "localhost", web_role="nixray-web") with ConnectionPool(dsn, min_size=1, max_size=1, open=True) as owner: RunScan( PostgresUnitOfWorkFactory(owner), FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3"))), clock, ).execute() def as_web(conn: psycopg.Connection) -> None: conn.execute('SET ROLE "nixray-web"') conn.commit() with ConnectionPool(dsn, min_size=1, max_size=1, open=True, configure=as_web) as web: # Everything the web interface does works. queries = VulnerabilityQueries(PostgresReadModel(web), clock) triage = TriageService(PostgresUnitOfWorkFactory(web), clock) rule = triage.mark_false_positive( MarkFalsePositive("CVE-2025-0002", None, None, "not relevant on this host", "alice") ) triage.revoke(rule, "bob", "it is relevant after all") triage.confirm(ReviewSelection(list(_keys(PostgresReadModel(web))), "alice", "known")) (confirmation,) = PostgresReadModel(web).confirmations() triage.revoke_confirmation(confirmation.id, "bob", "confirmed by mistake") assert queries.dashboard() is not None assert queries.findings(FindingQuery()).total == 1 # Nothing else does. for statement in ( "ALTER TABLE suppression DISABLE TRIGGER suppression_append_only", "DROP TRIGGER confirmation_append_only ON confirmation", "DELETE FROM suppression", "UPDATE suppression SET reason = 'rewritten history!'", "INSERT INTO host (name) VALUES ('forged')", "TRUNCATE scan CASCADE", "CREATE TABLE planted (x int)", ): with web.connection() as conn, pytest.raises(psycopg.errors.InsufficientPrivilege): conn.execute(statement) def test_reads_do_not_leave_pooled_connections_read_only(conninfo, clock): """A read must not turn the shared connection read-only for later writes.""" with ConnectionPool(conninfo, min_size=1, max_size=1, open=True) as single: uow = PostgresUnitOfWorkFactory(single) RunScan( uow, FakeScanner(report(detection("CVE-2025-0002", "zlib", "1.3"))), clock ).execute() VulnerabilityQueries(PostgresReadModel(single), clock).dashboard() TriageService(uow, clock).mark_false_positive( MarkFalsePositive("CVE-2025-0002", None, None, "not relevant on this host", "alice") ) def test_judgements_are_stored_and_replaced(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2024-13278", "Diff", "1.0.2"))), clock).execute() read = PostgresReadModel(pool) (finding,) = read.findings("localhost") first = Judgement(Applicability.UNCERTAIN, "Too little information.", "mistral/x", clock.now()) second = Judgement(Applicability.NOT_AFFECTED, "A Drupal module.", "mistral/y", clock.now()) for judgement in (first, second): with uow() as u: u.judgements.save(finding.id, judgement) u.commit() assert read.judgements() == {finding.id: second} with uow() as u: assert u.judgements.for_findings([finding.id, finding.id + 1]) == {finding.id: second} def test_migration_0007_keeps_the_history_of_the_existing_host(postgresql, clock): dsn = postgresql.info.dsn names = [name for name, _ in available_migrations()] before = available_migrations()[: names.index("0007_host.sql")] with psycopg.connect(dsn, autocommit=True) as conn: conn.execute( "CREATE TABLE schema_migration (name text PRIMARY KEY," " applied_at timestamptz NOT NULL DEFAULT now())" ) for name, sql in before: conn.execute(sql.encode()) conn.execute("INSERT INTO schema_migration (name) VALUES (%s)", (name,)) for sql in ( "INSERT INTO cve (id, first_seen_at, updated_at)" " VALUES ('CVE-2025-0002', %(t)s, %(t)s)", "INSERT INTO package (pname, version) VALUES ('zlib', '1.3')", "INSERT INTO finding (cve_id, package_id) SELECT 'CVE-2025-0002', id FROM package", "INSERT INTO scan (started_at, finished_at, status, target, finding_count)" " VALUES (%(t)s, %(t)s, 'succeeded', '--system', 1)", "INSERT INTO exposure_period (finding_id, opened_scan_id, period)" " SELECT f.id, s.id, tstzrange(%(t)s, NULL) FROM scan s, finding f", ): conn.execute(sql.encode(), {"t": clock.now()}) assert migrate(dsn, "server1")[0] == "0007_host.sql" clock.advance(timedelta(hours=12)) with ConnectionPool(dsn, min_size=1, max_size=2, open=True) as pool: uow = PostgresUnitOfWorkFactory(pool) detections = report(detection("CVE-2025-0002", "zlib", "1.3")) outcome = RunScan(uow, FakeScanner(detections), clock, host="server1").execute() assert len(outcome.opened) == 0 # still the same exposure period: history continues queries = VulnerabilityQueries(PostgresReadModel(pool), clock, host="server1") assert queries.hosts() == ["server1"] (finding,) = queries.findings(FindingQuery()).items assert finding.exposure == timedelta(hours=12) RunScan(uow, FakeScanner(detections), clock, host="web2").execute() with pool.connection() as conn, pytest.raises(psycopg.errors.ForeignKeyViolation): # A period on server1 cannot be opened by a scan of web2. conn.execute( "INSERT INTO exposure_period" " (host_id, finding_id, opened_scan_id, closed_scan_id, period)" " SELECT h.id, e.finding_id, s.id, s.id, tstzrange('2000-01-01', '2000-01-02')" " FROM host h, exposure_period e, scan s JOIN host w ON w.id = s.host_id" " WHERE h.name = 'server1' AND w.name = 'web2' LIMIT 1" ) def test_known_exploited_catalog_is_replaced_and_joined(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2024-3094", "xz", "5.6.0"))), clock).execute() for catalog in ( {CveId("CVE-2021-44228"): date(2021, 12, 10)}, {CveId("CVE-2024-3094"): date(2024, 4, 1), CveId("CVE-2026-0001"): date(2026, 1, 2)}, ): with uow() as u: u.known_exploited.replace(catalog) u.commit() (record,) = PostgresReadModel(pool).findings("localhost") assert record.cve.exploited == date(2024, 4, 1) with pool.connection() as conn: assert conn.execute("SELECT count(*) FROM known_exploited").fetchone() == (2,) def test_exploited_cves_are_found_in_kev_euvd_and_public_exploits(pool, clock): uow = PostgresUnitOfWorkFactory(pool) kev, euvd, exploit, known, plain = (CveId(f"CVE-2026-000{n}") for n in range(1, 6)) with uow() as u: u.known_exploited.replace({kev: date(2026, 1, 1)}) u.public_exploits.replace(ExploitSource.NUCLEI, {exploit: "https://nuclei.example/1"}) u.euvd.save(EuvdEntry(euvd, clock.now(), "EUVD-2026-1", date(2026, 1, 1))) u.euvd.save(EuvdEntry(known, clock.now(), "EUVD-2026-2")) # in EUVD, not exploited assert u.findings.exploited([kev, euvd, exploit, known, plain]) == {kev, euvd, exploit} assert u.findings.exploited([]) == frozenset() def test_epss_scores_are_replaced_and_joined(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2024-3094", "xz", "5.6.0"))), clock).execute() for scores in ( {CveId("CVE-2021-44228"): 0.9}, {CveId("CVE-2024-3094"): 0.84, CveId("CVE-2026-0001"): 0.0}, ): with uow() as u: u.epss.replace(scores) u.commit() (record,) = PostgresReadModel(pool).findings("localhost") assert record.cve.epss == 0.84 with pool.connection() as conn: assert conn.execute("SELECT count(*) FROM epss").fetchone() == (2,) def test_public_exploits_are_replaced_per_source_and_joined(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2021-44228", "log4j", "2.14"))), clock).execute() log4shell = CveId("CVE-2021-44228") for source, links in ( (ExploitSource.NUCLEI, {log4shell: "https://nuclei.example/old"}), (ExploitSource.EXPLOIT_DB, {log4shell: "https://edb.example/1"}), (ExploitSource.NUCLEI, {log4shell: "https://nuclei.example/new"}), ): with uow() as u: u.public_exploits.replace(source, links) u.commit() (record,) = PostgresReadModel(pool).findings("localhost") assert record.cve.exploits == ( PublicExploit(ExploitSource.EXPLOIT_DB, "https://edb.example/1"), PublicExploit(ExploitSource.NUCLEI, "https://nuclei.example/new"), ) with pool.connection() as conn, pytest.raises(psycopg.errors.CheckViolation): conn.execute( "INSERT INTO public_exploit VALUES ('CVE-2021-0001', 'nuclei', 'javascript:alert(1)')" ) def test_cve_records_are_cached_replaced_and_joined(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan( uow, FakeScanner(report(detection("CVE-2026-0001", "curl", "8", None))), clock ).execute() cve_id = CveId("CVE-2026-0001") first = CveRecord(cve_id, RecordState.PUBLISHED, clock.now()) second = CveRecord( cve_id, RecordState.PUBLISHED, clock.now(), 9.1, "3.1", "CISA-ADP", ("CWE-20",), "active", True, "total", published=clock.now(), ) for record in (first, second): with uow() as u: u.cve_records.save(record) u.commit() with uow() as u: assert u.cve_records.all() == {cve_id: second} (finding,) = PostgresReadModel(pool).findings("localhost") assert finding.cve.record == second and finding.cve.score == 9.1 def test_euvd_entries_are_cached_replaced_and_joined(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2021-44228", "log4j", "2.14"))), clock).execute() cve_id = CveId("CVE-2021-44228") found = EuvdEntry(cve_id, clock.now(), "EUVD-2021-34768", date(2021, 12, 10)) for entry in (EuvdEntry(cve_id, clock.now()), found): with uow() as u: u.euvd.save(entry) u.commit() with uow() as u: assert u.euvd.all() == {cve_id: found} (finding,) = PostgresReadModel(pool).findings("localhost") assert finding.cve.euvd == found and finding.cve.exploited_since == date(2021, 12, 10) with pool.connection() as conn, pytest.raises(psycopg.errors.CheckViolation): conn.execute("INSERT INTO euvd_entry VALUES ('CVE-2021-0001', NULL, '2021-01-01', now())") def test_debian_verdicts_are_replaced_and_joined(pool, clock): uow = PostgresUnitOfWorkFactory(pool) RunScan(uow, FakeScanner(report(detection("CVE-2026-6238", "glibc", "2.42"))), clock).execute() cve_id = CveId("CVE-2026-6238") verdicts = ( DebianVerdict(DebianStatus.REJECTED), DebianVerdict(DebianStatus.MINOR, "glibc", "Minor issue"), ) for replacement in ({CveId("CVE-2021-0001"): verdicts[:1]}, {cve_id: verdicts}): with uow() as u: u.debian.replace(replacement) u.commit() (finding,) = PostgresReadModel(pool).findings("localhost") assert finding.cve.debian == verdicts with pool.connection() as conn: assert conn.execute("SELECT count(*) FROM debian_verdict").fetchone() == (2,) with pytest.raises(psycopg.errors.CheckViolation): conn.execute( "INSERT INTO debian_verdict VALUES ('CVE-2021-0001', 'glibc', 'rejected', '')" ) def test_upstream_checks_are_stored_and_read_like_in_memory(pool): def run(uow_factory, read): run_clock = FakeClock() openssl = detection("CVE-2025-0001", "openssl", "3.0.13") curl = detection("CVE-2025-0002", "curl", "8.9.0") RunScan(uow_factory, FakeScanner(report(openssl, curl)), run_clock).execute() for result in ( report(detection("CVE-2025-0001", "openssl", "3.0.14")), ScannerError("nix eval of localhost failed"), report(), ): run_clock.advance(timedelta(hours=12)) check = CheckUpstream(uow_factory, FakeScanner(result), run_clock, host="localhost") with contextlib.suppress(ScannerError): check.execute() queries = VulnerabilityQueries(read, run_clock) fixes = {v.package.pname: v.upstream for v in queries.findings(FindingQuery()).items} return fixes, [(c.error, c.target) for c in read.upstream_checks("localhost")] store = InMemoryStore() expected = run(lambda: FakeUnitOfWork(store), store) assert run(PostgresUnitOfWorkFactory(pool), PostgresReadModel(pool)) == expected fixes, checks = expected assert fixes["curl"].since is not None and fixes["openssl"].since is not None assert [error for error, _ in checks] == [None, "nix eval of localhost failed", None] def test_processes_and_restart_needed_are_stored_per_observation(pool, clock): uow = PostgresUnitOfWorkFactory(pool) old = detection("CVE-2025-0001", "openssl", "3.0.13") loaded = replace(old, processes=("kernel", "sshd.service"), restart_needed=True) RunScan(uow, FakeScanner(report(loaded)), clock).execute() (finding,) = PostgresReadModel(pool).findings("localhost") assert (finding.processes, finding.restart_needed) == (("kernel", "sshd.service"), True) clock.advance(timedelta(hours=12)) RunScan(uow, FakeScanner(report(old)), clock).execute() # the latest observation counts (finding,) = PostgresReadModel(pool).findings("localhost") assert (finding.processes, finding.restart_needed) == ((), False)