Skip to main content
VulnParse-Pin emblem VulnParse-Pin emblem
VulnParse-Pin
Architecture Extension Playbooks.md
View source on GitHub ↗

Extension Playbooks

This guide provides step-by-step playbooks for extending VulnParse-Pin v2.1.0 (Apache-2.0) while keeping streaming memory bounded, DuckDB workspaces safe across upgrades, and runtime dependencies free of copyleft packages.

Playbook 1: Add a New Streaming Parser

Where to implement

  1. Create a parser module under src/vulnparse_pin/parsers/.
  2. Subclass BaseParser (src/vulnparse_pin/parsers/base_parser.py) implementing detect_file() and iter_batches(batch_size=...).
  3. Register a ParserSpec in PARSER_SPECS (src/vulnparse_pin/parsers/__init__.py).

Hardened streaming & licensing rules

  • XML parsers: Must use safe_iterparse() and prune_element() from src/vulnparse_pin/parsers/_xml_security.py (backed by lxml.etree.iterparse). Never introduce defusedxml or xml.etree.ElementTree.
  • JSON / SARIF / JSONL parsers: Must stream via chunked json.JSONDecoder.raw_decode (see _FastSarifStreamReader in sarif_parser.py), ijson, or bounded line iteration (nuclei_jsonl_parser.py)—never materialize multi-hundred-MB DOMs with json.load().
  • CSV parsers: Must enforce _MAX_CSV_FIELD_BYTES (32 MiB), build a single-pass header index map, and emit ledger events on malformed/dropped rows.
  • Zero-copyleft dependency gate: All new parser or utility dependencies must be Apache-2.0-compatible (MIT, BSD, PSF, Apache-2.0). Never add AGPL, GPL, or LGPL runtime dependencies.

Minimal streaming parser skeleton

from pathlib import Path
from typing import Any, Dict, Iterator, List, Optional

from vulnparse_pin.parsers.base_parser import BaseParser


class CustomStreamParser(BaseParser):
    NAME = "custom-stream"

    @classmethod
    def detect_file(
        cls,
        filepath: str | Path,
        *,
        ctx: Optional[Any] = None,
        allow_large: Optional[bool] = None,
        head_bytes: Optional[bytes] = None,
    ) -> tuple[float, list[tuple[str, str]]]:
        return 0.85, [("format", "custom")]

    def iter_batches(self, batch_size: int = 10_000) -> Iterator[List[Dict[str, Any]]]:
        path = self._validate_filepath_and_size()
        # Stream records via self._open_read(path, self.ctx, ...) and yield NormalizedFindingRecord dicts
        yield []

Parser extension checklist

  1. detect_file() inspects only bounded head_bytes (<= 64 KiB).
  2. iter_batches() emits complete NormalizedFindingRecord fields (detection_mode, signal_reliability, ingestion_confidence, fidelity_tier, source_format).
  3. Regression fixtures and tests cover detection, streaming batches, and malformed/adversarial edge cases (tests/test_streaming_parsers.py, tests/test_xxe_hardening.py).

Playbook 2: Add or Extend a DuckDB Repository Query or Pass

Where to implement

  • Schema, migrations & workspace lifecycle: src/vulnparse_pin/storage/schema.sql, src/vulnparse_pin/storage/db.py (VppDatabase), and ensure_v21_schema() in src/vulnparse_pin/storage/repositories.py.
  • Parameterized repository helpers: src/vulnparse_pin/storage/repositories.py.
  • Derived pass: src/vulnparse_pin/core/passes/<PassName>/ (including RemediationPass (Remediation@1.0) in src/vulnparse_pin/core/passes/Remediation/remediation_pass.py), wired into run_v2_duckdb_pipeline() (src/vulnparse_pin/core/passes/__init__.py).

Rules for DuckDB extensions

  1. Parameterized SQL only: Never interpolate user/scanner strings into SQL. Use ? parameter bindings and explicit allowlists for sort/table identifiers.
  2. Idempotent schema migrations: Whenever adding columns or tables, update both schema.sql and ensure_v21_schema() (ALTER TABLE ... ADD COLUMN IF NOT EXISTS / CREATE TABLE IF NOT EXISTS) so existing .vpp.db files migrate cleanly on write, while read-only query paths (_table_exists, _table_columns) keep working on older workspaces without mutating them.
  3. Deterministic ordering: Every query driving scores, triage, remediation, diffing, or UI pagination must end with deterministic tie-breakers (asset_id ASC / finding_id ASC, or rank ASC for remediation_actions).
  4. Bulk ingestion via Appender: Batch writes (> 100 rows) must stage via TEMP TABLE + conn.appender(...) inside BEGIN TRANSACTION / COMMIT.
  5. Pass DAG isolation: Declare name, semantic version, and requires_passes on the Pass subclass (for example, RemediationPass declares name = "Remediation", version = "1.0", requires_passes = ("Triage@2.0",)), write outputs to .vpp.db tables for the active run_id, and return DerivedPassResult.
  6. Test coverage: Update tests/test_storage_duckdb.py, tests/test_pass_contracts.py, tests/test_remediation_optimizer.py, and tests/test_iter2_cross_component.py.

Playbook 3: Add a New Threat-Intel Source or Triage Profile

Enrichment sources

  1. Implement source loading inside EnrichmentSourceLoader (src/vulnparse_pin/app/enrichment_source_loader.py).
  2. If maintaining a local SQLite cache, inherit or mirror _SignedSQLiteFeedCache (0o600 POSIX perms, S_IWOTH rejection, VP_SQLITE_HMAC_KEY anti-downgrade, .tampered.<UTCSTAMP> quarantine, <= 900-parameter SQLite chunking). For longitudinal feeds like EPSSFeedCache (src/vulnparse_pin/utils/enricher.py), keep time-series history inside the signed SQLite database (such as epss_history pruned to max_days=90 rolling days) so deltas remain reproducible and HMAC-protected.
  3. If fetching over HTTPS, use _open_https_stream() / stream_https_get_bytes() (allow_redirects=False, per-hop HTTPS validation, bounded byte cap).
  4. Wire snapshot hydration into populate_enrichment_snapshots() (src/vulnparse_pin/app/enrichment.py), expose health in vpp intel status / vpp intel sync (src/vulnparse_pin/cli/commands.py), and update tests/test_intel_v2.py, tests/test_epss_velocity_pre_kev.py, and tests/test_iter1_intel_sec.py.

Triage profiles (Triage@2.0)

  1. Register profile normalization in normalize_triage_profile() (src/vulnparse_pin/core/config_validator.py) and cli/args.py.
  2. Implement deterministic SSVC / SLA mapping in TriageDecisionPass (src/vulnparse_pin/core/passes/Triage/triage_pass.py) while preserving DecisionsRegistry (decisions.yaml) assumption checks and static_sast_p1_cap.
  3. Verify DiffEngine (src/vulnparse_pin/core/diff_engine.py) and renderer.py Dossier/Roadmap templates handle the profile cleanly (tests/test_bod_26_04.py, tests/test_diff_engine.py, tests/test_reporting_v2.py).

Playbook 4: Extend ML Models, Inventory Importers, MCP Tools & UI Workbench

Offline ML models (src/vulnparse_pin/ml/)

  • Keep default inference dependency-free (distilled.py, aci_model.py, pre_kev.py, calibration.py) with optional ONNX Runtime hooks ([ml]) and optional scikit-learn retraining ([ml-train]).
  • Load and write models only through src/vulnparse_pin/ml/registry.py (load_signed_model, write_signed_model_artifact), enforcing regular non-symlink files, < 2 MiB distilled JSON / < 64 MiB ONNX caps, and VP_MODEL_HMAC_KEY anti-downgrade verification.
  • Preserve ml.mode: shadow score neutrality (never alter Scoring@3.0 numerical scores unless ml.mode == "active") and record model IDs/hashes in RunManifest (ml_governance).

Inventory importers (src/vulnparse_pin/core/inventory_compiler.py)

  • Add new CMDB or cloud inventory adapters inside inventory_compiler.py, register the --source choice in cli/args.py, sanitize untrusted strings against terminal/ANSI control sequences, and merge rules through merge_compiled_rules() so manually pinned criticality, internet_facing, and owner overrides are preserved unless --overwrite-pinned is passed.

MCP tools & HTML workbench (src/vulnparse_pin/mcp/)

  • Register new tools in src/vulnparse_pin/mcp/tools.py (McpToolSpec) with additionalProperties: false JSON input schemas, marking mutating tools write_required=True so they stay disabled unless --allow-write is supplied, and confine file operations via PermFileHandler.
  • Keep src/vulnparse_pin/mcp/ui_app.py (used by vpp mcp, vpp gui, and simulator-html exports) self-contained with zero external CDN requests, strict Content Security Policy headers, and HTML-escaped dynamic values.

Verification Commands

pytest tests/test_streaming_parsers.py tests/test_xxe_hardening.py -v
pytest tests/test_storage_duckdb.py tests/test_pass_contracts.py tests/test_remediation_optimizer.py -v
pytest tests/test_intel_v2.py tests/test_epss_velocity_pre_kev.py tests/test_iter1_intel_sec.py -v
pytest tests/test_ml_aci_v3.py tests/test_inventory_compiler.py tests/test_mcp_server.py tests/test_gui_workbench.py -v
pytest tests/test_bod_26_04.py tests/test_diff_engine.py tests/test_reporting_v2.py -v
pytest tests/test_cli_v2.py tests/test_cli_v21_roundtable.py tests/test_iter2_cross_component.py -v