Files
rengine/shared/services/surface_query/vulnerabilities.py
T
Yogesh OjhaandClaude Opus 5 ef3d2d3a50 feat(exports): write the rows a query returns to a file
The export engine, with no surface on it yet. Given a dimension, a scope
and the filter body a result table POSTs to search, it writes the same
rows to csv, json or plain text.

It selects only the columns the file will carry, so a vulnerability
export does not drag a stored request and response through memory to
throw them away, and it streams with yield_per, so a 50,000 row export
holds one chunk at a time. Statement timeout is the export's own: a
background job does not read under the api's twenty second ceiling.

Two columns a table shows are joined per chunk rather than per row —
the ports behind a host's addresses, and the hosts behind an address —
because #523 and #703 ask for those by name. The four rollup counts the
api computes per page are left out rather than written blank.

A cell opening with = + - @ tab or return is a formula to Excel and
Sheets, and page titles and banners are written by the target, so every
cell is prefixed and stripped of control characters. CSV carries a BOM
or Excel reads utf-8 as latin-1.

Proven against a live scan and in tests: for every dimension, filtered
or not, the export writes exactly as many rows as the table reports.

Co-Authored-By: Claude Opus 5 (1M context) <noreply@anthropic.com>
Claude-Session: https://claude.ai/code/session_01LYZfaNjq3Ym8GPvWYuHisS
2026-09-13 08:04:10 +05:30

122 lines
4.1 KiB
Python

"""Vulnerability statement building, shared by the api's search and the worker's export."""
from __future__ import annotations
from typing import TYPE_CHECKING
from sqlalchemy import case, cast, func, not_, or_, select
from sqlalchemy.dialects.postgresql import JSONB
from shared.definitions.asset_query import VULN_QUERY
from shared.definitions.vulnerabilities import ACTIONABLE_SEVERITIES, SEVERITY_ORDER
from shared.models.vulnerability import Vulnerability
from shared.services.asset_query import (
QueryScope,
VulnQueryContext,
compile_vuln_query,
parse_query,
vuln_corroborated,
vuln_corroborated_ids,
vuln_is_new,
vuln_state,
vuln_suppressed,
)
if TYPE_CHECKING:
from datetime import datetime
from shared.models.vulnerability import VulnerabilityFilter
def severity_rank():
return case(
{name: index for index, name in enumerate(SEVERITY_ORDER)},
value=Vulnerability.severity,
else_=len(SEVERITY_ORDER),
)
def context(scope: QueryScope, now: datetime) -> VulnQueryContext:
return VulnQueryContext(scope=scope, now=now)
def apply_filter(query, f: VulnerabilityFilter, scope: QueryScope):
if f.severities:
query = query.where(Vulnerability.severity.in_(f.severities))
elif not f.include_info:
query = query.where(Vulnerability.severity.in_(ACTIONABLE_SEVERITIES))
if f.protocols:
query = query.where(Vulnerability.protocol.in_(f.protocols))
if f.templates:
query = query.where(Vulnerability.template_id.in_(f.templates))
if f.hosts:
query = query.where(Vulnerability.host.in_(f.hosts))
if f.scanners:
query = query.where(Vulnerability.scanner.in_(f.scanners))
if f.tags:
query = query.where(
or_(
*[
func.jsonb_exists(cast(Vulnerability.tags, JSONB), tag)
for tag in f.tags
]
)
)
if f.kev:
query = query.where(Vulnerability.is_kev.is_(True))
if f.cve:
query = query.where(
func.jsonb_array_length(cast(Vulnerability.cve_ids, JSONB)) > 0
)
if f.new:
query = query.where(vuln_is_new(scope))
if f.corroborated:
query = query.where(vuln_corroborated(scope))
if f.states:
query = query.where(vuln_state(scope).in_(f.states))
elif not f.include_suppressed:
query = query.where(not_(vuln_suppressed(scope)))
return query
def order(query, f: VulnerabilityFilter, scope: QueryScope):
if f.sort == "risk":
confirmed = vuln_corroborated_ids(scope).subquery()
return query.outerjoin(confirmed, confirmed.c.id == Vulnerability.id).order_by(
severity_rank().asc(),
Vulnerability.is_kev.desc(),
Vulnerability.exploit_score.desc(),
confirmed.c.id.isnot(None).desc(),
Vulnerability.epss_score.desc().nulls_last(),
Vulnerability.cvss_score.desc().nulls_last(),
Vulnerability.template_id.asc(),
Vulnerability.matched_at.asc(),
)
column = {
"severity": severity_rank(),
"name": Vulnerability.template_name,
"template": Vulnerability.template_id,
"host": Vulnerability.host,
"seen": Vulnerability.discovered_at,
"cvss": Vulnerability.cvss_score,
"epss": Vulnerability.epss_score,
"exploit": Vulnerability.exploit_score,
"type": Vulnerability.protocol,
}.get(f.sort, severity_rank())
primary = column.desc() if f.order == "desc" else column.asc()
return query.order_by(
primary.nulls_last(),
Vulnerability.template_id.asc(),
Vulnerability.matched_at.asc(),
)
def scoped(scope: QueryScope, f: VulnerabilityFilter, columns=None):
base = select(Vulnerability) if columns is None else select(*columns)
base = base.where(scope.match(Vulnerability.scan_id))
return apply_filter(base, f, scope)
def compiled(scope: QueryScope, f: VulnerabilityFilter, now: datetime):
return compile_vuln_query(parse_query(f.q, VULN_QUERY), context(scope, now))