diff --git a/dependency_live_roadmap_generator.py b/dependency_live_roadmap_generator.py index d1f6864..b350ccb 100644 --- a/dependency_live_roadmap_generator.py +++ b/dependency_live_roadmap_generator.py @@ -2439,6 +2439,25 @@ def _private_package(name): return osv_offline.private_package(name, os.environ.get("DEPLOOM_DRAFT_PRIVATE_SCOPES", "")) +def _public_evidence_block_reason(package=None): + from registry_privacy import public_evidence_block_reason + return public_evidence_block_reason(os.environ, package) + + +def _github_authorization(url, hosts): + """A GitHub token belongs only to an exact HTTPS GitHub origin.""" + try: + parsed = urlparse(url) + if (parsed.scheme != "https" or parsed.hostname not in hosts + or parsed.port not in (None, 443) or parsed.username is not None + or parsed.password is not None or any(ord(char) < 33 or ord(char) == 127 for char in url)): + return {} + except (TypeError, ValueError): + return {} + token = os.getenv("GITHUB_TOKEN") or os.getenv("GH_TOKEN") + return {"Authorization": f"Bearer {token}"} if token else {} + + def _corporate_advisory_fallback(registry): return (os.environ.get("DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE") == "1" and corporate_advisory_source_matches( @@ -3812,20 +3831,34 @@ def fetch_osv_vuln(self, vuln_id: str) -> Dict[str, Any]: ) from e + @contextmanager + def _public_evidence_session(self, url): + # Preserve the configured proxy and CA route, without carrying registry + # auth, cookies, headers, query parameters or client certificates to a + # public source. trust_env=False also prevents implicit netrc auth. + settings = self.session.merge_environment_settings(url, {}, True, None, None) + with requests.Session() as session: + session.trust_env = False + session.proxies.update(settings["proxies"]) + session.verify = settings["verify"] + yield session + def fetch_text(self, url: str, quiet: bool = True) -> Optional[str]: + if _public_evidence_block_reason(): + return None if url in self.text_cache: return self.text_cache[url] self.progress(operation="fetch text", step="scan") try: headers = {"Accept": "text/plain, text/markdown, application/json"} - token = os.getenv("GITHUB_TOKEN") or os.getenv("GH_TOKEN") - if token and "github" in url: - headers["Authorization"] = f"Bearer {token}" - response = self._supervised( - lambda url=url, headers=headers: self.session.get(url, timeout=self._budgeted_timeout(), headers=headers, stream=True) - ) - response.raise_for_status() - text = self._bounded_text(response) + headers.update(_github_authorization(url, {"github.com", "api.github.com", "raw.githubusercontent.com"})) + with self._public_evidence_session(url) as session: + response = self._supervised( + lambda: session.get(url, timeout=self._budgeted_timeout(), headers=headers, stream=True) + ) + with response: + response.raise_for_status() + text = self._bounded_text(response) self.text_cache[url] = text self._bounded_sleep(self.sleep_sec) return text @@ -3838,19 +3871,21 @@ def fetch_text(self, url: str, quiet: bool = True) -> Optional[str]: return None def fetch_json_url(self, url: str, quiet: bool = True) -> Optional[Any]: + if _public_evidence_block_reason(): + return None if url in self.json_cache: return self.json_cache[url] self.progress(operation="fetch json", step="scan") try: headers = {"Accept": "application/vnd.github+json, application/json"} - token = os.getenv("GITHUB_TOKEN") or os.getenv("GH_TOKEN") - if token and "api.github.com" in url: - headers["Authorization"] = f"Bearer {token}" - response = self._supervised( - lambda url=url, headers=headers: self.session.get(url, timeout=self._budgeted_timeout(), headers=headers, stream=True) - ) - response.raise_for_status() - data = self._bounded_json(response) + headers.update(_github_authorization(url, {"api.github.com"})) + with self._public_evidence_session(url) as session: + response = self._supervised( + lambda: session.get(url, timeout=self._budgeted_timeout(), headers=headers, stream=True) + ) + with response: + response.raise_for_status() + data = self._bounded_json(response) self.json_cache[url] = data self._bounded_sleep(self.sleep_sec) return data @@ -3927,6 +3962,8 @@ def _bounded_read_max(self, response, max_bytes: int) -> bytes: return b"".join(chunks) def fetch_release_intelligence(self, package: str, meta: Dict[str, Any], current: str, target: str) -> ReleaseIntelligence: + if _public_evidence_block_reason(package): + return build_release_intelligence(self, package, meta, current, target) cache_key = (package, current, target) if cache_key in self.release_intelligence_cache: return self.release_intelligence_cache[cache_key] @@ -4335,9 +4372,9 @@ def analyze_release_text(text: str, current: str, target: str, source_count: int def build_release_intelligence(client: LiveDataClient, package: str, meta: Dict[str, Any], current: str, target: str) -> ReleaseIntelligence: if not target_is_action(target): return ReleaseIntelligence(target=target, status="not-applicable", summary="Для строки нет target-обновления") - if _private_package(package): + if reason := _public_evidence_block_reason(package): return ReleaseIntelligence(target=target, status="unavailable", - summary="External release lookups are disabled for private packages") + summary=f"External release lookups unavailable: {reason}") repo_url = repository_url_from_metadata(meta, target) repo = github_repo_parts(repo_url) sources: List[Dict[str, str]] = [] diff --git a/docs/TESTING.md b/docs/TESTING.md index 9c1bf52..51aecee 100644 --- a/docs/TESTING.md +++ b/docs/TESTING.md @@ -12,6 +12,13 @@ The [headless Core CI](../.github/workflows/ci.yml) runs every - Ubuntu + Python 3.12 - Ubuntu + Python 3.13 - Windows + Python 3.12 +- Ubuntu + Python 3.14 +- Windows + Python 3.14 +- macOS arm64 + Python 3.14 + +Separate required jobs exercise Linux PID-namespace ownership and native macOS +arm64 process lifecycle on Python 3.12 and 3.13. The Python 3.14 matrix legs also +install and inspect the built wheel outside the checkout. This is a **single selected contract suite**, not a filtered invocation that silently ignores newly added files. Regression failures block the PR. diff --git a/docs/audits/2026-12-01/core-second-pass.md b/docs/audits/2026-12-01/core-second-pass.md new file mode 100644 index 0000000..7516eed --- /dev/null +++ b/docs/audits/2026-12-01/core-second-pass.md @@ -0,0 +1,77 @@ +# Core independent second pass — 2026-12-01 + +Baseline: `be67725766106529a2d9fdd76cd0abad617326f9`. +This checkpoint supplements the earlier [Core boundary audit](core-boundaries.md). +It records source fixes and local verification, not publication or installed +release acceptance. + +## Reproduced findings + +| ID | Priority | Reproducer and scope | Correction | +| --- | --- | --- | --- | +| C01 | P1 | The public `migration_research.collect` helper accepted `--include-osv` for a host-private package and dispatched its identity to the public lookup callback. Public release intelligence also ignored the host's external-evidence restriction for an ordinary public package. Calls were intercepted with synthetic names; no private data was transmitted. | Optional public research and release lookups now check the union of Core and MCP host restrictions before transport or evidence reuse. A private package, malformed scope policy or restricted host produces an explicit unavailable/unknown reason. | +| C02 | P1 | Generic text/JSON helpers selected `GITHUB_TOKEN` / `GH_TOKEN` by a substring anywhere in the URL. A non-GitHub URL containing `github` or `api.github.com` received the synthetic bearer header. The helpers also inherited registry authentication, cookies, query parameters, custom headers and client certificates when fetching public release information. Current release-building code constructs canonical GitHub URLs, so the substring reproducer establishes a generic helper defect, not an asserted remote exploit through current registry metadata. | GitHub bearer headers require an exact allowed HTTPS hostname on the default port without user information. Public evidence uses an independent session. Configured proxy routing and CA verification remain available; registry identity, client certificates and implicit netrc authentication do not transfer to public sources. Responses and temporary sessions are closed. | +| C03 | P2 | `refine_transition_safe_groups` reported `safe=True` for an unchanged target forbidden by `USER_BASELINE_REQUIRED_UPDATE` or `USER_EXACT_TARGET`. Normal planner callers use solver-validated targets, so this is a public transition API boundary defect. | Validate the complete final assignment before applying exceptions that permit the recorded baseline to predate a required change. Existing out-of-domain diagnostics and the explicit unsupported-cardinality result remain intact. | +| C04 | P3 | The test guide listed only three of the six configured general CI profiles. | List all current profiles and the separate ownership jobs. | + +The public evidence policy 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 public-research option selects a lookup; it +cannot override host restrictions. As in the previous audit, migration-only +and knowledge-only flags retain their separate meanings. + +## Verification + +Environment: Linux, CPython **3.13.5**, Node **24.22.3**. Dependencies were +installed with hash enforcement from the unchanged npm POSIX runtime lock, +SHA-256 `8d8bc412c46bf89d30af602e9664530f754e4558b7dddfee2600c4732d60accd`. + +The new policy, credential-origin and unchanged-target tests were exercised +against the baseline before implementing their fixes. They reproduced the +described failures using intercepted transports and synthetic credentials. +The final tests also use a real loopback HTTP receiver to confirm that a URL +whose path contains GitHub's name receives neither a GitHub token nor registry +identity. Allowed GitHub origins, unrestricted explicit public research, +approved private metadata routes, proxy/CA transport settings, valid solved +targets and current versions outside the final domain remain covered. + +The final focused command covers **42 passing tests**: + +```bash +python -m unittest tests.test_required_transition tests.test_peer_solver_transition tests.test_public_evidence_policy tests.test_manual_audit_host_policy tests.test_registry_privacy tests.test_private_metadata_routing -v +``` + +The complete suite was run before and after the changes without filtering: + +| Checkout | Tests executed | Failures | Errors | Skips | +| --- | ---: | ---: | ---: | ---: | +| Baseline | 849 | 6 | 11 | 95 | +| Corrected source | 858 | 6 | 11 | 95 | + +The failing test/subtest identities are identical. Their native preparation, +semver and process-lifecycle operations remain blocked by +`PROCESS_TREE_OWNERSHIP_UNAVAILABLE` because this host does not expose the +required `/proc/self/task//children` interface. A separate 97-test +integration selection covering OSV evidence, registry identity/context, +explicit targets and process supervision likewise had only the six known +native ownership errors, with one platform skip. + +This is **not a green full-suite result**. No process guard, dependency hash, +test or CI profile was weakened. Native CI must verify the eventual commit on +its configured platforms, followed by any required consumer pin and release +acceptance. + +## Further improvements + +1. Centralize optional evidence transport and host-policy admission across + standalone helpers so a new helper cannot accidentally omit the boundary. +2. Keep public evidence and private registry credentials in separate transport + objects by construction; add cross-component transport-admission checks to + installed consumer qualification. +3. Break the large planning module into separately testable metadata, + evidence, model-extraction and publication components while preserving the + current exported API and exact acceptance fixtures. +4. Continue recording source, consumer pin, signed package publication and + ordinary installed acceptance as different states; a merged Core fix is + not proof that the published CLI contains it. diff --git a/migration_research.py b/migration_research.py index 5331dd8..e85cf2e 100644 --- a/migration_research.py +++ b/migration_research.py @@ -4,6 +4,7 @@ import argparse import json +import os import re import queue import threading @@ -11,6 +12,7 @@ import requests from planning_cache import cached_query +from registry_privacy import public_evidence_block_reason MAX_RESPONSE = 2 * 1024 * 1024 @@ -62,6 +64,9 @@ def github_repository(value): def collect(package, before, after, *, repository="", include_osv=False, fetch=_public_json, root=None): result = {"schemaVersion": 1, "package": package, "from": before, "to": after, "authority": "guidance-only", "unknown": [], "releases": []} + if reason := public_evidence_block_reason(os.environ, package): + result["unknown"].append(reason) + return result repo = github_repository(repository) if repo: url = f"https://api.github.com/repos/{repo}/releases?per_page=30" diff --git a/peer_solver_transition.py b/peer_solver_transition.py index 16ba3de..31fdb6f 100644 --- a/peer_solver_transition.py +++ b/peer_solver_transition.py @@ -227,6 +227,11 @@ def refine_transition_safe_groups( unresolved=("UNSUPPORTED_TRANSITION_CARDINALITY",), ) + # Final-only obligations may be relaxed for the recorded baseline below, + # but never for the target itself, including an unchanged target. + if issue := model.assignment_issue(target_assignment): + return TransitionSafetyResult(groups=(), unresolved=(f"INVALID_TARGET_ENDPOINT: {issue}",)) + union_find = _UnionFind(names) for group in initial_groups or (): members = sorted(set(group) & expected) diff --git a/registry_privacy.py b/registry_privacy.py index 1f32c5c..a56dc96 100644 --- a/registry_privacy.py +++ b/registry_privacy.py @@ -3,6 +3,10 @@ import re _SCOPE_NAME = re.compile(r"[a-zA-Z0-9][a-zA-Z0-9_.~-]{0,213}") +_NETWORK_POLICY_FLAGS = ( + "DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE", "DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE", + "DEPLOOM_MCP_LOCAL_CACHE_ONLY", "DEPLOOM_MCP_RECORDS_MIRROR_ONLY", +) @lru_cache(maxsize=16) @@ -33,6 +37,25 @@ def private_package(package: str, private_scopes: str) -> bool: return True +def public_evidence_block_reason(host_environment, package: str | None = None) -> str: + """Admit optional public evidence only within the host's network policy. + + CLI options can select a public lookup; they cannot override private scopes + or a restricted host. Both Core and MCP spellings remain restrictions. + """ + scopes = set() + for key in ("DEPLOOM_DRAFT_PRIVATE_SCOPES", "DEPLOOM_MCP_PRIVATE_SCOPES"): + try: + scopes.update(normalize_private_scopes(host_environment.get(key, ""))) + except (ValueError, TypeError, AttributeError): + return "INVALID_PRIVATE_SCOPES" + if any(host_environment.get(key) == "1" for key in _NETWORK_POLICY_FLAGS): + return "EXTERNAL_EVIDENCE_DISABLED_BY_HOST_POLICY" + if package is not None and package.partition("/")[0].lower() in scopes: + return "PRIVATE_SCOPE_EXCLUDED" + return "" + + def standalone_audit_block_reason(host_environment, runtime_environment=None) -> str: """The standalone helper cannot enforce a guarded native audit route. @@ -47,9 +70,6 @@ def standalone_audit_block_reason(host_environment, runtime_environment=None) -> 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", - )): + if any(environment.get(key) == "1" for environment in environments for key in _NETWORK_POLICY_FLAGS): return "NETWORK_POLICY_REQUIRES_GUARDED_AUDIT" return "PRIVATE_SCOPE_POLICY_REQUIRES_GUARDED_AUDIT" if has_private_scopes else "" diff --git a/tests/test_public_evidence_policy.py b/tests/test_public_evidence_policy.py new file mode 100644 index 0000000..bbefbe2 --- /dev/null +++ b/tests/test_public_evidence_policy.py @@ -0,0 +1,199 @@ +"""Public guidance helpers must respect host policy and credential origins. + +All transports are intercepted before a socket can be opened. Every token, +cookie and credential below is a synthetic value used only by these tests. +""" +from __future__ import annotations + +import json +import http.server +import os +import tempfile +import threading +import unittest +from pathlib import Path +from unittest.mock import Mock, patch + +import requests + +import dependency_live_roadmap_generator as core +import migration_research + + +class PublicEvidencePolicyTests(unittest.TestCase): + def setUp(self): + self.client = core.LiveDataClient("https://mirror.example.invalid/npm", 1, 8, 0) + self.addCleanup(self.client.session.close) + + def test_research_refuses_private_or_restricted_public_queries(self): + cases = ( + ({"DEPLOOM_DRAFT_PRIVATE_SCOPES": "Company"}, "@company/private", "PRIVATE_SCOPE_EXCLUDED"), + ({"DEPLOOM_MCP_PRIVATE_SCOPES": "@Company"}, "@COMPANY/private", "PRIVATE_SCOPE_EXCLUDED"), + ({"DEPLOOM_DRAFT_PRIVATE_SCOPES": "@company,,other"}, "public-name", "INVALID_PRIVATE_SCOPES"), + *(({key: "1"}, "public-name", "EXTERNAL_EVIDENCE_DISABLED_BY_HOST_POLICY") for key in ( + "DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE", "DEPLOOM_MCP_DISABLE_EXTERNAL_EVIDENCE", + "DEPLOOM_MCP_LOCAL_CACHE_ONLY", "DEPLOOM_MCP_RECORDS_MIRROR_ONLY", + )), + ) + for environment, package, reason in cases: + with self.subTest(environment=environment), tempfile.TemporaryDirectory() as raw: + fetch = Mock(return_value=({"results": [{}]}, 1, "", "intercepted")) + with patch.dict(os.environ, environment, clear=True): + result = migration_research.collect( + package, "1.0.0", "2.0.0", repository="https://github.com/example/project", + include_osv=True, fetch=fetch, root=Path(raw), + ) + self.assertIn(reason, result["unknown"]) + fetch.assert_not_called() + self.assertNotIn("osv", result) + self.assertEqual([], list(Path(raw).iterdir())) + + def test_release_builder_refuses_host_policy_even_for_a_public_package(self): + with patch.dict(os.environ, {"DEPLOOM_DRAFT_DISABLE_EXTERNAL_EVIDENCE": "1"}, clear=True), patch.object( + self.client, "fetch_json_url", return_value=[], + ) as json_fetch, patch.object(self.client, "fetch_text", return_value=None) as text_fetch: + result = core.build_release_intelligence( + self.client, "public-name", {"repository": "https://github.com/example/project"}, + "1.0.0", "2.0.0", + ) + self.assertEqual("unavailable", result.status) + self.assertIn("EXTERNAL_EVIDENCE_DISABLED_BY_HOST_POLICY", result.summary) + json_fetch.assert_not_called() + text_fetch.assert_not_called() + + def test_release_cache_cannot_bypass_a_new_private_scope_policy(self): + cached = core.ReleaseIntelligence(target="2.0.0", status="no-breaking-found", summary="cached") + self.client.release_intelligence_cache[("@company/private", "1.0.0", "2.0.0")] = cached + with patch.dict(os.environ, {"DEPLOOM_MCP_PRIVATE_SCOPES": "@company"}, clear=True): + result = self.client.fetch_release_intelligence( + "@company/private", {}, "1.0.0", "2.0.0", + ) + self.assertEqual("unavailable", result.status) + self.assertIn("PRIVATE_SCOPE_EXCLUDED", result.summary) + + def test_generic_public_helpers_refuse_restricted_host_before_transport(self): + with patch.dict(os.environ, {"DEPLOOM_MCP_LOCAL_CACHE_ONLY": "1"}, clear=True), patch.object( + requests.Session, "send", side_effect=AssertionError("no network allowed"), + ) as send: + self.assertIsNone(self.client.fetch_text("https://raw.githubusercontent.com/example/project/main/README.md")) + self.assertIsNone(self.client.fetch_json_url("https://api.github.com/repos/example/project/releases")) + send.assert_not_called() + + def test_unrestricted_explicit_public_research_remains_available(self): + with tempfile.TemporaryDirectory() as raw, patch.dict(os.environ, {}, clear=True): + fetch = Mock(return_value=({"results": [{}]}, 1, "", "intercepted")) + result = migration_research.collect( + "public-name", "1.0.0", "2.0.0", include_osv=True, fetch=fetch, root=Path(raw), + ) + fetch.assert_called_once() + self.assertTrue(result["osv"]["complete"]) + self.assertEqual([], result["unknown"]) + + +class PublicEvidenceCredentialsTests(unittest.TestCase): + def setUp(self): + self.client = core.LiveDataClient("https://mirror.example.invalid/npm", 1, 8, 0) + self.addCleanup(self.client.session.close) + self.requests = [] + + def send(self, session, request, **kwargs): + self.requests.append((request, kwargs)) + response = requests.Response() + response.status_code = 200 + response.url = request.url + response.request = request + response._content = json.dumps({"ok": True}).encode() + response._content_consumed = True + return response + + def test_github_token_is_attached_only_to_exact_https_github_hosts(self): + cases = ( + ("fetch_text", "https://raw.githubusercontent.com/example/project/main/README.md", True), + ("fetch_text", "https://github.com/example/project", True), + ("fetch_json_url", "https://api.github.com:443/repos/example/project/releases", True), + ("fetch_text", "https://evil.invalid/github/changelog", False), + ("fetch_json_url", "https://api.github.com.evil.invalid/releases", False), + ("fetch_json_url", "https://evil.invalid/?next=api.github.com", False), + ("fetch_json_url", "https://api.github.com@evil.invalid/releases", False), + ("fetch_json_url", "http://api.github.com/repos/example/project/releases", False), + ("fetch_json_url", "https://api.github.com:444/repos/example/project/releases", False), + ) + for variable in ("GITHUB_TOKEN", "GH_TOKEN"): + for method, url, authorized in cases: + with self.subTest(variable=variable, method=method, url=url), patch.dict( + os.environ, {variable: "synthetic-github-token"}, clear=True, + ), patch.object(requests.Session, "send", autospec=True, side_effect=self.send): + self.client.text_cache.clear() + self.client.json_cache.clear() + self.assertIsNotNone(getattr(self.client, method)(url)) + request, _ = self.requests[-1] + self.assertEqual( + "Bearer synthetic-github-token" if authorized else None, + request.headers.get("Authorization"), + ) + + def test_public_evidence_does_not_inherit_registry_credentials_or_parameters(self): + self.client.session.auth = ("synthetic-registry-user", "synthetic-registry-password") + self.client.session.headers["X-Registry-Api-Key"] = "synthetic-registry-key" + self.client.session.cookies.set("registry-cookie", "synthetic-cookie") + self.client.session.params["tenant"] = "synthetic-private-tenant" + self.client.session.cert = ("registry-only-client.crt", "registry-only-client.key") + self.client.session.proxies["https"] = "http://proxy.example.invalid:8080" + self.client.session.verify = "company-ca.pem" + with patch.dict(os.environ, {"GH_TOKEN": "synthetic-github-token"}, clear=True), patch.object( + requests.Session, "send", autospec=True, side_effect=self.send, + ): + for method, url in ( + ("fetch_text", "https://raw.githubusercontent.com/example/project/main/README.md"), + ("fetch_json_url", "https://api.github.com/repos/example/project/releases"), + ): + self.assertIsNotNone(getattr(self.client, method)(url)) + request, kwargs = self.requests[-1] + self.assertEqual(url, request.url) + self.assertEqual("Bearer synthetic-github-token", request.headers.get("Authorization")) + self.assertNotIn("Cookie", request.headers) + self.assertNotIn("X-Registry-Api-Key", request.headers) + self.assertIsNone(kwargs.get("cert")) + self.assertEqual("company-ca.pem", kwargs["verify"]) + self.assertEqual("http://proxy.example.invalid:8080", kwargs["proxies"]["https"]) + + def test_real_loopback_receiver_cannot_receive_tokens_from_a_github_named_path(self): + observations = [] + + class Handler(http.server.BaseHTTPRequestHandler): + def do_GET(self): + observations.append((self.path, dict(self.headers))) + body = b'{"ok": true}' + self.send_response(200) + self.send_header("Content-Length", str(len(body))) + self.end_headers() + self.wfile.write(body) + + def log_message(self, *_): + pass + + server = http.server.ThreadingHTTPServer(("127.0.0.1", 0), Handler) + thread = threading.Thread(target=server.serve_forever, daemon=True) + thread.start() + self.client.session.headers["X-Registry-Api-Key"] = "synthetic-registry-key" + self.client.session.cookies.set("registry-cookie", "synthetic-cookie") + self.client.session.params["tenant"] = "synthetic-private-tenant" + try: + with patch.dict(os.environ, {"GITHUB_TOKEN": "synthetic-github-token"}, clear=True): + for method, path in (("fetch_text", "/github/changelog"), + ("fetch_json_url", "/api.github.com/releases")): + result = getattr(self.client, method)(f"http://127.0.0.1:{server.server_port}{path}") + self.assertIsNotNone(result) + seen_path, headers = observations[-1] + self.assertEqual(path, seen_path) + self.assertNotIn("Authorization", headers) + self.assertNotIn("Cookie", headers) + self.assertNotIn("X-Registry-Api-Key", headers) + finally: + server.shutdown() + server.server_close() + thread.join(timeout=3) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_required_transition.py b/tests/test_required_transition.py index 2a3948d..fd32c34 100644 --- a/tests/test_required_transition.py +++ b/tests/test_required_transition.py @@ -15,6 +15,28 @@ def package(name: str, current: str = "1.0.0", upgraded: str = "2.0.0") -> Packa class RequiredUpdateTransitionTests(unittest.TestCase): + def test_final_only_obligations_still_reject_an_unchanged_target(self): + current = {"router": "1.0.0"} + for reason, provenance in ( + ("USER_BASELINE_REQUIRED_UPDATE: router must change", "user-baseline-intent"), + ("USER_EXACT_TARGET: router must be 2.0.0", "user-exact-target"), + ): + with self.subTest(reason=reason): + model = PeerOptimizationModel( + packages=(package("router"),), + constraints=(forbidden( + [("router", "1.0.0")], reason=reason, provenance=provenance, + ),), + objective_width=1, + ) + self.assertEqual(reason, model.assignment_issue(current)) + + transition = refine_transition_safe_groups(model, current, current) + + self.assertFalse(transition.safe) + self.assertEqual((), transition.groups) + self.assertEqual((f"INVALID_TARGET_ENDPOINT: {reason}",), transition.unresolved) + def test_required_is_final_only_and_z3_enforces_it(self): current = {"router": "1.0.0"} target = {"router": "2.0.0"}