Skip to content

πŸ’« Toolkit to help you get started with SDD or any other process!

92.3 KB
Raw Blame
"""Tests for the authentication domain registry and config-driven HTTP helpers.

Covers:
- Config loading (auth.json parsing, validation, permission warning)
- Registry mechanics (_register, get_provider, duplicate/empty-key guards)
- GitHubAuth β€” bearer headers
- AzureDevOpsAuth β€” basic-pat, bearer, azure-cli, azure-ad headers
- BitbucketAuth β€” bearer and basic (username:token) headers
- Host matching (find_entries_for_url)
- open_url β€” config-driven auth with fallthrough and redirect stripping
- build_request β€” single-shot request construction
- _fetch_latest_release_tag() delegation
"""

from __future__ import annotations

import base64
import io
import json
import os

import pytest

from specify_cli.authentication import AUTH_REGISTRY, _register, get_provider
from specify_cli.authentication.azure_devops import AzureDevOpsAuth
from specify_cli.authentication.base import AuthProvider
from specify_cli.authentication.bitbucket import BitbucketAuth
from specify_cli.authentication.config import (
    AuthConfigEntry,
    find_entries_for_url,
    load_auth_config,
)
from specify_cli.authentication.github import GitHubAuth, GitHubCliAuthError


# ---------------------------------------------------------------------------
# Helpers
# ---------------------------------------------------------------------------


def _github_entry(token_env: str = "GH_TOKEN", token: str | None = None) -> AuthConfigEntry:
    """Build a standard GitHub config entry."""
    return AuthConfigEntry(
        hosts=("github.com", "api.github.com", "raw.githubusercontent.com", "codeload.github.com"),
        provider="github",
        auth="bearer",
        token=token,
        token_env=token_env if token is None else None,
    )


def _github_cli_entry(
    hosts: tuple[str, ...] = (
        "github.com",
        "api.github.com",
        "raw.githubusercontent.com",
        "codeload.github.com",
    ),
) -> AuthConfigEntry:
    """Build a GitHub CLI config entry."""
    return AuthConfigEntry(
        hosts=hosts,
        provider="github",
        auth="github-cli",
    )


def _ado_basic_entry(token_env: str = "AZURE_DEVOPS_PAT") -> AuthConfigEntry:
    """Build an ADO basic-pat config entry."""
    return AuthConfigEntry(
        hosts=("dev.azure.com",),
        provider="azure-devops",
        auth="basic-pat",
        token_env=token_env,
    )


class _StubProvider(AuthProvider):
    """Minimal concrete provider for registry mechanics tests."""

    key = "stub-provider"
    supported_auth_schemes = ("bearer",)

    def auth_headers(self, token: str, auth_scheme: str) -> dict[str, str]:
        return {"Authorization": f"Bearer {token}"}


# ---------------------------------------------------------------------------
# Config loading
# ---------------------------------------------------------------------------


class TestLoadAuthConfig:
    def test_missing_file_returns_empty(self, tmp_path):
        assert load_auth_config(tmp_path / "nonexistent.json") == []

    def test_valid_github_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["github.com"],
                "provider": "github",
                "auth": "bearer",
                "token_env": "GH_TOKEN",
            }]
        }))
        entries = load_auth_config(cfg)
        assert len(entries) == 1
        assert entries[0].provider == "github"
        assert entries[0].auth == "bearer"
        assert entries[0].token_env == "GH_TOKEN"

    def test_valid_github_cli_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["github.com", "api.github.com"],
                "provider": "github",
                "auth": "github-cli",
            }]
        }))

        entries = load_auth_config(cfg)

        assert len(entries) == 1
        assert entries[0].auth == "github-cli"
        assert entries[0].token is None
        assert entries[0].token_env is None

    def test_padded_token_env_is_normalized_and_resolves(self, tmp_path, monkeypatch):
        # token_env is validated on its stripped form but was stored raw, so a
        # padded env-var name passed validation yet broke the verbatim
        # os.environ.get() lookup β€” resolve_token silently returned None.
        monkeypatch.setenv("GH_TOKEN", "secret-tok")
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["github.com"],
                "provider": "github",
                "auth": "bearer",
                "token_env": "  GH_TOKEN  ",
            }]
        }))
        entries = load_auth_config(cfg)
        assert len(entries) == 1
        # Stored normalized (matching how hosts are normalized), ...
        assert entries[0].token_env == "GH_TOKEN"
        # ... so the env lookup finds the token instead of returning None.
        assert GitHubAuth().resolve_token(entries[0]) == "secret-tok"

    def test_valid_ado_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["dev.azure.com"],
                "provider": "azure-devops",
                "auth": "basic-pat",
                "token_env": "AZURE_DEVOPS_PAT",
            }]
        }))
        entries = load_auth_config(cfg)
        assert len(entries) == 1
        assert entries[0].provider == "azure-devops"
        assert entries[0].auth == "basic-pat"

    def test_valid_bitbucket_bearer_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["api.bitbucket.org", "bitbucket.org"],
                "provider": "bitbucket",
                "auth": "bearer",
                "token_env": "BITBUCKET_ACCESS_TOKEN",
            }]
        }))
        entries = load_auth_config(cfg)
        assert len(entries) == 1
        assert entries[0].provider == "bitbucket"
        assert entries[0].auth == "bearer"
        assert entries[0].username is None

    def test_valid_bitbucket_basic_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["api.bitbucket.org"],
                "provider": "bitbucket",
                "auth": "basic",
                "username": "  [email protected]  ",
                "token_env": "ATLASSIAN_API_TOKEN",
            }]
        }))
        entries = load_auth_config(cfg)
        assert entries[0].auth == "basic"
        # Stored normalized, matching token_env/tenant_id handling.
        assert entries[0].username == "[email protected]"

    def test_username_field_is_appended_after_azure_fields(self):
        # `username` was added to AuthConfigEntry after the Azure AD fields so
        # a positional construction written before it existed still maps its
        # sixth argument to tenant_id (not to username).
        entry = AuthConfigEntry(
            ("dev.azure.com",), "azure-devops", "azure-ad",
            None, None, "tid", "cid", "SECRET",
        )
        assert entry.tenant_id == "tid"
        assert entry.client_id == "cid"
        assert entry.client_secret_env == "SECRET"
        assert entry.username is None

    def test_basic_without_username_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["api.bitbucket.org"],
                "provider": "bitbucket",
                "auth": "basic",
                "token_env": "ATLASSIAN_API_TOKEN",
            }]
        }))
        with pytest.raises(ValueError, match="requires 'username'"):
            load_auth_config(cfg)

    def test_basic_without_token_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["api.bitbucket.org"],
                "provider": "bitbucket",
                "auth": "basic",
                "username": "[email protected]",
            }]
        }))
        with pytest.raises(ValueError, match="requires 'token' or 'token_env'"):
            load_auth_config(cfg)

    def test_username_with_colon_raises(self, tmp_path):
        # RFC 7617 forbids ':' in the user-id; the server would split on the
        # first colon and authenticate as the wrong user.
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["api.bitbucket.org"],
                "provider": "bitbucket",
                "auth": "basic",
                "username": "user:name",
                "token_env": "ATLASSIAN_API_TOKEN",
            }]
        }))
        with pytest.raises(ValueError, match="must not contain ':'"):
            load_auth_config(cfg)

    @pytest.mark.parametrize("username", ["", "   ", 42, False])
    def test_invalid_username_raises(self, tmp_path, username):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["api.bitbucket.org"],
                "provider": "bitbucket",
                "auth": "basic",
                "username": username,
                "token_env": "ATLASSIAN_API_TOKEN",
            }]
        }))
        with pytest.raises(ValueError, match="username"):
            load_auth_config(cfg)

    def test_inline_token(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["github.com"],
                "provider": "github",
                "auth": "bearer",
                "token": "ghp_inline_token",
            }]
        }))
        entries = load_auth_config(cfg)
        assert entries[0].token == "ghp_inline_token"

    def test_azure_ad_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["dev.azure.com"],
                "provider": "azure-devops",
                "auth": "azure-ad",
                "tenant_id": "tid",
                "client_id": "cid",
                "client_secret_env": "SECRET",
            }]
        }))
        entries = load_auth_config(cfg)
        assert entries[0].auth == "azure-ad"
        assert entries[0].tenant_id == "tid"

    def test_padded_azure_ad_refs_are_normalized(self, tmp_path):
        # The normalization also covers tenant_id / client_id / client_secret_env
        # (used verbatim in the OAuth token URL/body and os.environ.get). Padded
        # values were validated on their stripped form but stored raw.
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["dev.azure.com"],
                "provider": "azure-devops",
                "auth": "azure-ad",
                "tenant_id": "  tid  ",
                "client_id": "  cid  ",
                "client_secret_env": "  SECRET  ",
            }]
        }))
        entries = load_auth_config(cfg)
        assert entries[0].tenant_id == "tid"
        assert entries[0].client_id == "cid"
        assert entries[0].client_secret_env == "SECRET"

    def test_azure_cli_config(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["dev.azure.com"],
                "provider": "azure-devops",
                "auth": "azure-cli",
            }]
        }))
        entries = load_auth_config(cfg)
        assert entries[0].auth == "azure-cli"

    def test_multiple_entries(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [
                {"hosts": ["github.com"], "provider": "github", "auth": "bearer", "token_env": "GH_TOKEN"},
                {"hosts": ["dev.azure.com"], "provider": "azure-devops", "auth": "basic-pat", "token_env": "ADO_PAT"},
            ]
        }))
        entries = load_auth_config(cfg)
        assert len(entries) == 2

    # -- Negative: validation errors --

    def test_invalid_json_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text("not json")
        with pytest.raises(ValueError, match="invalid JSON"):
            load_auth_config(cfg)

    def test_not_object_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text("[]")
        with pytest.raises(ValueError, match="JSON object"):
            load_auth_config(cfg)

    def test_missing_providers_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({"foo": "bar"}))
        with pytest.raises(ValueError, match="providers"):
            load_auth_config(cfg)

    def test_empty_hosts_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": [], "provider": "github", "auth": "bearer", "token_env": "X"}]
        }))
        with pytest.raises(ValueError, match="non-empty"):
            load_auth_config(cfg)

    def test_missing_provider_key_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["github.com"], "auth": "bearer", "token_env": "X"}]
        }))
        with pytest.raises(ValueError, match="provider"):
            load_auth_config(cfg)

    def test_unsupported_auth_scheme_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["github.com"], "provider": "github", "auth": "ntlm", "token_env": "X"}]
        }))
        with pytest.raises(ValueError, match="does not support"):
            load_auth_config(cfg)

    def test_bearer_without_token_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["github.com"], "provider": "github", "auth": "bearer"}]
        }))
        with pytest.raises(ValueError, match="token"):
            load_auth_config(cfg)

    def test_azure_ad_missing_fields_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["dev.azure.com"],
                "provider": "azure-devops",
                "auth": "azure-ad",
                "tenant_id": "tid",
            }]
        }))
        with pytest.raises(ValueError, match="azure-ad"):
            load_auth_config(cfg)

    def test_unknown_provider_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["example.com"], "provider": "gitlab", "auth": "bearer", "token_env": "X"}]
        }))
        with pytest.raises(ValueError, match="unknown provider"):
            load_auth_config(cfg)

    def test_incompatible_provider_scheme_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": ["github.com"],
                "provider": "github",
                "auth": "basic-pat",
                "token_env": "X",
            }]
        }))
        with pytest.raises(ValueError, match="does not support"):
            load_auth_config(cfg)

    def test_dangerous_wildcard_host_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["*github.com"], "provider": "github", "auth": "bearer", "token_env": "X"}]
        }))
        with pytest.raises(ValueError, match="invalid host pattern"):
            load_auth_config(cfg)

    def test_multi_wildcard_host_raises(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["*.*.example.com"], "provider": "github", "auth": "bearer", "token_env": "X"}]
        }))
        with pytest.raises(ValueError, match="invalid host pattern"):
            load_auth_config(cfg)

    @pytest.mark.parametrize("host", ["gith?b.com", "[a-z].example.com"])
    def test_unsupported_glob_metacharacters_raise(self, tmp_path, host):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{
                "hosts": [host],
                "provider": "github",
                "auth": "bearer",
                "token_env": "X",
            }]
        }))
        with pytest.raises(ValueError, match="invalid host pattern"):
            load_auth_config(cfg)

    def test_valid_star_dot_host_accepted(self, tmp_path):
        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["*.visualstudio.com"], "provider": "azure-devops", "auth": "basic-pat", "token_env": "X"}]
        }))
        entries = load_auth_config(cfg)
        assert entries[0].hosts == ("*.visualstudio.com",)

    @pytest.mark.skipif(os.name == "nt", reason="POSIX permission bits not supported on Windows")
    def test_world_readable_warns(self, tmp_path):
        import stat

        cfg = tmp_path / "auth.json"
        cfg.write_text(json.dumps({
            "providers": [{"hosts": ["github.com"], "provider": "github", "auth": "bearer", "token_env": "GH_TOKEN"}]
        }))
        cfg.chmod(stat.S_IRUSR | stat.S_IWUSR | stat.S_IRGRP | stat.S_IROTH)
        with pytest.warns(UserWarning, match="readable by group"):
            load_auth_config(cfg)


# ---------------------------------------------------------------------------
# Host matching
# ---------------------------------------------------------------------------


class TestFindEntriesForUrl:
    def test_exact_match(self):
        entry = _github_entry()
        result = find_entries_for_url("https://github.com:443/org/repo", [entry])
        assert result == [entry]

    def test_wildcard_match(self):
        entry = AuthConfigEntry(
            hosts=("*.visualstudio.com",),
            provider="azure-devops",
            auth="basic-pat",
            token_env="ADO_PAT",
        )
        result = find_entries_for_url("https://myorg.visualstudio.com/project", [entry])
        assert result == [entry]

    @pytest.mark.parametrize(
        "url",
        [
            "https://visualstudio.com/project",
            "https://evilvisualstudio.com/project",
            "https://visualstudio.com.evil.example/project",
        ],
    )
    def test_wildcard_does_not_match_apex_or_lookalikes(self, url):
        entry = AuthConfigEntry(
            hosts=("*.visualstudio.com",),
            provider="azure-devops",
            auth="basic-pat",
            token_env="ADO_PAT",
        )
        assert find_entries_for_url(url, [entry]) == []

    @pytest.mark.parametrize(
        ("pattern", "url"),
        [
            ("gith?b.com", "https://github.com/org/repo"),
            ("[a-z].example.com", "https://a.example.com/file"),
        ],
    )
    def test_exact_hosts_do_not_apply_glob_semantics(self, pattern, url):
        entry = AuthConfigEntry(
            hosts=(pattern,),
            provider="github",
            auth="bearer",
            token="sentinel",
        )
        assert find_entries_for_url(url, [entry]) == []

    def test_no_match_returns_empty(self):
        entry = _github_entry()
        result = find_entries_for_url("https://evil.example.com/file", [entry])
        assert result == []

    def test_no_match_for_lookalike_host(self):
        entry = _github_entry()
        result = find_entries_for_url("https://github.com.evil.com/file", [entry])
        assert result == []

    def test_empty_url_returns_empty(self):
        assert find_entries_for_url("", [_github_entry()]) == []

    @pytest.mark.parametrize(
        "url",
        [
            "https://[::1",                 # unterminated ipv6 bracket
            "https://[not-an-ip]/file",     # bracketed non-ip host
            "https://github.com:notaport/x", # non-numeric port
            "https://github.com:99999/x",   # out-of-range port
        ],
    )
    def test_malformed_url_returns_empty(self, url):
        # A malformed authority makes urlparse, hostname, or port raise ValueError.
        # Since no entry can match such a URL, this must return no matches
        # (like a host-less URL) rather than leaking a raw ValueError out of
        # the shared HTTP client.
        assert find_entries_for_url(url, [_github_entry()]) == []

    def test_empty_entries_returns_empty(self):
        assert find_entries_for_url("https://github.com/org/repo", []) == []

    def test_multiple_matches_returned(self):
        e1 = _github_entry(token_env="GH_TOKEN")
        e2 = _github_entry(token_env="GITHUB_TOKEN")
        result = find_entries_for_url("https://github.com/org/repo", [e1, e2])
        assert len(result) == 2


# ---------------------------------------------------------------------------
# Registry mechanics
# ---------------------------------------------------------------------------


class TestAuthRegistry:
    def test_github_registered(self):
        assert "github" in AUTH_REGISTRY

    def test_azure_devops_registered(self):
        assert "azure-devops" in AUTH_REGISTRY

    def test_get_provider_returns_github(self):
        assert isinstance(get_provider("github"), GitHubAuth)

    def test_get_provider_returns_azure_devops(self):
        assert isinstance(get_provider("azure-devops"), AzureDevOpsAuth)

    def test_bitbucket_registered(self):
        assert "bitbucket" in AUTH_REGISTRY

    def test_get_provider_returns_bitbucket(self):
        assert isinstance(get_provider("bitbucket"), BitbucketAuth)

    def test_get_provider_unknown_returns_none(self):
        assert get_provider("does-not-exist") is None

    def test_register_duplicate_raises_key_error(self):
        class _UniqueStub(_StubProvider):
            key = "__test_duplicate__"

        try:
            _register(_UniqueStub())
            with pytest.raises(KeyError, match="already registered"):
                _register(_UniqueStub())
        finally:
            AUTH_REGISTRY.pop("__test_duplicate__", None)

    def test_register_empty_key_raises_value_error(self):
        class _EmptyKey(_StubProvider):
            key = ""

        with pytest.raises(ValueError, match="empty key"):
            _register(_EmptyKey())


# ---------------------------------------------------------------------------
# GitHubAuth
# ---------------------------------------------------------------------------


class TestGitHubAuth:
    def test_bearer_headers(self):
        assert GitHubAuth().auth_headers("my-token", "bearer") == {"Authorization": "Bearer my-token"}

    def test_github_cli_headers(self):
        assert GitHubAuth().auth_headers("my-token", "github-cli") == {
            "Authorization": "Bearer my-token"
        }

    def test_github_cli_resolves_token_with_fixed_command(self):
        from unittest.mock import MagicMock, patch

        result = MagicMock(returncode=0, stdout="  cli-token\n")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ) as run:
            token = GitHubAuth().resolve_token(_github_cli_entry())

        assert token == "cli-token"
        run.assert_called_once_with(
            [executable, "auth", "token", "--hostname", "github.com"],
            capture_output=True,
            text=True,
            timeout=10,
            check=False,
            shell=False,
        )

    def test_github_cli_uses_bare_enterprise_host(self):
        from unittest.mock import MagicMock, patch

        entry = _github_cli_entry((
            "ghes.example.com",
            "raw.ghes.example.com",
            "codeload.ghes.example.com",
        ))
        result = MagicMock(returncode=0, stdout="enterprise-token")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ) as run:
            assert GitHubAuth().resolve_token(entry) == "enterprise-token"

        assert run.call_args.args[0][-2:] == ["--hostname", "ghes.example.com"]

    @pytest.mark.parametrize("hosts", [
        ("api.company.example",),
        ("raw.company.example", "api.raw.company.example"),
        ("api.github.com", "github.com"),
        ("ghes.example.com", "*.ghes.example.com"),
        ("first.example.com", "second.example.com"),
    ])
    def test_github_cli_uses_first_hostname(self, hosts):
        from unittest.mock import patch

        with patch.object(
            GitHubAuth, "_acquire_via_gh_cli", return_value="cli-token",
        ) as acquire:
            assert GitHubAuth().resolve_token(_github_cli_entry(hosts)) == "cli-token"

        acquire.assert_called_once_with(hosts[0])

    def test_github_cli_rejects_wildcard_first_hostname(self):
        from unittest.mock import patch

        entry = _github_cli_entry(("*.ghes.example.com", "ghes.example.com"))
        with patch(
            "specify_cli.authentication.github.shutil.which",
        ) as which, patch(
            "specify_cli.authentication.github.subprocess.run",
        ) as run, pytest.raises(GitHubCliAuthError, match="first hostname"):
            GitHubAuth().resolve_token(entry)

        which.assert_not_called()
        run.assert_not_called()

    def test_github_cli_caches_by_first_hostname(self):
        from unittest.mock import patch

        provider = GitHubAuth()
        with patch.object(
            GitHubAuth, "_acquire_via_gh_cli", side_effect=["first-token", "second-token"],
        ) as acquire:
            assert provider.resolve_token(_github_cli_entry((
                "first.example.com", "api.first.example.com",
            ))) == "first-token"
            assert provider.resolve_token(_github_cli_entry((
                "first.example.com", "*.first.example.com",
            ))) == "first-token"
            assert provider.resolve_token(_github_cli_entry((
                "second.example.com", "first.example.com",
            ))) == "second-token"

        assert [call.args for call in acquire.call_args_list] == [
            ("first.example.com",), ("second.example.com",),
        ]

    def test_github_cli_caches_token_per_process(self):
        from unittest.mock import MagicMock, patch

        provider = GitHubAuth()
        result = MagicMock(returncode=0, stdout="cached-token")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ) as run:
            assert provider.resolve_token(_github_cli_entry()) == "cached-token"
            assert provider.resolve_token(_github_cli_entry()) == "cached-token"

        run.assert_called_once()

    @pytest.mark.parametrize("executable", [None, r".\gh.exe", "gh.exe", "./gh"])
    def test_github_cli_rejects_missing_or_relative_executable(self, executable):
        from unittest.mock import patch

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
        ) as run, pytest.raises(GitHubCliAuthError, match="was not found"):
            GitHubAuth().resolve_token(_github_cli_entry())

        run.assert_not_called()

    def test_github_cli_nonzero_suggests_login_without_command_output(self):
        from unittest.mock import MagicMock, patch

        secret = "ghp_must_not_leak"
        result = MagicMock(returncode=1, stdout=secret, stderr=secret)
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ), pytest.raises(GitHubCliAuthError) as exc_info:
            GitHubAuth().resolve_token(_github_cli_entry())

        message = str(exc_info.value)
        assert "gh auth login --hostname github.com" in message
        assert secret not in message

    def test_github_cli_empty_output_raises(self):
        from unittest.mock import MagicMock, patch

        result = MagicMock(returncode=0, stdout=" \n", stderr="")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ), pytest.raises(GitHubCliAuthError, match="empty token"):
            GitHubAuth().resolve_token(_github_cli_entry())

    @pytest.mark.parametrize("invalid_text", ["\r", "\n", "\r\n", "\u00e9", "\u2603"])
    def test_github_cli_caches_sanitized_malformed_token_failure(self, invalid_text):
        from unittest.mock import MagicMock, patch

        secret = "synthetic_credential"
        result = MagicMock(returncode=0, stdout=f" {secret}{invalid_text}extra\n")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")
        provider = GitHubAuth()
        messages = []

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ) as run:
            for _ in range(2):
                with pytest.raises(GitHubCliAuthError, match="malformed token") as exc_info:
                    provider.resolve_token(_github_cli_entry())
                messages.append(str(exc_info.value))
                assert secret not in messages[-1]
                assert "extra" not in messages[-1]

        assert messages[0] == messages[1]
        assert provider._github_cli_cache == {
            "github.com": (False, exc_info.value.reason),
        }
        run.assert_called_once()

    def test_github_cli_timeout_raises(self):
        import subprocess
        from unittest.mock import patch

        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            side_effect=subprocess.TimeoutExpired(["gh"], 10),
        ), pytest.raises(GitHubCliAuthError, match="timed out"):
            GitHubAuth().resolve_token(_github_cli_entry())

    @pytest.mark.parametrize("error", [
        None,
        PermissionError("secret"),
        UnicodeDecodeError("utf-8", b"secret\xff", 6, 7, "secret"),
    ], ids=["nonzero-exit", "permission-error", "decode-error"])
    def test_github_cli_caches_sanitized_failure(self, error):
        from unittest.mock import MagicMock, patch

        provider = GitHubAuth()
        result = MagicMock(returncode=1, stdout="secret", stderr="secret")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")
        messages = []

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
            side_effect=error,
        ) as run:
            for _ in range(2):
                with pytest.raises(GitHubCliAuthError) as exc_info:
                    provider.resolve_token(_github_cli_entry())
                assert "secret" not in str(exc_info.value)
                messages.append(str(exc_info.value))

        assert messages[0] == messages[1]
        assert "provider 'github'" in messages[0]
        assert "could not provide a token" in messages[0]
        run.assert_called_once()

    def test_github_cli_rejects_shell_unsafe_host_without_echoing_it(self):
        from unittest.mock import patch

        unsafe_host = "a&whoami&b.ghes.example.com"
        entry = _github_cli_entry((unsafe_host,))

        with patch(
            "specify_cli.authentication.github.shutil.which",
        ) as which, patch(
            "specify_cli.authentication.github.subprocess.run",
        ) as run, pytest.raises(GitHubCliAuthError) as exc_info:
            GitHubAuth().resolve_token(entry)

        assert unsafe_host not in str(exc_info.value)
        which.assert_not_called()
        run.assert_not_called()

    def test_unsupported_scheme_raises(self):
        with pytest.raises(ValueError, match="basic-pat"):
            GitHubAuth().auth_headers("tok", "basic-pat")

    def test_resolve_token_from_env(self, monkeypatch):
        monkeypatch.setenv("GH_TOKEN", "env-token")
        assert GitHubAuth().resolve_token(_github_entry()) == "env-token"

    def test_resolve_token_inline(self):
        assert GitHubAuth().resolve_token(_github_entry(token="inline-tok")) == "inline-tok"

    def test_resolve_token_strips_whitespace(self, monkeypatch):
        monkeypatch.setenv("GH_TOKEN", "  my-token  ")
        assert GitHubAuth().resolve_token(_github_entry()) == "my-token"

    def test_resolve_token_empty_env_returns_none(self, monkeypatch):
        monkeypatch.setenv("GH_TOKEN", "   ")
        assert GitHubAuth().resolve_token(_github_entry()) is None

    def test_resolve_token_missing_env_returns_none(self, monkeypatch):
        monkeypatch.delenv("GH_TOKEN", raising=False)
        assert GitHubAuth().resolve_token(_github_entry()) is None

    def test_key(self):
        assert GitHubAuth.key == "github"

    def test_supported_schemes(self):
        assert GitHubAuth.supported_auth_schemes == ("bearer", "github-cli")


# ---------------------------------------------------------------------------
# AzureDevOpsAuth
# ---------------------------------------------------------------------------


class TestAzureDevOpsAuth:
    def test_basic_pat_headers(self):
        headers = AzureDevOpsAuth().auth_headers("my-pat", "basic-pat")
        encoded = base64.b64encode(b":my-pat").decode("ascii")
        assert headers == {"Authorization": f"Basic {encoded}"}

    def test_basic_pat_format(self):
        header = AzureDevOpsAuth().auth_headers("test-pat", "basic-pat")["Authorization"]
        raw = base64.b64decode(header[len("Basic "):]).decode("ascii")
        assert raw == ":test-pat"

    def test_bearer_headers(self):
        assert AzureDevOpsAuth().auth_headers("tok", "bearer") == {"Authorization": "Bearer tok"}

    def test_azure_cli_headers(self):
        assert AzureDevOpsAuth().auth_headers("tok", "azure-cli") == {"Authorization": "Bearer tok"}

    def test_azure_ad_headers(self):
        assert AzureDevOpsAuth().auth_headers("tok", "azure-ad") == {"Authorization": "Bearer tok"}

    def test_unsupported_scheme_raises(self):
        with pytest.raises(ValueError):
            AzureDevOpsAuth().auth_headers("tok", "ntlm")

    def test_resolve_token_basic_pat(self, monkeypatch):
        monkeypatch.setenv("AZURE_DEVOPS_PAT", "my-pat")
        assert AzureDevOpsAuth().resolve_token(_ado_basic_entry()) == "my-pat"

    def test_resolve_token_strips_whitespace(self, monkeypatch):
        monkeypatch.setenv("AZURE_DEVOPS_PAT", "  my-pat  ")
        assert AzureDevOpsAuth().resolve_token(_ado_basic_entry()) == "my-pat"

    def test_resolve_token_missing_returns_none(self, monkeypatch):
        monkeypatch.delenv("AZURE_DEVOPS_PAT", raising=False)
        assert AzureDevOpsAuth().resolve_token(_ado_basic_entry()) is None

    def test_key(self):
        assert AzureDevOpsAuth.key == "azure-devops"

    def test_supported_schemes(self):
        schemes = AzureDevOpsAuth.supported_auth_schemes
        assert "basic-pat" in schemes
        assert "bearer" in schemes
        assert "azure-cli" in schemes
        assert "azure-ad" in schemes

    def test_resolve_token_azure_cli_success(self):
        """azure-cli acquires token via az CLI."""
        from unittest.mock import patch, MagicMock
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        result = MagicMock()
        result.returncode = 0
        result.stdout = '{"accessToken": "cli-acquired-token"}'
        with patch("specify_cli.authentication.azure_devops.subprocess.run", return_value=result):
            assert AzureDevOpsAuth().resolve_token(entry) == "cli-acquired-token"

    def test_resolve_token_azure_cli_failure_returns_none(self):
        """azure-cli returns None when az CLI fails."""
        from unittest.mock import patch, MagicMock
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        result = MagicMock()
        result.returncode = 1
        result.stdout = ""
        with patch("specify_cli.authentication.azure_devops.subprocess.run", return_value=result):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    def test_resolve_token_azure_cli_resolves_executable(self):
        """The az executable is resolved via shutil.which before invocation, so
        the .cmd/.bat shim on Windows (CreateProcess ignores PATHEXT) is used."""
        from unittest.mock import patch, MagicMock
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        # Build the absolute path with the HOST's rules: the production code
        # calls os.path.isabs(), so a hardcoded Windows path would read as
        # RELATIVE on POSIX runners and silently exercise the fallback branch
        # instead of the one under test.
        resolved_path = os.path.join(os.path.abspath(os.sep), "opt", "az", "az.CMD")
        assert os.path.isabs(resolved_path)
        result = MagicMock()
        result.returncode = 0
        result.stdout = '{"accessToken": "tok"}'
        with patch(
            "specify_cli.authentication.azure_devops.shutil.which",
            return_value=resolved_path,
        ), patch(
            "specify_cli.authentication.azure_devops.subprocess.run",
            return_value=result,
        ) as run:
            assert AzureDevOpsAuth().resolve_token(entry) == "tok"
        argv = run.call_args.args[0]
        assert argv[0] == resolved_path
        assert argv[1:4] == ["account", "get-access-token", "--resource"]

    @pytest.mark.parametrize("which_result", [None, r".\az.CMD", "az.cmd", "./az"])
    def test_resolve_token_azure_cli_falls_back_to_bare_az(self, which_result):
        """Fall back to the bare "az" when shutil.which finds nothing OR returns a
        NON-ABSOLUTE path. On Windows shutil.which searches the current directory
        first, so a stray .\\az.cmd must never be executed for a credential
        operation; the bare name also preserves the not-installed OSError path."""
        from unittest.mock import patch, MagicMock
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        result = MagicMock()
        result.returncode = 0
        result.stdout = '{"accessToken": "tok"}'
        with patch(
            "specify_cli.authentication.azure_devops.shutil.which",
            return_value=which_result,
        ), patch(
            "specify_cli.authentication.azure_devops.subprocess.run",
            return_value=result,
        ) as run:
            assert AzureDevOpsAuth().resolve_token(entry) == "tok"
        assert run.call_args.args[0][0] == "az", which_result

    def test_resolve_token_azure_cli_not_installed_returns_none(self):
        """azure-cli returns None when az is not installed."""
        from unittest.mock import patch
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        with patch("specify_cli.authentication.azure_devops.subprocess.run", side_effect=OSError("not found")):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    def test_resolve_token_azure_cli_undecodable_output_returns_none(self):
        """Undecodable az output returns None, not a crash. With text=True,
        subprocess.run decodes stdout with the locale encoding and raises
        UnicodeDecodeError (not a JSONDecodeError) when it can't β€” the helper's
        contract is to return None on any failure."""
        from unittest.mock import patch
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        boom = UnicodeDecodeError("utf-8", b"\xff\xfe", 0, 1, "invalid start byte")
        with patch("specify_cli.authentication.azure_devops.subprocess.run", side_effect=boom):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    @pytest.mark.parametrize("payload", [[], {"accessToken": None}, {"accessToken": 123}])
    def test_resolve_token_azure_cli_unexpected_json_shape_returns_none(
        self, payload
    ):
        from unittest.mock import MagicMock, patch

        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-cli",
        )
        result = MagicMock(returncode=0, stdout=json.dumps(payload))

        with patch(
            "specify_cli.authentication.azure_devops.subprocess.run",
            return_value=result,
        ):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    def test_resolve_token_azure_ad_success(self, monkeypatch):
        """azure-ad acquires token via OAuth2 client credentials."""
        from unittest.mock import patch, MagicMock
        monkeypatch.setenv("MY_SECRET", "secret-value")
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        mock_resp = MagicMock()
        mock_resp.read.side_effect = io.BytesIO(b'{"access_token": "ad-acquired-token"}').read
        mock_resp.__enter__ = lambda s: s
        mock_resp.__exit__ = MagicMock(return_value=False)
        # The token request goes through a strict-redirect opener (so a 307/308
        # cannot forward the client_secret body to a non-HTTPS host), not bare
        # urlopen; patch the opener it builds.
        mock_opener = MagicMock()
        mock_opener.open.return_value = mock_resp
        with patch("urllib.request.build_opener", return_value=mock_opener):
            assert AzureDevOpsAuth().resolve_token(entry) == "ad-acquired-token"

    def test_resolve_token_azure_ad_missing_secret_returns_none(self, monkeypatch):
        """azure-ad returns None when client secret env var is missing."""
        monkeypatch.delenv("MY_SECRET", raising=False)
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        assert AzureDevOpsAuth().resolve_token(entry) is None

    def test_resolve_token_azure_ad_network_error_returns_none(self, monkeypatch):
        """azure-ad returns None on network errors."""
        import urllib.error
        from unittest.mock import MagicMock, patch
        monkeypatch.setenv("MY_SECRET", "secret-value")
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        mock_opener = MagicMock()
        mock_opener.open.side_effect = urllib.error.URLError("connection refused")
        with patch("urllib.request.build_opener", return_value=mock_opener):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    @pytest.mark.parametrize(
        ("status", "reason"),
        [(307, "Temporary Redirect"), (308, "Permanent Redirect")],
    )
    def test_resolve_token_azure_ad_rejects_https_redirect(
        self, monkeypatch, status, reason
    ):
        """The client-secret POST must never be redirected to another host."""
        import urllib.error
        from unittest.mock import MagicMock, patch
        from urllib.request import Request

        monkeypatch.setenv("MY_SECRET", "secret-value")
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        mock_opener = MagicMock()
        mock_opener.open.side_effect = urllib.error.URLError("stop after setup")

        with patch("urllib.request.build_opener", return_value=mock_opener) as build_opener:
            assert AzureDevOpsAuth().resolve_token(entry) is None

        redirect_handler = build_opener.call_args.args[0]
        request = Request(
            "https://login.microsoftonline.com/tid/oauth2/v2.0/token",
            data=b"grant_type=client_credentials&client_secret=secret-value",
            headers={"Content-Type": "application/x-www-form-urlencoded"},
        )
        assert request.get_method() == "POST"
        assert b"client_secret=secret-value" in request.data
        with pytest.raises(urllib.error.URLError, match="must not be redirected"):
            redirect_handler.redirect_request(
                request,
                io.BytesIO(b""),
                status,
                reason,
                {},
                "https://evil.example/token",
            )

    def test_resolve_token_azure_ad_oversized_response_returns_none(
        self, monkeypatch
    ):
        """Oversized token metadata is rejected before JSON parsing."""
        from unittest.mock import MagicMock, patch

        from specify_cli._download_security import MAX_JSON_METADATA_BYTES

        monkeypatch.setenv("MY_SECRET", "secret-value")
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        mock_resp = MagicMock()
        mock_resp.read.side_effect = io.BytesIO(
            b"x" * (MAX_JSON_METADATA_BYTES + 1)
        ).read
        mock_resp.__enter__ = lambda s: s
        mock_resp.__exit__ = MagicMock(return_value=False)
        mock_opener = MagicMock()
        mock_opener.open.return_value = mock_resp

        with patch("urllib.request.build_opener", return_value=mock_opener), patch(
            "specify_cli.authentication.azure_devops._json.loads",
            side_effect=AssertionError("oversized body must not be parsed"),
        ):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    @pytest.mark.parametrize("payload", [[], {"access_token": None}, {"access_token": 123}])
    def test_resolve_token_azure_ad_unexpected_json_shape_returns_none(
        self, monkeypatch, payload
    ):
        from unittest.mock import MagicMock, patch

        monkeypatch.setenv("MY_SECRET", "secret-value")
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        mock_resp = MagicMock()
        mock_resp.read.side_effect = io.BytesIO(json.dumps(payload).encode()).read
        mock_resp.__enter__ = lambda s: s
        mock_resp.__exit__ = MagicMock(return_value=False)
        mock_opener = MagicMock()
        mock_opener.open.return_value = mock_resp

        with patch("urllib.request.build_opener", return_value=mock_opener):
            assert AzureDevOpsAuth().resolve_token(entry) is None

    def test_resolve_token_azure_ad_invalid_utf8_returns_none(self, monkeypatch):
        """azure-ad returns None when the token response is not valid UTF-8."""
        from unittest.mock import MagicMock, patch
        monkeypatch.setenv("MY_SECRET", "secret-value")
        entry = AuthConfigEntry(
            hosts=("dev.azure.com",), provider="azure-devops", auth="azure-ad",
            tenant_id="tid", client_id="cid", client_secret_env="MY_SECRET",
        )
        mock_resp = MagicMock()
        mock_resp.read.side_effect = io.BytesIO(b"\xff").read
        mock_resp.__enter__ = lambda s: s
        mock_resp.__exit__ = MagicMock(return_value=False)
        mock_opener = MagicMock()
        mock_opener.open.return_value = mock_resp

        with patch("urllib.request.build_opener", return_value=mock_opener):
            assert AzureDevOpsAuth().resolve_token(entry) is None


# ---------------------------------------------------------------------------
# BitbucketAuth
# ---------------------------------------------------------------------------


def _bitbucket_basic_entry(
    username: str | None = "[email protected]",
    token: str | None = None,
    token_env: str | None = "ATLASSIAN_API_TOKEN",
) -> AuthConfigEntry:
    """Build a Bitbucket basic config entry."""
    return AuthConfigEntry(
        hosts=("api.bitbucket.org", "bitbucket.org"),
        provider="bitbucket",
        auth="basic",
        token=token,
        token_env=token_env if token is None else None,
        username=username,
    )


class TestBitbucketAuth:
    def test_bearer_headers(self):
        headers = BitbucketAuth().auth_headers("bb-token", "bearer")
        assert headers == {"Authorization": "Bearer bb-token"}

    def test_basic_headers_encode_credential_verbatim(self):
        # For "basic", resolve_token has already combined username:secret;
        # auth_headers must encode that credential as-is.
        headers = BitbucketAuth().auth_headers("[email protected]:api-tok", "basic")
        expected = base64.b64encode(b"[email protected]:api-tok").decode("ascii")
        assert headers == {"Authorization": f"Basic {expected}"}

    def test_basic_headers_encode_non_ascii_as_utf8(self):
        # Deliberately UTF-8 (unlike AzureDevOpsAuth's ASCII encode) so a
        # non-ASCII username or secret does not raise UnicodeEncodeError.
        credential = "zoΓ«@example.com:pΓ€sswΓΆrd"
        headers = BitbucketAuth().auth_headers(credential, "basic")
        expected = base64.b64encode(credential.encode("utf-8")).decode("ascii")
        assert headers == {"Authorization": f"Basic {expected}"}

    def test_basic_headers_reject_bare_secret(self):
        # Guards the resolve_token -> auth_headers contract: a raw secret
        # would otherwise become a valid-looking header with an empty user.
        with pytest.raises(ValueError, match="<username>:<secret>"):
            BitbucketAuth().auth_headers("just-a-secret", "basic")

    @pytest.mark.parametrize("credential", [":secret", "user:", ":"])
    def test_basic_headers_reject_empty_half(self, credential):
        # A colon alone is not enough: ":secret" is exactly the empty-user
        # credential the guard exists to block, and "user:" has no secret.
        with pytest.raises(ValueError, match="both parts non-empty"):
            BitbucketAuth().auth_headers(credential, "basic")

    def test_basic_headers_preserve_colons_inside_secret(self):
        # Only the first colon separates the halves; a secret containing ':'
        # must be encoded intact.
        credential = "[email protected]:se:cr:et"
        headers = BitbucketAuth().auth_headers(credential, "basic")
        expected = base64.b64encode(credential.encode("utf-8")).decode("ascii")
        assert headers == {"Authorization": f"Basic {expected}"}

    def test_unsupported_scheme_raises(self):
        with pytest.raises(ValueError, match="does not support auth scheme"):
            BitbucketAuth().auth_headers("tok", "basic-pat")

    def test_resolve_token_bearer_from_env(self, monkeypatch):
        monkeypatch.setenv("BITBUCKET_ACCESS_TOKEN", "bb-secret")
        entry = AuthConfigEntry(
            hosts=("api.bitbucket.org",),
            provider="bitbucket",
            auth="bearer",
            token_env="BITBUCKET_ACCESS_TOKEN",
        )
        assert BitbucketAuth().resolve_token(entry) == "bb-secret"

    def test_resolve_token_basic_combines_username_and_secret(self, monkeypatch):
        monkeypatch.setenv("ATLASSIAN_API_TOKEN", "api-tok")
        entry = _bitbucket_basic_entry()
        assert BitbucketAuth().resolve_token(entry) == "[email protected]:api-tok"

    def test_resolve_token_basic_inline_token(self):
        entry = _bitbucket_basic_entry(token="inline-tok")
        assert BitbucketAuth().resolve_token(entry) == "[email protected]:inline-tok"

    def test_resolve_token_basic_missing_username_returns_none(self, monkeypatch):
        # Config validation requires username, but a directly-constructed
        # entry must not yield a malformed ":<secret>" credential.
        monkeypatch.setenv("ATLASSIAN_API_TOKEN", "api-tok")
        entry = _bitbucket_basic_entry(username=None)
        assert BitbucketAuth().resolve_token(entry) is None

    def test_resolve_token_basic_blank_username_returns_none(self, monkeypatch):
        monkeypatch.setenv("ATLASSIAN_API_TOKEN", "api-tok")
        entry = _bitbucket_basic_entry(username="   ")
        assert BitbucketAuth().resolve_token(entry) is None

    def test_resolve_token_basic_colon_username_returns_none(self, monkeypatch):
        # load_auth_config rejects this, but a directly-constructed entry
        # must not yield "user:name:<secret>", which a server parses as
        # user "user" (RFC 7617 Β§2).
        monkeypatch.setenv("ATLASSIAN_API_TOKEN", "api-tok")
        entry = _bitbucket_basic_entry(username="user:name")
        assert BitbucketAuth().resolve_token(entry) is None

    def test_resolve_token_basic_missing_secret_returns_none(self, monkeypatch):
        monkeypatch.delenv("ATLASSIAN_API_TOKEN", raising=False)
        entry = _bitbucket_basic_entry()
        assert BitbucketAuth().resolve_token(entry) is None

    def test_key(self):
        assert BitbucketAuth().key == "bitbucket"

    def test_supported_schemes(self):
        assert BitbucketAuth().supported_auth_schemes == ("bearer", "basic")


# ---------------------------------------------------------------------------
# open_url / build_request β€” positive tests
# ---------------------------------------------------------------------------


class TestAuthenticatedHttp:
    def _set_config(self, monkeypatch, entries):
        from specify_cli.authentication import http as _mod
        monkeypatch.setattr(_mod, "_config_override", entries)

    def test_build_request_attaches_auth_for_matching_host(self, monkeypatch):
        from specify_cli.authentication.http import build_request
        monkeypatch.setenv("GH_TOKEN", "my-token")
        self._set_config(monkeypatch, [_github_entry()])
        req = build_request("https://github.com/org/repo")
        assert req.get_header("Authorization") == "Bearer my-token"

    def test_build_request_attaches_bitbucket_basic_auth(self, monkeypatch):
        from specify_cli.authentication.http import build_request
        monkeypatch.setenv("ATLASSIAN_API_TOKEN", "api-tok")
        self._set_config(monkeypatch, [_bitbucket_basic_entry()])
        req = build_request(
            "https://api.bitbucket.org/2.0/repositories/ws/repo/downloads/x.tar.gz"
        )
        expected = base64.b64encode(b"[email protected]:api-tok").decode("ascii")
        assert req.get_header("Authorization") == f"Basic {expected}"

    def test_build_request_no_auth_for_non_matching_host(self, monkeypatch):
        from specify_cli.authentication.http import build_request
        monkeypatch.setenv("GH_TOKEN", "my-token")
        self._set_config(monkeypatch, [_github_entry()])
        req = build_request("https://evil.example.com/file")
        assert "Authorization" not in req.headers

    def test_build_request_no_auth_when_no_config(self, monkeypatch):
        from specify_cli.authentication.http import build_request
        self._set_config(monkeypatch, [])
        req = build_request("https://github.com/org/repo")
        assert "Authorization" not in req.headers

    def test_build_request_extra_headers(self, monkeypatch):
        from specify_cli.authentication.http import build_request
        monkeypatch.setenv("GH_TOKEN", "my-token")
        self._set_config(monkeypatch, [_github_entry()])
        req = build_request("https://github.com/api", extra_headers={"Accept": "application/json"})
        assert req.get_header("Accept") == "application/json"
        assert req.get_header("Authorization") == "Bearer my-token"

    def test_open_url_attaches_auth_for_matching_host(self, monkeypatch):
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        monkeypatch.setenv("GH_TOKEN", "my-token")
        self._set_config(monkeypatch, [_github_entry()])
        captured = {}
        mock_opener = MagicMock()
        def fake_open(req, timeout=None):
            captured["req"] = req
            resp = MagicMock()
            resp.__enter__ = lambda s: s
            resp.__exit__ = MagicMock(return_value=False)
            return resp
        mock_opener.open.side_effect = fake_open
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            open_url("https://github.com/org/repo/catalog.json")
        assert captured["req"].get_header("Authorization") == "Bearer my-token"

    def test_open_url_no_auth_for_non_matching_host(self, monkeypatch):
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        monkeypatch.setenv("GH_TOKEN", "my-token")
        self._set_config(monkeypatch, [_github_entry()])
        captured = {}
        def fake_open(req, timeout=None):
            captured["req"] = req
            resp = MagicMock()
            resp.__enter__ = lambda s: s
            resp.__exit__ = MagicMock(return_value=False)
            return resp
        mock_opener = MagicMock()
        mock_opener.open.side_effect = fake_open
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            open_url("https://example.com/file.json")
        assert captured["req"].get_header("Authorization") is None

    def test_open_url_no_auth_when_no_config(self, monkeypatch):
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        self._set_config(monkeypatch, [])
        captured = {}
        def fake_open(req, timeout=None):
            captured["req"] = req
            resp = MagicMock()
            resp.__enter__ = lambda s: s
            resp.__exit__ = MagicMock(return_value=False)
            return resp
        mock_opener = MagicMock()
        mock_opener.open.side_effect = fake_open
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            open_url("https://github.com/org/repo")
        assert captured["req"].get_header("Authorization") is None

    def test_open_url_falls_through_on_401(self, monkeypatch):
        import urllib.error
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        monkeypatch.setenv("GH_TOKEN", "bad-token")
        self._set_config(monkeypatch, [_github_entry()])
        call_count = 0
        def fake_side_effect(req, timeout=None):
            nonlocal call_count
            call_count += 1
            if call_count == 1:
                raise urllib.error.HTTPError("url", 401, "Unauthorized", {}, None)
            resp = MagicMock()
            resp.__enter__ = lambda s: s
            resp.__exit__ = MagicMock(return_value=False)
            return resp
        mock_opener = MagicMock()
        mock_opener.open.side_effect = fake_side_effect
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            open_url("https://github.com/org/repo")
        assert call_count == 2


# ---------------------------------------------------------------------------
# open_url β€” negative tests
# ---------------------------------------------------------------------------


class TestAuthenticatedHttpNegative:
    def _set_config(self, monkeypatch, entries):
        from specify_cli.authentication import http as _mod
        monkeypatch.setattr(_mod, "_config_override", entries)

    def test_500_raises_immediately(self, monkeypatch):
        import urllib.error
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        monkeypatch.setenv("GH_TOKEN", "tok")
        self._set_config(monkeypatch, [_github_entry()])
        mock_opener = MagicMock()
        mock_opener.open.side_effect = urllib.error.HTTPError("url", 500, "ISE", {}, None)
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            with pytest.raises(urllib.error.HTTPError, match="500"):
                open_url("https://github.com/org/repo")

    def test_404_raises_immediately(self, monkeypatch):
        import urllib.error
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        monkeypatch.setenv("GH_TOKEN", "tok")
        self._set_config(monkeypatch, [_github_entry()])
        mock_opener = MagicMock()
        mock_opener.open.side_effect = urllib.error.HTTPError("url", 404, "Not Found", {}, None)
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            with pytest.raises(urllib.error.HTTPError, match="404"):
                open_url("https://github.com/org/repo")

    def test_urlerror_propagates(self, monkeypatch):
        import urllib.error
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        self._set_config(monkeypatch, [])
        mock_opener = MagicMock()
        mock_opener.open.side_effect = urllib.error.URLError("refused")
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            with pytest.raises(urllib.error.URLError):
                open_url("https://example.com/file")

    def test_timeout_propagates(self, monkeypatch):
        import socket
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication.http import open_url
        self._set_config(monkeypatch, [])
        mock_opener = MagicMock()
        mock_opener.open.side_effect = socket.timeout("timed out")
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            with pytest.raises(socket.timeout):
                open_url("https://example.com/file")


# ---------------------------------------------------------------------------
# GitHub CLI β€” registered provider HTTP wiring
# ---------------------------------------------------------------------------


class TestGitHubCliAuthenticatedHttp:
    @pytest.fixture(autouse=True)
    def isolate_config_and_cache(self, monkeypatch):
        from specify_cli.authentication import http

        provider = get_provider("github")
        assert isinstance(provider, GitHubAuth)
        monkeypatch.setattr(provider, "_github_cli_cache", {})
        monkeypatch.setattr(http, "_config_override", [_github_cli_entry()])

    @pytest.mark.parametrize("helper", ["build_request", "open_url"])
    def test_resolved_token_becomes_bearer_header(self, helper):
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication import http

        result = MagicMock(returncode=0, stdout="  cli-token\n")
        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")
        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=result,
        ) as run, patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener:
            if helper == "build_request":
                request = http.build_request("https://api.github.com/repos/org/repo")
                build_opener.assert_not_called()
            else:
                response = http.open_url("https://api.github.com/repos/org/repo")
                opener = build_opener.return_value
                assert response is opener.open.return_value
                opener.open.assert_called_once()
                request = opener.open.call_args.args[0]

        assert request.get_header("Authorization") == "Bearer cli-token"
        run.assert_called_once_with(
            [executable, "auth", "token", "--hostname", "github.com"],
            capture_output=True,
            text=True,
            timeout=10,
            check=False,
            shell=False,
        )

    @pytest.mark.parametrize("helper", ["build_request", "open_url"])
    def test_acquisition_failure_stops_credential_and_anonymous_fallback(
        self, monkeypatch, helper,
    ):
        from unittest.mock import patch
        from specify_cli.authentication import http

        entry = _github_cli_entry()
        monkeypatch.setattr(http, "_config_override", [
            entry, _github_entry(token="backup-token"),
        ])
        provider = get_provider("github")
        assert isinstance(provider, GitHubAuth)
        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=None,
        ) as which, patch(
            "specify_cli.authentication.github.subprocess.run",
        ) as run, patch.object(
            provider, "resolve_token", wraps=provider.resolve_token,
        ) as resolve, patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener, pytest.raises(GitHubCliAuthError, match="was not found"):
            getattr(http, helper)("https://api.github.com/repos/org/repo")

        resolve.assert_called_once_with(entry)
        which.assert_called_once_with("gh")
        run.assert_not_called()
        build_opener.assert_not_called()

    @pytest.mark.parametrize("target,expected_auth", [
        ("https://codeload.github.com/org/repo/zip", "Bearer cli-token"),
        ("https://unlisted.example.com/archive.zip", None),
    ])
    def test_open_url_wires_declared_redirect_hosts(self, target, expected_auth):
        from unittest.mock import MagicMock, patch
        from specify_cli.authentication import http

        executable = os.path.join(os.path.abspath(os.sep), "opt", "gh", "gh")
        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=executable,
        ), patch(
            "specify_cli.authentication.github.subprocess.run",
            return_value=MagicMock(returncode=0, stdout="cli-token"),
        ), patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener:
            http.open_url("https://github.com/org/repo/archive.zip")

        handler = build_opener.call_args.args[0]
        request = build_opener.return_value.open.call_args.args[0]
        redirected = handler.redirect_request(
            request, io.BytesIO(b""), 302, "Found", {}, target,
        )
        assert redirected is not None
        assert redirected.get_header("Authorization") == expected_auth

    def test_failed_cli_catalog_does_not_abort_other_catalogs(
        self, tmp_path, monkeypatch, capsys,
    ):
        from unittest.mock import MagicMock, patch
        from specify_cli.integrations import IntegrationCatalog, IntegrationCatalogEntry

        catalog = IntegrationCatalog(tmp_path)
        entries = [
            IntegrationCatalogEntry(
                url="https://github.com/org/private/catalog.json",
                name="private", priority=1, install_allowed=True,
            ),
            IntegrationCatalogEntry(
                url="https://catalog.example.com/catalog.json",
                name="public", priority=2, install_allowed=True,
            ),
        ]
        monkeypatch.setattr(catalog, "get_active_catalogs", lambda: entries)
        response = MagicMock()
        response.__enter__.return_value = response
        response.geturl.return_value = entries[1].url
        response.read.side_effect = io.BytesIO(json.dumps({
            "schema_version": "1.0",
            "integrations": {"example": {"name": "Example"}},
        }).encode()).read
        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=None,
        ), patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener:
            build_opener.return_value.open.return_value = response
            results = catalog.search()

        assert [item["id"] for item in results] == ["example"]
        warning = capsys.readouterr().err
        assert "Could not fetch catalog 'private'" in warning
        assert "GitHub CLI ('gh') was not found" in warning
        build_opener.return_value.open.assert_called_once()

    def test_release_check_preserves_cli_failure_reason(self):
        from unittest.mock import patch
        from specify_cli._version import _fetch_latest_release_tag

        with patch(
            "specify_cli.authentication.github.shutil.which",
            return_value=None,
        ), patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener:
            tag, reason = _fetch_latest_release_tag()

        assert tag is None
        assert reason is not None
        assert "GitHub CLI ('gh') was not found" in reason
        assert "offline or timeout" not in reason

        build_opener.assert_not_called()

    @pytest.mark.parametrize("detail", [
        "GitHub CLI ('gh') was not found.",
        "Run 'gh auth login --hostname github.com'.",
    ])
    @pytest.mark.parametrize("command,exit_code", [("check", 0), ("upgrade", 1)])
    def test_release_commands_preserve_cli_failure(
        self, detail, command, exit_code, uv_tool_argv0
    ):
        from unittest.mock import patch
        from typer.testing import CliRunner
        from specify_cli import app, _version

        error = GitHubCliAuthError(
            "GitHub authentication failed for provider 'github': " + detail
        )
        with patch.object(
            GitHubAuth, "_acquire_via_gh_cli", side_effect=error,
        ), patch.object(
            _version, "_get_installed_version", return_value="1.0.0",
        ), patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener, patch.object(_version.subprocess, "run") as run:
            result = CliRunner().invoke(app, ["self", command])

        assert result.exit_code == exit_code, result.output
        output = " ".join(result.output.split())
        assert detail in output
        assert "offline or timeout" not in output
        build_opener.assert_not_called()
        run.assert_not_called()

    @pytest.mark.parametrize("url", [
        "builtin://default",
        "https://github.com/org/repo/catalog.json",
    ])
    def test_bundle_catalog_auth_failure_does_not_use_snapshot(self, url):
        from unittest.mock import patch
        from specify_cli.bundles import BundlerError, adapters
        from specify_cli.bundles.catalogs import CatalogSource, InstallPolicy

        source = CatalogSource(
            id="test", url=url, priority=1,
            install_policy=InstallPolicy.INSTALL_ALLOWED,
        )
        with patch(
            "specify_cli.authentication.github.shutil.which", return_value=None,
        ), patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener, patch.object(
            adapters, "_load_packaged_catalog",
        ) as snapshot, pytest.raises(BundlerError, match="was not found") as exc_info:
            adapters.make_catalog_fetcher(allow_network=True)(source)

        assert not isinstance(exc_info.value, adapters._CatalogUnavailable)
        snapshot.assert_not_called()
        build_opener.assert_not_called()

    def test_bundle_reference_auth_failure_is_not_left_unchecked(self, tmp_path):
        from types import SimpleNamespace
        from unittest.mock import patch
        from specify_cli.bundles.manifest import ComponentRef
        from specify_cli.bundles.references import make_reference_checker
        from specify_cli.extensions import ExtensionCatalog

        source = SimpleNamespace(
            name="private", install_allowed=True,
            url="https://github.com/org/repo/catalog.json",
        )
        warnings = []
        with patch.object(
            ExtensionCatalog, "get_active_catalogs", return_value=[source],
        ), patch(
            "specify_cli.authentication.github.shutil.which", return_value=None,
        ), patch(
            "specify_cli.authentication.http.urllib.request.build_opener",
        ) as build_opener:
            check = make_reference_checker(tmp_path, allow_network=True, warnings=warnings)
            problem = check(ComponentRef(
                kind="extensions", id="private-extension", version="1.0.0", source="private",
            ))

        assert problem is not None
        assert "GitHub CLI ('gh') was not found" in problem
        assert warnings == []
        build_opener.assert_not_called()


# ---------------------------------------------------------------------------
# _load_config caching
# ---------------------------------------------------------------------------


class TestLoadConfigCaching:
    def test_config_cached_after_first_load(self, monkeypatch):
        """_load_config() should call load_auth_config only once per process."""
        from unittest.mock import patch
        from specify_cli.authentication import http as _mod
        # Allow the real load path (no override)
        monkeypatch.setattr(_mod, "_config_override", None)
        monkeypatch.setattr(_mod, "_config_cache", None)

        entry = _github_entry()
        call_count = 0

        def fake_load(path=None):
            nonlocal call_count
            call_count += 1
            return [entry]

        with patch.object(_mod, "load_auth_config", side_effect=fake_load):
            _mod._load_config()
            _mod._load_config()
            _mod._load_config()

        assert call_count == 1

    def test_cache_bypassed_by_override(self, monkeypatch):
        """When _config_override is set, the cache is ignored entirely."""
        from specify_cli.authentication import http as _mod
        sentinel = [_github_entry()]
        monkeypatch.setattr(_mod, "_config_override", sentinel)
        monkeypatch.setattr(_mod, "_config_cache", None)

        result = _mod._load_config()
        assert result is sentinel
        # Cache must not have been populated when override is active
        assert _mod._config_cache is None

    def test_failed_load_warns_once_and_caches_empty(self, monkeypatch):
        """A bad auth.json emits exactly one warning and subsequent calls use cache."""
        from unittest.mock import patch
        from specify_cli.authentication import http as _mod
        import warnings as _warnings
        monkeypatch.setattr(_mod, "_config_override", None)
        monkeypatch.setattr(_mod, "_config_cache", None)

        call_count = 0

        def fail_load(path=None):
            nonlocal call_count
            call_count += 1
            raise ValueError("bad config")

        with patch.object(_mod, "load_auth_config", side_effect=fail_load):
            with _warnings.catch_warnings(record=True) as w:
                _warnings.simplefilter("always")
                result1 = _mod._load_config()
                result2 = _mod._load_config()
                result3 = _mod._load_config()

        user_warnings = [x for x in w if issubclass(x.category, UserWarning)]
        assert len(user_warnings) == 1, "Expected exactly one warning"
        # Loader called only once β€” subsequent calls used cache
        assert call_count == 1
        # All calls returned the cached empty list
        assert result1 == result2 == result3 == []


# ---------------------------------------------------------------------------
# Redirect stripping
# ---------------------------------------------------------------------------


class TestRedirectStripping:
    def test_redirect_within_hosts_preserves_auth(self):
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io
        handler = _StripAuthOnRedirect(("github.com", "codeload.github.com"))
        req = Request("https://github.com/org/repo", headers={"Authorization": "Bearer tok"})
        new_req = handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                           "https://codeload.github.com/org/repo/zip")
        assert new_req is not None
        auth = new_req.get_header("Authorization") or new_req.unredirected_hdrs.get("Authorization")
        assert auth == "Bearer tok"

    def test_redirect_outside_hosts_strips_auth(self):
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io
        handler = _StripAuthOnRedirect(("github.com",))
        req = Request("https://github.com/org/repo", headers={"Authorization": "Bearer tok"})
        new_req = handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                           "https://objects.githubusercontent.com/asset")
        assert new_req is not None
        assert new_req.headers.get("Authorization") is None
        assert new_req.unredirected_hdrs.get("Authorization") is None

    @pytest.mark.parametrize(
        ("hosts", "target", "expected_auth"),
        [
            (("*.example.com",), "https://api.example.com/asset", "Bearer tok"),
            (("*.example.com",), "https://example.com/asset", None),
            (("*.example.com",), "https://evil-example.com/asset", None),
            (("gith?b.com",), "https://github.com/asset", None),
            (("[a-z].example.com",), "https://a.example.com/asset", None),
        ],
    )
    def test_redirect_host_patterns_use_literal_safe_matching(
        self, hosts, target, expected_auth
    ):
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io

        handler = _StripAuthOnRedirect(hosts)
        req = Request(
            "https://source.example.org/file",
            headers={"Authorization": "Bearer tok"},
        )
        new_req = handler.redirect_request(
            req, io.BytesIO(b""), 302, "Found", {}, target
        )

        assert new_req is not None
        auth = (
            new_req.get_header("Authorization")
            or new_req.unredirected_hdrs.get("Authorization")
        )
        assert auth == expected_auth

    def test_https_to_http_same_host_redirect_rejected(self):
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io
        import urllib.error

        handler = _StripAuthOnRedirect(("github.com",))
        req = Request("https://github.com/org/repo", headers={"Authorization": "Bearer tok"})

        with pytest.raises(urllib.error.URLError, match="unsafe redirect"):
            handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                     "http://github.com/org/repo")

    def test_redirect_validator_can_reject_before_following_redirect(self):
        import urllib.error
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io

        def reject_http(old_url, new_url):
            if new_url.startswith("http://"):
                raise urllib.error.URLError("scheme downgrade")

        handler = _StripAuthOnRedirect(("github.com",), reject_http)
        req = Request("https://github.com/org/repo", headers={"Authorization": "Bearer tok"})

        with pytest.raises(urllib.error.URLError, match="scheme downgrade"):
            handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                     "http://github.com/org/repo")

    def test_multi_hop_redirect_within_hosts_preserves_auth(self):
        """Auth survives a multi-hop redirect chain within allowed hosts."""
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io
        hosts = ("github.com", "codeload.github.com", "objects-origin.githubusercontent.com")
        handler = _StripAuthOnRedirect(hosts)

        # First hop: github.com β†’ codeload.github.com
        req1 = Request("https://github.com/org/repo", headers={"Authorization": "Bearer tok"})
        req2 = handler.redirect_request(req1, io.BytesIO(b""), 302, "Found", {},
                                        "https://codeload.github.com/org/repo/zip")
        assert req2 is not None
        auth2 = req2.get_header("Authorization") or req2.unredirected_hdrs.get("Authorization")
        assert auth2 == "Bearer tok"

        # Second hop: codeload.github.com β†’ objects-origin.githubusercontent.com
        req3 = handler.redirect_request(req2, io.BytesIO(b""), 302, "Found", {},
                                        "https://objects-origin.githubusercontent.com/asset")
        assert req3 is not None
        auth3 = req3.get_header("Authorization") or req3.unredirected_hdrs.get("Authorization")
        assert auth3 == "Bearer tok"

    def test_malformed_redirect_url_raises_urlerror_not_valueerror(self):
        """A redirect to a malformed URL (unterminated IPv6 bracket) surfaces
        as URLError, which download paths already handle, rather than an
        unhandled ValueError traceback."""
        import urllib.error
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io

        handler = _StripAuthOnRedirect(("github.com",))
        req = Request("https://github.com/org/repo")

        with pytest.raises(urllib.error.URLError):
            handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                     "https://[::1/asset")

    def test_redirect_rejects_https_downgrade(self):
        """HTTPS downloads must not follow redirects to non-local HTTP URLs."""
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io
        import urllib.error
        handler = _StripAuthOnRedirect(("example.com",))
        req = Request("https://example.com/archive.zip")
        with pytest.raises(urllib.error.URLError, match="unsafe redirect"):
            handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                     "http://evil.example.com/archive.zip")

    @pytest.mark.parametrize(
        "target",
        [
            "http://127.0.0.1/internal",
            "https://localhost/internal",
            "https://localhost./internal",
            "https://service.localhost/internal",
            "https://service.localhost./internal",
            "https://127.0.0.2/internal",
            "https://127.1/internal",
            "https://2130706433/internal",
            "https://0x7f000001/internal",
            "https://017700000001/internal",
            "https://0177.0.0.1/internal",
            "https://[::1]/internal",
            "https://[::1%25lo0]/internal",
            "https://[::ffff:127.0.0.1]/internal",
            "https://127%2e0%2e0%2e1/internal",
            "https://%31%32%37.0.0.1/internal",
            "https://127%2E1/internal",
            "https://local%68ost/internal",
            "https://[::ffff:127%2e0.0.1]/internal",
            "https://[::ffff:7f00%3a1]/internal",
            "https://[::ffff%3a127.0.0.1]/internal",
            "https://β„“ocalhost/internal",
            "https://ο½Œο½ο½ƒο½ο½Œο½ˆο½ο½“ο½”/internal",
            "https://127。0。0。1/internal",
            "https://0.0.0.0/internal",
            "https://0/internal",
            "https://00.00.00.00/internal",
            "https://[::]/internal",
            "https://[::ffff:0.0.0.0]/internal",
        ],
    )
    def test_redirect_rejects_remote_to_loopback(self, target):
        """A remote response must not redirect a download into loopback."""
        import io
        import urllib.error
        from urllib.request import Request

        from specify_cli.authentication.http import _StripAuthOnRedirect

        handler = _StripAuthOnRedirect(())
        request = Request("https://example.com/archive.zip")

        with pytest.raises(urllib.error.URLError, match="unsafe redirect"):
            handler.redirect_request(
                request,
                io.BytesIO(b""),
                302,
                "Found",
                {},
                target,
            )

    @pytest.mark.parametrize(
        ("source", "target"),
        [
            (
                "http://localhost:8000/archive.zip",
                "http://127.0.0.1:8001/archive.zip",
            ),
            (
                "http://127.0.0.2:8000/archive.zip",
                "http://127.255.255.254:8001/archive.zip",
            ),
            (
                "https://[0:0:0:0:0:0:0:1]/archive.zip",
                "http://[::1]:8001/archive.zip",
            ),
        ],
    )
    def test_redirect_allows_loopback_to_http_loopback(self, source, target):
        """Local development may continue redirecting between loopback URLs."""
        import io
        from urllib.request import Request

        from specify_cli.authentication.http import _StripAuthOnRedirect

        handler = _StripAuthOnRedirect(())
        request = Request(source)
        redirected = handler.redirect_request(
            request,
            io.BytesIO(b""),
            302,
            "Found",
            {},
            target,
        )

        assert redirected is not None

    def test_multi_hop_remote_to_loopback_chain_is_rejected_at_first_hop(self):
        import io
        import urllib.error
        from urllib.request import Request

        from specify_cli.authentication.http import _StripAuthOnRedirect

        handler = _StripAuthOnRedirect(())
        request = Request("https://example.com/archive.zip")

        with pytest.raises(urllib.error.URLError, match="unsafe redirect"):
            handler.redirect_request(
                request,
                io.BytesIO(b""),
                302,
                "Found",
                {},
                "https://localhost:4443/hop",
            )

    @pytest.mark.parametrize(
        "target",
        [
            "https://example.com:notaport/archive.zip",
            "https://example.com:+443/archive.zip",
            "https://example.com:65536/archive.zip",
        ],
    )
    def test_malformed_redirect_port_raises_urlerror(self, target):
        import io
        import urllib.error
        from urllib.request import Request

        from specify_cli.authentication.http import _StripAuthOnRedirect

        handler = _StripAuthOnRedirect(())
        request = Request("https://example.com/archive.zip")

        with pytest.raises(urllib.error.URLError, match="malformed redirect URL"):
            handler.redirect_request(
                request,
                io.BytesIO(b""),
                302,
                "Found",
                {},
                target,
            )

    def test_strict_redirect_error_describes_target_and_allowed_localhost(self):
        from specify_cli.authentication.http import _StripAuthOnRedirect
        from urllib.request import Request
        import io
        import urllib.error

        handler = _StripAuthOnRedirect(("example.com",))
        req = Request("https://example.com/archive.zip")

        with pytest.raises(urllib.error.URLError) as exc_info:
            handler.redirect_request(req, io.BytesIO(b""), 302, "Found", {},
                                     "http://evil.example.com/archive.zip")

        error_message = str(exc_info.value)
        assert "http://evil.example.com/archive.zip" in error_message
        assert "localhost" in error_message
        assert "127.0.0.1" in error_message
        assert "::1" in error_message


# ---------------------------------------------------------------------------
# _fetch_latest_release_tag delegation
# ---------------------------------------------------------------------------


class TestFetchLatestReleaseTagDelegation:
    def _set_config(self, monkeypatch, entries):
        from specify_cli.authentication import http as _mod
        monkeypatch.setattr(_mod, "_config_override", entries)

    def _capture_request(self):
        import json as _json
        from unittest.mock import MagicMock
        captured: dict = {}
        def side_effect(req, timeout=None):
            captured["request"] = req
            body = _json.dumps({"tag_name": "v9.9.9"}).encode()
            resp = MagicMock()
            resp.read.side_effect = io.BytesIO(body).read
            cm = MagicMock()
            cm.__enter__.return_value = resp
            cm.__exit__.return_value = False
            return cm
        return captured, side_effect

    def test_gh_token_forwarded_when_configured(self, monkeypatch):
        from unittest.mock import MagicMock, patch
        from specify_cli._version import _fetch_latest_release_tag
        monkeypatch.setenv("GH_TOKEN", "forwarded-sentinel")
        self._set_config(monkeypatch, [_github_entry()])
        captured, side_effect = self._capture_request()
        mock_opener = MagicMock()
        mock_opener.open.side_effect = side_effect
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            _fetch_latest_release_tag()
        assert captured["request"].get_header("Authorization") == "Bearer forwarded-sentinel"

    def test_no_config_means_no_auth(self, monkeypatch):
        from unittest.mock import MagicMock, patch
        from specify_cli._version import _fetch_latest_release_tag
        self._set_config(monkeypatch, [])
        captured, side_effect = self._capture_request()
        # The unauthenticated path uses the strict redirect opener too.
        mock_opener = MagicMock()
        mock_opener.open.side_effect = side_effect
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            _fetch_latest_release_tag()
        assert captured["request"].get_header("Authorization") is None

    def test_accept_header_present(self, monkeypatch):
        from unittest.mock import MagicMock, patch
        from specify_cli._version import _fetch_latest_release_tag
        self._set_config(monkeypatch, [])
        captured, side_effect = self._capture_request()
        mock_opener = MagicMock()
        mock_opener.open.side_effect = side_effect
        with patch("specify_cli.authentication.http.urllib.request.build_opener", return_value=mock_opener):
            _fetch_latest_release_tag()
        assert captured["request"].get_header("Accept") == "application/vnd.github+json"


# ---------------------------------------------------------------------------
# github_provider_hosts
# ---------------------------------------------------------------------------


class TestGithubProviderHosts:
    """Tests for github_provider_hosts() β€” the GHES host allowlist source."""

    def _set_config(self, monkeypatch, entries):
        from specify_cli.authentication import http as _auth_http
        monkeypatch.setattr(_auth_http, "_config_override", entries)

    def test_returns_hosts_from_github_entries(self, monkeypatch):
        from specify_cli.authentication.http import github_provider_hosts
        self._set_config(monkeypatch, [
            AuthConfigEntry(hosts=("ghes.example", "raw.ghes.example"),
                            provider="github", auth="bearer", token="t"),
        ])
        assert github_provider_hosts() == ("ghes.example", "raw.ghes.example")

    def test_empty_when_no_config(self, monkeypatch):
        from specify_cli.authentication.http import github_provider_hosts
        self._set_config(monkeypatch, [])
        assert github_provider_hosts() == ()

    def test_ignores_non_github_providers(self, monkeypatch):
        from specify_cli.authentication.http import github_provider_hosts
        self._set_config(monkeypatch, [
            AuthConfigEntry(hosts=("dev.azure.com",), provider="azure-devops",
                            auth="basic-pat", token="t"),
        ])
        assert github_provider_hosts() == ()

    def test_unions_multiple_github_entries(self, monkeypatch):
        from specify_cli.authentication.http import github_provider_hosts
        self._set_config(monkeypatch, [
            AuthConfigEntry(hosts=("ghes.example",), provider="github", auth="bearer", token="t"),
            AuthConfigEntry(hosts=("github.com",), provider="github", auth="bearer", token="t"),
        ])
        assert github_provider_hosts() == ("ghes.example", "github.com")