From 672d2693bbef067d59e27641ed82312305ce7b40 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:41:04 -0600 Subject: [PATCH 1/7] Harden initial URL validation in HTTP helpers Apply the shared HTTPS and loopback transport policy before resolving authentication or constructing requests. Cover accepted and rejected initial URLs and document the policy. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/reference/authentication.md | 5 + src/specify_cli/authentication/http.py | 18 ++- .../authentication/test_authentication.py | 103 ++++++++++++++++++ 3 files changed, 124 insertions(+), 2 deletions(-) diff --git a/docs/reference/authentication.md b/docs/reference/authentication.md index f7f2e02749..09f3fc981a 100644 --- a/docs/reference/authentication.md +++ b/docs/reference/authentication.md @@ -329,6 +329,11 @@ You can configure multiple entries for different hosts or organizations: ## How it works +Initial request URLs must use HTTPS with a hostname. HTTP is allowed only for +unambiguous loopback hosts, such as `localhost`, `127.0.0.1`, and `::1`. +Unsafe URLs are rejected before credentials are resolved or any request is +made, including when no authentication is configured. + 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..ed8ed8468e 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, @@ -69,6 +70,14 @@ class RedirectPolicyError(urllib.error.URLError): """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 urllib.error.URLError( + "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( @@ -135,7 +144,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 +204,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/tests/specify_cli/authentication/test_authentication.py b/tests/specify_cli/authentication/test_authentication.py index afed3ec30e..f3699edc97 100644 --- a/tests/specify_cli/authentication/test_authentication.py +++ b/tests/specify_cli/authentication/test_authentication.py @@ -1481,6 +1481,109 @@ 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, + ): + import urllib.error + 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(urllib.error.URLError, 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): + import urllib.error + 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(urllib.error.URLError, 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 From 243edf8bcbf74d289e9ac77fda298f891c855f10 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:54:53 -0600 Subject: [PATCH 2/7] Classify URL policy rejections as definitive catalog failures Share a URLPolicyError base between initial URL and redirect policy rejections. Preserve definitive errors in bundle catalog fetches and reference validation instead of treating them as temporary outages. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/reference/authentication.md | 2 + src/specify_cli/authentication/http.py | 8 +++- src/specify_cli/bundles/adapters.py | 6 +-- src/specify_cli/bundles/component_catalog.py | 4 +- .../authentication/test_authentication.py | 6 +-- tests/specify_cli/bundles/test_adapters.py | 30 ++++++++++++++ tests/specify_cli/bundles/test_references.py | 39 +++++++++++++++++++ 7 files changed, 84 insertions(+), 11 deletions(-) diff --git a/docs/reference/authentication.md b/docs/reference/authentication.md index 09f3fc981a..931285af02 100644 --- a/docs/reference/authentication.md +++ b/docs/reference/authentication.md @@ -333,6 +333,8 @@ Initial request URLs must use HTTPS with a hostname. HTTP is allowed only for unambiguous loopback hosts, such as `localhost`, `127.0.0.1`, and `::1`. Unsafe URLs are rejected before credentials are resolved or any request is made, including when no authentication is configured. +Catalog validation treats URL-policy rejections as definitive errors rather +than temporary availability failures. 1. For each outbound HTTP request, the URL hostname is matched against the `hosts` patterns in `auth.json`. diff --git a/src/specify_cli/authentication/http.py b/src/specify_cli/authentication/http.py index ed8ed8468e..3b4db60167 100644 --- a/src/specify_cli/authentication/http.py +++ b/src/specify_cli/authentication/http.py @@ -66,13 +66,17 @@ 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 urllib.error.URLError( + raise URLPolicyError( "unsafe request URL: target must use HTTPS with a hostname, " "or HTTP to loopback (for example localhost, 127.0.0.1, ::1)" ) diff --git a/src/specify_cli/bundles/adapters.py b/src/specify_cli/bundles/adapters.py index 52979de5bd..7c31f94ce2 100644 --- a/src/specify_cli/bundles/adapters.py +++ b/src/specify_cli/bundles/adapters.py @@ -229,7 +229,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) @@ -259,8 +259,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/tests/specify_cli/authentication/test_authentication.py b/tests/specify_cli/authentication/test_authentication.py index f3699edc97..f3ba3a1e85 100644 --- a/tests/specify_cli/authentication/test_authentication.py +++ b/tests/specify_cli/authentication/test_authentication.py @@ -1496,7 +1496,6 @@ class TestInitialUrlSafety: def test_rejects_cleartext_before_resolving_credentials( self, monkeypatch, helper, provider_key, scheme, url, ): - import urllib.error from unittest.mock import patch from specify_cli.authentication import http @@ -1511,7 +1510,7 @@ def test_rejects_cleartext_before_resolving_credentials( with patch.object( provider, "resolve_token", return_value=token, ) as resolve, patch.object(http.urllib.request, "build_opener") as build_opener: - with pytest.raises(urllib.error.URLError, match="HTTPS"): + with pytest.raises(http.URLPolicyError, match="HTTPS"): getattr(http, helper)(url) resolve.assert_not_called() build_opener.assert_not_called() @@ -1527,13 +1526,12 @@ def test_rejects_cleartext_before_resolving_credentials( "file:///tmp/archive.zip", ]) def test_rejects_unsafe_urls_without_auth_config(self, monkeypatch, helper, url): - import urllib.error 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(urllib.error.URLError, match="HTTPS"): + with pytest.raises(http.URLPolicyError, match="HTTPS"): getattr(http, helper)(url) build_opener.assert_not_called() 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..f1156a1469 100644 --- a/tests/specify_cli/bundles/test_references.py +++ b/tests/specify_cli/bundles/test_references.py @@ -879,6 +879,45 @@ def unsafe_redirect(*args, **kwargs): assert warnings == [] +@pytest.mark.parametrize("kind", ["extensions", "presets", "workflows", "steps"]) +def test_online_validation_rejects_initial_catalog_url_policy_failure( + tmp_path, monkeypatch, kind, +): + 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), + ], + ) + 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( From e119279d8574bfd78724368d05f1244a78761576 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:11:09 -0600 Subject: [PATCH 3/7] Clarify bundle URL policy failure documentation scope Name online bundle catalog fetching and reference validation explicitly without implying changes to ordinary catalog lookup or cache policies. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/reference/authentication.md | 5 +++-- 1 file changed, 3 insertions(+), 2 deletions(-) diff --git a/docs/reference/authentication.md b/docs/reference/authentication.md index 931285af02..2e50d04fa5 100644 --- a/docs/reference/authentication.md +++ b/docs/reference/authentication.md @@ -333,8 +333,9 @@ Initial request URLs must use HTTPS with a hostname. HTTP is allowed only for unambiguous loopback hosts, such as `localhost`, `127.0.0.1`, and `::1`. Unsafe URLs are rejected before credentials are resolved or any request is made, including when no authentication is configured. -Catalog validation treats URL-policy rejections as definitive errors rather -than temporary availability failures. +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`. From 4961c6f214ac4575f7bdff994cb6b6bc32825ae6 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:42:25 -0600 Subject: [PATCH 4/7] Preserve URL policy errors across workflow catalog cache fallbacks Bypass stale-cache fallback for shared URL policy rejections in workflow and step catalog fetchers while retaining the domain error contract and original cause. Cover expired cache, forced refresh, bundle reference rejection, and transport outage fallback. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/catalogs.md | 11 +++-- src/specify_cli/workflows/catalog/_domain.py | 6 ++- .../workflows/step/catalog/_domain.py | 6 ++- tests/specify_cli/bundles/test_references.py | 21 ++++++++- .../workflows/test_catalog_cache.py | 47 ++++++++++++++++++- 5 files changed, 81 insertions(+), 10 deletions(-) diff --git a/design/catalogs.md b/design/catalogs.md index dd0d5fe352..33d0a6fcfe 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -181,7 +181,8 @@ Current behavior differs by primitive: 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. + rejected after that fallback boundary. Shared HTTP URL-policy failures bypass + stale-cache fallback and retain their cause in a workflow catalog error. - 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 @@ -235,9 +236,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 catalog-validator redirect rejections, + bounded-read failures, decoding failures, and malformed JSON. Shared HTTP + URL-policy failures bypass stale-cache fallback, including during forced + refresh. 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/src/specify_cli/workflows/catalog/_domain.py b/src/specify_cli/workflows/catalog/_domain.py index 29717e1556..a0ec52eae6 100644 --- a/src/specify_cli/workflows/catalog/_domain.py +++ b/src/specify_cli/workflows/catalog/_domain.py @@ -562,7 +562,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 / @@ -615,6 +615,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}" + ) 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 50e79daa47..3abda7116c 100644 --- a/src/specify_cli/workflows/step/catalog/_domain.py +++ b/src/specify_cli/workflows/step/catalog/_domain.py @@ -501,7 +501,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 / @@ -557,6 +557,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}" + ) from exc except Exception as exc: try: cached = read_cache_json( diff --git a/tests/specify_cli/bundles/test_references.py b/tests/specify_cli/bundles/test_references.py index f1156a1469..ee94ad66b2 100644 --- a/tests/specify_cli/bundles/test_references.py +++ b/tests/specify_cli/bundles/test_references.py @@ -879,9 +879,16 @@ def unsafe_redirect(*args, **kwargs): assert warnings == [] -@pytest.mark.parametrize("kind", ["extensions", "presets", "workflows", "steps"]) +@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, + tmp_path, monkeypatch, kind, expired_cache, ): from unittest.mock import patch @@ -904,6 +911,16 @@ def test_online_validation_rejects_initial_catalog_url_policy_failure( 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) diff --git a/tests/specify_cli/workflows/test_catalog_cache.py b/tests/specify_cli/workflows/test_catalog_cache.py index c6fe46353a..6d012973c2 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,49 @@ 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", ["initial", "redirect"]) +def test_url_policy_failure_does_not_use_expired_cache( + tmp_path, monkeypatch, catalog_kind, force_refresh, rejection, +): + from unittest.mock import 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 = "https://ex%61mple.com/catalog.json" 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: + def reject_redirect(request, timeout): + handler = build_opener.call_args.args[0] + return handler.redirect_request( + request, None, 302, "Found", {}, "https://localhost/catalog.json", + ) + + build_opener.return_value.open.side_effect = reject_redirect + 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) + if rejection == "initial": + build_opener.assert_not_called() + else: + build_opener.return_value.open.assert_called_once() + + 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"]) From f59e539d7a82b315d91c32a1299c67f5f4fa7b88 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:11:26 -0600 Subject: [PATCH 5/7] Unify catalog URL rejection fallback behavior Classify catalog callback and final URL validation rejections as URL policy failures so workflow and step catalogs never return stale data after rejected URLs, regardless of validator order. Preserve domain errors and ordinary fetch fallback, and extend expired-cache coverage. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/catalogs.md | 23 +++++++-------- src/specify_cli/workflows/catalog/_domain.py | 9 +++--- .../workflows/step/catalog/_domain.py | 9 +++--- .../workflows/test_catalog_cache.py | 28 +++++++++++++++---- 4 files changed, 43 insertions(+), 26 deletions(-) diff --git a/design/catalogs.md b/design/catalogs.md index 33d0a6fcfe..85e2202487 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -177,12 +177,13 @@ Current behavior differs by primitive: apply it to a changed terminal URL. They 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. Shared HTTP URL-policy failures bypass - stale-cache fallback and retain their cause in a workflow catalog error. +- 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 @@ -236,11 +237,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 catalog-validator redirect rejections, - bounded-read failures, decoding failures, and malformed JSON. Shared HTTP - URL-policy failures bypass stale-cache fallback, including during forced - refresh. Fresh non-object payloads and step duplicate-field errors also - 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/src/specify_cli/workflows/catalog/_domain.py b/src/specify_cli/workflows/catalog/_domain.py index a0ec52eae6..b9fc191556 100644 --- a/src/specify_cli/workflows/catalog/_domain.py +++ b/src/specify_cli/workflows/catalog/_domain.py @@ -575,23 +575,21 @@ 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 is_localhost = hostname in ("localhost", "127.0.0.1", "::1") if parsed.scheme != "https" and not ( parsed.scheme == "http" and is_localhost ): - 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 @@ -603,6 +601,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: diff --git a/src/specify_cli/workflows/step/catalog/_domain.py b/src/specify_cli/workflows/step/catalog/_domain.py index 3abda7116c..78f5ec1d39 100644 --- a/src/specify_cli/workflows/step/catalog/_domain.py +++ b/src/specify_cli/workflows/step/catalog/_domain.py @@ -514,23 +514,21 @@ 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 is_localhost = hostname in ("localhost", "127.0.0.1", "::1") if parsed.scheme != "https" and not ( parsed.scheme == "http" and is_localhost ): - 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 @@ -542,6 +540,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: diff --git a/tests/specify_cli/workflows/test_catalog_cache.py b/tests/specify_cli/workflows/test_catalog_cache.py index 6d012973c2..327b3e0734 100644 --- a/tests/specify_cli/workflows/test_catalog_cache.py +++ b/tests/specify_cli/workflows/test_catalog_cache.py @@ -214,9 +214,21 @@ def unavailable(*args, **kwargs): @pytest.mark.parametrize("force_refresh", [False, True]) -@pytest.mark.parametrize("rejection", ["initial", "redirect"]) +@pytest.mark.parametrize("rejection,target", [ + ("initial", "https://ex%61mple.com/catalog.json"), + ("initial", "http://example.com/catalog.json"), + ("initial", "https://[::1"), + ("redirect", "https://localhost/catalog.json"), + ("redirect", "http://example.com/catalog.json"), + ("redirect", "https://[::1"), + ("redirect", "https:///catalog.json"), + ("redirect", "https://example.com:invalid/catalog.json"), + ("final", "http://example.com/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, + tmp_path, monkeypatch, catalog_kind, force_refresh, rejection, target, ): from unittest.mock import patch @@ -225,7 +237,7 @@ def test_url_policy_failure_does_not_use_expired_cache( monkeypatch.setattr(http, "_config_override", []) catalog_cls, entry_cls, field, *_ = catalog_kind catalog = catalog_cls(tmp_path) - url = "https://ex%61mple.com/catalog.json" if rejection == "initial" else URL + 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) @@ -239,10 +251,14 @@ def test_url_policy_failure_does_not_use_expired_cache( def reject_redirect(request, timeout): handler = build_opener.call_args.args[0] return handler.redirect_request( - request, None, 302, "Found", {}, "https://localhost/catalog.json", + request, None, 302, "Found", {}, target, ) - build_opener.return_value.open.side_effect = reject_redirect + 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) @@ -250,6 +266,8 @@ def reject_redirect(request, timeout): build_opener.assert_not_called() else: build_opener.return_value.open.assert_called_once() + if rejection == "final": + response.read.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} From bd690cb962ed42a72cbff820fafc1bc9e8894486 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:48:10 -0600 Subject: [PATCH 6/7] Validate redirect headers before urllib normalization Classify malformed Location and URI targets before urllib parses or normalizes them, covering every supported redirect status. Exercise the real redirect response entry point for expired-cache regressions, preserve valid relative redirects and auth handling, and explain the intentional URL-policy fallback change. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/catalogs.md | 11 +++ src/specify_cli/authentication/http.py | 32 ++++++++- .../authentication/test_authentication.py | 71 +++++++++++++++++++ .../workflows/test_catalog_cache.py | 15 +++- 4 files changed, 123 insertions(+), 6 deletions(-) diff --git a/design/catalogs.md b/design/catalogs.md index 85e2202487..b13b27bff6 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -199,6 +199,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 diff --git a/src/specify_cli/authentication/http.py b/src/specify_cli/authentication/http.py index 3b4db60167..1387cd6574 100644 --- a/src/specify_cli/authentication/http.py +++ b/src/specify_cli/authentication/http.py @@ -94,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__( @@ -109,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) diff --git a/tests/specify_cli/authentication/test_authentication.py b/tests/specify_cli/authentication/test_authentication.py index f3ba3a1e85..725d978a3e 100644 --- a/tests/specify_cli/authentication/test_authentication.py +++ b/tests/specify_cli/authentication/test_authentication.py @@ -2244,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/workflows/test_catalog_cache.py b/tests/specify_cli/workflows/test_catalog_cache.py index 327b3e0734..31e9479a45 100644 --- a/tests/specify_cli/workflows/test_catalog_cache.py +++ b/tests/specify_cli/workflows/test_catalog_cache.py @@ -230,7 +230,8 @@ def unavailable(*args, **kwargs): def test_url_policy_failure_does_not_use_expired_cache( tmp_path, monkeypatch, catalog_kind, force_refresh, rejection, target, ): - from unittest.mock import patch + from email.message import Message + from unittest.mock import MagicMock, patch from specify_cli.authentication import http @@ -248,10 +249,17 @@ def test_url_policy_failure_does_not_use_expired_cache( 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] - return handler.redirect_request( - request, None, 302, "Found", {}, target, + 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": @@ -268,6 +276,7 @@ def reject_redirect(request, timeout): 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} From e33721833e1ba7013f28d9e40c649d13086b5932 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 13:25:05 -0600 Subject: [PATCH 7/7] Show clean URL policy reasons in catalog errors Format URLPolicyError.reason in workflow and step catalog diagnostics while retaining the original exception as the cause. Assert exact messages across initial URL, redirect, and final URL rejections. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/specify_cli/workflows/catalog/_domain.py | 2 +- src/specify_cli/workflows/step/catalog/_domain.py | 2 +- tests/specify_cli/workflows/test_catalog_cache.py | 3 +++ 3 files changed, 5 insertions(+), 2 deletions(-) diff --git a/src/specify_cli/workflows/catalog/_domain.py b/src/specify_cli/workflows/catalog/_domain.py index bfebe29a65..364e71028b 100644 --- a/src/specify_cli/workflows/catalog/_domain.py +++ b/src/specify_cli/workflows/catalog/_domain.py @@ -610,7 +610,7 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: ) except URLPolicyError as exc: raise WorkflowCatalogError( - f"Failed to fetch catalog from {entry.url}: {exc}" + f"Failed to fetch catalog from {entry.url}: {exc.reason}" ) from exc except Exception as exc: # Fall back to cache if available diff --git a/src/specify_cli/workflows/step/catalog/_domain.py b/src/specify_cli/workflows/step/catalog/_domain.py index 8a414ddb71..ec6b859aa5 100644 --- a/src/specify_cli/workflows/step/catalog/_domain.py +++ b/src/specify_cli/workflows/step/catalog/_domain.py @@ -404,7 +404,7 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: raise except URLPolicyError as exc: raise StepCatalogError( - f"Failed to fetch catalog from {entry.url}: {exc}" + f"Failed to fetch catalog from {entry.url}: {exc.reason}" ) from exc except Exception as exc: try: diff --git a/tests/specify_cli/workflows/test_catalog_cache.py b/tests/specify_cli/workflows/test_catalog_cache.py index a54424c2f4..54cf0a38df 100644 --- a/tests/specify_cli/workflows/test_catalog_cache.py +++ b/tests/specify_cli/workflows/test_catalog_cache.py @@ -273,6 +273,9 @@ def reject_redirect(request, timeout): 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: