From 017debbdac4fd98b7791213cfc3bc32be23caa51 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:36:21 -0600 Subject: [PATCH 1/7] Require HTTPS consistently for catalog sources Align catalog source validation and documentation across all catalog types. Report preset configuration errors and use trusted HTTPS in installed-adapter tests. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .github/security-audit-requirements.txt | 4 +- design/catalogs.md | 14 ++- design/extension.md | 4 +- docs/bundles/catalogs.md | 5 +- docs/extensions/api.md | 2 +- docs/extensions/catalogs.md | 14 ++- docs/integrations/cli.md | 4 +- docs/presets/catalogs.md | 2 +- docs/workflow-steps/catalogs.md | 3 +- docs/workflows/catalogs.md | 4 +- pyproject.toml | 1 + src/specify_cli/bundles/adapters.py | 8 +- src/specify_cli/bundles/catalog_config.py | 8 +- src/specify_cli/catalogs.py | 8 +- .../integrations/catalog/command_add.py | 5 +- src/specify_cli/presets/_catalog.py | 12 +-- src/specify_cli/workflows/catalog/_domain.py | 15 +--- .../workflows/step/catalog/_domain.py | 15 +--- .../bundles/test_catalog_config.py | 19 ++-- tests/specify_cli/bundles/test_offline.py | 29 ++++++ .../specify_cli/integrations/test_catalog.py | 7 +- .../integrations/test_installed_adapters.py | 51 ++++++++++- tests/specify_cli/presets/test_catalog.py | 8 +- tests/specify_cli/test_catalog_contracts.py | 89 ++++++++++++++++++- tests/test_extensions.py | 10 +-- tests/test_workflows.py | 18 ++-- 26 files changed, 255 insertions(+), 104 deletions(-) diff --git a/.github/security-audit-requirements.txt b/.github/security-audit-requirements.txt index fd2718d3f1..22f4473363 100644 --- a/.github/security-audit-requirements.txt +++ b/.github/security-audit-requirements.txt @@ -315,7 +315,9 @@ cryptography==50.0.2 \ --hash=sha256:f9f6143a8c75945eb960d9eb98905a441394abfa24afaae239d514ffb2586480 \ --hash=sha256:fa8f5efb344d6908a1ce62f4a24e2e5780f825d6f53f5f50ec5ffacac72936cb \ --hash=sha256:fdd28f912fccfec1846a94e2e1e8f9b0012f557f0c46fe4f3eb0d7a87afcf90b - # via pyjwt + # via + # specify-cli (pyproject.toml) + # pyjwt execnet==2.1.2 \ --hash=sha256:63d83bfdd9a23e35b9c6a3261412324f964c2ec8dcd8d3c6916ee9373e0befcd \ --hash=sha256:67fba928dd5a544b783f6056f449e5e3931a5c378b128bc18501f7ea79e296ec diff --git a/design/catalogs.md b/design/catalogs.md index dd0d5fe352..61adf557da 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -107,9 +107,13 @@ catalogs: install_policy: discovery-only ``` -Supported bundle source schemes are `https`, localhost `http`, `file`, -`builtin`, and local filesystem paths. The other five catalog types accept -remote HTTPS URLs, with HTTP allowed only for localhost. +Supported bundle source schemes are `https`, `file`, `builtin`, and local +filesystem paths. The other five catalog types accept remote HTTPS URLs. +All six types reject plain HTTP catalog sources, including localhost and +loopback addresses, before network access. This intentionally removes the +former local-development HTTP exception so every source layer follows the +same HTTPS policy. Local HTTPS development servers need a certificate trusted +by the system. Archive download policies are separate and unchanged. ## Configuration semantics @@ -130,7 +134,7 @@ phase and accepted values otherwise differ: to `1`. Bundle `CatalogSource` materialization rejects booleans and floats rather than coercing them, but `_read()` and `remove_source()` can carry or remove those raw values without materializing them. -- Replacement-layer loaders reject malformed remote URLs and non-localhost +- Replacement-layer loaders reject malformed remote URLs and all plain HTTP while resolving the active stack. Bundle source validation depends on the path: catalog commands validate supported schemes and remote security before writing, while a hand-edited stack is revalidated by the fetcher when @@ -228,6 +232,8 @@ usable. Validation errors are not uniformly recoverable: expose a lower-precedence copy. - Preset lookup preserves the first fetch error when no source is readable; preset search currently converts ordinary fetch failures to an empty result. + Invalid source configuration (`PresetValidationError`) is fatal in search, + including rejected HTTP catalog URLs. `PresetCatalogValidationError` remains fatal: search can fail on invalid lower-precedence content even after reading a valid higher source, while a targeted lookup can return as soon as it finds the requested higher entry. diff --git a/design/extension.md b/design/extension.md index fea066f57a..e8899eeb05 100644 --- a/design/extension.md +++ b/design/extension.md @@ -346,8 +346,8 @@ packaging and output writes; they are not a sandbox. Network and package trust rules are: -- catalog and archive URLs require HTTPS, except loopback HTTP for local - development; +- catalog URLs require HTTPS, including for local development; archive URLs + retain the loopback HTTP exception; - catalog redirects are validated at every hop; - configured authentication providers may add credentials for matching hosts, and redirect handling does not forward them to untrusted hosts; diff --git a/docs/bundles/catalogs.md b/docs/bundles/catalogs.md index 2cba001aca..d293b42b40 100644 --- a/docs/bundles/catalogs.md +++ b/docs/bundles/catalogs.md @@ -81,8 +81,9 @@ CLI add/remove operations write project scope only. Both readers accept a missing schema version for compatibility and reject an unsupported major version. -Source URLs can be HTTPS, HTTP on localhost, `file://`, local paths, or known -`builtin://` URLs. Added local paths are stored as absolute paths. This +Source URLs can be HTTPS, `file://`, local paths, or known +`builtin://` URLs. Plain HTTP is rejected before network access, including on +localhost. Added local paths are stored as absolute paths. This flexibility applies to the catalog file, not its bundle download URLs. ### Precedence diff --git a/docs/extensions/api.md b/docs/extensions/api.md index adb18e2472..8c118c3b16 100644 --- a/docs/extensions/api.md +++ b/docs/extensions/api.md @@ -353,7 +353,7 @@ entry = CatalogEntry( | Field | Type | Description | |-------|------|-------------| -| `url` | `str` | Catalog URL (must use HTTPS, or HTTP for localhost) | +| `url` | `str` | Catalog URL (must use HTTPS, including for localhost) | | `name` | `str` | Human-readable catalog name | | `priority` | `int` | Sort order (lower = higher priority, wins on conflicts) | | `install_allowed` | `bool` | Whether extensions from this catalog can be installed | diff --git a/docs/extensions/catalogs.md b/docs/extensions/catalogs.md index 64902ad368..f5f90c81b7 100644 --- a/docs/extensions/catalogs.md +++ b/docs/extensions/catalogs.md @@ -179,9 +179,10 @@ Create a `catalog.json` file containing the releases your team has vetted: | GitHub Pages | `https://your-org.github.io/spec-kit-catalog/catalog.json` | Public or org-visible | | Internal web server | `https://internal.company.com/spec-kit/catalog.json` | Corporate network | | S3/cloud storage | `https://s3.amazonaws.com/your-bucket/catalog.json` | Cloud-hosted teams | -| Local file server | `http://localhost:8000/catalog.json` | Development/testing | +| Local HTTPS server | `https://localhost:8443/catalog.json` | Development/testing with a trusted certificate | -URLs must use HTTPS, except localhost for testing. +Catalog URLs must use HTTPS, including localhost. Plain HTTP catalogs are +rejected before network access. Add your catalog with `specify extension catalog add`, or use: ```yaml @@ -236,14 +237,11 @@ inside the network. For example, an entry can use ### Development and testing -```bash -python -m http.server 8000 --directory ./my-catalog/ -``` - -In another terminal: +Serve `./my-catalog/` through an HTTPS server with a certificate trusted by your +system, then point the CLI at it: ```bash -export SPECKIT_CATALOG_URL="http://localhost:8000/catalog.json" +export SPECKIT_CATALOG_URL="https://localhost:8443/catalog.json" specify extension add my-new-extension ``` diff --git a/docs/integrations/cli.md b/docs/integrations/cli.md index d67252af5d..b5668866fd 100644 --- a/docs/integrations/cli.md +++ b/docs/integrations/cli.md @@ -335,7 +335,9 @@ specify integration catalog add | --------------- | ----------------------------- | | `--name ` | Optional name for the catalog | -Adds a custom catalog URL to the project's `.specify/integration-catalogs.yml`. The URL must use HTTPS (except `http://localhost`, `http://127.0.0.1`, or `http://[::1]` for local testing). +Adds a custom catalog URL to the project's `.specify/integration-catalogs.yml`. +The URL must use HTTPS, including for local testing. Plain HTTP is rejected +before network access, including on localhost and loopback addresses. Re-adding the same URL with the same name succeeds without changing the configuration; a different name is rejected. diff --git a/docs/presets/catalogs.md b/docs/presets/catalogs.md index 2c4aa6b6fa..a849f98990 100644 --- a/docs/presets/catalogs.md +++ b/docs/presets/catalogs.md @@ -61,7 +61,7 @@ catalogs: | Entry field | Meaning | | --- | --- | -| `url` | HTTPS catalog URL; loopback HTTP is allowed for local development | +| `url` | HTTPS catalog URL, including for local development; plain HTTP is rejected | | `name` | Source name displayed by the CLI and used for provenance | | `priority` | Lower numbers are checked first | | `install_allowed` | Whether ID-based installation is permitted; default `false` | diff --git a/docs/workflow-steps/catalogs.md b/docs/workflow-steps/catalogs.md index 55724bf67f..54acb43f89 100644 --- a/docs/workflow-steps/catalogs.md +++ b/docs/workflow-steps/catalogs.md @@ -39,7 +39,8 @@ catalogs: description: Our vetted workflow steps ``` -`url` requires HTTPS (loopback HTTP is allowed for development). Lower numeric +`url` requires HTTPS, including for local development; plain HTTP is rejected +before network access. Lower numeric priorities win; the first source wins ties. `install_allowed` defaults to false in hand-authored configuration. diff --git a/docs/workflows/catalogs.md b/docs/workflows/catalogs.md index fa13d90dca..b62652ea25 100644 --- a/docs/workflows/catalogs.md +++ b/docs/workflows/catalogs.md @@ -37,7 +37,9 @@ catalogs: description: Our vetted workflows ``` -`url` requires HTTPS (loopback HTTP is allowed for development). Lower numeric priorities win; the first source wins ties. `install_allowed` defaults to false in hand-authored configuration. +`url` requires HTTPS, including for local development; plain HTTP is rejected +before network access. Lower numeric priorities win; the first source wins ties. +`install_allowed` defaults to false in hand-authored configuration. `specify workflow catalog add` creates project entries with installation allowed and a priority after existing entries. It does not expose preset-style `--install-allowed` or `--priority` flags. Add only vetted sources; edit the configuration when a discovery-only source is intended. Adding a project stack replaces implicit defaults unless you include them explicitly. diff --git a/pyproject.toml b/pyproject.toml index b4264442e2..e4b3f09a08 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -61,6 +61,7 @@ packages = ["src/specify_cli"] [project.optional-dependencies] test = [ + "cryptography", "pytest>=7.0", "pytest-cov>=4.0", "pytest-xdist>=3.0", diff --git a/src/specify_cli/bundles/adapters.py b/src/specify_cli/bundles/adapters.py index 52979de5bd..7054ae2248 100644 --- a/src/specify_cli/bundles/adapters.py +++ b/src/specify_cli/bundles/adapters.py @@ -92,7 +92,7 @@ def _file_url_to_path(parsed: ParseResult) -> Path: def _validate_remote_url(source_id: str, url: str) -> None: - """Restrict remote catalogs to HTTPS (HTTP only for localhost) with a host. + """Restrict remote catalogs to HTTPS with a host, including localhost. Mirrors ``specify_cli.catalogs`` URL validation to avoid MITM/downgrade issues before any network call. @@ -110,11 +110,9 @@ def _validate_remote_url(source_id: str, url: str) -> None: raise BundlerError( f"Catalog '{source_id}' URL is malformed: {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): + if parsed.scheme != "https": raise BundlerError( - f"Catalog '{source_id}' URL must use HTTPS (got {parsed.scheme}://). " - "HTTP is only allowed for localhost." + f"Catalog '{source_id}' URL must use HTTPS (got {parsed.scheme}://)." ) # Check hostname, not netloc: netloc is truthy for host-less URLs like # "https://:8080" or "https://user@...", so requiring netloc would let diff --git a/src/specify_cli/bundles/catalog_config.py b/src/specify_cli/bundles/catalog_config.py index 7a8bcd7174..a28a35b2c2 100644 --- a/src/specify_cli/bundles/catalog_config.py +++ b/src/specify_cli/bundles/catalog_config.py @@ -171,15 +171,13 @@ def add_source( ) if parsed.scheme.lower() in {"http", "https"}: # Mirror specify_cli.catalogs._validate_catalog_url (#3209/#3210): - # HTTPS only (HTTP just for localhost), and check hostname, not + # HTTPS only, including localhost, and check hostname, not # netloc — netloc is truthy for host-less URLs like "https://:8080" # or "https://user@". Validating here keeps junk out of # bundle-catalogs.yml instead of failing later at fetch time. - is_localhost = hostname in ("localhost", "127.0.0.1", "::1") - if parsed.scheme.lower() != "https" and not is_localhost: + if parsed.scheme.lower() != "https": raise BundlerError( - f"Catalog url must use HTTPS (got {parsed.scheme}://). " - "HTTP is only allowed for localhost." + f"Catalog url must use HTTPS (got {parsed.scheme}://)." ) if not hostname: raise BundlerError(f"Catalog url must be a valid URL with a host: {url}") diff --git a/src/specify_cli/catalogs.py b/src/specify_cli/catalogs.py index 9e9fc96d6a..25f8c813b5 100644 --- a/src/specify_cli/catalogs.py +++ b/src/specify_cli/catalogs.py @@ -68,7 +68,7 @@ def _entry( @classmethod def _validate_catalog_url(cls, url: str) -> None: - """Validate that a catalog URL uses HTTPS, except localhost HTTP.""" + """Validate that a catalog URL uses HTTPS, including local hosts.""" from urllib.parse import urlparse try: @@ -83,14 +83,12 @@ def _validate_catalog_url(cls, url: str) -> None: _ = parsed.port except ValueError: raise cls._error(f"Catalog URL is malformed: {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): + if parsed.scheme != "https": # A scheme-less value (``example.com/catalog.json``) would otherwise read # "got ://". The value itself is not echoed: callers render errors as Rich markup. got = f"{parsed.scheme}://" if parsed.scheme else "a URL with no scheme" raise cls._error( - f"Catalog URL must use HTTPS (got {got}). " - "HTTP is only allowed for localhost." + f"Catalog URL must use HTTPS (got {got})." ) # Check hostname, not netloc: netloc is truthy for host-less URLs like # "https://:8080" or "https://user@", so the host guarantee this error diff --git a/src/specify_cli/integrations/catalog/command_add.py b/src/specify_cli/integrations/catalog/command_add.py index 0087b06034..60b72763d1 100644 --- a/src/specify_cli/integrations/catalog/command_add.py +++ b/src/specify_cli/integrations/catalog/command_add.py @@ -14,10 +14,7 @@ def integration_catalog_add( url: str = typer.Argument( ..., - help=( - "Catalog URL to add (HTTPS required, except http://localhost, " - "http://127.0.0.1, or http://[::1] for local testing)" - ), + help="Catalog URL to add (HTTPS required, including localhost)", ), name: Optional[str] = typer.Option(None, "--name", help="Catalog name"), ): diff --git a/src/specify_cli/presets/_catalog.py b/src/specify_cli/presets/_catalog.py index a55e7d11e3..e3cea50657 100644 --- a/src/specify_cli/presets/_catalog.py +++ b/src/specify_cli/presets/_catalog.py @@ -107,7 +107,7 @@ def __init__(self, project_root: Path): self.cache_metadata_file = self.cache_dir / "catalog-metadata.json" def _validate_catalog_url(self, url: str) -> None: - """Validate that a catalog URL uses HTTPS (localhost HTTP allowed). + """Validate that a catalog URL uses HTTPS, including local hosts. Args: url: URL to validate @@ -129,16 +129,12 @@ def _validate_catalog_url(self, url: str) -> None: _ = parsed.port except ValueError: raise PresetValidationError(f"Catalog URL is malformed: {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 - ): + if parsed.scheme != "https": # A scheme-less value (``example.com/catalog.json``) would otherwise read # "got ://". The value itself is not echoed: callers render errors as Rich markup. got = f"{parsed.scheme}://" if parsed.scheme else "a URL with no scheme" raise PresetValidationError( - f"Catalog URL must use HTTPS (got {got}). " - "HTTP is only allowed for localhost." + f"Catalog URL must use HTTPS (got {got})." ) # Check hostname, not netloc: netloc is truthy for host-less URLs like # "https://:8080" or "https://user@", so the host guarantee this error @@ -767,7 +763,7 @@ def search( """ try: packs = self._get_merged_packs() - except PresetCatalogValidationError: + except (PresetCatalogValidationError, PresetValidationError): raise except PresetError: return [] diff --git a/src/specify_cli/workflows/catalog/_domain.py b/src/specify_cli/workflows/catalog/_domain.py index 29717e1556..c6b8b0cabd 100644 --- a/src/specify_cli/workflows/catalog/_domain.py +++ b/src/specify_cli/workflows/catalog/_domain.py @@ -329,7 +329,7 @@ def __init__(self, project_root: Path) -> None: # -- Catalog resolution ----------------------------------------------- def _validate_catalog_url(self, url: str) -> None: - """Validate that a catalog URL uses HTTPS (localhost HTTP allowed).""" + """Validate that a catalog URL uses HTTPS, including local hosts.""" from urllib.parse import urlparse # A malformed authority (e.g. an unterminated IPv6 bracket @@ -346,16 +346,12 @@ def _validate_catalog_url(self, url: str) -> None: raise WorkflowValidationError( f"Catalog URL is malformed: {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 - ): + if parsed.scheme != "https": # A scheme-less value (``example.com/catalog.json``) would otherwise read # "got ://". The value itself is not echoed: callers render errors as Rich markup. got = f"{parsed.scheme}://" if parsed.scheme else "a URL with no scheme" raise WorkflowValidationError( - f"Catalog URL must use HTTPS (got {got}). " - "HTTP is only allowed for localhost." + f"Catalog URL must use HTTPS (got {got})." ) if not hostname: raise WorkflowValidationError( @@ -578,10 +574,7 @@ def _validate_catalog_url(url: str) -> None: raise WorkflowCatalogError( 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 - ): + if parsed.scheme != "https": raise WorkflowCatalogError( f"Refusing to fetch catalog from non-HTTPS URL: {url}" ) diff --git a/src/specify_cli/workflows/step/catalog/_domain.py b/src/specify_cli/workflows/step/catalog/_domain.py index 50e79daa47..a533286322 100644 --- a/src/specify_cli/workflows/step/catalog/_domain.py +++ b/src/specify_cli/workflows/step/catalog/_domain.py @@ -277,7 +277,7 @@ def __init__(self, project_root: Path) -> None: # -- Catalog resolution ----------------------------------------------- def _validate_catalog_url(self, url: str) -> None: - """Validate that a catalog URL uses HTTPS (localhost HTTP allowed).""" + """Validate that a catalog URL uses HTTPS, including local hosts.""" from urllib.parse import urlparse # A malformed authority (e.g. an unterminated IPv6 bracket @@ -294,16 +294,12 @@ def _validate_catalog_url(self, url: str) -> None: raise StepValidationError( f"Catalog URL is malformed: {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 - ): + if parsed.scheme != "https": # A scheme-less value (``example.com/catalog.json``) would otherwise read # "got ://". The value itself is not echoed: callers render errors as Rich markup. got = f"{parsed.scheme}://" if parsed.scheme else "a URL with no scheme" raise StepValidationError( - f"Catalog URL must use HTTPS (got {got}). " - "HTTP is only allowed for localhost." + f"Catalog URL must use HTTPS (got {got})." ) if not hostname: raise StepValidationError( @@ -517,10 +513,7 @@ def _validate_url(url: str) -> None: raise StepCatalogError( 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 - ): + if parsed.scheme != "https": raise StepCatalogError( f"Refusing to fetch catalog from non-HTTPS URL: {url}" ) diff --git a/tests/specify_cli/bundles/test_catalog_config.py b/tests/specify_cli/bundles/test_catalog_config.py index 2df4cc921b..063950106b 100644 --- a/tests/specify_cli/bundles/test_catalog_config.py +++ b/tests/specify_cli/bundles/test_catalog_config.py @@ -425,17 +425,18 @@ def test_add_source_rejects_plain_http_for_non_localhost(tmp_path: Path): cc.add_source(project, "http://example.com/catalog.json", policy="install-allowed", priority=50) -def test_add_source_allows_http_for_localhost(tmp_path: Path): +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) +def test_add_source_rejects_http_for_localhost(tmp_path: Path, host: str): project = tmp_path / "proj" (project / ".specify").mkdir(parents=True) - source, status = cc.add_source( - project, - "http://localhost:8080/c.json", - policy="install-allowed", - priority=50, - ) - assert status == "added" - assert source.url == "http://localhost:8080/c.json" + with pytest.raises(BundlerError, match="HTTPS"): + cc.add_source( + project, + f"http://{host}:8080/c.json", + policy="install-allowed", + priority=50, + ) + assert not cc._config_path(project).exists() def test_add_source_rejects_host_less_remote_urls(tmp_path: Path): diff --git a/tests/specify_cli/bundles/test_offline.py b/tests/specify_cli/bundles/test_offline.py index 8acb513fc5..fcc655189f 100644 --- a/tests/specify_cli/bundles/test_offline.py +++ b/tests/specify_cli/bundles/test_offline.py @@ -122,6 +122,35 @@ def test_http_source_refused_when_offline(): stack.resolve("anything") +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) +def test_project_catalog_loopback_http_refused_before_network( + tmp_path, monkeypatch, host +): + from unittest.mock import Mock + + from specify_cli.bundles.catalogs import load_source_stack + + config_dir = tmp_path / ".specify" + config_dir.mkdir() + (config_dir / "bundle-catalogs.yml").write_text( + "schema_version: '1.0'\ncatalogs:\n" + " - id: default\n" + f" url: 'http://{host}:8080/catalog.json?channel=test'\n" + " priority: 1\n" + " install_policy: discovery-only\n", + encoding="utf-8", + ) + sources = load_source_stack(tmp_path, user_config_dir=tmp_path / "user") + open_url = Mock(side_effect=AssertionError("Catalog URL reached the network")) + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + stack = CatalogStack(sources, make_catalog_fetcher()) + + with pytest.raises(BundlerError, match="HTTPS"): + stack.search() + + open_url.assert_not_called() + + def test_missing_file_catalog_errors_offline(tmp_path: Path): fetcher = make_catalog_fetcher(allow_network=False) stack = CatalogStack([_src("local", str(tmp_path / "nope.json"))], fetcher) diff --git a/tests/specify_cli/integrations/test_catalog.py b/tests/specify_cli/integrations/test_catalog.py index 81d217eec1..4878716f05 100644 --- a/tests/specify_cli/integrations/test_catalog.py +++ b/tests/specify_cli/integrations/test_catalog.py @@ -91,9 +91,10 @@ def test_schemeless_url_names_the_value(self): assert "(got a URL with no scheme)" in str(excinfo.value) assert "got ://" not in str(excinfo.value) - def test_http_localhost_allowed(self): - IntegrationCatalog._validate_catalog_url("http://localhost:8080/catalog.json") - IntegrationCatalog._validate_catalog_url("http://127.0.0.1/catalog.json") + @pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) + def test_http_localhost_rejected(self, host): + with pytest.raises(IntegrationCatalogError, match="HTTPS"): + IntegrationCatalog._validate_catalog_url(f"http://{host}:8080/catalog.json") def test_missing_host_rejected(self): with pytest.raises(IntegrationCatalogError, match="valid URL"): diff --git a/tests/specify_cli/integrations/test_installed_adapters.py b/tests/specify_cli/integrations/test_installed_adapters.py index 4c8f131bd3..ebc3dc733d 100644 --- a/tests/specify_cli/integrations/test_installed_adapters.py +++ b/tests/specify_cli/integrations/test_installed_adapters.py @@ -8,6 +8,7 @@ import marshal import os import shutil +import ssl import stat import struct import subprocess @@ -15,13 +16,19 @@ import tarfile import threading import zipfile +from datetime import datetime, timedelta, timezone from functools import partial from http.server import SimpleHTTPRequestHandler, ThreadingHTTPServer +from ipaddress import ip_address from pathlib import Path from types import SimpleNamespace import pytest import yaml +from cryptography import x509 +from cryptography.hazmat.primitives import hashes, serialization +from cryptography.hazmat.primitives.asymmetric import ec +from cryptography.x509.oid import NameOID from typer.testing import CliRunner from specify_cli import AGENT_CONFIG, app @@ -89,8 +96,43 @@ def isolated_registry(monkeypatch, tmp_path): unload_installed_integrations() +@pytest.fixture(scope="module") +def tls_certificate(tmp_path_factory): + root = tmp_path_factory.mktemp("integration-catalog-tls") + key = ec.generate_private_key(ec.SECP256R1()) + subject = x509.Name([x509.NameAttribute(NameOID.COMMON_NAME, "127.0.0.1")]) + now = datetime.now(timezone.utc) + certificate = ( + x509.CertificateBuilder() + .subject_name(subject) + .issuer_name(subject) + .public_key(key.public_key()) + .serial_number(x509.random_serial_number()) + .not_valid_before(now - timedelta(minutes=1)) + .not_valid_after(now + timedelta(days=1)) + .add_extension(x509.BasicConstraints(ca=True, path_length=None), critical=True) + .add_extension( + x509.SubjectAlternativeName([x509.IPAddress(ip_address("127.0.0.1"))]), + critical=False, + ) + .sign(key, hashes.SHA256()) + ) + cert_path = root / "certificate.pem" + key_path = root / "key.pem" + cert_path.write_bytes(certificate.public_bytes(serialization.Encoding.PEM)) + key_path.write_bytes( + key.private_bytes( + serialization.Encoding.PEM, + serialization.PrivateFormat.PKCS8, + serialization.NoEncryption(), + ) + ) + key_path.chmod(0o600) + return cert_path, key_path + + @pytest.fixture -def server(tmp_path): +def server(tmp_path, monkeypatch, tls_certificate): downloads = tmp_path / "downloads" downloads.mkdir() requests = [] @@ -104,10 +146,15 @@ def log_message(self, *args): pass http = ThreadingHTTPServer(("127.0.0.1", 0), partial(Handler, directory=str(downloads))) + cert_path, key_path = tls_certificate + context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.load_cert_chain(cert_path, key_path) + http.socket = context.wrap_socket(http.socket, server_side=True) + monkeypatch.setenv("SSL_CERT_FILE", str(cert_path)) thread = threading.Thread(target=http.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True) thread.start() result = SimpleNamespace( - root=downloads, url=f"http://127.0.0.1:{http.server_port}", requests=requests, + root=downloads, url=f"https://127.0.0.1:{http.server_port}", requests=requests, ) try: yield result diff --git a/tests/specify_cli/presets/test_catalog.py b/tests/specify_cli/presets/test_catalog.py index aadbca2f20..7fcc38713f 100644 --- a/tests/specify_cli/presets/test_catalog.py +++ b/tests/specify_cli/presets/test_catalog.py @@ -193,11 +193,11 @@ def test_validate_catalog_url_schemeless_names_the_value(self, project_dir): with pytest.raises(PresetValidationError, match=r"\(got a URL with no scheme\)"): catalog._validate_catalog_url("example.com/catalog.json") - def test_validate_catalog_url_localhost_http_allowed(self, project_dir): - """Test that HTTP is allowed for localhost.""" + @pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) + def test_validate_catalog_url_localhost_http_rejected(self, project_dir, host): catalog = PresetCatalog(project_dir) - catalog._validate_catalog_url("http://localhost:8080/catalog.json") - catalog._validate_catalog_url("http://127.0.0.1:8080/catalog.json") + with pytest.raises(PresetValidationError, match="HTTPS"): + catalog._validate_catalog_url(f"http://{host}:8080/catalog.json") @pytest.mark.parametrize( "url", diff --git a/tests/specify_cli/test_catalog_contracts.py b/tests/specify_cli/test_catalog_contracts.py index a5cfe2490c..9eb336573e 100644 --- a/tests/specify_cli/test_catalog_contracts.py +++ b/tests/specify_cli/test_catalog_contracts.py @@ -13,14 +13,22 @@ from specify_cli.extensions import ExtensionCatalog, ValidationError from specify_cli.integrations import ( IntegrationCatalog, + IntegrationCatalogError, IntegrationValidationError, ) from specify_cli.presets import PresetCatalog, PresetValidationError from specify_cli.workflows.catalog import ( WorkflowCatalog, + WorkflowCatalogEntry, + WorkflowCatalogError, WorkflowValidationError, ) -from specify_cli.workflows.step.catalog import StepCatalog, StepValidationError +from specify_cli.workflows.step.catalog import ( + StepCatalog, + StepCatalogEntry, + StepCatalogError, + StepValidationError, +) @dataclass(frozen=True) @@ -83,6 +91,85 @@ class RemoteCatalogCase: ) +@pytest.mark.parametrize("case", REMOTE_CATALOGS, ids=lambda case: case.name) +@pytest.mark.parametrize("layer", ["project", "user", "environment"]) +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) +def test_catalog_search_rejects_loopback_http_before_network( + case: RemoteCatalogCase, + layer: str, + host: str, + tmp_path: Path, + monkeypatch: pytest.MonkeyPatch, +) -> None: + from unittest.mock import Mock + + project = tmp_path / "project" + home = tmp_path / "home" + project.mkdir() + home.mkdir() + monkeypatch.setattr(Path, "home", lambda: home) + monkeypatch.delenv(case.env_var, raising=False) + url = f"http://{host}:8080/catalog.json?channel=test" + if layer == "environment": + monkeypatch.setenv(case.env_var, url) + else: + root = project if layer == "project" else home + config_dir = root / ".specify" + config_dir.mkdir() + (config_dir / case.config_filename).write_text( + yaml.safe_dump({"catalogs": [{"name": "local", "url": url}]}), + encoding="utf-8", + ) + open_url = Mock(side_effect=AssertionError("Catalog URL reached the network")) + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + + catalog = case.catalog_type(project) + error_type = IntegrationCatalogError if case.name == "integration" else case.error_type + with pytest.raises(error_type, match="HTTPS"): + catalog.get_active_catalogs() + + with pytest.raises(error_type, match="HTTPS"): + catalog.search() + + open_url.assert_not_called() + + +@pytest.mark.parametrize("case", REMOTE_CATALOGS, ids=lambda case: case.name) +@pytest.mark.parametrize("host", ["example.com", "localhost", "127.0.0.1", "[::1]"]) +def test_catalog_https_urls_remain_allowed(case, host, tmp_path): + case.catalog_type(tmp_path)._validate_catalog_url( + f"https://{host}:8443/catalog.json" + ) + + +@pytest.mark.parametrize( + "catalog_type,entry_type,error_type", + [ + (WorkflowCatalog, WorkflowCatalogEntry, WorkflowCatalogError), + (StepCatalog, StepCatalogEntry, StepCatalogError), + ], +) +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) +def test_workflow_catalog_fetch_rejects_loopback_http_before_network( + catalog_type, entry_type, error_type, host, tmp_path, monkeypatch +): + from unittest.mock import Mock + + entry = entry_type( + url=f"http://{host}:8080/catalog.json?channel=test", + name="local", + priority=1, + install_allowed=False, + ) + open_url = Mock(side_effect=AssertionError("Catalog URL reached the network")) + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + + with pytest.raises(error_type, match="HTTPS"): + catalog_type(tmp_path)._fetch_single_catalog(entry, force_refresh=True) + + open_url.assert_not_called() + + def _write_remote_config(root: Path, filename: str, name: str) -> None: config_dir = root / ".specify" config_dir.mkdir(parents=True, exist_ok=True) diff --git a/tests/test_extensions.py b/tests/test_extensions.py index 8f370b1a64..bb7df29a1a 100644 --- a/tests/test_extensions.py +++ b/tests/test_extensions.py @@ -6946,8 +6946,8 @@ def test_load_catalog_config_missing_file(self, temp_dir): result = catalog._load_catalog_config(project_dir / ".specify" / "nonexistent.yml") assert result is None - def test_load_catalog_config_localhost_allowed(self, temp_dir): - """Localhost HTTP URLs are allowed in config.""" + def test_load_catalog_config_localhost_rejected(self, temp_dir): + """Localhost HTTP URLs are rejected before fetching.""" project_dir = self._make_project(temp_dir) self._write_catalog_config( project_dir, @@ -6962,10 +6962,8 @@ def test_load_catalog_config_localhost_allowed(self, temp_dir): ) catalog = ExtensionCatalog(project_dir) - entries = catalog.get_active_catalogs() - - assert len(entries) == 1 - assert entries[0].url == "http://localhost:8000/catalog.json" + with pytest.raises(ValidationError, match="HTTPS"): + catalog.get_active_catalogs() @pytest.mark.parametrize( "config_content", ["[]\n", "false\n", "0\n", "''\n", "- item\n"] diff --git a/tests/test_workflows.py b/tests/test_workflows.py index 04fd5903cb..57fba0a17b 100644 --- a/tests/test_workflows.py +++ b/tests/test_workflows.py @@ -10427,12 +10427,13 @@ def test_validate_url_schemeless_names_the_value(self, project_dir): with pytest.raises(error, match=r"\(got a URL with no scheme\)"): catalog._validate_catalog_url("example.com/catalog.json") - def test_validate_url_localhost_http_allowed(self, project_dir): - from specify_cli.workflows.catalog import WorkflowCatalog + @pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) + def test_validate_url_localhost_http_rejected(self, project_dir, host): + from specify_cli.workflows.catalog import WorkflowCatalog, WorkflowValidationError catalog = WorkflowCatalog(project_dir) - # Should not raise - catalog._validate_catalog_url("http://localhost:8080/catalog.json") + with pytest.raises(WorkflowValidationError, match="HTTPS"): + catalog._validate_catalog_url(f"http://{host}:8080/catalog.json") @pytest.mark.parametrize( "url", @@ -11248,12 +11249,13 @@ def test_validate_url_http_rejected(self, project_dir): with pytest.raises(StepValidationError, match="HTTPS"): catalog._validate_catalog_url("http://evil.com/step-catalog.json") - def test_validate_url_localhost_http_allowed(self, project_dir): - from specify_cli.workflows.step.catalog import StepCatalog + @pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) + def test_validate_url_localhost_http_rejected(self, project_dir, host): + from specify_cli.workflows.step.catalog import StepCatalog, StepValidationError catalog = StepCatalog(project_dir) - # Should not raise - catalog._validate_catalog_url("http://localhost:8080/step-catalog.json") + with pytest.raises(StepValidationError, match="HTTPS"): + catalog._validate_catalog_url(f"http://{host}:8080/step-catalog.json") @pytest.mark.parametrize( "url", From a5c57a1e108a2b3c848b7780224a61fb1b43ccde Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 17:54:04 -0600 Subject: [PATCH 2/7] Set explicit TLS minimum in catalog test server Require TLS 1.2 or newer in the local HTTPS fixture and verify that the minimum is set explicitly rather than inherited from runtime defaults. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- .../integrations/test_installed_adapters.py | 22 +++++++++++++++++++ 1 file changed, 22 insertions(+) diff --git a/tests/specify_cli/integrations/test_installed_adapters.py b/tests/specify_cli/integrations/test_installed_adapters.py index ebc3dc733d..5d20cd61d6 100644 --- a/tests/specify_cli/integrations/test_installed_adapters.py +++ b/tests/specify_cli/integrations/test_installed_adapters.py @@ -148,6 +148,7 @@ def log_message(self, *args): http = ThreadingHTTPServer(("127.0.0.1", 0), partial(Handler, directory=str(downloads))) cert_path, key_path = tls_certificate context = ssl.SSLContext(ssl.PROTOCOL_TLS_SERVER) + context.minimum_version = ssl.TLSVersion.TLSv1_2 context.load_cert_chain(cert_path, key_path) http.socket = context.wrap_socket(http.socket, server_side=True) monkeypatch.setenv("SSL_CERT_FILE", str(cert_path)) @@ -164,6 +165,27 @@ def log_message(self, *args): thread.join() +def test_catalog_server_explicitly_requires_tls12(request, monkeypatch): + configured = [] + minimum_version = ssl.SSLContext.minimum_version + + def set_minimum_version(context, version): + configured.append((context, version)) + minimum_version.fset(context, version) + + monkeypatch.setattr( + ssl.SSLContext, + "minimum_version", + property(minimum_version.fget, set_minimum_version), + ) + request.getfixturevalue("server") + + assert len(configured) == 1 + context, version = configured[0] + assert version == ssl.TLSVersion.TLSv1_2 + assert context.minimum_version > ssl.TLSVersion.TLSv1_1 + + def publish(server, *, metadata=None, code=None, version="1.0.0", members=None, archive="zip"): data = descriptor(version) if metadata is None else metadata source = implementation() if code is None else code From ffeed141416128be2c6ae933c0b21d24047046a4 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:04:55 -0600 Subject: [PATCH 3/7] Align catalog redirect and fetch handling Validate every integration catalog redirect, separate preset source configuration errors from recoverable fetch failures, and retain end-to-end loopback HTTP archive coverage with HTTPS catalogs. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/catalogs.md | 18 +++--- src/specify_cli/integrations/__init__.py | 7 ++- src/specify_cli/presets/_catalog.py | 14 +++-- .../specify_cli/integrations/test_catalog.py | 39 ++++++++++++ .../integrations/test_installed_adapters.py | 36 +++++++++++ tests/specify_cli/presets/test_catalog.py | 62 +++++++++++++++++++ 6 files changed, 162 insertions(+), 14 deletions(-) diff --git a/design/catalogs.md b/design/catalogs.md index 61adf557da..e47291bb58 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -175,12 +175,11 @@ Current behavior differs by primitive: - Extensions and presets use one-hour per-URL caches, retain legacy cache names for the official source, validate every redirect hop, validate cached payload shape, and treat cache read/write failures as best-effort. -- Integrations use one-hour per-URL caches. The shared HTTP redirect handler - applies its strict scheme, host, and remote-to-local policy on every hop; - integrations do not add their catalog-specific URL validator per hop, but do - 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. +- Integrations use one-hour per-URL caches and apply their catalog-specific URL + validator on every redirect hop and to a changed terminal URL. The shared HTTP + 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 @@ -231,9 +230,10 @@ usable. Validation errors are not uniformly recoverable: an `IntegrationCatalogError`, so the merge warns, skips that source, and can expose a lower-precedence copy. - Preset lookup preserves the first fetch error when no source is readable; - preset search currently converts ordinary fetch failures to an empty result. - Invalid source configuration (`PresetValidationError`) is fatal in search, - including rejected HTTP catalog URLs. + preset search converts recoverable fetch failures, including rejected + redirects, to an empty result when no source is readable, regardless of source + order. Invalid source configuration (`PresetValidationError`) is fatal in + search and is validated before fetching, including rejected HTTP catalog URLs. `PresetCatalogValidationError` remains fatal: search can fail on invalid lower-precedence content even after reading a valid higher source, while a targeted lookup can return as soon as it finds the requested higher entry. diff --git a/src/specify_cli/integrations/__init__.py b/src/specify_cli/integrations/__init__.py index bc7595332d..e38d471387 100644 --- a/src/specify_cli/integrations/__init__.py +++ b/src/specify_cli/integrations/__init__.py @@ -357,7 +357,12 @@ def _fetch_single_catalog( try: from specify_cli.authentication.http import open_url - with open_url(entry.url, timeout=10) as resp: + def _validate_redirect(_old_url: str, new_url: str) -> None: + self._validate_catalog_url(new_url) + + with open_url( + entry.url, timeout=10, redirect_validator=_validate_redirect + ) as resp: # Validate final URL after redirects final_url = resp.geturl() if final_url != entry.url: diff --git a/src/specify_cli/presets/_catalog.py b/src/specify_cli/presets/_catalog.py index e3cea50657..beff554a05 100644 --- a/src/specify_cli/presets/_catalog.py +++ b/src/specify_cli/presets/_catalog.py @@ -551,7 +551,11 @@ def _validate_redirect(_old_url: str, new_url: str) -> None: ) def _get_merged_packs( - self, force_refresh: bool = False, *, pack_id: str | None = None + self, + force_refresh: bool = False, + *, + pack_id: str | None = None, + active_catalogs: List[PresetCatalogEntry] | None = None, ) -> Dict[str, Dict[str, Any]]: """Fetch and merge presets from all active catalogs. @@ -562,7 +566,8 @@ def _get_merged_packs( Returns: Merged dictionary of pack_id -> pack_data """ - active_catalogs = self.get_active_catalogs() + if active_catalogs is None: + active_catalogs = self.get_active_catalogs() merged: Dict[str, Dict[str, Any]] = {} first_fetch_error: PresetError | None = None readable_source = False @@ -761,9 +766,10 @@ def search( Returns: List of matching preset metadata """ + active_catalogs = self.get_active_catalogs() try: - packs = self._get_merged_packs() - except (PresetCatalogValidationError, PresetValidationError): + packs = self._get_merged_packs(active_catalogs=active_catalogs) + except PresetCatalogValidationError: raise except PresetError: return [] diff --git a/tests/specify_cli/integrations/test_catalog.py b/tests/specify_cli/integrations/test_catalog.py index 4878716f05..e828d61b48 100644 --- a/tests/specify_cli/integrations/test_catalog.py +++ b/tests/specify_cli/integrations/test_catalog.py @@ -1,5 +1,6 @@ """Tests for the integration package's catalog domain API.""" +import io import json import pytest @@ -398,6 +399,44 @@ def fake_urlopen(req, timeout=10): with pytest.raises(IntegrationCatalogError, match="exceeds maximum size"): cat._fetch_single_catalog(entry, force_refresh=True) + @pytest.mark.parametrize("scheme", ["https", "http"]) + @pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) + def test_fetch_validates_catalog_redirects_before_each_request( + self, tmp_path, monkeypatch, scheme, host + ): + start_url = f"https://{host}:8443/catalog.json" + intermediate_url = f"{scheme}://{host}:8080/intermediate.json" + final_url = f"https://{host}:8443/final.json" + requested = [] + payload = {"schema_version": "1.0", "integrations": {}} + + class Response(io.BytesIO): + def geturl(self): + return final_url + + def open_url(url, timeout=10, redirect_validator=None): + requested.append(url) + for old_url, new_url in ( + (url, intermediate_url), + (intermediate_url, final_url), + ): + if redirect_validator is not None: + redirect_validator(old_url, new_url) + requested.append(new_url) + return Response(json.dumps(payload).encode()) + + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + catalog = IntegrationCatalog(tmp_path) + entry = IntegrationCatalogEntry(start_url, "test", 1, False) + + if scheme == "http": + with pytest.raises(IntegrationCatalogError, match="HTTPS"): + catalog._fetch_single_catalog(entry, force_refresh=True) + assert requested == [start_url] + else: + assert catalog._fetch_single_catalog(entry, force_refresh=True) == payload + assert requested == [start_url, intermediate_url, final_url] + def _patch_urlopen_bytes(self, monkeypatch, bodies): """Patch urlopen to serve raw *bodies* keyed by URL substring. diff --git a/tests/specify_cli/integrations/test_installed_adapters.py b/tests/specify_cli/integrations/test_installed_adapters.py index 5d20cd61d6..1b097d7eb2 100644 --- a/tests/specify_cli/integrations/test_installed_adapters.py +++ b/tests/specify_cli/integrations/test_installed_adapters.py @@ -1368,6 +1368,42 @@ def test_catalog_install_renders_host_templates_and_fresh_process(tmp_path, serv assert json.loads(status.output)["default_integration"] == KEY +def test_https_catalog_installs_loopback_http_archive(tmp_path, server): + requested = [] + + class Handler(SimpleHTTPRequestHandler): + def do_GET(self): + requested.append(self.path) + super().do_GET() + + def log_message(self, *args): + pass + + http = ThreadingHTTPServer( + ("127.0.0.1", 0), partial(Handler, directory=str(server.root)) + ) + thread = threading.Thread( + target=http.serve_forever, kwargs={"poll_interval": 0.01}, daemon=True + ) + thread.start() + try: + info, archive = publish(server) + info["download_url"] = f"http://127.0.0.1:{http.server_port}/{archive.name}" + write_catalog(server, info) + project = catalog_project(tmp_path, server) + + install(project) + + assert read_records(project)[KEY]["version"] == "1.0.0" + assert "/catalog.json" in server.requests + assert requested == [f"/{archive.name}"] + assert f"/{archive.name}" not in server.requests + finally: + http.shutdown() + http.server_close() + thread.join() + + def test_markdown_adapter_renders_host_commands(tmp_path, server): publish(server, code=implementation(flavor="markdown")) project = catalog_project(tmp_path, server) diff --git a/tests/specify_cli/presets/test_catalog.py b/tests/specify_cli/presets/test_catalog.py index 7fcc38713f..ea6b2a26ba 100644 --- a/tests/specify_cli/presets/test_catalog.py +++ b/tests/specify_cli/presets/test_catalog.py @@ -428,6 +428,68 @@ def fake_open(url, timeout=None, redirect_validator=None): catalog._fetch_single_catalog(entry, force_refresh=True) assert captured["rv"] is not None + @pytest.mark.parametrize("reverse_sources", [False, True]) + @pytest.mark.parametrize( + "source_kinds", + [ + ("unavailable", "unavailable"), + ("redirect", "redirect"), + ("unavailable", "redirect"), + ("unavailable", "healthy"), + ("redirect", "healthy"), + ], + ) + def test_search_fetch_failures_are_independent_of_source_order( + self, project_dir, monkeypatch, source_kinds, reverse_sources + ): + catalog = PresetCatalog(project_dir) + entries = [ + PresetCatalogEntry( + f"https://example.com/{index}.json", str(index), index, False + ) + for index in range(len(source_kinds)) + ] + kinds_by_url = { + entry.url: kind for entry, kind in zip(entries, source_kinds) + } + if reverse_sources: + entries.reverse() + active_catalogs = MagicMock(return_value=entries) + monkeypatch.setattr(catalog, "get_active_catalogs", active_catalogs) + requested = [] + payload = { + "schema_version": "1.0", + "presets": {"sample": {"name": "Sample", "version": "1.0.0"}}, + } + + class Response(io.BytesIO): + def __init__(self, url): + super().__init__(json.dumps(payload).encode()) + self.url = url + + def geturl(self): + return self.url + + def open_url(url, timeout=10, redirect_validator=None): + requested.append(url) + kind = kinds_by_url[url] + if kind == "unavailable": + raise OSError("catalog unavailable") + if kind == "redirect": + redirect_validator(url, "http://localhost:8080/catalog.json") + raise AssertionError("HTTP redirect should have been rejected") + return Response(url) + + monkeypatch.setattr(catalog, "_open_url", open_url) + + results = catalog.search() + + assert [result["id"] for result in results] == ( + ["sample"] if "healthy" in source_kinds else [] + ) + assert set(requested) == set(kinds_by_url) + active_catalogs.assert_called_once_with() + def test_fetch_catalog_legacy_revalidates_redirected_url(self, project_dir): """The legacy single-catalog fetch_catalog() path also rejects an HTTPS -> http redirected payload (final geturl() check), matching From 7641e0d8723560a6b3571fe967511144ad5141e1 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Mon, 9 Nov 2026 18:13:32 -0600 Subject: [PATCH 4/7] Document catalog migration and cover preset search errors Explain manual migration of legacy HTTP workflow and step catalog entries in project, user, and environment configuration. Cover fatal HTTP configuration and nonfatal fetch failures through the preset search CLI. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- docs/workflow-steps/catalogs.md | 16 ++++ docs/workflows/catalogs.md | 16 ++++ .../presets/test_command_search.py | 75 +++++++++++++++++++ 3 files changed, 107 insertions(+) diff --git a/docs/workflow-steps/catalogs.md b/docs/workflow-steps/catalogs.md index 54acb43f89..e3e258b89a 100644 --- a/docs/workflow-steps/catalogs.md +++ b/docs/workflow-steps/catalogs.md @@ -50,6 +50,22 @@ allowed and a priority after existing entries. It does not expose preset-style configuration when a discovery-only source is intended. Adding a project stack replaces implicit defaults unless you include them explicitly. +### Migrating legacy HTTP sources + +Older configurations may contain loopback HTTP URLs that are no longer accepted. +`specify workflow step catalog remove` validates the project configuration before +deleting an entry, so it cannot remove an invalid HTTP source. Instead, edit +`.specify/step-catalogs.yml` for project sources or +`~/.specify/step-catalogs.yml` for user sources. Replace the source's `url` with +a working HTTPS catalog URL, or remove its entire item from `catalogs`. +Local HTTPS servers need a trusted certificate; changing the URL scheme alone +does not enable HTTPS. + +If no custom sources remain in a file, delete that configuration file to fall +through to the next level. Built-in defaults apply when no higher level supplies +a stack. Also update or unset `SPECKIT_STEP_CATALOG_URL` if it still selects +an HTTP source. + ## Step entry schema Catalog JSON contains `schema_version` and a `steps` collection. Entries identify diff --git a/docs/workflows/catalogs.md b/docs/workflows/catalogs.md index b62652ea25..c9ce6b636f 100644 --- a/docs/workflows/catalogs.md +++ b/docs/workflows/catalogs.md @@ -43,6 +43,22 @@ before network access. Lower numeric priorities win; the first source wins ties. `specify workflow catalog add` creates project entries with installation allowed and a priority after existing entries. It does not expose preset-style `--install-allowed` or `--priority` flags. Add only vetted sources; edit the configuration when a discovery-only source is intended. Adding a project stack replaces implicit defaults unless you include them explicitly. +### Migrating legacy HTTP sources + +Older configurations may contain loopback HTTP URLs that are no longer accepted. +`specify workflow catalog remove` validates the project configuration before +deleting an entry, so it cannot remove an invalid HTTP source. Instead, edit +`.specify/workflow-catalogs.yml` for project sources or +`~/.specify/workflow-catalogs.yml` for user sources. Replace the source's `url` +with a working HTTPS catalog URL, or remove its entire item from `catalogs`. +Local HTTPS servers need a trusted certificate; changing the URL scheme alone +does not enable HTTPS. + +If no custom sources remain in a file, delete that configuration file to fall +through to the next level. Built-in defaults apply when no higher level supplies +a stack. Also update or unset `SPECKIT_WORKFLOW_CATALOG_URL` if it still selects +an HTTP source. + ## Workflow entry schema Catalog JSON contains `schema_version` and a `workflows` mapping keyed by workflow ID. Entries carry `id`, `name`, `description`, `author`, `version`, `url`, and optional `sha256`, `requires`, `repository`, `license`, `tags`, and timestamps. A download can be raw YAML or a complete workflow archive. First-party entries marked `bundled: true` use packaged definitions rather than a network download. diff --git a/tests/specify_cli/presets/test_command_search.py b/tests/specify_cli/presets/test_command_search.py index 91e2447619..cf397d0b3b 100644 --- a/tests/specify_cli/presets/test_command_search.py +++ b/tests/specify_cli/presets/test_command_search.py @@ -3,6 +3,9 @@ from pathlib import Path from typing import ClassVar +import pytest +import yaml + from specify_cli.presets import PresetCatalog from tests.conftest import strip_ansi from tests.specify_cli.presets._helpers import ( @@ -11,6 +14,78 @@ ) +class TestPresetSearchCatalogFailures: + @pytest.mark.parametrize("layer", ["project", "user", "environment"]) + @pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) + def test_invalid_http_catalog_reports_error( + self, project_dir, tmp_path, monkeypatch, layer, host + ): + from unittest.mock import Mock + + from typer.testing import CliRunner + + from specify_cli import app + + home = tmp_path / "home" + home.mkdir() + monkeypatch.setattr(Path, "cwd", lambda: project_dir) + monkeypatch.setattr(Path, "home", lambda: home) + monkeypatch.delenv("SPECKIT_PRESET_CATALOG_URL", raising=False) + url = f"http://{host}:8080/catalog.json" + if layer == "environment": + monkeypatch.setenv("SPECKIT_PRESET_CATALOG_URL", url) + else: + root = project_dir if layer == "project" else home + config_dir = root / ".specify" + config_dir.mkdir(exist_ok=True) + (config_dir / "preset-catalogs.yml").write_text( + yaml.safe_dump({"catalogs": [{"name": "local", "url": url}]}), + encoding="utf-8", + ) + open_url = Mock(side_effect=AssertionError("Unexpected network request")) + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + + result = CliRunner().invoke(app, ["preset", "search"]) + + assert result.exit_code == 1, result.output + output = " ".join(strip_ansi(result.output).split()) + assert "must use HTTPS" in output + assert "No presets found" not in output + open_url.assert_not_called() + + def test_recoverable_fetch_failure_reports_no_results( + self, project_dir, monkeypatch + ): + from unittest.mock import Mock + + from typer.testing import CliRunner + + from specify_cli import app + from specify_cli.presets import PresetError + + monkeypatch.setattr(Path, "cwd", lambda: project_dir) + monkeypatch.delenv("SPECKIT_PRESET_CATALOG_URL", raising=False) + (project_dir / ".specify" / "preset-catalogs.yml").write_text( + yaml.safe_dump({ + "catalogs": [{ + "name": "unavailable", + "url": "https://example.com/catalog.json", + }], + }), + encoding="utf-8", + ) + fetch = Mock(side_effect=PresetError("catalog unavailable")) + monkeypatch.setattr(PresetCatalog, "_fetch_single_catalog", fetch) + + result = CliRunner().invoke(app, ["preset", "search"]) + + assert result.exit_code == 0, result.output + output = strip_ansi(result.output) + assert "No presets found" in output + assert "Error:" not in output + fetch.assert_called_once() + + class TestPresetTagsNonString: """Non-string catalog tags must not crash preset display commands. From ca58b22e541d2239d9f64e8fc7bc1733358d7e63 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 07:47:07 -0600 Subject: [PATCH 5/7] Strengthen catalog redirect tests and URL guidance Fail preset search tests immediately if an HTTP redirect is unexpectedly accepted, and recommend HTTPS rather than HTTP in bundle catalog source guidance. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- src/specify_cli/bundles/catalog_config.py | 2 +- tests/specify_cli/bundles/test_catalog_config.py | 5 ++++- tests/specify_cli/presets/test_catalog.py | 2 +- 3 files changed, 6 insertions(+), 3 deletions(-) diff --git a/src/specify_cli/bundles/catalog_config.py b/src/specify_cli/bundles/catalog_config.py index a28a35b2c2..536c22dfa0 100644 --- a/src/specify_cli/bundles/catalog_config.py +++ b/src/specify_cli/bundles/catalog_config.py @@ -167,7 +167,7 @@ def add_source( if "://" in url and parsed.scheme.lower() not in _REMOTE_SCHEMES: raise BundlerError( f"Unsupported catalog url scheme '{parsed.scheme}://' in '{url}'. " - "Use http(s)://, file://, builtin://, or a local path." + "Use https://, file://, builtin://, or a local path." ) if parsed.scheme.lower() in {"http", "https"}: # Mirror specify_cli.catalogs._validate_catalog_url (#3209/#3210): diff --git a/tests/specify_cli/bundles/test_catalog_config.py b/tests/specify_cli/bundles/test_catalog_config.py index 063950106b..a5e5107d01 100644 --- a/tests/specify_cli/bundles/test_catalog_config.py +++ b/tests/specify_cli/bundles/test_catalog_config.py @@ -402,7 +402,10 @@ def test_derive_id_ignores_credentials_and_port(): def test_add_source_rejects_unsupported_scheme(tmp_path: Path): project = tmp_path / "proj" (project / ".specify").mkdir(parents=True) - with pytest.raises(BundlerError, match="Unsupported catalog url scheme"): + with pytest.raises( + BundlerError, + match=r"Use https://, file://, builtin://, or a local path\.", + ): cc.add_source(project, "ssh://host/catalog.json", policy="install-allowed", priority=50) diff --git a/tests/specify_cli/presets/test_catalog.py b/tests/specify_cli/presets/test_catalog.py index ea6b2a26ba..8fe393effe 100644 --- a/tests/specify_cli/presets/test_catalog.py +++ b/tests/specify_cli/presets/test_catalog.py @@ -477,7 +477,7 @@ def open_url(url, timeout=10, redirect_validator=None): raise OSError("catalog unavailable") if kind == "redirect": redirect_validator(url, "http://localhost:8080/catalog.json") - raise AssertionError("HTTP redirect should have been rejected") + pytest.fail("HTTP redirect should have been rejected") return Response(url) monkeypatch.setattr(catalog, "_open_url", open_url) From 1178e30a3ed913941a90193b73f0b992af2ba3ae Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 08:23:48 -0600 Subject: [PATCH 6/7] Clarify Python certificate trust for local catalogs Distinguish Python TLS trust from browser and operating-system trust, document SSL_CERT_FILE CA-bundle configuration, and link local catalog guidance to the shared instructions. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/catalogs.md | 5 ++++- docs/extensions/catalogs.md | 9 ++++++--- docs/reference/authentication.md | 20 ++++++++++++++++++++ docs/workflow-steps/catalogs.md | 6 ++++-- docs/workflows/catalogs.md | 6 ++++-- 5 files changed, 38 insertions(+), 8 deletions(-) diff --git a/design/catalogs.md b/design/catalogs.md index e47291bb58..bcfadc92c7 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -113,7 +113,10 @@ All six types reject plain HTTP catalog sources, including localhost and loopback addresses, before network access. This intentionally removes the former local-development HTTP exception so every source layer follows the same HTTPS policy. Local HTTPS development servers need a certificate trusted -by the system. Archive download policies are separate and unchanged. +by Python's TLS client using its default OpenSSL trust configuration, which may +differ from browser or operating-system trust. `SSL_CERT_FILE` can select a PEM +CA bundle containing the development CA. Archive download policies are separate +and unchanged. ## Configuration semantics diff --git a/docs/extensions/catalogs.md b/docs/extensions/catalogs.md index f5f90c81b7..083c11631b 100644 --- a/docs/extensions/catalogs.md +++ b/docs/extensions/catalogs.md @@ -179,7 +179,7 @@ Create a `catalog.json` file containing the releases your team has vetted: | GitHub Pages | `https://your-org.github.io/spec-kit-catalog/catalog.json` | Public or org-visible | | Internal web server | `https://internal.company.com/spec-kit/catalog.json` | Corporate network | | S3/cloud storage | `https://s3.amazonaws.com/your-bucket/catalog.json` | Cloud-hosted teams | -| Local HTTPS server | `https://localhost:8443/catalog.json` | Development/testing with a trusted certificate | +| Local HTTPS server | `https://localhost:8443/catalog.json` | Development/testing with a certificate trusted by Python | Catalog URLs must use HTTPS, including localhost. Plain HTTP catalogs are rejected before network access. @@ -237,10 +237,13 @@ inside the network. For example, an entry can use ### Development and testing -Serve `./my-catalog/` through an HTTPS server with a certificate trusted by your -system, then point the CLI at it: +Serve `./my-catalog/` through an HTTPS server with a certificate trusted by +Python's TLS client, not just your browser or operating system. For a development +CA, point `SSL_CERT_FILE` at a PEM CA bundle containing that CA before running +the CLI (see [TLS certificates](../reference/authentication.md#tls-certificates)): ```bash +export SSL_CERT_FILE="/absolute/path/to/ca-bundle.pem" export SPECKIT_CATALOG_URL="https://localhost:8443/catalog.json" specify extension add my-new-extension ``` diff --git a/docs/reference/authentication.md b/docs/reference/authentication.md index f7f2e02749..794d10e693 100644 --- a/docs/reference/authentication.md +++ b/docs/reference/authentication.md @@ -343,6 +343,26 @@ You can configure multiple entries for different hosts or organizations: target leaves the entry's declared hosts — preventing credential leakage to CDNs or third-party services. +## TLS certificates + +HTTPS catalog requests use Python's `urllib` and `ssl` certificate verification. +The trusted certificate authorities depend on the Python distribution and its +OpenSSL configuration. Trusting a development CA in a browser or macOS Keychain +alone does not necessarily make it trusted by the Python interpreter running +Specify. + +For a private or local development CA, set `SSL_CERT_FILE` to the absolute path +of a PEM CA bundle containing that CA before running Specify: + +```bash +export SSL_CERT_FILE="/absolute/path/to/ca-bundle.pem" +``` + +This selects a CA file rather than appending to Python's default CA file. Keep +any other required trust roots in the bundle, including those needed for public +catalogs and downloads. The server certificate must still be valid for the +requested hostname or IP address. Keep certificate verification enabled. + ## Template A reference `auth.json` with GitHub pre-configured: diff --git a/docs/workflow-steps/catalogs.md b/docs/workflow-steps/catalogs.md index e3e258b89a..2fcaa93390 100644 --- a/docs/workflow-steps/catalogs.md +++ b/docs/workflow-steps/catalogs.md @@ -58,8 +58,10 @@ deleting an entry, so it cannot remove an invalid HTTP source. Instead, edit `.specify/step-catalogs.yml` for project sources or `~/.specify/step-catalogs.yml` for user sources. Replace the source's `url` with a working HTTPS catalog URL, or remove its entire item from `catalogs`. -Local HTTPS servers need a trusted certificate; changing the URL scheme alone -does not enable HTTPS. +Local HTTPS servers need a certificate trusted by Python's TLS client; browser +or operating-system trust alone may not suffice. See +[TLS certificates](../reference/authentication.md#tls-certificates) for +`SSL_CERT_FILE` configuration. Changing the URL scheme alone does not enable HTTPS. If no custom sources remain in a file, delete that configuration file to fall through to the next level. Built-in defaults apply when no higher level supplies diff --git a/docs/workflows/catalogs.md b/docs/workflows/catalogs.md index c9ce6b636f..46168ccd12 100644 --- a/docs/workflows/catalogs.md +++ b/docs/workflows/catalogs.md @@ -51,8 +51,10 @@ deleting an entry, so it cannot remove an invalid HTTP source. Instead, edit `.specify/workflow-catalogs.yml` for project sources or `~/.specify/workflow-catalogs.yml` for user sources. Replace the source's `url` with a working HTTPS catalog URL, or remove its entire item from `catalogs`. -Local HTTPS servers need a trusted certificate; changing the URL scheme alone -does not enable HTTPS. +Local HTTPS servers need a certificate trusted by Python's TLS client; browser +or operating-system trust alone may not suffice. See +[TLS certificates](../reference/authentication.md#tls-certificates) for +`SSL_CERT_FILE` configuration. Changing the URL scheme alone does not enable HTTPS. If no custom sources remain in a file, delete that configuration file to fall through to the next level. Built-in defaults apply when no higher level supplies From 3b5684f0cf6b2144b74c5dd911852e8156910010 Mon Sep 17 00:00:00 2001 From: Manfred Riem <15701806+mnriem@users.noreply.github.com> Date: Tue, 10 Nov 2026 09:26:08 -0600 Subject: [PATCH 7/7] Allow cleanup of legacy workflow catalog sources Skip URL validation only for local workflow and step catalog removal while preserving priority ordering, configuration validation, and HTTPS requirements for discovery and fetching. Update migration guidance and cover legacy entries and invalid indexes through the CLI. Assisted-by: GitHub Copilot (model: GPT-6.1 Sol, autonomous) Co-authored-by: Copilot App <223556219+Copilot@users.noreply.github.com> --- design/catalogs.md | 5 ++ docs/workflow-steps/catalogs.md | 18 +++-- docs/workflows/catalogs.md | 18 +++-- src/specify_cli/workflows/catalog/_domain.py | 9 ++- .../workflows/step/catalog/_domain.py | 9 ++- .../workflows/catalog/test_command_remove.py | 64 +++++++++++++++++- .../step/catalog/test_command_remove.py | 66 ++++++++++++++++++- 7 files changed, 167 insertions(+), 22 deletions(-) diff --git a/design/catalogs.md b/design/catalogs.md index bcfadc92c7..70e397daaa 100644 --- a/design/catalogs.md +++ b/design/catalogs.md @@ -132,6 +132,11 @@ phase and accepted values otherwise differ: while `remove_source()` intentionally filters raw mappings by ID or URL without validating their other fields. This lets users remove a hand-edited invalid source instead of being trapped by the invalid entry. +- Workflow and workflow-step catalog removal retains configuration-shape and + priority validation, but skips URL validation. Removal never fetches a source, + so legacy HTTP entries do not prevent removing either that source or an + unrelated HTTPS entry. Discovery and fetching still require HTTPS. Removal + retains priority order, with YAML declaration order breaking ties. - All readers reject boolean priorities. Replacement-layer loaders otherwise call `int(value)`, so a fractional numeric value such as `1.9` is truncated to `1`. Bundle `CatalogSource` materialization rejects booleans and floats diff --git a/docs/workflow-steps/catalogs.md b/docs/workflow-steps/catalogs.md index 2fcaa93390..e538c63b41 100644 --- a/docs/workflow-steps/catalogs.md +++ b/docs/workflow-steps/catalogs.md @@ -53,9 +53,14 @@ replaces implicit defaults unless you include them explicitly. ### Migrating legacy HTTP sources Older configurations may contain loopback HTTP URLs that are no longer accepted. -`specify workflow step catalog remove` validates the project configuration before -deleting an entry, so it cannot remove an invalid HTTP source. Instead, edit -`.specify/step-catalogs.yml` for project sources or +Remove a legacy project source with `specify workflow step catalog remove `; +removal does not fetch or validate source URLs. Indexes follow ascending +priority, with YAML declaration order breaking ties; entries without a URL are +skipped. `step catalog list` still rejects invalid URLs, so inspect +`.specify/step-catalogs.yml` to determine the index when it cannot list them. +Other entries can also be removed while a legacy HTTP source remains. + +Alternatively, edit `.specify/step-catalogs.yml` for project sources or `~/.specify/step-catalogs.yml` for user sources. Replace the source's `url` with a working HTTPS catalog URL, or remove its entire item from `catalogs`. Local HTTPS servers need a certificate trusted by Python's TLS client; browser @@ -63,10 +68,9 @@ or operating-system trust alone may not suffice. See [TLS certificates](../reference/authentication.md#tls-certificates) for `SSL_CERT_FILE` configuration. Changing the URL scheme alone does not enable HTTPS. -If no custom sources remain in a file, delete that configuration file to fall -through to the next level. Built-in defaults apply when no higher level supplies -a stack. Also update or unset `SPECKIT_STEP_CATALOG_URL` if it still selects -an HTTP source. +An empty or deleted configuration falls through to the next level. Built-in +defaults apply when no higher level supplies a stack. Also update or unset +`SPECKIT_STEP_CATALOG_URL` if it still selects an HTTP source. ## Step entry schema diff --git a/docs/workflows/catalogs.md b/docs/workflows/catalogs.md index 46168ccd12..d03f9f3ce0 100644 --- a/docs/workflows/catalogs.md +++ b/docs/workflows/catalogs.md @@ -46,9 +46,14 @@ before network access. Lower numeric priorities win; the first source wins ties. ### Migrating legacy HTTP sources Older configurations may contain loopback HTTP URLs that are no longer accepted. -`specify workflow catalog remove` validates the project configuration before -deleting an entry, so it cannot remove an invalid HTTP source. Instead, edit -`.specify/workflow-catalogs.yml` for project sources or +Remove a legacy project source with `specify workflow catalog remove `; +removal does not fetch or validate source URLs. Indexes follow ascending +priority, with YAML declaration order breaking ties; entries without a URL are +skipped. `catalog list` still rejects invalid URLs, so inspect +`.specify/workflow-catalogs.yml` to determine the index when it cannot list them. +Other entries can also be removed while a legacy HTTP source remains. + +Alternatively, edit `.specify/workflow-catalogs.yml` for project sources or `~/.specify/workflow-catalogs.yml` for user sources. Replace the source's `url` with a working HTTPS catalog URL, or remove its entire item from `catalogs`. Local HTTPS servers need a certificate trusted by Python's TLS client; browser @@ -56,10 +61,9 @@ or operating-system trust alone may not suffice. See [TLS certificates](../reference/authentication.md#tls-certificates) for `SSL_CERT_FILE` configuration. Changing the URL scheme alone does not enable HTTPS. -If no custom sources remain in a file, delete that configuration file to fall -through to the next level. Built-in defaults apply when no higher level supplies -a stack. Also update or unset `SPECKIT_WORKFLOW_CATALOG_URL` if it still selects -an HTTP source. +An empty or deleted configuration falls through to the next level. Built-in +defaults apply when no higher level supplies a stack. Also update or unset +`SPECKIT_WORKFLOW_CATALOG_URL` if it still selects an HTTP source. ## Workflow entry schema diff --git a/src/specify_cli/workflows/catalog/_domain.py b/src/specify_cli/workflows/catalog/_domain.py index c6b8b0cabd..415ee52542 100644 --- a/src/specify_cli/workflows/catalog/_domain.py +++ b/src/specify_cli/workflows/catalog/_domain.py @@ -376,7 +376,7 @@ def _load_catalog_config( return [entry for _, entry in indexed_entries] def _parse_catalog_config( - self, data: Any, config_path: Path + self, data: Any, config_path: Path, *, validate_urls: bool = True ) -> list[tuple[int, WorkflowCatalogEntry]] | None: """Validate and order sources, retaining their original YAML positions.""" # An empty document (or explicit ``null``) parses to None -> this config @@ -424,7 +424,8 @@ def _parse_catalog_config( url = str(item.get("url", "")).strip() if not url: continue - self._validate_catalog_url(url) + if validate_urls: + self._validate_catalog_url(url) raw_priority = item.get("priority", idx + 1) # bool is an int subclass: int(True) == 1 would silently accept a # ``priority: true`` as priority 1. Reject it explicitly, mirroring @@ -861,7 +862,9 @@ def remove_catalog(self, index: int) -> str: raise WorkflowValidationError( f"Catalog config file is unreadable or malformed: {exc}" ) from exc - entries = self._parse_catalog_config(data, config_path) or [] + entries = self._parse_catalog_config( + data, config_path, validate_urls=False + ) or [] if index < 0 or index >= len(entries): raise WorkflowValidationError( diff --git a/src/specify_cli/workflows/step/catalog/_domain.py b/src/specify_cli/workflows/step/catalog/_domain.py index a533286322..655adc5042 100644 --- a/src/specify_cli/workflows/step/catalog/_domain.py +++ b/src/specify_cli/workflows/step/catalog/_domain.py @@ -324,7 +324,7 @@ def _load_catalog_config( return [entry for _, entry in indexed_entries] def _parse_catalog_config( - self, data: Any, config_path: Path + self, data: Any, config_path: Path, *, validate_urls: bool = True ) -> list[tuple[int, StepCatalogEntry]] | None: """Validate and order sources, retaining their original YAML positions.""" # Same two guards as WorkflowCatalog._load_catalog_config above, kept in @@ -360,7 +360,8 @@ def _parse_catalog_config( url = str(item.get("url", "")).strip() if not url: continue - self._validate_catalog_url(url) + if validate_urls: + self._validate_catalog_url(url) raw_priority = item.get("priority", idx + 1) # bool is an int subclass: reject ``priority: true`` explicitly rather # than silently coercing it to 1 (mirrors CatalogStackBase). @@ -785,7 +786,9 @@ def remove_catalog(self, index: int) -> str: raise StepValidationError( f"Catalog config file is unreadable or malformed: {exc}" ) from exc - entries = self._parse_catalog_config(data, config_path) or [] + entries = self._parse_catalog_config( + data, config_path, validate_urls=False + ) or [] if index < 0 or index >= len(entries): raise StepValidationError( diff --git a/tests/specify_cli/workflows/catalog/test_command_remove.py b/tests/specify_cli/workflows/catalog/test_command_remove.py index bff564cda2..2b01d78830 100644 --- a/tests/specify_cli/workflows/catalog/test_command_remove.py +++ b/tests/specify_cli/workflows/catalog/test_command_remove.py @@ -1,10 +1,13 @@ """Tests for ``specify workflow catalog remove``.""" +from unittest.mock import Mock + +import pytest from typer.testing import CliRunner import yaml from specify_cli import app -from specify_cli.workflows.catalog import WorkflowCatalog +from specify_cli.workflows.catalog import WorkflowCatalog, WorkflowValidationError def test_workflow_catalog_remove_deletes_selected_source(project_dir, monkeypatch): @@ -62,3 +65,62 @@ def test_workflow_catalog_remove_refuses_environment_source(project_dir, monkeyp assert "SPECKIT_WORKFLOW_CATALOG_URL" in result.output assert "Unset" in result.output assert config.read_bytes() == before + + +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) +@pytest.mark.parametrize("index,original_index", [(0, 1), (1, 0)]) +def test_workflow_catalog_remove_with_legacy_http_source( + project_dir, monkeypatch, host, index, original_index +): + monkeypatch.delenv("SPECKIT_WORKFLOW_CATALOG_URL", raising=False) + config = project_dir / ".specify" / "workflow-catalogs.yml" + data = {"notes": "keep", "catalogs": [ + {"name": "legacy", "url": f"http://{host}:8080/catalog.json", "priority": 10}, + {"name": "team", "url": "https://example.com/team.json", "priority": 1}, + ]} + config.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8") + catalog = WorkflowCatalog(project_dir) + with pytest.raises(WorkflowValidationError, match="HTTPS"): + catalog.get_active_catalogs() + open_url = Mock(side_effect=AssertionError("Removal must not fetch catalogs")) + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + + with monkeypatch.context() as context: + context.chdir(project_dir) + result = CliRunner().invoke(app, ["workflow", "catalog", "remove", str(index)]) + + assert result.exit_code == 0, result.output + removed = data["catalogs"].pop(original_index) + assert f"'{removed['name']}' removed" in result.output + assert yaml.safe_load(config.read_text(encoding="utf-8")) == data + if removed["name"] == "legacy": + assert [entry.name for entry in catalog.get_active_catalogs()] == ["team"] + else: + with pytest.raises(WorkflowValidationError, match="HTTPS"): + catalog.get_active_catalogs() + open_url.assert_not_called() + + +@pytest.mark.parametrize("index", [-1, 2]) +def test_workflow_catalog_remove_legacy_http_bounds_preserve_config( + project_dir, monkeypatch, index +): + monkeypatch.delenv("SPECKIT_WORKFLOW_CATALOG_URL", raising=False) + config = project_dir / ".specify" / "workflow-catalogs.yml" + config.write_text( + "# preserve\ncatalogs:\n - name: legacy\n" + " url: http://localhost:8080/catalog.json\n" + " - name: team\n url: https://example.com/team.json\n", + encoding="utf-8", + ) + before = config.read_bytes() + + with monkeypatch.context() as context: + context.chdir(project_dir) + result = CliRunner().invoke( + app, ["workflow", "catalog", "remove", "--", str(index)] + ) + + assert result.exit_code == 1, result.output + assert "out of range" in result.output + assert config.read_bytes() == before diff --git a/tests/specify_cli/workflows/step/catalog/test_command_remove.py b/tests/specify_cli/workflows/step/catalog/test_command_remove.py index d2dd50b6bc..645fb4e8de 100644 --- a/tests/specify_cli/workflows/step/catalog/test_command_remove.py +++ b/tests/specify_cli/workflows/step/catalog/test_command_remove.py @@ -1,10 +1,13 @@ """Tests for ``specify workflow step catalog remove``.""" +from unittest.mock import Mock + +import pytest from typer.testing import CliRunner import yaml from specify_cli import app -from specify_cli.workflows.step.catalog import StepCatalog +from specify_cli.workflows.step.catalog import StepCatalog, StepValidationError def test_workflow_step_catalog_remove_deletes_selected_source( @@ -66,3 +69,64 @@ def test_workflow_step_catalog_remove_refuses_environment_source(project_dir, mo assert "SPECKIT_STEP_CATALOG_URL" in result.output assert "Unset" in result.output assert config.read_bytes() == before + + +@pytest.mark.parametrize("host", ["localhost", "127.0.0.1", "[::1]"]) +@pytest.mark.parametrize("index,original_index", [(0, 1), (1, 0)]) +def test_workflow_step_catalog_remove_with_legacy_http_source( + project_dir, monkeypatch, host, index, original_index +): + monkeypatch.delenv("SPECKIT_STEP_CATALOG_URL", raising=False) + config = project_dir / ".specify" / "step-catalogs.yml" + data = {"notes": "keep", "catalogs": [ + {"name": "legacy", "url": f"http://{host}:8080/catalog.json", "priority": 10}, + {"name": "team", "url": "https://example.com/team.json", "priority": 1}, + ]} + config.write_text(yaml.safe_dump(data, sort_keys=False), encoding="utf-8") + catalog = StepCatalog(project_dir) + with pytest.raises(StepValidationError, match="HTTPS"): + catalog.get_active_catalogs() + open_url = Mock(side_effect=AssertionError("Removal must not fetch catalogs")) + monkeypatch.setattr("specify_cli.authentication.http.open_url", open_url) + + with monkeypatch.context() as context: + context.chdir(project_dir) + result = CliRunner().invoke( + app, ["workflow", "step", "catalog", "remove", str(index)] + ) + + assert result.exit_code == 0, result.output + removed = data["catalogs"].pop(original_index) + assert f"'{removed['name']}' removed" in result.output + assert yaml.safe_load(config.read_text(encoding="utf-8")) == data + if removed["name"] == "legacy": + assert [entry.name for entry in catalog.get_active_catalogs()] == ["team"] + else: + with pytest.raises(StepValidationError, match="HTTPS"): + catalog.get_active_catalogs() + open_url.assert_not_called() + + +@pytest.mark.parametrize("index", [-1, 2]) +def test_workflow_step_catalog_remove_legacy_http_bounds_preserve_config( + project_dir, monkeypatch, index +): + monkeypatch.delenv("SPECKIT_STEP_CATALOG_URL", raising=False) + config = project_dir / ".specify" / "step-catalogs.yml" + config.write_text( + "# preserve\ncatalogs:\n - name: legacy\n" + " url: http://localhost:8080/catalog.json\n" + " - name: team\n url: https://example.com/team.json\n", + encoding="utf-8", + ) + before = config.read_bytes() + + with monkeypatch.context() as context: + context.chdir(project_dir) + result = CliRunner().invoke( + app, ["workflow", "step", "catalog", "remove", "--", str(index)] + ) + + assert result.exit_code == 1, result.output + assert "out of range" in result.output + assert config.read_bytes() == before