from __future__ import annotations

import ssl
import typing
from unittest import mock

import pytest

from urllib3._constant import MOZ_INTERMEDIATE_CIPHERS
from urllib3.exceptions import ProxySchemeUnsupported, SSLError
from urllib3.util import ssl_


class TestSSL:
    @pytest.fixture(autouse=True)
    def _clear_ssl_context_cache(self) -> typing.Iterator[None]:
        from urllib3.util.ssl_ import _SSLContextCache

        _SSLContextCache.clear()
        try:
            yield
        finally:
            _SSLContextCache.clear()

    @pytest.mark.parametrize(
        "addr",
        [
            # IPv6
            "::1",
            "::",
            "FE80::8939:7684:D84b:a5A4%251",
            # IPv4
            "127.0.0.1",
            "8.8.8.8",
            b"127.0.0.1",
            # IPv6 w/ Zone IDs
            "FE80::8939:7684:D84b:a5A4%251",
            b"FE80::8939:7684:D84b:a5A4%251",
            "FE80::8939:7684:D84b:a5A4%19",
            b"FE80::8939:7684:D84b:a5A4%19",
        ],
    )
    def test_is_ipaddress_true(self, addr: bytes | str) -> None:
        assert ssl_.is_ipaddress(addr)

    @pytest.mark.parametrize(
        "addr",
        [
            "www.python.org",
            b"www.python.org",
            "v2.sg.media-imdb.com",
            b"v2.sg.media-imdb.com",
        ],
    )
    def test_is_ipaddress_false(self, addr: bytes | str) -> None:
        assert not ssl_.is_ipaddress(addr)

    def test_create_urllib3_context_set_ciphers(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        ciphers = "ECDH+AESGCM:ECDH+CHACHA20"
        context = mock.create_autospec(ssl_.SSLContext)
        context.set_ciphers = mock.Mock()
        context.options = 0
        monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context)

        assert ssl_.create_urllib3_context(ciphers=ciphers) is context

        assert context.set_ciphers.call_count == 1
        assert context.set_ciphers.call_args == mock.call(ciphers)

    def test_create_urllib3_no_context(self) -> None:
        with mock.patch("urllib3.util.ssl_.SSLContext", None):
            with pytest.raises(TypeError):
                ssl_.create_urllib3_context()

    def test_wrap_socket_given_context_no_load_default_certs(self) -> None:
        context = mock.create_autospec(ssl_.SSLContext)
        context.load_default_certs = mock.Mock()
        context.set_ciphers = mock.Mock()
        context.cert_store_stats = mock.Mock(return_value={"x509_ca": 5})

        sock = mock.Mock()
        ssl_.ssl_wrap_socket(sock, ssl_context=context, use_recommended_ciphers=True)

        context.load_default_certs.assert_not_called()
        context.set_ciphers.assert_not_called()

    def test_wrap_socket_given_ca_certs_no_load_default_certs(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        context = mock.create_autospec(ssl_.SSLContext)
        context.load_default_certs = mock.Mock()
        context.options = 0

        monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context)

        sock = mock.Mock()
        ssl_.ssl_wrap_socket(sock, ca_certs="/tmp/fake-file-1")

        context.load_default_certs.assert_not_called()
        context.load_verify_locations.assert_called_with("/tmp/fake-file-1", None, None)

    def test_wrap_socket_default_loads_default_certs(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        context = mock.create_autospec(ssl_.SSLContext)
        context.load_default_certs = mock.Mock()
        context.options = 0

        monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context)

        sock = mock.Mock()
        ssl_.ssl_wrap_socket(sock)

        context.load_default_certs.assert_called_with()

    def test_wrap_socket_no_ssltransport(self) -> None:
        with mock.patch("urllib3.util.ssl_.SSLTransport", None):
            with pytest.raises(ProxySchemeUnsupported):
                sock = mock.Mock()
                ssl_.ssl_wrap_socket(sock, tls_in_tls=True)

    @pytest.mark.parametrize(
        ["pha", "expected_pha"], [(None, None), (False, True), (True, True)]
    )
    def test_create_urllib3_context_pha(
        self,
        monkeypatch: pytest.MonkeyPatch,
        pha: bool | None,
        expected_pha: bool | None,
    ) -> None:
        context = mock.create_autospec(ssl_.SSLContext)
        context.set_ciphers = mock.Mock()
        context.options = 0
        context.post_handshake_auth = pha
        monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context)

        assert ssl_.create_urllib3_context() is context

        assert context.post_handshake_auth == expected_pha

    def test_create_urllib3_context_default_ciphers(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        context = mock.create_autospec(ssl_.SSLContext)
        context.set_ciphers = mock.Mock()
        context.options = 0

        monkeypatch.setattr(ssl_, "SSLContext", lambda *_, **__: context)
        monkeypatch.setattr(ssl_, "IS_NONSTDLIB", False)

        ssl_.create_urllib3_context()

        if ssl_.SUPPORT_MIN_MAX_TLS_VERSION:
            context.set_ciphers.assert_called_once_with(MOZ_INTERMEDIATE_CIPHERS)
        else:
            context.set_ciphers.assert_not_called()

        context.set_ciphers.reset_mock()
        ssl_.create_urllib3_context(use_recommended_ciphers=False)
        context.set_ciphers.assert_not_called()

    @pytest.mark.parametrize(
        "kwargs",
        [
            {
                "ssl_version": ssl.PROTOCOL_TLSv1,
                "ssl_minimum_version": ssl.TLSVersion.MINIMUM_SUPPORTED,
            },
            {
                "ssl_version": ssl.PROTOCOL_TLSv1,
                "ssl_maximum_version": ssl.TLSVersion.TLSv1,
            },
            {
                "ssl_version": ssl.PROTOCOL_TLSv1,
                "ssl_minimum_version": ssl.TLSVersion.MINIMUM_SUPPORTED,
                "ssl_maximum_version": ssl.TLSVersion.MAXIMUM_SUPPORTED,
            },
        ],
    )
    def test_create_urllib3_context_ssl_version_and_ssl_min_max_version_errors(
        self, kwargs: dict[str, typing.Any]
    ) -> None:
        with pytest.raises(ValueError) as e:
            ssl_.create_urllib3_context(**kwargs)

        assert str(e.value) == (
            "Can't specify both 'ssl_version' and either 'ssl_minimum_version' or 'ssl_maximum_version'"
        )

    @pytest.mark.parametrize(
        "kwargs",
        [
            {
                "ssl_version": ssl.PROTOCOL_TLS,
                "ssl_minimum_version": ssl.TLSVersion.MINIMUM_SUPPORTED,
            },
            {
                "ssl_version": ssl.PROTOCOL_TLS_CLIENT,
                "ssl_minimum_version": ssl.TLSVersion.MINIMUM_SUPPORTED,
            },
            {
                "ssl_version": None,
                "ssl_minimum_version": ssl.TLSVersion.MINIMUM_SUPPORTED,
            },
        ],
    )
    def test_create_urllib3_context_ssl_version_and_ssl_min_max_version_no_warning(
        self, kwargs: dict[str, typing.Any]
    ) -> None:
        ssl_.create_urllib3_context(**kwargs)

    def test_assert_fingerprint_raises_exception_on_none_cert(self) -> None:
        with pytest.raises(SSLError):
            ssl_.assert_fingerprint(
                cert=None, fingerprint="55:39:BF:70:05:12:43:FA:1F:D1:BF:4E:E8:1B:07:1D"
            )

    def test_create_urllib3_context_force_stdlib_backend(self) -> None:
        ctx = ssl_.create_urllib3_context(ssl_backend="ssl")
        # The stdlib backend must always produce a stdlib ``ssl.SSLContext``.
        assert type(ctx).__module__ == "ssl"

    @pytest.mark.parametrize("backend", ["rtls", "utls"])
    def test_create_urllib3_context_force_nonstdlib_backend(self, backend: str) -> None:
        from urllib3.contrib import anytls

        module = getattr(anytls, backend)
        if module is None:
            pytest.skip(f"{backend} backend is not installed")

        ctx = ssl_.create_urllib3_context(ssl_backend=backend)  # type: ignore[arg-type]
        assert type(ctx).__module__.split(".")[0] == backend

    def test_create_urllib3_context_force_unavailable_backend(
        self, monkeypatch: pytest.MonkeyPatch
    ) -> None:
        from urllib3.contrib import anytls

        monkeypatch.setattr(anytls, "utls", None, raising=False)
        with pytest.raises(SSLError, match="utls.* is not available"):
            ssl_.create_urllib3_context(ssl_backend="utls")

    def test_ssl_backend_changes_ssl_context_cache_key(self) -> None:
        # Forcing different backends must not collide in the SSLContext cache.
        from urllib3.util.ssl_ import _SSLContextCache

        keys = []
        for backend in ("ssl", "rtls", "utls", None):
            args = [None] * 16 + [backend]
            with _SSLContextCache.lock(*args):
                keys.append(_SSLContextCache._cursor)
        assert len(set(keys)) == len(keys)

    def test_anytls_getattr_unknown_attribute(self) -> None:
        from urllib3.contrib import anytls

        with pytest.raises(AttributeError):
            anytls.does_not_exist
