Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

379 lines · 12.3 KiB · Python

Last changed by

Type-check test_auth.py (#665)Florimond Mancabefore adoption49e4d15

History of this file

Take it

1import hashlib2import json3import os4import typing56import pytest78from httpx import URL, Client, DigestAuth, ProtocolError, Request, Response9from httpx.config import CertTypes, TimeoutTypes, VerifyTypes10from httpx.dispatch.base import Dispatcher111213class MockDispatch(Dispatcher):14    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:15        self.auth_header = auth_header16        self.status_code = status_code1718    async def send(19        self,20        request: Request,21        verify: VerifyTypes = None,22        cert: CertTypes = None,23        timeout: TimeoutTypes = None,24    ) -> Response:25        headers = [("www-authenticate", self.auth_header)] if self.auth_header else []26        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()27        return Response(28            self.status_code, headers=headers, content=body, request=request29        )303132class MockDigestAuthDispatch(Dispatcher):33    def __init__(34        self,35        algorithm: str = "SHA-256",36        send_response_after_attempt: int = 1,37        qop: str = "auth",38        regenerate_nonce: bool = True,39    ) -> None:40        self.algorithm = algorithm41        self.send_response_after_attempt = send_response_after_attempt42        self.qop = qop43        self._regenerate_nonce = regenerate_nonce44        self._response_count = 04546    async def send(47        self,48        request: Request,49        verify: VerifyTypes = None,50        cert: CertTypes = None,51        timeout: TimeoutTypes = None,52    ) -> Response:53        if self._response_count < self.send_response_after_attempt:54            return self.challenge_send(request)5556        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()57        return Response(200, content=body, request=request)5859    def challenge_send(self, request: Request) -> Response:60        self._response_count += 161        nonce = (62            hashlib.sha256(os.urandom(8)).hexdigest()63            if self._regenerate_nonce64            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"65        )66        challenge_data = {67            "nonce": nonce,68            "qop": self.qop,69            "opaque": (70                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"71            ),72            "algorithm": self.algorithm,73            "stale": "FALSE",74        }75        challenge_str = ", ".join(76            '{}="{}"'.format(key, value)77            for key, value in challenge_data.items()78            if value79        )8081        headers = [82            ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)83        ]84        return Response(401, headers=headers, content=b"", request=request)858687@pytest.mark.asyncio88async def test_basic_auth() -> None:89    url = "https://example.org/"90    auth = ("tomchristie", "password123")9192    client = Client(dispatch=MockDispatch())93    response = await client.get(url, auth=auth)9495    assert response.status_code == 20096    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}979899@pytest.mark.asyncio100async def test_basic_auth_in_url() -> None:101    url = "https://tomchristie:password123@example.org/"102103    client = Client(dispatch=MockDispatch())104    response = await client.get(url)105106    assert response.status_code == 200107    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}108109110@pytest.mark.asyncio111async def test_basic_auth_on_session() -> None:112    url = "https://example.org/"113    auth = ("tomchristie", "password123")114115    client = Client(dispatch=MockDispatch(), auth=auth)116    response = await client.get(url)117118    assert response.status_code == 200119    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}120121122@pytest.mark.asyncio123async def test_custom_auth() -> None:124    url = "https://example.org/"125126    def auth(request: Request) -> Request:127        request.headers["Authorization"] = "Token 123"128        return request129130    client = Client(dispatch=MockDispatch())131    response = await client.get(url, auth=auth)132133    assert response.status_code == 200134    assert response.json() == {"auth": "Token 123"}135136137@pytest.mark.asyncio138async def test_netrc_auth() -> None:139    os.environ["NETRC"] = "tests/.netrc"140    url = "http://netrcexample.org"141142    client = Client(dispatch=MockDispatch())143    response = await client.get(url)144145    assert response.status_code == 200146    assert response.json() == {147        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"148    }149150151@pytest.mark.asyncio152async def test_auth_header_has_priority_over_netrc() -> None:153    os.environ["NETRC"] = "tests/.netrc"154    url = "http://netrcexample.org"155156    client = Client(dispatch=MockDispatch())157    response = await client.get(url, headers={"Authorization": "Override"})158159    assert response.status_code == 200160    assert response.json() == {"auth": "Override"}161162163@pytest.mark.asyncio164async def test_trust_env_auth() -> None:165    os.environ["NETRC"] = "tests/.netrc"166    url = "http://netrcexample.org"167168    client = Client(dispatch=MockDispatch(), trust_env=False)169    response = await client.get(url)170171    assert response.status_code == 200172    assert response.json() == {"auth": None}173174    client = Client(dispatch=MockDispatch(), trust_env=True)175    response = await client.get(url)176177    assert response.status_code == 200178    assert response.json() == {179        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"180    }181182183def test_auth_hidden_url() -> None:184    url = "http://example-username:example-password@example.org/"185    expected = "URL('http://example-username:[secure]@example.org/')"186    assert url == URL(url)187    assert expected == repr(URL(url))188189190@pytest.mark.asyncio191async def test_auth_hidden_header() -> None:192    url = "https://example.org/"193    auth = ("example-username", "example-password")194195    client = Client(dispatch=MockDispatch())196    response = await client.get(url, auth=auth)197198    assert "'authorization': '[secure]'" in str(response.request.headers)199200201@pytest.mark.asyncio202async def test_auth_invalid_type() -> None:203    url = "https://example.org/"204    client = Client(205        dispatch=MockDispatch(), auth="not a tuple, not a callable",  # type: ignore206    )207    with pytest.raises(TypeError):208        await client.get(url)209210211@pytest.mark.asyncio212async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:213    url = "https://example.org/"214    auth = DigestAuth(username="tomchristie", password="password123")215216    client = Client(dispatch=MockDispatch())217    response = await client.get(url, auth=auth)218219    assert response.status_code == 200220    assert response.json() == {"auth": None}221222223@pytest.mark.asyncio224async def test_digest_auth_200_response_including_digest_auth_header() -> None:225    url = "https://example.org/"226    auth = DigestAuth(username="tomchristie", password="password123")227    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'228229    client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=200))230    response = await client.get(url, auth=auth)231232    assert response.status_code == 200233    assert response.json() == {"auth": None}234235236@pytest.mark.asyncio237async def test_digest_auth_401_response_without_digest_auth_header() -> None:238    url = "https://example.org/"239    auth = DigestAuth(username="tomchristie", password="password123")240241    client = Client(dispatch=MockDispatch(auth_header="", status_code=401))242    response = await client.get(url, auth=auth)243244    assert response.status_code == 401245    assert response.json() == {"auth": None}246247248@pytest.mark.parametrize(249    "algorithm,expected_hash_length,expected_response_length",250    [251        ("MD5", 64, 32),252        ("MD5-SESS", 64, 32),253        ("SHA", 64, 40),254        ("SHA-SESS", 64, 40),255        ("SHA-256", 64, 64),256        ("SHA-256-SESS", 64, 64),257        ("SHA-512", 64, 128),258        ("SHA-512-SESS", 64, 128),259    ],260)261@pytest.mark.asyncio262async def test_digest_auth(263    algorithm: str, expected_hash_length: int, expected_response_length: int264) -> None:265    url = "https://example.org/"266    auth = DigestAuth(username="tomchristie", password="password123")267268    client = Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm))269    response = await client.get(url, auth=auth)270271    assert response.status_code == 200272    authorization = typing.cast(dict, response.json())["auth"]273    scheme, _, fields = authorization.partition(" ")274    assert scheme == "Digest"275276    response_fields = [field.strip() for field in fields.split(",")]277    digest_data = dict(field.split("=") for field in response_fields)278279    assert digest_data["username"] == '"tomchristie"'280    assert digest_data["realm"] == '"httpx@example.org"'281    assert "nonce" in digest_data282    assert digest_data["uri"] == '"/"'283    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes284    assert len(digest_data["opaque"]) == expected_hash_length + 2285    assert digest_data["algorithm"] == algorithm286    assert digest_data["qop"] == "auth"287    assert digest_data["nc"] == "00000001"288    assert len(digest_data["cnonce"]) == 16 + 2289290291@pytest.mark.asyncio292async def test_digest_auth_no_specified_qop() -> None:293    url = "https://example.org/"294    auth = DigestAuth(username="tomchristie", password="password123")295296    client = Client(dispatch=MockDigestAuthDispatch(qop=""))297    response = await client.get(url, auth=auth)298299    assert response.status_code == 200300    authorization = typing.cast(dict, response.json())["auth"]301    scheme, _, fields = authorization.partition(" ")302    assert scheme == "Digest"303304    response_fields = [field.strip() for field in fields.split(",")]305    digest_data = dict(field.split("=") for field in response_fields)306307    assert "qop" not in digest_data308    assert "nc" not in digest_data309    assert "cnonce" not in digest_data310    assert digest_data["username"] == '"tomchristie"'311    assert digest_data["realm"] == '"httpx@example.org"'312    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes313    assert digest_data["uri"] == '"/"'314    assert len(digest_data["response"]) == 64 + 2315    assert len(digest_data["opaque"]) == 64 + 2316    assert digest_data["algorithm"] == "SHA-256"317318319@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))320@pytest.mark.asyncio321async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:322    url = "https://example.org/"323    auth = DigestAuth(username="tomchristie", password="password123")324325    client = Client(dispatch=MockDigestAuthDispatch(qop=qop))326    await client.get(url, auth=auth)327328329@pytest.mark.asyncio330async def test_digest_auth_qop_auth_int_not_implemented() -> None:331    url = "https://example.org/"332    auth = DigestAuth(username="tomchristie", password="password123")333    client = Client(dispatch=MockDigestAuthDispatch(qop="auth-int"))334335    with pytest.raises(NotImplementedError):336        await client.get(url, auth=auth)337338339@pytest.mark.asyncio340async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:341    url = "https://example.org/"342    auth = DigestAuth(username="tomchristie", password="password123")343    client = Client(dispatch=MockDigestAuthDispatch(qop="not-auth"))344345    with pytest.raises(ProtocolError):346        await client.get(url, auth=auth)347348349@pytest.mark.asyncio350async def test_digest_auth_incorrect_credentials() -> None:351    url = "https://example.org/"352    auth = DigestAuth(username="tomchristie", password="password123")353354    client = Client(dispatch=MockDigestAuthDispatch(send_response_after_attempt=2))355    response = await client.get(url, auth=auth)356357    assert response.status_code == 401358359360@pytest.mark.parametrize(361    "auth_header",362    [363        'Digest realm="httpx@example.org", qop="auth"',  # missing fields364        'realm="httpx@example.org", qop="auth"',  # not starting with Digest365        'DigestZ realm="httpx@example.org", qop="auth"'366        'qop="auth,auth-int",nonce="abc",opaque="xyz"',367        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list368    ],369)370@pytest.mark.asyncio371async def test_digest_auth_raises_protocol_error_on_malformed_header(372    auth_header: str,373) -> None:374    url = "https://example.org/"375    auth = DigestAuth(username="tomchristie", password="password123")376    client = Client(dispatch=MockDispatch(auth_header=auth_header, status_code=401))377378    with pytest.raises(ProtocolError):379        await client.get(url, auth=auth)