Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

358 lines · 11.4 KiB · Python

Last changed by

Additional DigestAuth tests (#334)Yeray Diaz Diazbefore adoption1cd9156

History of this file

Take it

1import hashlib2import json3import os45import pytest67from httpx import (8    URL,9    AsyncDispatcher,10    AsyncRequest,11    AsyncResponse,12    CertTypes,13    Client,14    DigestAuth,15    ProtocolError,16    TimeoutTypes,17    VerifyTypes,18)192021class MockDispatch(AsyncDispatcher):22    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23        self.auth_header = auth_header24        self.status_code = status_code2526    async def send(27        self,28        request: AsyncRequest,29        verify: VerifyTypes = None,30        cert: CertTypes = None,31        timeout: TimeoutTypes = None,32    ) -> AsyncResponse:33        headers = [("www-authenticate", self.auth_header)] if self.auth_header else []34        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()35        return AsyncResponse(36            self.status_code, headers=headers, content=body, request=request37        )383940class MockDigestAuthDispatch(AsyncDispatcher):41    def __init__(42        self,43        algorithm: str = "SHA-256",44        send_response_after_attempt: int = 1,45        qop: str = "auth",46        regenerate_nonce: bool = True,47    ) -> None:48        self.algorithm = algorithm49        self.send_response_after_attempt = send_response_after_attempt50        self.qop = qop51        self._regenerate_nonce = regenerate_nonce52        self._response_count = 05354    async def send(55        self,56        request: AsyncRequest,57        verify: VerifyTypes = None,58        cert: CertTypes = None,59        timeout: TimeoutTypes = None,60    ) -> AsyncResponse:61        if self._response_count < self.send_response_after_attempt:62            return self.challenge_send(request)6364        body = json.dumps({"auth": request.headers.get("Authorization")}).encode()65        return AsyncResponse(200, content=body, request=request)6667    def challenge_send(self, request: AsyncRequest) -> AsyncResponse:68        self._response_count += 169        nonce = (70            hashlib.sha256(os.urandom(8)).hexdigest()71            if self._regenerate_nonce72            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"73        )74        challenge_data = {75            "nonce": nonce,76            "qop": self.qop,77            "opaque": (78                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"79            ),80            "algorithm": self.algorithm,81            "stale": "FALSE",82        }83        challenge_str = ", ".join(84            '{}="{}"'.format(key, value)85            for key, value in challenge_data.items()86            if value87        )8889        headers = [90            ("www-authenticate", 'Digest realm="httpx@example.org", ' + challenge_str)91        ]92        return AsyncResponse(401, headers=headers, content=b"", request=request)9394    def reset(self) -> None:95        self._response_count = 0969798def test_basic_auth():99    url = "https://example.org/"100    auth = ("tomchristie", "password123")101102    with Client(dispatch=MockDispatch()) as client:103        response = client.get(url, auth=auth)104105    assert response.status_code == 200106    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}107108109def test_basic_auth_in_url():110    url = "https://tomchristie:password123@example.org/"111112    with Client(dispatch=MockDispatch()) as client:113        response = client.get(url)114115    assert response.status_code == 200116    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}117118119def test_basic_auth_on_session():120    url = "https://example.org/"121    auth = ("tomchristie", "password123")122123    with Client(dispatch=MockDispatch(), auth=auth) as client:124        response = client.get(url)125126    assert response.status_code == 200127    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}128129130def test_custom_auth():131    url = "https://example.org/"132133    def auth(request):134        request.headers["Authorization"] = "Token 123"135        return request136137    with Client(dispatch=MockDispatch()) as client:138        response = client.get(url, auth=auth)139140    assert response.status_code == 200141    assert response.json() == {"auth": "Token 123"}142143144def test_netrc_auth():145    os.environ["NETRC"] = "tests/.netrc"146    url = "http://netrcexample.org"147148    with Client(dispatch=MockDispatch()) as client:149        response = client.get(url)150151    assert response.status_code == 200152    assert response.json() == {153        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"154    }155156157def test_trust_env_auth():158    os.environ["NETRC"] = "tests/.netrc"159    url = "http://netrcexample.org"160161    with Client(dispatch=MockDispatch()) as client:162        response = client.get(url, trust_env=False)163164    assert response.status_code == 200165    assert response.json() == {"auth": None}166167    with Client(dispatch=MockDispatch(), trust_env=False) as client:168        response = client.get(url, trust_env=True)169170    assert response.status_code == 200171    assert response.json() == {172        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"173    }174175176def test_auth_hidden_url():177    url = "http://example-username:example-password@example.org/"178    expected = "URL('http://example-username:[secure]@example.org/')"179    assert url == URL(url)180    assert expected == repr(URL(url))181182183def test_auth_hidden_header():184    url = "https://example.org/"185    auth = ("example-username", "example-password")186187    with Client(dispatch=MockDispatch()) as client:188        response = client.get(url, auth=auth)189190    assert "'authorization': '[secure]'" in str(response.request.headers)191192193def test_auth_invalid_type():194    url = "https://example.org/"195    with Client(dispatch=MockDispatch(), auth="not a tuple, not a callable") as client:196        with pytest.raises(TypeError):197            client.get(url)198199200def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():201    url = "https://example.org/"202    auth = DigestAuth(username="tomchristie", password="password123")203204    with Client(dispatch=MockDispatch()) as client:205        response = client.get(url, auth=auth)206207    assert response.status_code == 200208    assert response.json() == {"auth": None}209210211def test_digest_auth_200_response_including_digest_auth_header_is_returned_as_is():212    url = "https://example.org/"213    auth = DigestAuth(username="tomchristie", password="password123")214    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'215216    with Client(217        dispatch=MockDispatch(auth_header=auth_header, status_code=200)218    ) as client:219        response = client.get(url, auth=auth)220221    assert response.status_code == 200222    assert response.json() == {"auth": None}223224225def test_digest_auth_401_response_without_digest_auth_header_is_returned_as_is():226    url = "https://example.org/"227    auth = DigestAuth(username="tomchristie", password="password123")228229    with Client(dispatch=MockDispatch(auth_header="", status_code=401)) as client:230        response = client.get(url, auth=auth)231232    assert response.status_code == 401233    assert response.json() == {"auth": None}234235236@pytest.mark.parametrize(237    "algorithm,expected_hash_length,expected_response_length",238    [239        ("MD5", 64, 32),240        ("MD5-SESS", 64, 32),241        ("SHA", 64, 40),242        ("SHA-SESS", 64, 40),243        ("SHA-256", 64, 64),244        ("SHA-256-SESS", 64, 64),245        ("SHA-512", 64, 128),246        ("SHA-512-SESS", 64, 128),247    ],248)249def test_digest_auth(algorithm, expected_hash_length, expected_response_length):250    url = "https://example.org/"251    auth = DigestAuth(username="tomchristie", password="password123")252253    with Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm)) as client:254        response = client.get(url, auth=auth)255256    assert response.status_code == 200257    auth = response.json()["auth"]258    assert auth.startswith("Digest ")259260    response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]261    digest_data = dict(field.split("=") for field in response_fields)262263    assert digest_data["username"] == '"tomchristie"'264    assert digest_data["realm"] == '"httpx@example.org"'265    assert "nonce" in digest_data266    assert digest_data["uri"] == '"/"'267    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes268    assert len(digest_data["opaque"]) == expected_hash_length + 2269    assert digest_data["algorithm"] == algorithm270    assert digest_data["qop"] == "auth"271    assert digest_data["nc"] == "00000001"272    assert len(digest_data["cnonce"]) == 16 + 2273274275def test_digest_auth_no_specified_qop():276    url = "https://example.org/"277    auth = DigestAuth(username="tomchristie", password="password123")278279    with Client(dispatch=MockDigestAuthDispatch(qop=None)) as client:280        response = client.get(url, auth=auth)281282    assert response.status_code == 200283    auth = response.json()["auth"]284    assert auth.startswith("Digest ")285286    response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]287    digest_data = dict(field.split("=") for field in response_fields)288289    assert "qop" not in digest_data290    assert "nc" not in digest_data291    assert "cnonce" not in digest_data292    assert digest_data["username"] == '"tomchristie"'293    assert digest_data["realm"] == '"httpx@example.org"'294    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes295    assert digest_data["uri"] == '"/"'296    assert len(digest_data["response"]) == 64 + 2297    assert len(digest_data["opaque"]) == 64 + 2298    assert digest_data["algorithm"] == "SHA-256"299300301@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))302def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):303    url = "https://example.org/"304    auth = DigestAuth(username="tomchristie", password="password123")305306    with Client(dispatch=MockDigestAuthDispatch(qop=qop)) as client:307        client.get(url, auth=auth)308309310def test_digest_auth_qop_auth_int_not_implemented():311    url = "https://example.org/"312    auth = DigestAuth(username="tomchristie", password="password123")313314    with pytest.raises(NotImplementedError):315        with Client(dispatch=MockDigestAuthDispatch(qop="auth-int")) as client:316            client.get(url, auth=auth)317318319def test_digest_auth_qop_must_be_auth_or_auth_int():320    url = "https://example.org/"321    auth = DigestAuth(username="tomchristie", password="password123")322323    with pytest.raises(ProtocolError):324        with Client(dispatch=MockDigestAuthDispatch(qop="not-auth")) as client:325            client.get(url, auth=auth)326327328def test_digest_auth_incorrect_credentials():329    url = "https://example.org/"330    auth = DigestAuth(username="tomchristie", password="password123")331332    with Client(333        dispatch=MockDigestAuthDispatch(send_response_after_attempt=2)334    ) as client:335        response = client.get(url, auth=auth)336337    assert response.status_code == 401338339340@pytest.mark.parametrize(341    "auth_header",342    [343        'Digest realm="httpx@example.org", qop="auth"',  # missing fields344        'realm="httpx@example.org", qop="auth"',  # not starting with Digest345        'DigestZ realm="httpx@example.org", qop="auth"'346        'qop="auth,auth-int",nonce="abc",opaque="xyz"',347        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list348    ],349)350def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):351    url = "https://example.org/"352    auth = DigestAuth(username="tomchristie", password="password123")353354    with pytest.raises(ProtocolError):355        with Client(356            dispatch=MockDispatch(auth_header=auth_header, status_code=401)357        ) as client:358            client.get(url, auth=auth)