From aeccbe2457786c17396876695b4c58187b2b0111 Mon Sep 17 00:00:00 2001 From: AlexanderLevenskikh Date: Tue, 1 Dec 2026 01:48:59 +0500 Subject: [PATCH] fix: enforce standalone audit policy and transition target domain --- README.md | 19 ++- dependency_live_roadmap_generator.py | 65 ++++++--- docs/audits/2026-12-01/core-boundaries.md | 58 ++++++++ manual_dependency_audit.py | 56 +++++-- peer_solver_transition.py | 11 ++ registry_privacy.py | 22 +++ tests/test_manual_audit_host_policy.py | 170 ++++++++++++++++++++++ tests/test_peer_solver_transition.py | 27 ++++ 8 files changed, 395 insertions(+), 33 deletions(-) create mode 100644 docs/audits/2026-12-01/core-boundaries.md create mode 100644 tests/test_manual_audit_host_policy.py diff --git a/README.md b/README.md index fd1cd03..3b52aab 100644 --- a/README.md +++ b/README.md @@ -20,7 +20,7 @@ For an application migration, start with the [npm installer and walkthrough](htt ### Check the engine from source -Supported Core Python range: **3.12–3.13** (`>=3.12,<3.14`). From a clean checkout: +Supported Core Python range: **3.12–3.14** (`>=3.12,<3.15`). From a clean checkout: ```sh python -m venv .venv @@ -43,6 +43,23 @@ Use the interpreter from your virtual environment if `python` resolves elsewhere A Draft proposal is **`PLANNING_ONLY` / `NOT_VERIFIED`**. An accepted lockfile, a clean install, effective dependency providers, project checks, and runtime acceptance are separate results. +### Manual audit under a host policy + +The standalone `manual_dependency_audit.py` helper runs native package-manager +commands. When the host configures private scopes or restricts network evidence, +use MCP `audit_dependencies`, which admits the inventory and controls its native +audit route. The standalone helper refuses these host policies before native +dispatch with a typed error. A blocked or unavailable guarded route remains +`UNKNOWN`. Ordinary explicit registry and mirror audits without a restrictive +host policy retain the standalone helper path. + +This admission check covers `DEPLOOM_DRAFT_PRIVATE_SCOPES`, +`DEPLOOM_MCP_PRIVATE_SCOPES`, `DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE`, +`DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE`, `DEPLOOM_MCP_LOCAL_CACHE_ONLY`, and +`DEPLOOM_MCP_RECORDS_MIRROR_ONLY`. Migration and knowledge-only flags retain +their separate scope. These settings do not provide a system-wide network +sandbox for package managers, installation scripts, or project commands. + ## Where it fits ```text diff --git a/dependency_live_roadmap_generator.py b/dependency_live_roadmap_generator.py index ae31e0f..d1f6864 100644 --- a/dependency_live_roadmap_generator.py +++ b/dependency_live_roadmap_generator.py @@ -25699,6 +25699,23 @@ def _draft_audit_command_block(policy_hash: str, language: str, ctx: Mapping[str """The ready-to-run manual_dependency_audit.py PowerShell command with real values substituted (batch B3 contract) plus the engine/accuracy rationale delivered directly in the prompt.""" + from registry_privacy import standalone_audit_block_reason + + blocked = standalone_audit_block_reason(os.environ) + if blocked: + if language == "ru": + return ( + f"Host policy: `{blocked}`. Для аудита используй MCP `audit_dependencies` с разрешённым host маршрутом. " + "Самостоятельный helper не обеспечивает ограничения сети и приватных scopes. Если MCP недоступен " + "или отказывает по политике, сохрани blocked/UNKNOWN и укажи недостающее разрешение или evidence. " + "Не обходи ограничение прямым npm/yarn audit или npm view и не отключай host policy." + ) + return ( + f"Host policy: `{blocked}`. Use MCP `audit_dependencies` with the host-approved audit route. " + "The standalone helper cannot enforce network or private-scope restrictions. If MCP is unavailable " + "or refuses under policy, preserve blocked/UNKNOWN and identify the missing authorization or evidence. " + "Do not bypass the restriction with npm/yarn audit or npm view, or disable the host policy." + ) tool_root = str(ctx.get("toolRoot") or Path(__file__).resolve().parent) project_path = str(ctx.get("projectPath") or "") project_name = str(ctx.get("projectName") or "") @@ -25750,7 +25767,7 @@ def _draft_audit_command_block(policy_hash: str, language: str, ctx: Mapping[str + "\n\n" + f"- `policyHash` этого run: `{policy_hash}`; подставляй пользовательскую политику, а не константы примера.\n" + "- Если задана per-package политика (dashboard-state), передавай её через `--dashboard-state`.\n" - + "- Проект именно Yarn: `--lag-months/--min-lag-ok-pct/--max-known-high` берутся из политики выше; " + + "- `--lag-months/--min-lag-ok-pct/--max-known-high` берутся из политики запуска выше; " + "проверь, что все флаги поддерживаются текущей версией helper (иначе threshold невыразим — это честное ограничение, не скрывай расхождение)." ) return ( @@ -25758,7 +25775,7 @@ def _draft_audit_command_block(policy_hash: str, language: str, ctx: Mapping[str + "\n\n" + f"- `policyHash` of this run: `{policy_hash}`; substitute the user policy, not example constants.\n" + "- If a per-package policy exists (dashboard-state), pass it via `--dashboard-state`.\n" - + "- The project is Yarn: `--lag-months/--min-lag-ok-pct/--max-known-high` come from the policy above; " + + "- `--lag-months/--min-lag-ok-pct/--max-known-high` come from the run policy above; " + "verify the flags are supported by the installed helper (otherwise the threshold is simply not expressible - an honest limitation, not a hidden drift)." ) @@ -25999,6 +26016,8 @@ def build_draft_prompt( contract = contract_from_snapshot(snapshot if snapshot is not None else policy_snapshot_from_env()) lines += decision_contract_prompt(contract, language) + from registry_privacy import standalone_audit_block_reason + audit_helper_blocked = bool(standalone_audit_block_reason(os.environ)) ctx = execution_context or {} registry = str(ctx.get("registry") or "").strip() registry_note = "—" if not registry else "см. ниже (без credentials)" @@ -26079,16 +26098,21 @@ def build_draft_prompt( "", ] lines += [ - "## Аудит уязвимостей (штатная команда, подставлены реальные значения)", + "## Аудит уязвимостей", "", _draft_audit_command_block(policy_hash, language, ctx, artifact_root) + "", - "- НЕ заменяй helper прямым `yarn audit`: Yarn `auto` сейчас означает изолированный npm-lock-bridge; " - "корневой yarn.lock остаётся каноническим, сгенерированный package-lock не попадает в исходный проект.", - "- `accuracy=npm-resolved-approximation` — сверка по другому разрешённому графу, а не точное доказательство " - "безопасности Yarn-графа; не выдавай approximate/trusted за canonical pass.", - "- Для строгой canonical проверки используй `--yarn-audit-engine yarn-inventory`: точные package/version из " - "yarn.lock через npm security endpoint без нового разрешения диапазонов; неполный inventory/registry — " - "unknown, не zero.", + ] + if not audit_helper_blocked: + lines += [ + "- НЕ заменяй helper прямым `yarn audit`: Yarn `auto` сейчас означает изолированный npm-lock-bridge; " + "корневой yarn.lock остаётся каноническим, сгенерированный package-lock не попадает в исходный проект.", + "- `accuracy=npm-resolved-approximation` — сверка по другому разрешённому графу, а не точное доказательство " + "безопасности Yarn-графа; не выдавай approximate/trusted за canonical pass.", + "- Для строгой canonical проверки используй `--yarn-audit-engine yarn-inventory`: точные package/version из " + "yarn.lock через npm security endpoint без нового разрешения диапазонов; неполный inventory/registry — " + "unknown, не zero.", + ] + lines += [ "- Выводи отдельно: OSV/direct (генератор), canonical inventory и npm bridge. До/после сравнивай ОДИН engine " "и одну единицу подсчёта; храни время и источник adivsories, coverage, raw evidence.", "- Exit code аудита интерпретируй по структурированному результату: findings и failure получения данных — " @@ -26221,16 +26245,21 @@ def build_draft_prompt( "", ] lines += [ - "## Vulnerability audit (canonical helper command, real values substituted)", + "## Vulnerability audit", "", _draft_audit_command_block(policy_hash, language, ctx, artifact_root) + "", - "- Do NOT replace the helper with a plain `yarn audit`: Yarn `auto` currently means an isolated npm-lock-" - "bridge; the root yarn.lock stays canonical and the generated package-lock never lands in the project.", - "- `accuracy=npm-resolved-approximation` is a cross-check against another resolved graph, not proof of " - "security of the Yarn graph; do not present approximate/trusted as a canonical pass.", - "- For a strict canonical check use `--yarn-audit-engine yarn-inventory`: exact package/version from " - "yarn.lock via the npm security endpoint without re-resolving ranges; an incomplete inventory/registry is " - "unknown, not zero.", + ] + if not audit_helper_blocked: + lines += [ + "- Do NOT replace the helper with a plain `yarn audit`: Yarn `auto` currently means an isolated npm-lock-" + "bridge; the root yarn.lock stays canonical and the generated package-lock never lands in the project.", + "- `accuracy=npm-resolved-approximation` is a cross-check against another resolved graph, not proof of " + "security of the Yarn graph; do not present approximate/trusted as a canonical pass.", + "- For a strict canonical check use `--yarn-audit-engine yarn-inventory`: exact package/version from " + "yarn.lock via the npm security endpoint without re-resolving ranges; an incomplete inventory/registry is " + "unknown, not zero.", + ] + lines += [ "- Report separately: OSV/direct (generator), canonical inventory, and npm bridge. Before/after must use " "the SAME engine and the same counting unit; keep advisory source/time, coverage, raw evidence.", "- Interpret the audit exit code from the structured result: findings and data-fetch failure are different " diff --git a/docs/audits/2026-12-01/core-boundaries.md b/docs/audits/2026-12-01/core-boundaries.md new file mode 100644 index 0000000..9dba944 --- /dev/null +++ b/docs/audits/2026-12-01/core-boundaries.md @@ -0,0 +1,58 @@ +# Core boundary follow-up — 2026-12-01 + +Base reviewed: `7f6426c001f7197fd1659d51f6946fcc9a8655b3`. +This note records the narrowly reproduced Core findings and local remediation. +It is not a release acceptance receipt or a replacement for the earlier audit matrix. + +## Findings and changes + +| Finding | Before | Change | +| --- | --- | --- | +| N01 residual standalone helper policy gap | The generated prompt could recommend `manual_dependency_audit.py` under a private-scope host policy, while the helper constructed a native public-registry audit command without that policy admission. A synthetic lockfile contained a private transitive dependency; dispatch was intercepted and no data was sent. The separately guarded MCP audit route already enforced its policy. | Standalone report/audit entry points and the original native dispatch refuse private, malformed, or restricted host policies before dispatch. Restricted generated prompts direct the agent to MCP `audit_dependencies`. Its admitted injected Runner remains supported. | +| Transition target endpoint hardening | The public transition refiner could return `safe=True` for a target outside a package's finite domain. Normal planner callers supply a domain-valid solver target, so this reproducer does not establish an unsafe end-to-end plan. | Refuse an out-of-domain target with `INVALID_TARGET_ENDPOINT: OUTSIDE_DOMAIN`. A recorded current version outside the final candidate domain remains a valid baseline. | +| D08 Python documentation | README stated Python 3.12–3.13 while project metadata and the configured CI matrix supported 3.12–3.14. | Align README with `>=3.12,<3.15`. | + +The standalone policy check covers `DEPLOOM_DRAFT_PRIVATE_SCOPES`, +`DEPLOOM_MCP_PRIVATE_SCOPES`, `DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE`, +`DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE`, `DEPLOOM_MCP_LOCAL_CACHE_ONLY`, and +`DEPLOOM_MCP_RECORDS_MIRROR_ONLY`. A supplied runtime environment can add a +restriction but cannot erase the host's restriction. `MIGRATION_OFFLINE` and +`KNOWLEDGE_DISABLED` retain their separate migration/knowledge meaning; these +flags are not a system-wide network sandbox. An unavailable guarded audit +remains blocked or `UNKNOWN`, never an assumed clean result. Ordinary explicit +registry/mirror routes without a restrictive audit policy remain available. + +## Negative tests and verification + +The added tests fail against the preceding implementation: private and malformed +scope policies reached native dispatch; restricted metadata dispatch and prompt +generation lacked the new boundary; an out-of-domain target was reported safe. +The mirror-only admission test also failed before its parity correction. +Tests intercept native calls and do not contact registries. + +Final focused Core verification: **72 tests passed** on Python 3.13.5, using the +hash-locked dependencies from the matching npm runtime lock. Coverage includes +canonical scopes, malformed policy, runtime-environment restriction union, +pre-dispatch refusal, typed CLI errors with no report output, RU/EN prompts, +unrestricted explicit mirrors, guarded Runner preservation, target-domain +rejection, and a current endpoint outside the final domain. + +Independent integration against MCP `0ff43ef1fcf4fdd050c75139c83bb3d633842dc2` +and this helper: **51 tests passed**, including scoped inventory, aliases, +transitive dependencies, approved mirrors, redirects, and candidate audit +admission. The test helper path was explicitly set to this candidate checkout; +no release manifest or integrity check was weakened. + +## Environment limitations + +The full local Core candidate run executed **849 tests** and reported +**6 failures, 11 errors, and 95 skips**. All errors and the native preparation +failures were blocked by `PROCESS_TREE_OWNERSHIP_UNAVAILABLE`: this container +does not expose the required `/proc/self/task//children` capability. +The native semver comparison consequently received unknown results; an +instrumented dispatch confirmed the same supervisor exception without changing +the guard. This is not a green full-suite result. The full run preceded the +final mirror-only parity and documentation edits; the final focused run above +includes them. Native platform CI and release checks must establish their own +results against the eventual commit. No process ownership guard or test matrix +was weakened, and this note makes no new Windows/macOS execution claim. diff --git a/manual_dependency_audit.py b/manual_dependency_audit.py index 51836ac..1d14b48 100644 --- a/manual_dependency_audit.py +++ b/manual_dependency_audit.py @@ -31,12 +31,30 @@ from dateutil.relativedelta import relativedelta from cli_io import configure_utf8_stdio +from registry_privacy import standalone_audit_block_reason SECTIONS = ("dependencies", "devDependencies", "optionalDependencies", "peerDependencies") AUDIT_ROOT_SECTIONS = ("dependencies", "devDependencies", "optionalDependencies") SEVERITIES = ("critical", "high", "moderate", "low", "unknown") +class ManualAuditPolicyError(ValueError): + """The standalone helper cannot satisfy the host's native network policy.""" + + def __init__(self, code: str): + self.code = code + super().__init__( + f"{code}: use MCP audit_dependencies with the host-approved audit route; " + "keep a blocked or UNKNOWN result when that route is unavailable." + ) + + +def _require_standalone_audit_policy(runtime_env=None) -> None: + reason = standalone_audit_block_reason(os.environ, runtime_env) + if reason: + raise ManualAuditPolicyError(reason) + + def read_json(path: Path) -> Dict[str, Any]: return json.loads(path.read_text(encoding="utf-8-sig")) @@ -518,6 +536,9 @@ def direct_dependencies(project: Path) -> List[Dict[str, str]]: def run(command: List[str], cwd: Path, env: Optional[Dict[str, str]] = None, timeout: Optional[int] = None) -> Tuple[int, str, str]: + # This is the standalone subprocess adapter. The MCP worker supplies its + # own admitted Runner instead of asking this helper to enforce egress. + _require_standalone_audit_policy(env) if not command: return 127, "", "cannot execute empty command" @@ -1504,6 +1525,7 @@ def run_audit( yarn_audit_engine: Optional[str] = None, runtime_env: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: + _require_standalone_audit_policy(runtime_env) if manager == "yarn": mode = str( yarn_audit_engine @@ -1935,6 +1957,7 @@ def build_report( max_known_low: Optional[int] = None, runtime_env: Optional[Dict[str, str]] = None, ) -> Dict[str, Any]: + _require_standalone_audit_policy(runtime_env) manager = package_manager(project) deps = direct_dependencies(project) policies = load_lag_policies(dashboard_state, project_name) @@ -2050,20 +2073,25 @@ def main() -> int: raise SystemExit(f"package.json not found: {project / 'package.json'}") dashboard_state = Path(args.dashboard_state).expanduser().resolve() if args.dashboard_state else None audit_workspace = Path(args.audit_workspace).expanduser().resolve() if args.audit_workspace else None - report = build_report( - project, - args.project_name, - args.registry, - args.lag_months, - dashboard_state, - audit_workspace, - yarn_audit_engine=args.yarn_audit_engine, - target_level=args.target_level, - min_lag_ok_pct=args.min_lag_ok_pct, - max_known_high=args.max_known_high, - max_known_moderate=args.max_known_moderate, - max_known_low=args.max_known_low, - ) + try: + report = build_report( + project, + args.project_name, + args.registry, + args.lag_months, + dashboard_state, + audit_workspace, + yarn_audit_engine=args.yarn_audit_engine, + target_level=args.target_level, + min_lag_ok_pct=args.min_lag_ok_pct, + max_known_high=args.max_known_high, + max_known_moderate=args.max_known_moderate, + max_known_low=args.max_known_low, + ) + except ManualAuditPolicyError as exc: + print(json.dumps({"complete": False, "auditComplete": False, + "error": {"code": exc.code, "message": str(exc)}}, ensure_ascii=False), file=sys.stderr) + return 2 md = markdown(report, args.lang) print(md) if args.json_out: diff --git a/peer_solver_transition.py b/peer_solver_transition.py index 2a1890b..16ba3de 100644 --- a/peer_solver_transition.py +++ b/peer_solver_transition.py @@ -209,6 +209,17 @@ def refine_transition_safe_groups( missing = sorted(expected - set(target_assignment)) raise ValueError(f"transition target assignment is missing: {', '.join(missing)}") + # The normal planner supplies a solved assignment, but this API must not + # label an out-of-domain target safe. The recorded baseline may be outside + # the final candidate domain when an upgrade is required. + outside_domain = tuple( + f"INVALID_TARGET_ENDPOINT: OUTSIDE_DOMAIN: {package.name}@{target_assignment[package.name]}" + for package in model.packages + if target_assignment[package.name] not in package.domain + ) + if outside_domain: + return TransitionSafetyResult(groups=(), unresolved=outside_domain) + # shortcut: grouped cardinalities need a dedicated transition proof before support. if model.cardinalities: return TransitionSafetyResult( diff --git a/registry_privacy.py b/registry_privacy.py index 91386d8..1f32c5c 100644 --- a/registry_privacy.py +++ b/registry_privacy.py @@ -31,3 +31,25 @@ def private_package(package: str, private_scopes: str) -> bool: return package.partition("/")[0].lower() in normalize_private_scopes(private_scopes) except ValueError: return True + + +def standalone_audit_block_reason(host_environment, runtime_environment=None) -> str: + """The standalone helper cannot enforce a guarded native audit route. + + A supplied command environment may add restrictions, but cannot erase the + host's policy. The MCP worker owns its separate admitted native Runner. + """ + environments = (host_environment,) if runtime_environment is None else (host_environment, runtime_environment) + has_private_scopes = False + for environment in environments: + for key in ("DEPLOOM_DRAFT_PRIVATE_SCOPES", "DEPLOOM_MCP_PRIVATE_SCOPES"): + try: + has_private_scopes = bool(normalize_private_scopes(environment.get(key, ""))) or has_private_scopes + except (ValueError, TypeError, AttributeError): + return "INVALID_PRIVATE_SCOPES" + if any(environment.get(key) == "1" for environment in environments for key in ( + "DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE", "DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE", + "DEPLOOM_MCP_LOCAL_CACHE_ONLY", "DEPLOOM_MCP_RECORDS_MIRROR_ONLY", + )): + return "NETWORK_POLICY_REQUIRES_GUARDED_AUDIT" + return "PRIVATE_SCOPE_POLICY_REQUIRES_GUARDED_AUDIT" if has_private_scopes else "" diff --git a/tests/test_manual_audit_host_policy.py b/tests/test_manual_audit_host_policy.py new file mode 100644 index 0000000..7e6b3c9 --- /dev/null +++ b/tests/test_manual_audit_host_policy.py @@ -0,0 +1,170 @@ +"""Standalone native audit must not bypass the host's evidence policy. + +Every native dispatch is intercepted. The guarded MCP worker supplies its own +Runner; the last test preserves that existing adapter boundary. +""" +from __future__ import annotations + +import io +import json +import os +import tempfile +import unittest +from contextlib import redirect_stderr +from pathlib import Path +from unittest.mock import patch + +import dependency_live_roadmap_generator as core +import manual_dependency_audit as manual + + +class ManualAuditHostPolicyTests(unittest.TestCase): + def setUp(self): + temp = tempfile.TemporaryDirectory() + self.addCleanup(temp.cleanup) + self.project = Path(temp.name) + (self.project / "package.json").write_text(json.dumps({ + "name": "fixture", "dependencies": {"public-parent": "1.0.0"}, + }), encoding="utf-8") + # The private identity exists only in the transitive inventory. + (self.project / "package-lock.json").write_text(json.dumps({ + "lockfileVersion": 3, + "packages": { + "": {"dependencies": {"public-parent": "1.0.0"}}, + "node_modules/public-parent": { + "version": "1.0.0", "dependencies": {"@fixture/private": "1.0.0"}, + }, + "node_modules/@fixture/private": {"version": "1.0.0"}, + }, + }), encoding="utf-8") + self.clean_audit = json.dumps({ + "auditReportVersion": 2, "vulnerabilities": {}, + "metadata": {"vulnerabilities": {"total": 0}}, + }) + + def test_scoped_standalone_audit_is_refused_before_native_dispatch(self): + for variable in ("DEPLOOM_DRAFT_PRIVATE_SCOPES", "DEPLOOM_MCP_PRIVATE_SCOPES"): + for scopes in ("fixture", "@Fixture", " other, @FIXTURE "): + with self.subTest(variable=variable, scopes=scopes), patch.dict( + os.environ, {variable: scopes}, clear=True, + ), patch.object(manual, "run", return_value=(0, self.clean_audit, "")) as dispatch: + with self.assertRaisesRegex(ValueError, "PRIVATE_SCOPE_POLICY_REQUIRES_GUARDED_AUDIT"): + manual.run_audit(self.project, "npm", "https://registry.npmjs.org") + dispatch.assert_not_called() + + def test_malformed_scope_policy_is_not_a_public_audit(self): + with patch.dict(os.environ, {"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture,,other"}, clear=True), patch.object( + manual, "run", return_value=(0, self.clean_audit, ""), + ) as dispatch: + with self.assertRaisesRegex(ValueError, "INVALID_PRIVATE_SCOPES"): + manual.run_audit(self.project, "npm", "https://registry.npmjs.org") + dispatch.assert_not_called() + + def test_restricted_native_metadata_is_refused_before_subprocess(self): + for variable in ( + "DEPLOOM_MCP_LOCAL_CACHE_ONLY", "DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE", + "DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE", "DEPLOOM_MCP_RECORDS_MIRROR_ONLY", + ): + with self.subTest(variable=variable), patch.dict(os.environ, {variable: "1"}, clear=True), patch.object( + manual.shutil, "which", return_value="synthetic-npm", + ), patch.object(manual.subprocess, "run") as native: + with self.assertRaisesRegex(ValueError, "NETWORK_POLICY_REQUIRES_GUARDED_AUDIT"): + manual._npm_view_json(self.project, "public-parent", ["time"], "https://registry.npmjs.org") + native.assert_not_called() + + def test_runtime_environment_cannot_clear_the_host_policy(self): + with patch.dict(os.environ, {"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture"}, clear=True), patch.object( + manual, "run", return_value=(0, self.clean_audit, ""), + ) as dispatch: + with self.assertRaisesRegex(ValueError, "PRIVATE_SCOPE_POLICY_REQUIRES_GUARDED_AUDIT"): + manual.run_audit(self.project, "npm", "https://mirror.example.invalid/npm", runtime_env={ + "DEPLOOM_MCP_PRIVATE_SCOPES": "", + }) + dispatch.assert_not_called() + + def test_runtime_environment_can_supply_a_restrictive_policy(self): + with patch.dict(os.environ, {}, clear=True), patch.object( + manual, "run", return_value=(0, self.clean_audit, ""), + ) as dispatch: + with self.assertRaisesRegex(ValueError, "NETWORK_POLICY_REQUIRES_GUARDED_AUDIT"): + manual.run_audit(self.project, "npm", "https://mirror.example.invalid/npm", runtime_env={ + "DEPLOOM_MCP_LOCAL_CACHE_ONLY": "1", + }) + dispatch.assert_not_called() + + def test_report_refuses_before_audit_lag_or_cache_allocation(self): + workspace = self.project / "new-audit-cache" + with patch.dict(os.environ, {"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture"}, clear=True), patch.object( + manual, "run_audit", + ) as native_audit, patch.object(manual, "check_lag") as lag: + with self.assertRaisesRegex(ValueError, "PRIVATE_SCOPE_POLICY_REQUIRES_GUARDED_AUDIT"): + manual.build_report(self.project, "fixture", "https://registry.npmjs.org", audit_workspace=workspace) + native_audit.assert_not_called() + lag.assert_not_called() + self.assertFalse(workspace.exists()) + + def test_cli_returns_a_typed_error_without_a_traceback_or_output_files(self): + output = self.project / "reports" / "audit.json" + stderr = io.StringIO() + with patch.dict(os.environ, {"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture"}, clear=True), patch.object( + manual.sys, "argv", ["manual_dependency_audit.py", "--project-dir", str(self.project), + "--json-out", str(output)], + ), patch.object(manual, "configure_utf8_stdio"), patch.object( + manual.subprocess, "run", + ) as native, redirect_stderr(stderr): + self.assertEqual(2, manual.main()) + result = json.loads(stderr.getvalue()) + self.assertFalse(result["auditComplete"]) + self.assertEqual("PRIVATE_SCOPE_POLICY_REQUIRES_GUARDED_AUDIT", result["error"]["code"]) + native.assert_not_called() + self.assertFalse(output.parent.exists()) + + def test_no_host_policy_preserves_explicit_native_registry_routes(self): + # Migration/knowledge-only flags do not disable native audit admission. + for policy in ({}, {"DEPLOOM_MCP_MIGRATION_OFFLINE": "1"}, {"DEPLOOM_MCP_KNOWLEDGE_DISABLED": "1"}): + for registry in ("https://registry.npmjs.org", "https://mirror.example.invalid/npm"): + with self.subTest(policy=policy, registry=registry), patch.dict(os.environ, policy, clear=True), patch.object( + manual, "run", return_value=(0, self.clean_audit, ""), + ) as dispatch: + result = manual.run_audit(self.project, "npm", registry) + self.assertTrue(result["complete"]) + self.assertEqual(["npm", "audit", "--json", "--registry", registry], dispatch.call_args.args[0]) + + def test_guarded_worker_keeps_control_of_metadata_dispatch(self): + # audit_worker installs its already-admitted Runner as manual.run. + registry = "https://mirror.example.invalid/npm" + with patch.dict(os.environ, {"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture"}, clear=True), patch.object( + manual, "run", return_value=(0, '{"time": {"1.0.0": "2026-01-01T00:00:00Z"}}', ""), + ) as guarded_runner: + result, error = manual._npm_view_json(self.project, "@fixture/private", ["time"], registry) + self.assertFalse(error) + self.assertIn("time", result) + self.assertEqual( + ["npm", "view", "@fixture/private", "time", "--json", "--registry", registry], + guarded_runner.call_args.args[0], + ) + + def test_generated_prompt_routes_restricted_or_scoped_audit_to_mcp(self): + policies = ({"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture"}, + {"DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE": "1"}, + {"DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE": "1"}, + {"DEPLOOM_MCP_LOCAL_CACHE_ONLY": "1"}, + {"DEPLOOM_MCP_RECORDS_MIRROR_ONLY": "1"}, + {"DEPLOOM_MCP_PRIVATE_SCOPES": "@fixture,,other"}) + for policy in policies: + for language in ("en", "ru"): + with self.subTest(policy=policy, language=language), patch.dict(os.environ, policy, clear=True): + prompt = core.build_draft_prompt( + "run-fixture", "workspace", "fixture", "draft", "policy", {}, {}, + language=language, execution_context={ + "registry": "https://registry.npmjs.org", "packageManager": "npm", + "projectPath": str(self.project), "toolRoot": "", + }, + ) + self.assertIn("audit_dependencies", prompt) + self.assertNotIn("python '/manual_dependency_audit.py'", prompt) + self.assertNotIn("--yarn-audit-engine", prompt) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_peer_solver_transition.py b/tests/test_peer_solver_transition.py index 1281fa1..a31ae17 100644 --- a/tests/test_peer_solver_transition.py +++ b/tests/test_peer_solver_transition.py @@ -24,6 +24,33 @@ def assert_all_transition_vertices_safe(self, model, current, target, groups): assignment = transition_assignment_for_groups(current, target, groups, applied) self.assertEqual("", model.assignment_issue(assignment), (groups, applied, assignment)) + def test_target_outside_model_domain_is_not_a_safe_transition(self): + model = PeerOptimizationModel(packages=(package("a"),), objective_width=1) + current, target = {"a": "1"}, {"a": "3"} + self.assertEqual("", model.validation_issue()) + self.assertEqual("OUTSIDE_DOMAIN: a@3", model.assignment_issue(target)) + + result = refine_transition_safe_groups(model, current, target) + + self.assertFalse(result.safe) + self.assertEqual((), result.groups) + self.assertEqual(("INVALID_TARGET_ENDPOINT: OUTSIDE_DOMAIN: a@3",), result.unresolved) + + def test_recorded_current_version_may_be_outside_final_candidate_domain(self): + # A required upgrade can exclude the installed baseline from the final + # candidate domain. Domain admission must not reject that starting point. + variable = dataclasses.replace(package("a"), domain=("2",), scores=(("2", (1,)),)) + model = PeerOptimizationModel(packages=(variable,), objective_width=1) + current, target = {"a": "1"}, {"a": "2"} + self.assertEqual("", model.validation_issue()) + self.assertEqual("OUTSIDE_DOMAIN: a@1", model.assignment_issue(current)) + self.assertEqual("", model.assignment_issue(target)) + + result = refine_transition_safe_groups(model, current, target) + + self.assertTrue(result.safe, result.unresolved) + self.assertEqual((("a",),), result.groups) + def test_cardinality_rejects_transition_with_valid_endpoints_and_invalid_intermediate_states(self): current = {"a": "1", "b": "2"} target = {"a": "2", "b": "1"}