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.pysrc/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.pysrc/vulnparse_pin/cli/args.py
Runtime bootstrap sequence (initialize_runtime)
- Resolve
AppPaths.resolve(portable=...)(XDG/platform app-data vs--portable./data/). - Create required directories (
paths.ensure_dirs()). - Initialize bootstrap
LoggerWrapper(bootstrap.log). - Construct
PermFileHandlerviabuild_pfh(paths, logger, args). - Load, validate, and project configs via
ConfigSource -> ConfigValidator -> ConfigProjector. - Initialize
FeedCacheManager, optionalNVDFeedCache,LedgerService, andWebhookRuntimeConfig. - Assemble frozen
ServicesandRunContext. - Rebind
LoggerWrapperto the run-specific log file (build_run_log()). - 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-readwith vs. without--portable:build_pfh()anchorsroot_dirtopaths.base_dir. When--portable(-P) is not set,paths.base_diris the OS user data directory (e.g.,~/.local/share/VulnParse-Pin/), so--enforce-root-readfails closed (FilePathError) on scan or manifest files under$PWD. When--portableis set,paths.base_diris$PWD, allowing reads under$PWDwhile still blocking reads outside$PWDand./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 andELOOPloops (_check_no_symlinks_or_loops), creates missing directories with0o777 & ~dir_modeunder_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 restrictedumask(_UMASK_LOCK), applies0o600POSIX permissions, and atomically replaces the target viaos.replace().VppDatabase&_validate_duckdb_paths(): Before opening.vpp.db, validates the DB path, all ancestors, and.wal/.tmpsidecars against symlinks andELOOP. In read-write mode on POSIX,duckdb.connect()andBEGIN TRANSACTIONexecute withumask(0o177)under_UMASK_LOCKso.vpp.dband.walare born0o600without a race window, followed by_chmod_0600_if_exists().- Darwin SSV root symlink exception (
_is_trusted_darwin_root_symlink()): BothPermFileHandler(_inspect_raw_symlinksandallow_workspace_rootinsrc/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 targetPathstrictly whensys.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/varor/private/var,/tmp -> private/tmpor/private/tmp,/etc -> private/etcor/private/etc), the symlink itself is owned byuid 0(st.st_uid == 0),os.readlink(cur)matches the exact expected target, andos.lstat(target_path)verifies a root-owned (st_uid == 0) non-symlink directory under/private. Traversal then re-anchorscurtotarget_pathso every subsequent child segment remains subject to strictos.lstatsymlink andELOOPrejection.
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 callsbuild_pfh(paths, silent_logger, args)without callingpaths.ensure_dirs(), sovpp verifyperforms zero writes to$HOME,$XDG_DATA_HOME,$XDG_CONFIG_HOME, or$XDG_CACHE_HOME(allowing execution in read-only containers and0o500home 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 inmanifest["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 withO_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 * 1024strictly< 2 MiBfor JSON models,MAX_SIGNATURE_ARTIFACT_BYTES = 64 * 1024, andMAX_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. WhenVP_MODEL_HMAC_KEY(MODEL_HMAC_ENV) is set,_verify_signature_payload()requiresmode == "hmac-sha256"and rejects plainsha256signatures (preventing downgrade). Conversely,hmac-sha256artifacts fail closed whenVP_MODEL_HMAC_KEYis unset. Companiononnx_pathentries 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/ HTTP403) unless--allow-writeis 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 least16characters; when configured, every request requiresAuthorization: Bearer <token>(hmac.compare_digest). - Header, framing & concurrency checks:
HttpSecurityPolicyrejects duplicateHost,Origin,Authorization,Content-Length, andX-VPP-CSRFheaders, rejectsTransfer-Encoding(501), enforces exactHostallowlisting (blocking DNS rebinding), validatesOriginhost/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:
VppGuiHttpServergenerates a per-server randomcsrf_token(secrets.token_urlsafe(32)) and requiresX-VPP-CSRFon allPOST /api/rpccalls (403on mismatch).GET /serves the self-contained HTML workbench withX-Frame-Options: DENY,X-Content-Type-Options: nosniff,Referrer-Policy: no-referrer,Cache-Control: no-store, and a zero-CDNContent-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).