diff --git a/design/catalogs.md b/design/catalogs.md index 70e397daaa..ff8b42cd41 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -188,11 +188,13 @@ Current behavior differs by primitive: redirect handler also applies its strict scheme, host, and remote-to-local policy on every hop. Integrations validate cached payload shape, discard invalid cache entries when possible, and treat cache writes as best-effort. -- Workflows use one-hour per-URL caches, validate every redirect hop, fall back - to any readable stale cache after errors while opening, redirecting, bounded - reading, UTF-8 decoding, or JSON parsing, and currently require only a mapping - at the payload root before merge. A freshly parsed non-object payload is - rejected after that fallback boundary. +- Workflows use one-hour per-URL caches, validate every redirect hop, and fall + back to any readable stale cache after transport, bounded-read, UTF-8 decoding, + or JSON parsing errors. Initial URL, redirect, and final URL validation + rejections bypass stale-cache fallback, whether raised by a catalog validator + or the shared HTTP handler, and retain their cause in a workflow catalog + error. A freshly parsed non-object payload is rejected after the fallback + boundary; the payload root must be a mapping before merge. - Workflow steps follow the workflow cache/fallback model, validate every redirect hop, and disable cache use when the cache path contains a symlink. Duplicate JSON fields are re-raised as fatal validation errors before stale @@ -208,6 +210,17 @@ A future shared fetch boundary may share URL validation, redirect validation, bounded reads, cache records, and error types. It must preserve each primitive's fallback policy until a separate behavior change is approved. +The workflow and step URL-policy behavior above is an intentional transport +hardening change: stale metadata must not mask a rejected URL or redirect during +an online fetch, particularly when bundles rely on the result to validate a +reference. Previously, a catalog callback could reject a redirect or final URL +and still return expired metadata. Both catalog and shared HTTP validators now +preserve these rejections as definitive catalog errors; ordinary fetch failures +retain their existing stale-cache fallback. The shared redirect handler checks +raw `Location` and legacy `URI` headers before urllib can normalize malformed +absolute targets or raise an unclassified parsing error. Valid relative and +scheme-relative redirects retain urllib's normal resolution behavior. + ## Payload validation ownership The shared source layer should own source configuration, fetching, cache @@ -249,9 +262,11 @@ usable. Validation errors are not uniformly recoverable: fails. Workflow-step duplicate JSON fields and duplicate IDs are fatal validation errors rather than skippable source-fetch errors. - Workflow and step fetches may use readable stale cache data after broad - fetch-path failures, including rejected redirects, bounded-read failures, - decoding failures, and malformed JSON. Fresh non-object payloads and step - duplicate-field errors remain outside that fallback. + fetch-path failures, including transport errors, bounded-read failures, + decoding failures, and malformed JSON. All URL-policy rejections bypass + stale-cache fallback, including during forced refresh, independently of + which validator rejects the URL first. Fresh non-object payloads and step + duplicate-field errors also remain outside that fallback. Bundle lookup is fail-fast in precedence order: loading a source error stops the operation. Built-in fetch fallback is handled inside the bundle fetcher, diff --git a/docs/reference/authentication.md b/docs/reference/authentication.md index 794d10e693..4909061d4c 100644 --- a/docs/reference/authentication.md +++ b/docs/reference/authentication.md @@ -329,6 +329,16 @@ You can configure multiple entries for different hosts or organizations: ## How it works +The shared HTTP helpers require initial request URLs to use HTTPS with a +hostname. They allow HTTP only for unambiguous loopback hosts, such as +`localhost`, `127.0.0.1`, and `::1`. Catalog sources have a stricter policy: +they require HTTPS even on loopback hosts. +Unsafe URLs are rejected before credentials are resolved or any request is +made, including when no authentication is configured. +Online bundle catalog fetching and reference validation treat URL-policy +rejections as definitive errors, not as availability fallbacks to packaged +snapshots or unchecked references. + 1. For each outbound HTTP request, the URL hostname is matched against the `hosts` patterns in `auth.json`. 2. If a match is found, the corresponding provider resolves the token diff --git a/src/specify_cli/authentication/http.py b/src/specify_cli/authentication/http.py index 795b491e1e..1387cd6574 100644 --- a/src/specify_cli/authentication/http.py +++ b/src/specify_cli/authentication/http.py @@ -3,7 +3,8 @@ No credentials are sent unless the user has created ``auth.json``. For each outbound URL the helper matches the hostname against configured entries, resolves the token via the appropriate provider -class, and attaches auth headers. Redirect safety is enforced: +class, and attaches auth headers. Initial URLs must use HTTPS, except +for HTTP to unambiguous loopback hosts. Redirect safety is enforced: the ``Authorization`` header is stripped when a redirect leaves the entry's declared hosts. On 401/403 the next matching entry is tried, then unauthenticated. @@ -16,7 +17,7 @@ from typing import Callable from urllib.parse import urlparse -from .._download_security import is_safe_download_redirect +from .._download_security import is_https_or_localhost_http, is_safe_download_redirect from . import get_provider from .config import ( AuthConfigEntry, @@ -65,10 +66,22 @@ def _hostname_in_hosts(hostname: str, hosts: tuple[str, ...]) -> bool: RedirectValidator = Callable[[str, str], None] -class RedirectPolicyError(urllib.error.URLError): +class URLPolicyError(urllib.error.URLError): + """A URL rejected because it violates the client's transport policy.""" + + +class RedirectPolicyError(URLPolicyError): """A redirect rejected because it violates the client's security policy.""" +def _validate_initial_url(url: str) -> None: + if not is_https_or_localhost_http(url): + raise URLPolicyError( + "unsafe request URL: target must use HTTPS with a hostname, " + "or HTTP to loopback (for example localhost, 127.0.0.1, ::1)" + ) + + def _validate_strict_redirect(old_url: str, new_url: str) -> None: if not is_safe_download_redirect(old_url, new_url): raise RedirectPolicyError( @@ -81,10 +94,11 @@ def _validate_strict_redirect(old_url: str, new_url: str) -> None: class _StripAuthOnRedirect(urllib.request.HTTPRedirectHandler): """Redirect handler that guards every redirect it is installed for. - 1. Run any caller-provided redirect validator. - 2. Reject redirects that are not HTTPS with a hostname. HTTP loopback is + 1. Reject malformed absolute targets before urllib normalizes their headers. + 2. Run any caller-provided redirect validator. + 3. Reject redirects that are not HTTPS with a hostname. HTTP loopback is allowed only when the previous hop is also loopback. - 3. Drop ``Authorization`` when a redirect leaves trusted hosts or downgrades. + 4. Drop ``Authorization`` when a redirect leaves trusted hosts or downgrades. """ def __init__( @@ -96,6 +110,31 @@ def __init__( self._hosts = hosts self._redirect_validator = redirect_validator + def http_error_302(self, req, fp, code, msg, headers): + if "location" in headers: + target = headers["location"] + elif "uri" in headers: + target = headers["uri"] + else: + return super().http_error_302(req, fp, code, msg, headers) + + try: + parsed = urlparse(target) + hostname = parsed.hostname + parsed.port + except ValueError as exc: + raise RedirectPolicyError(f"malformed redirect URL: {exc}") from exc + + # urllib can otherwise normalize a hostless absolute URL onto the + # current host before redirect_request sees the original target. + if parsed.scheme and (parsed.scheme not in ("http", "https") or not hostname): + raise RedirectPolicyError( + "unsafe redirect URL: an absolute target must use HTTP(S) with a hostname" + ) + return super().http_error_302(req, fp, code, msg, headers) + + http_error_301 = http_error_303 = http_error_307 = http_error_308 = http_error_302 + def redirect_request(self, req, fp, code, msg, headers, newurl): try: new_parsed = urlparse(newurl) @@ -135,7 +174,9 @@ def build_request(url: str, extra_headers: dict[str, str] | None = None) -> urll Returns a plain request when no entry matches or the file doesn't exist. A ``github-cli`` acquisition failure raises immediately, without trying later matching entries or returning an unauthenticated request. + Rejects URLs that are not HTTPS or loopback HTTP before resolving tokens. """ + _validate_initial_url(url) headers: dict[str, str] = {} if extra_headers: # Strip Authorization from extra_headers to prevent bypass @@ -193,7 +234,10 @@ def open_url( Redirect scheme safety: every attempt goes through ``_StripAuthOnRedirect``, which rejects redirects to non-HTTPS URLs except HTTP between loopback URLs, and rejects remote-to-local redirects. + Initial URLs must also use HTTPS or loopback HTTP; unsafe URLs are + rejected before resolving tokens or making any request. """ + _validate_initial_url(url) entries = find_entries_for_url(url, _load_config()) def _make_req(auth_headers: dict[str, str]) -> urllib.request.Request: diff --git a/src/specify_cli/bundles/adapters.py b/src/specify_cli/bundles/adapters.py index 7054ae2248..b88969400d 100644 --- a/src/specify_cli/bundles/adapters.py +++ b/src/specify_cli/bundles/adapters.py @@ -227,7 +227,7 @@ def _http_get_json(source_id: str, url: str) -> dict: rather than only on the initial URL. """ from ..authentication.github import GitHubCliAuthError - from ..authentication.http import RedirectPolicyError, open_url + from ..authentication.http import URLPolicyError, open_url def _validate_redirect(_old_url: str, new_url: str) -> None: _validate_remote_url(source_id, new_url) @@ -257,8 +257,8 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: raise BundlerError( f"Failed to fetch catalog from {url}: {exc}" ) from exc - except (GitHubCliAuthError, RedirectPolicyError) as exc: - # Authentication and redirect-policy failures are definitive, not + except (GitHubCliAuthError, URLPolicyError) as exc: + # Authentication and URL-policy failures are definitive, not # transient catalog unavailability. raise BundlerError( f"Failed to fetch catalog from {url}: {exc}" diff --git a/src/specify_cli/bundles/component_catalog.py b/src/specify_cli/bundles/component_catalog.py index aef547e6ac..8abb947da4 100644 --- a/src/specify_cli/bundles/component_catalog.py +++ b/src/specify_cli/bundles/component_catalog.py @@ -7,7 +7,7 @@ from urllib.error import HTTPError, URLError from ..authentication.github import GitHubCliAuthError -from ..authentication.http import RedirectPolicyError +from ..authentication.http import URLPolicyError from . import BundlerError from .manifest import ComponentRef @@ -20,7 +20,7 @@ def _is_unavailable(exc: BaseException) -> bool: seen: set[int] = set() while exc is not None and id(exc) not in seen: seen.add(id(exc)) - if isinstance(exc, (GitHubCliAuthError, RedirectPolicyError)): + if isinstance(exc, (GitHubCliAuthError, URLPolicyError)): return False if isinstance(exc, HTTPError): return exc.code in (408, 429) or 500 <= exc.code <= 599 diff --git a/src/specify_cli/workflows/catalog/_domain.py b/src/specify_cli/workflows/catalog/_domain.py index 415ee52542..364e71028b 100644 --- a/src/specify_cli/workflows/catalog/_domain.py +++ b/src/specify_cli/workflows/catalog/_domain.py @@ -559,7 +559,7 @@ def _fetch_single_catalog( # Fetch from URL — validate scheme before opening and after redirects from urllib.parse import urlparse - from specify_cli.authentication.http import open_url as _open_url + from specify_cli.authentication.http import URLPolicyError, open_url as _open_url def _validate_catalog_url(url: str) -> None: # A malformed authority (e.g. "https://[::1") makes urlparse / @@ -572,20 +572,18 @@ def _validate_catalog_url(url: str) -> None: hostname = parsed.hostname _ = parsed.port except (TypeError, ValueError): - raise WorkflowCatalogError( + raise URLPolicyError( f"Refusing to fetch catalog from malformed URL: {url}" ) from None if parsed.scheme != "https": - raise WorkflowCatalogError( + raise URLPolicyError( f"Refusing to fetch catalog from non-HTTPS URL: {url}" ) if not hostname: - raise WorkflowCatalogError( + raise URLPolicyError( f"Refusing to fetch catalog from URL with no hostname: {url}" ) - _validate_catalog_url(entry.url) - # Validate EVERY redirect hop, not just the final URL: _open_url follows # redirects, so an https:// entry that 30x-redirects through http:// (or # to a non-HTTPS host mid-chain) could otherwise let a network attacker @@ -597,6 +595,7 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: _validate_catalog_url(new_url) try: + _validate_catalog_url(entry.url) with _open_url( entry.url, timeout=30, redirect_validator=_validate_redirect ) as resp: @@ -609,6 +608,10 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: label="workflow catalog", ).decode("utf-8") ) + except URLPolicyError as exc: + raise WorkflowCatalogError( + f"Failed to fetch catalog from {entry.url}: {exc.reason}" + ) from exc except Exception as exc: # Fall back to cache if available try: diff --git a/src/specify_cli/workflows/step/catalog/_domain.py b/src/specify_cli/workflows/step/catalog/_domain.py index 77b508ce41..ec6b859aa5 100644 --- a/src/specify_cli/workflows/step/catalog/_domain.py +++ b/src/specify_cli/workflows/step/catalog/_domain.py @@ -350,7 +350,7 @@ def _fetch_single_catalog( from urllib.parse import urlparse - from specify_cli.authentication.http import open_url as _open_url + from specify_cli.authentication.http import URLPolicyError, open_url as _open_url def _validate_url(url: str) -> None: # A malformed authority (e.g. "https://[::1") makes urlparse / @@ -363,20 +363,18 @@ def _validate_url(url: str) -> None: hostname = parsed.hostname _ = parsed.port except (TypeError, ValueError): - raise StepCatalogError( + raise URLPolicyError( f"Refusing to fetch catalog from malformed URL: {url}" ) from None if parsed.scheme != "https": - raise StepCatalogError( + raise URLPolicyError( f"Refusing to fetch catalog from non-HTTPS URL: {url}" ) if not hostname: - raise StepCatalogError( + raise URLPolicyError( f"Refusing to fetch catalog from URL with no hostname: {url}" ) - _validate_url(entry.url) - # Validate EVERY redirect hop, not just the final URL: _open_url follows # redirects, so an https:// entry that 30x-redirects through http:// (or # to a non-HTTPS host mid-chain) could otherwise let a network attacker @@ -388,6 +386,7 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: _validate_url(new_url) try: + _validate_url(entry.url) with _open_url( entry.url, timeout=30, redirect_validator=_validate_redirect ) as resp: @@ -403,6 +402,10 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: ) except _DuplicateCatalogField: raise + except URLPolicyError as exc: + raise StepCatalogError( + f"Failed to fetch catalog from {entry.url}: {exc.reason}" + ) from exc except Exception as exc: try: cached = read_cache_json( diff --git a/tests/specify_cli/authentication/test_authentication.py b/tests/specify_cli/authentication/test_authentication.py index afed3ec30e..725d978a3e 100644 --- a/tests/specify_cli/authentication/test_authentication.py +++ b/tests/specify_cli/authentication/test_authentication.py @@ -1481,6 +1481,107 @@ def fake_side_effect(req, timeout=None): # --------------------------------------------------------------------------- +class TestInitialUrlSafety: + @pytest.mark.parametrize("helper", ["build_request", "open_url"]) + @pytest.mark.parametrize("provider_key,scheme", [ + ("github", "bearer"), + ("github", "github-cli"), + ("azure-devops", "basic-pat"), + ("bitbucket", "basic"), + ]) + @pytest.mark.parametrize("url", [ + "http://example.com/archive.zip", + "ftp://example.com/archive.zip", + ]) + def test_rejects_cleartext_before_resolving_credentials( + self, monkeypatch, helper, provider_key, scheme, url, + ): + from unittest.mock import patch + from specify_cli.authentication import http + + entry = AuthConfigEntry( + hosts=("example.com",), provider=provider_key, auth=scheme, + token="test-token", username="test-user", + ) + monkeypatch.setattr(http, "_config_override", [entry]) + provider = get_provider(provider_key) + assert provider is not None + token = "test-user:test-token" if scheme == "basic" else "test-token" + with patch.object( + provider, "resolve_token", return_value=token, + ) as resolve, patch.object(http.urllib.request, "build_opener") as build_opener: + with pytest.raises(http.URLPolicyError, match="HTTPS"): + getattr(http, helper)(url) + resolve.assert_not_called() + build_opener.assert_not_called() + + @pytest.mark.parametrize("helper", ["build_request", "open_url"]) + @pytest.mark.parametrize("url", [ + "http://example.com/archive.zip", + "http://0.0.0.0/archive.zip", + "http://127.1/archive.zip", + "https:///archive.zip", + "https://[::1", + "https://example.com:invalid/archive.zip", + "file:///tmp/archive.zip", + ]) + def test_rejects_unsafe_urls_without_auth_config(self, monkeypatch, helper, url): + from unittest.mock import patch + from specify_cli.authentication import http + + monkeypatch.setattr(http, "_config_override", []) + with patch.object(http.urllib.request, "build_opener") as build_opener: + with pytest.raises(http.URLPolicyError, match="HTTPS"): + getattr(http, helper)(url) + build_opener.assert_not_called() + + @pytest.mark.parametrize("helper", ["build_request", "open_url"]) + @pytest.mark.parametrize("provider_key,scheme", [ + ("github", "bearer"), + ("azure-devops", "basic-pat"), + ("bitbucket", "basic"), + ]) + @pytest.mark.parametrize("url", [ + "https://example.com/archive.zip", + "http://localhost:8000/archive.zip", + "http://127.0.0.1:8000/archive.zip", + "http://[::1]:8000/archive.zip", + ]) + def test_allows_https_and_loopback_http( + self, monkeypatch, helper, provider_key, scheme, url, + ): + from unittest.mock import patch + from urllib.parse import urlparse + from specify_cli.authentication import http + + entry = AuthConfigEntry( + hosts=(urlparse(url).hostname,), provider=provider_key, auth=scheme, + token="test-token", username="test-user", + ) + monkeypatch.setattr(http, "_config_override", [entry]) + provider = get_provider(provider_key) + assert provider is not None + token = "test-user:test-token" if scheme == "basic" else "test-token" + with patch.object( + provider, "resolve_token", return_value=token, + ) as resolve, patch.object(http.urllib.request, "build_opener") as build_opener: + result = getattr(http, helper)(url, extra_headers={"Accept": "application/zip"}) + if helper == "build_request": + request = result + build_opener.assert_not_called() + else: + opener = build_opener.return_value + assert result is opener.open.return_value + opener.open.assert_called_once() + request = opener.open.call_args.args[0] + resolve.assert_called_once_with(entry) + assert request.full_url == url + assert request.get_header("Accept") == "application/zip" + assert request.get_header("Authorization") == provider.auth_headers( + token, scheme, + )["Authorization"] + + class TestAuthenticatedHttpNegative: def _set_config(self, monkeypatch, entries): from specify_cli.authentication import http as _mod @@ -2143,6 +2244,77 @@ def test_malformed_redirect_port_raises_urlerror(self, target): target, ) + @pytest.mark.parametrize("code", [301, 302, 303, 307, 308]) + @pytest.mark.parametrize("header", ["Location", "URI"]) + @pytest.mark.parametrize("target", [ + "https://[::1", + "https://example.com:invalid/catalog.json", + "https:///catalog.json", + "https://:443/catalog.json", + "http:///catalog.json", + "file:///catalog.json", + ]) + def test_redirect_response_rejects_malformed_location(self, code, header, target): + from email.message import Message + from unittest.mock import MagicMock + from urllib.request import Request + + from specify_cli.authentication.http import RedirectPolicyError, _StripAuthOnRedirect + + handler = _StripAuthOnRedirect(("example.com",)) + parent = MagicMock() + handler.add_parent(parent) + request = Request("https://example.com/catalog.json") + request.timeout = 10 + headers = Message() + headers[header] = target + + with pytest.raises(RedirectPolicyError): + getattr(handler, f"http_error_{code}")( + request, io.BytesIO(b""), code, "Found", headers, + ) + parent.open.assert_not_called() + + @pytest.mark.parametrize("code", [301, 302, 303, 307, 308]) + @pytest.mark.parametrize("header", ["Location", "URI"]) + @pytest.mark.parametrize("target,expected_url,expected_auth", [ + ("/next.json", "https://example.com/next.json", "test-token"), + ("next.json", "https://example.com/next.json", "test-token"), + ("?page=2", "https://example.com/catalog.json?page=2", "test-token"), + ("//cdn.example.org/next.json", "https://cdn.example.org/next.json", None), + ("https://example.com/next file.json", "https://example.com/next%20file.json", "test-token"), + ]) + def test_redirect_response_preserves_supported_locations( + self, code, header, target, expected_url, expected_auth, + ): + from email.message import Message + from unittest.mock import MagicMock + from urllib.request import Request + + from specify_cli.authentication.http import _StripAuthOnRedirect + + handler = _StripAuthOnRedirect(("example.com",)) + parent = MagicMock() + handler.add_parent(parent) + request = Request( + "https://example.com/catalog.json", + headers={"Authorization": "test-token"}, + ) + request.timeout = 10 + headers = Message() + headers[header] = target + response = io.BytesIO(b"redirect body") + + result = getattr(handler, f"http_error_{code}")( + request, response, code, "Found", headers, + ) + assert result is parent.open.return_value + parent.open.assert_called_once() + redirected = parent.open.call_args.args[0] + assert redirected.full_url == expected_url + assert redirected.get_header("Authorization") == expected_auth + assert response.closed + def test_strict_redirect_error_describes_target_and_allowed_localhost(self): from specify_cli.authentication.http import _StripAuthOnRedirect from urllib.request import Request diff --git a/tests/specify_cli/bundles/test_adapters.py b/tests/specify_cli/bundles/test_adapters.py index 58e05d9706..40a9dd0688 100644 --- a/tests/specify_cli/bundles/test_adapters.py +++ b/tests/specify_cli/bundles/test_adapters.py @@ -441,6 +441,36 @@ def redirect_into_policy_violation( assert not isinstance(excinfo.value, adapters._CatalogUnavailable) +def test_builtin_community_catalog_does_not_fall_back_for_initial_url_policy_error( + monkeypatch, tmp_path, +): + from specify_cli.authentication import http + + monkeypatch.setitem( + adapters._BUILTIN_REPOSITORY_URLS, + "builtin://community", + "https://ex%61mple.com/catalog.json", + ) + catalog_path = tmp_path / "bundles" / "catalog.community.json" + catalog_path.parent.mkdir() + catalog_path.write_text( + '{"schema_version":"1.0","bundles":{}}', encoding="utf-8", + ) + monkeypatch.setattr(adapters, "_locate_core_pack", lambda: tmp_path) + fetcher = adapters.make_catalog_fetcher(allow_network=True) + + with patch.object(http, "_load_config") as load_config, patch.object( + http.urllib.request, "build_opener", + ) as build_opener, warnings.catch_warnings(record=True) as caught: + warnings.simplefilter("always") + with pytest.raises(BundlerError, match="unsafe request URL") as excinfo: + fetcher(_source("builtin://community")) + assert not isinstance(excinfo.value, adapters._CatalogUnavailable) + assert caught == [] + load_config.assert_not_called() + build_opener.assert_not_called() + + def test_builtin_community_catalog_falls_back_for_incomplete_read( monkeypatch, tmp_path ): diff --git a/tests/specify_cli/bundles/test_references.py b/tests/specify_cli/bundles/test_references.py index 261e1b2661..ee94ad66b2 100644 --- a/tests/specify_cli/bundles/test_references.py +++ b/tests/specify_cli/bundles/test_references.py @@ -879,6 +879,62 @@ def unsafe_redirect(*args, **kwargs): assert warnings == [] +@pytest.mark.parametrize("kind,expired_cache", [ + ("extensions", False), + ("presets", False), + ("workflows", False), + ("steps", False), + ("workflows", True), + ("steps", True), +]) +def test_online_validation_rejects_initial_catalog_url_policy_failure( + tmp_path, monkeypatch, kind, expired_cache, +): + from unittest.mock import patch + + from specify_cli.authentication import http + from specify_cli.extensions import CatalogEntry, ExtensionCatalog + from specify_cli.presets import PresetCatalog, PresetCatalogEntry + from specify_cli.workflows.catalog import ( + StepCatalog, StepCatalogEntry, WorkflowCatalog, WorkflowCatalogEntry, + ) + + catalog, entry = { + "extensions": (ExtensionCatalog, CatalogEntry), + "presets": (PresetCatalog, PresetCatalogEntry), + "workflows": (WorkflowCatalog, WorkflowCatalogEntry), + "steps": (StepCatalog, StepCatalogEntry), + }[kind] + monkeypatch.setattr( + catalog, "get_active_catalogs", + lambda self: [ + entry("https://ex%61mple.com/catalog.json", "trusted", 1, True), + ], + ) + if expired_cache: + import json + + instance = catalog(tmp_path) + data, metadata = instance._get_cache_paths("https://ex%61mple.com/catalog.json") + data.parent.mkdir(parents=True, exist_ok=True) + data.write_text(json.dumps({ + kind: {"requested": _installable_current(kind)}, + }), encoding="utf-8") + metadata.write_text(json.dumps({"fetched_at": 0}), encoding="utf-8") + warnings = [] + check = make_reference_checker(tmp_path, allow_network=True, warnings=warnings) + + with patch.object(http, "_load_config") as load_config, patch.object( + http.urllib.request, "build_opener", + ) as build_opener: + problem = check(_ref(kind, "requested")) + assert problem is not None + assert "unsafe request URL" in problem + assert warnings == [] + load_config.assert_not_called() + build_opener.assert_not_called() + + @pytest.mark.parametrize("kind", ["extensions", "presets"]) @pytest.mark.parametrize("redirect", ["validator", "policy"]) def test_online_validation_does_not_skip_unsafe_higher_priority_catalog( diff --git a/tests/specify_cli/workflows/test_catalog_cache.py b/tests/specify_cli/workflows/test_catalog_cache.py index c6fe46353a..54cf0a38df 100644 --- a/tests/specify_cli/workflows/test_catalog_cache.py +++ b/tests/specify_cli/workflows/test_catalog_cache.py @@ -187,8 +187,9 @@ def test_symlinked_cache_ancestor_cannot_redirect_write( assert list(outside.iterdir()) == [] +@pytest.mark.parametrize("force_refresh", [False, True]) def test_regular_cache_fresh_refresh_and_stale_fallback( - tmp_path, catalog_kind, fetch, monkeypatch + tmp_path, catalog_kind, fetch, monkeypatch, force_refresh, ): catalog_cls, entry_cls, *_ = catalog_kind catalog = catalog_cls(tmp_path) @@ -209,7 +210,82 @@ def unavailable(*args, **kwargs): raise URLError("isolated offline test") monkeypatch.setattr("specify_cli.authentication.http.open_url", unavailable) - assert catalog._fetch_single_catalog(entry) == fetch[0] + assert catalog._fetch_single_catalog(entry, force_refresh=force_refresh) == fetch[0] + + +@pytest.mark.parametrize("force_refresh", [False, True]) +@pytest.mark.parametrize("rejection,target", [ + ("initial", "https://ex%61mple.com/catalog.json"), + ("initial", "http://example.com/catalog.json"), + ("initial", "http://localhost/catalog.json"), + ("initial", "https://[::1"), + ("redirect", "https://localhost/catalog.json"), + ("redirect", "http://example.com/catalog.json"), + ("redirect", "http://localhost/catalog.json"), + ("redirect", "https://[::1"), + ("redirect", "https:///catalog.json"), + ("redirect", "https://example.com:invalid/catalog.json"), + ("final", "http://example.com/catalog.json"), + ("final", "http://localhost/catalog.json"), + ("final", "https://[::1"), + ("final", "https:///catalog.json"), +]) +def test_url_policy_failure_does_not_use_expired_cache( + tmp_path, monkeypatch, catalog_kind, force_refresh, rejection, target, +): + from email.message import Message + from unittest.mock import MagicMock, patch + + from specify_cli.authentication import http + + monkeypatch.setattr(http, "_config_override", []) + catalog_cls, entry_cls, field, *_ = catalog_kind + catalog = catalog_cls(tmp_path) + url = target if rejection == "initial" else URL + entry = entry_cls(url, "test", 1, False) + data, metadata = catalog._get_cache_paths(url) + data.parent.mkdir(parents=True, exist_ok=True) + payload = {field: {"cached": {"version": "1.0.0"}}} + data.write_text(json.dumps(payload), encoding="utf-8") + metadata.write_text(json.dumps({"fetched_at": 0}), encoding="utf-8") + assert not catalog._is_url_cache_valid(url) + error = WorkflowCatalogError if field == "workflows" else StepCatalogError + + with patch.object(http.urllib.request, "build_opener") as build_opener: + redirect_parent = MagicMock() + redirect_parent.open.side_effect = AssertionError("Rejected redirect was followed") + + def reject_redirect(request, timeout): + handler = build_opener.call_args.args[0] + handler.add_parent(redirect_parent) + request.timeout = timeout + headers = Message() + headers["Location"] = target + return handler.http_error_302( + request, io.BytesIO(b""), 302, "Found", headers, + ) + + if rejection == "redirect": + build_opener.return_value.open.side_effect = reject_redirect + elif rejection == "final": + response = build_opener.return_value.open.return_value.__enter__.return_value + response.geturl.return_value = target + with pytest.raises(error, match="Failed to fetch catalog") as excinfo: + catalog._fetch_single_catalog(entry, force_refresh=force_refresh) + assert isinstance(excinfo.value.__cause__, http.URLPolicyError) + assert str(excinfo.value) == ( + f"Failed to fetch catalog from {url}: {excinfo.value.__cause__.reason}" + ) + if rejection == "initial": + build_opener.assert_not_called() + else: + build_opener.return_value.open.assert_called_once() + if rejection == "final": + response.read.assert_not_called() + redirect_parent.open.assert_not_called() + + assert json.loads(data.read_text(encoding="utf-8")) == payload + assert json.loads(metadata.read_text(encoding="utf-8")) == {"fetched_at": 0} @pytest.mark.parametrize("leaf", ["data", "metadata"])