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
- Create a parser module under
src/vulnparse_pin/parsers/. - Subclass
BaseParser(src/vulnparse_pin/parsers/base_parser.py) implementingdetect_file()anditer_batches(batch_size=...). - Register a
ParserSpecinPARSER_SPECS(src/vulnparse_pin/parsers/__init__.py).
Hardened streaming & licensing rules
- XML parsers: Must use
safe_iterparse()andprune_element()fromsrc/vulnparse_pin/parsers/_xml_security.py(backed bylxml.etree.iterparse). Never introducedefusedxmlorxml.etree.ElementTree. - JSON / SARIF / JSONL parsers: Must stream via chunked
json.JSONDecoder.raw_decode(see_FastSarifStreamReaderinsarif_parser.py),ijson, or bounded line iteration (nuclei_jsonl_parser.py)—never materialize multi-hundred-MB DOMs withjson.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 addAGPL,GPL, orLGPLruntime 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
detect_file()inspects only boundedhead_bytes(<= 64 KiB).iter_batches()emits completeNormalizedFindingRecordfields (detection_mode,signal_reliability,ingestion_confidence,fidelity_tier,source_format).- 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), andensure_v21_schema()insrc/vulnparse_pin/storage/repositories.py. - Parameterized repository helpers:
src/vulnparse_pin/storage/repositories.py. - Derived pass:
src/vulnparse_pin/core/passes/<PassName>/(includingRemediationPass(Remediation@1.0) insrc/vulnparse_pin/core/passes/Remediation/remediation_pass.py), wired intorun_v2_duckdb_pipeline()(src/vulnparse_pin/core/passes/__init__.py).
Rules for DuckDB extensions
- Parameterized SQL only: Never interpolate user/scanner strings into SQL. Use
?parameter bindings and explicit allowlists for sort/table identifiers. - Idempotent schema migrations: Whenever adding columns or tables, update both
schema.sqlandensure_v21_schema()(ALTER TABLE ... ADD COLUMN IF NOT EXISTS/CREATE TABLE IF NOT EXISTS) so existing.vpp.dbfiles migrate cleanly on write, while read-only query paths (_table_exists,_table_columns) keep working on older workspaces without mutating them. - Deterministic ordering: Every query driving scores, triage, remediation, diffing, or UI pagination must end with deterministic tie-breakers (
asset_id ASC/finding_id ASC, orrank ASCforremediation_actions). - Bulk ingestion via Appender: Batch writes (
> 100rows) must stage viaTEMP TABLE+conn.appender(...)insideBEGIN TRANSACTION/COMMIT. - Pass DAG isolation: Declare
name, semanticversion, andrequires_passeson thePasssubclass (for example,RemediationPassdeclaresname = "Remediation",version = "1.0",requires_passes = ("Triage@2.0",)), write outputs to.vpp.dbtables for the activerun_id, and returnDerivedPassResult. - Test coverage: Update
tests/test_storage_duckdb.py,tests/test_pass_contracts.py,tests/test_remediation_optimizer.py, andtests/test_iter2_cross_component.py.
Playbook 3: Add a New Threat-Intel Source or Triage Profile
Enrichment sources
- Implement source loading inside
EnrichmentSourceLoader(src/vulnparse_pin/app/enrichment_source_loader.py). - If maintaining a local SQLite cache, inherit or mirror
_SignedSQLiteFeedCache(0o600POSIX perms,S_IWOTHrejection,VP_SQLITE_HMAC_KEYanti-downgrade,.tampered.<UTCSTAMP>quarantine,<= 900-parameter SQLite chunking). For longitudinal feeds likeEPSSFeedCache(src/vulnparse_pin/utils/enricher.py), keep time-series history inside the signed SQLite database (such asepss_historypruned tomax_days=90rolling days) so deltas remain reproducible and HMAC-protected. - If fetching over HTTPS, use
_open_https_stream()/stream_https_get_bytes()(allow_redirects=False, per-hop HTTPS validation, bounded byte cap). - Wire snapshot hydration into
populate_enrichment_snapshots()(src/vulnparse_pin/app/enrichment.py), expose health invpp intel status/vpp intel sync(src/vulnparse_pin/cli/commands.py), and updatetests/test_intel_v2.py,tests/test_epss_velocity_pre_kev.py, andtests/test_iter1_intel_sec.py.
Triage profiles (Triage@2.0)
- Register profile normalization in
normalize_triage_profile()(src/vulnparse_pin/core/config_validator.py) andcli/args.py. - Implement deterministic SSVC / SLA mapping in
TriageDecisionPass(src/vulnparse_pin/core/passes/Triage/triage_pass.py) while preservingDecisionsRegistry(decisions.yaml) assumption checks andstatic_sast_p1_cap. - Verify
DiffEngine(src/vulnparse_pin/core/diff_engine.py) andrenderer.pyDossier/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 MiBdistilled JSON /< 64 MiBONNX caps, andVP_MODEL_HMAC_KEYanti-downgrade verification. - Preserve
ml.mode: shadowscore neutrality (never alterScoring@3.0numerical scores unlessml.mode == "active") and record model IDs/hashes inRunManifest(ml_governance).
Inventory importers (src/vulnparse_pin/core/inventory_compiler.py)
- Add new CMDB or cloud inventory adapters inside
inventory_compiler.py, register the--sourcechoice incli/args.py, sanitize untrusted strings against terminal/ANSI control sequences, and merge rules throughmerge_compiled_rules()so manually pinnedcriticality,internet_facing, andowneroverrides are preserved unless--overwrite-pinnedis passed.
MCP tools & HTML workbench (src/vulnparse_pin/mcp/)
- Register new tools in
src/vulnparse_pin/mcp/tools.py(McpToolSpec) withadditionalProperties: falseJSON input schemas, marking mutating toolswrite_required=Trueso they stay disabled unless--allow-writeis supplied, and confine file operations viaPermFileHandler. - Keep
src/vulnparse_pin/mcp/ui_app.py(used byvpp mcp,vpp gui, andsimulator-htmlexports) 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