Skip to main content
VulnParse-Pin emblem VulnParse-Pin emblem
VulnParse-Pin
Architecture Runtime Policy Deep Dive.md
View source on GitHub ↗

Runtime Policy Deep Dive

This page explains runtime control-plane policy in VulnParse-Pin v2.1.1 (Apache-2.0): PermFileHandler (PFH), _UMASK_LOCK & non-PFH atomic writes, DuckDB workspace permissions, read-only vpp verify enforcement, signed ML artifact verification (VP_MODEL_HMAC_KEY), webhook HMAC signing (VP_WEBHOOK_HMAC_KEY), vpp mcp/vpp gui HTTP & --allow-write controls, logging policy, and RunContext / Services wiring.

Scope

Primary implementation files:

  • src/vulnparse_pin/app/bootstrap.py
  • src/vulnparse_pin/cli/commands.py (_build_verify_pfh, run_verify_command, run_intel_command, run_gui_command)
  • src/vulnparse_pin/core/classes/dataclass.py (RunContext, Services, WebhookRuntimeConfig)
  • src/vulnparse_pin/io/pfhandler.py (PermFileHandler, _UMASK_LOCK, _is_trusted_darwin_root_symlink)
  • src/vulnparse_pin/storage/db.py (VppDatabase, _check_no_symlinks_or_loops, _validate_duckdb_paths, ensure_safe_dir_non_pfh, open_for_write_non_pfh)
  • src/vulnparse_pin/ml/registry.py (load_signed_model, MODEL_HMAC_ENV)
  • src/vulnparse_pin/mcp/server.py (validate_http_security, HttpSecurityPolicy, VppMcpServer)
  • src/vulnparse_pin/ui/gui_server.py (VppGuiHttpServer, _VppGuiHttpHandler, create_gui_http_server)
  • src/vulnparse_pin/utils/logger.py
  • src/vulnparse_pin/cli/args.py

Runtime bootstrap sequence (initialize_runtime)

  1. Resolve AppPaths.resolve(portable=...) (XDG/platform app-data vs --portable ./data/).
  2. Create required directories (paths.ensure_dirs()).
  3. Initialize bootstrap LoggerWrapper (bootstrap.log).
  4. Construct PermFileHandler via build_pfh(paths, logger, args).
  5. Load, validate, and project configs via ConfigSource -> ConfigValidator -> ConfigProjector.
  6. Initialize FeedCacheManager, optional NVDFeedCache, LedgerService, and WebhookRuntimeConfig.
  7. Assemble frozen Services and RunContext.
  8. Rebind LoggerWrapper to the run-specific log file (build_run_log()).
  9. Construct SchemaDetector(PARSER_SPECS).

RunContext and Services

Services (feed_cache, nvd_cache, scoring_config, topn_config, post_enrichment_index, ledger, runmanifest_mode, nmap_ctx_config, webhook_config, global_config, enrichment_stats, db, run_id, asset_matcher, decisions_registry) and RunContext (paths, pfh, logger, services, plus promoted optional fields enrichment_stats, db, run_id, asset_matcher, decisions_registry copied from services in __post_init__ when omitted) are frozen dataclasses so runtime policy cannot be mutated mid-run.

PFH Policy (PermFileHandler) and CLI Defaults

build_pfh() constructs PermFileHandler with secure-by-default flags from cli/args.py:

Flag / Attribute Default Override Flag Effect
forbid_symlinks_read True --allow-symlinks-read Rejects symlinks and symlink ancestors on read
forbid_symlinks_write True (fail-closed) Rejects symlinks and symlink ancestors on write
enforce_roots_on_read False --enforce-root-read (-err) Confines reads to allowed_roots (paths.base_dir, config_dir, cache_dir, log_dir, output_dir)
enforce_roots_on_write True (enforced) Confines writes to authorized output paths & allowed_roots
file_mode (POSIX) 0o600 --file-mode (-fm) Owner-only read/write permissions on created files
dir_mode (POSIX) 0o700 --dir-mode (-dm) Owner-only permissions on created directories

IMPORTANT--enforce-root-read with vs. without --portable: build_pfh() anchors root_dir to paths.base_dir. When --portable (-P) is not set, paths.base_dir is the OS user data directory (e.g., ~/.local/share/VulnParse-Pin/), so --enforce-root-read fails closed (FilePathError) on scan or manifest files under $PWD. When --portable is set, paths.base_dir is $PWD, allowing reads under $PWD while still blocking reads outside $PWD and ./data/.

Diagnostic mode:

vpp scan --debug-path-policy

prints pfh.describe_policy() and exits without running a scan.

_UMASK_LOCK, Non-PFH Atomic Writes, and DuckDB Path Hardening

Because os.umask() is process-global, src/vulnparse_pin/io/pfhandler.py defines _UMASK_LOCK = threading.Lock(). Both PFH and src/vulnparse_pin/storage/db.py serialize umask transitions under _UMASK_LOCK:

  • ensure_safe_dir_non_pfh(dir_path, dir_mode=0o700): Checks every path ancestor against symlinks and ELOOP loops (_check_no_symlinks_or_loops), creates missing directories with 0o777 & ~dir_mode under _UMASK_LOCK, and re-verifies post-create.
  • open_for_write_non_pfh(target_path, file_mode=0o600, dir_mode=0o700): Validates ancestors and existing targets against symlinks/non-regular files, creates a sibling staging temp file under restricted umask (_UMASK_LOCK), applies 0o600 POSIX permissions, and atomically replaces the target via os.replace().
  • VppDatabase & _validate_duckdb_paths(): Before opening .vpp.db, validates the DB path, all ancestors, and .wal / .tmp sidecars against symlinks and ELOOP. In read-write mode on POSIX, duckdb.connect() and BEGIN TRANSACTION execute with umask(0o177) under _UMASK_LOCK so .vpp.db and .wal are born 0o600 without a race window, followed by _chmod_0600_if_exists().
  • Darwin SSV root symlink exception (_is_trusted_darwin_root_symlink()): Both PermFileHandler (_inspect_raw_symlinks and allow_workspace_root in src/vulnparse_pin/io/pfhandler.py) and _check_no_symlinks_or_loops() (src/vulnparse_pin/storage/db.py) invoke _is_trusted_darwin_root_symlink(cur, st) when traversing path segments. It returns the canonical target Path strictly when sys.platform == "darwin", stat.S_ISLNK(st.st_mode) is true, cur.as_posix() is one of macOS’s three immutable Signed System Volume entries in _DARWIN_ROOT_SYMLINK_TARGETS (/var -> private/var or /private/var, /tmp -> private/tmp or /private/tmp, /etc -> private/etc or /private/etc), the symlink itself is owned by uid 0 (st.st_uid == 0), os.readlink(cur) matches the exact expected target, and os.lstat(target_path) verifies a root-owned (st_uid == 0) non-symlink directory under /private. Traversal then re-anchors cur to target_path so every subsequent child segment remains subject to strict os.lstat symlink and ELOOP rejection.

Read-Only Default Policy on vpp verify (_build_verify_pfh)

run_verify_command() (src/vulnparse_pin/cli/commands.py) uses _build_verify_pfh(args) rather than initialize_runtime(args):

  • Attaches a silent logging.NullHandler() logger and calls build_pfh(paths, silent_logger, args) without calling paths.ensure_dirs(), so vpp verify performs zero writes to $HOME, $XDG_DATA_HOME, $XDG_CONFIG_HOME, or $XDG_CACHE_HOME (allowing execution in read-only containers and 0o500 home environments).
  • Directories and log files are created only if the operator explicitly passes a non-default --log-file (!= "vulnparse_pin.log").
  • All security flags (forbid_symlinks_read=True, --allow-symlinks-read, --enforce-root-read, --portable) remain strictly enforced across both the RunManifest file and every non-null artifact listed in manifest["outputs"].

Signed ML Artifact Verification (VP_MODEL_HMAC_KEY)

load_signed_model() (src/vulnparse_pin/ml/registry.py) loads distilled JSON and optional ONNX ML artifacts fail-closed:

  • Filesystem & size caps: _read_verified_regular_bytes() inspects path ancestors via _check_no_symlinks_or_loops(), opens with O_NOFOLLOW | O_NONBLOCK, rejects symlinks, non-regular files, and world-writable (S_IWOTH) files on POSIX, and enforces strict byte limits (MAX_MODEL_ARTIFACT_BYTES = 2 * 1024 * 1024 strictly < 2 MiB for JSON models, MAX_SIGNATURE_ARTIFACT_BYTES = 64 * 1024, and MAX_ONNX_ARTIFACT_BYTES = 64 * 1024 * 1024). Non-standard JSON constants (NaN, Infinity) are rejected.
  • Anti-downgrade signature checks: Every artifact requires a companion .sig.json. When VP_MODEL_HMAC_KEY (MODEL_HMAC_ENV) is set, _verify_signature_payload() requires mode == "hmac-sha256" and rejects plain sha256 signatures (preventing downgrade). Conversely, hmac-sha256 artifacts fail closed when VP_MODEL_HMAC_KEY is unset. Companion onnx_path entries inside metadata must be relative without .. traversal.

Webhook HMAC Signing (VP_WEBHOOK_HMAC_KEY)

WebhookRuntimeConfig (src/vulnparse_pin/core/classes/dataclass.py) defaults signing_key_env to "VP_WEBHOOK_HMAC_KEY" (key_id: "primary", replay_window_seconds: 300, max_payload_bytes: 262144). ConfigValidator enforces HTTPS-only webhook URLs without embedded credentials and private/loopback/metadata IP blocking unless explicitly overridden (VP_WEBHOOK_ALLOW_PRIVATE).

vpp mcp and vpp gui HTTP & --allow-write Enforcement

Both vpp mcp --transport streamable-http (src/vulnparse_pin/mcp/server.py) and vpp gui (src/vulnparse_pin/ui/gui_server.py) share fail-closed HTTP and write-gating controls:

  • Read-only by default: Write tools (vpp_scan_and_diff, vpp_propose_deferral, vpp_export_dossier) and GUI write mutations (deferral recording, Shadow-IT asset promotion) are blocked (ToolDisabledError / HTTP 403) unless --allow-write is explicitly passed. Even with --allow-write, writes remain confined to PFH-authorized paths (--workspace-root / assets.yaml / decisions.yaml).
  • Loopback & non-loopback --auth-token-env: validate_http_security() rejects any non-loopback bind host unless --auth-token-env <ENV_VAR> is set and points to a secret of at least 16 characters; when configured, every request requires Authorization: Bearer <token> (hmac.compare_digest).
  • Header, framing & concurrency checks: HttpSecurityPolicy rejects duplicate Host, Origin, Authorization, Content-Length, and X-VPP-CSRF headers, rejects Transfer-Encoding (501), enforces exact Host allowlisting (blocking DNS rebinding), validates Origin host/port when present (403), bounds concurrency (MAX_HTTP_CONCURRENCY = 32), caps body size (MAX_MESSAGE_BYTES = 4 MiB), and caps JSON nesting depth (MAX_JSON_DEPTH = 64).
  • GUI CSRF & zero-CDN CSP: VppGuiHttpServer generates a per-server random csrf_token (secrets.token_urlsafe(32)) and requires X-VPP-CSRF on all POST /api/rpc calls (403 on mismatch). GET / serves the self-contained HTML workbench with X-Frame-Options: DENY, X-Content-Type-Options: nosniff, Referrer-Policy: no-referrer, Cache-Control: no-store, and a zero-CDN Content-Security-Policy (default-src 'none'; script-src 'unsafe-inline'; style-src 'unsafe-inline'; img-src data:; connect-src 'self'; frame-ancestors 'none'; base-uri 'none'; form-action 'none'; object-src 'none').

Logging Policy (LoggerWrapper)

LoggerWrapper (src/vulnparse_pin/utils/logger.py) configures a DEBUG file handler (ANSI-stripped) and a CLI-level console handler (INFO default, custom SUCCESS level 25).