Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

355 lines · 11.3 KiB · Python

Last changed by

Get test suite back to ~100% line coverage (#406)Seth Michael Larsonbefore adoption05f5dc2

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)939495def test_basic_auth():96    url = "https://example.org/"97    auth = ("tomchristie", "password123")9899    with Client(dispatch=MockDispatch()) as client:100        response = client.get(url, auth=auth)101102    assert response.status_code == 200103    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}104105106def test_basic_auth_in_url():107    url = "https://tomchristie:password123@example.org/"108109    with Client(dispatch=MockDispatch()) as client:110        response = client.get(url)111112    assert response.status_code == 200113    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}114115116def test_basic_auth_on_session():117    url = "https://example.org/"118    auth = ("tomchristie", "password123")119120    with Client(dispatch=MockDispatch(), auth=auth) as client:121        response = client.get(url)122123    assert response.status_code == 200124    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}125126127def test_custom_auth():128    url = "https://example.org/"129130    def auth(request):131        request.headers["Authorization"] = "Token 123"132        return request133134    with Client(dispatch=MockDispatch()) as client:135        response = client.get(url, auth=auth)136137    assert response.status_code == 200138    assert response.json() == {"auth": "Token 123"}139140141def test_netrc_auth():142    os.environ["NETRC"] = "tests/.netrc"143    url = "http://netrcexample.org"144145    with Client(dispatch=MockDispatch()) as client:146        response = client.get(url)147148    assert response.status_code == 200149    assert response.json() == {150        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"151    }152153154def test_trust_env_auth():155    os.environ["NETRC"] = "tests/.netrc"156    url = "http://netrcexample.org"157158    with Client(dispatch=MockDispatch()) as client:159        response = client.get(url, trust_env=False)160161    assert response.status_code == 200162    assert response.json() == {"auth": None}163164    with Client(dispatch=MockDispatch(), trust_env=False) as client:165        response = client.get(url, trust_env=True)166167    assert response.status_code == 200168    assert response.json() == {169        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"170    }171172173def test_auth_hidden_url():174    url = "http://example-username:example-password@example.org/"175    expected = "URL('http://example-username:[secure]@example.org/')"176    assert url == URL(url)177    assert expected == repr(URL(url))178179180def test_auth_hidden_header():181    url = "https://example.org/"182    auth = ("example-username", "example-password")183184    with Client(dispatch=MockDispatch()) as client:185        response = client.get(url, auth=auth)186187    assert "'authorization': '[secure]'" in str(response.request.headers)188189190def test_auth_invalid_type():191    url = "https://example.org/"192    with Client(dispatch=MockDispatch(), auth="not a tuple, not a callable") as client:193        with pytest.raises(TypeError):194            client.get(url)195196197def test_digest_auth_returns_no_auth_if_no_digest_header_in_response():198    url = "https://example.org/"199    auth = DigestAuth(username="tomchristie", password="password123")200201    with Client(dispatch=MockDispatch()) as client:202        response = client.get(url, auth=auth)203204    assert response.status_code == 200205    assert response.json() == {"auth": None}206207208def test_digest_auth_200_response_including_digest_auth_header_is_returned_as_is():209    url = "https://example.org/"210    auth = DigestAuth(username="tomchristie", password="password123")211    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'212213    with Client(214        dispatch=MockDispatch(auth_header=auth_header, status_code=200)215    ) as client:216        response = client.get(url, auth=auth)217218    assert response.status_code == 200219    assert response.json() == {"auth": None}220221222def test_digest_auth_401_response_without_digest_auth_header_is_returned_as_is():223    url = "https://example.org/"224    auth = DigestAuth(username="tomchristie", password="password123")225226    with Client(dispatch=MockDispatch(auth_header="", status_code=401)) as client:227        response = client.get(url, auth=auth)228229    assert response.status_code == 401230    assert response.json() == {"auth": None}231232233@pytest.mark.parametrize(234    "algorithm,expected_hash_length,expected_response_length",235    [236        ("MD5", 64, 32),237        ("MD5-SESS", 64, 32),238        ("SHA", 64, 40),239        ("SHA-SESS", 64, 40),240        ("SHA-256", 64, 64),241        ("SHA-256-SESS", 64, 64),242        ("SHA-512", 64, 128),243        ("SHA-512-SESS", 64, 128),244    ],245)246def test_digest_auth(algorithm, expected_hash_length, expected_response_length):247    url = "https://example.org/"248    auth = DigestAuth(username="tomchristie", password="password123")249250    with Client(dispatch=MockDigestAuthDispatch(algorithm=algorithm)) as client:251        response = client.get(url, auth=auth)252253    assert response.status_code == 200254    auth = response.json()["auth"]255    assert auth.startswith("Digest ")256257    response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]258    digest_data = dict(field.split("=") for field in response_fields)259260    assert digest_data["username"] == '"tomchristie"'261    assert digest_data["realm"] == '"httpx@example.org"'262    assert "nonce" in digest_data263    assert digest_data["uri"] == '"/"'264    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes265    assert len(digest_data["opaque"]) == expected_hash_length + 2266    assert digest_data["algorithm"] == algorithm267    assert digest_data["qop"] == "auth"268    assert digest_data["nc"] == "00000001"269    assert len(digest_data["cnonce"]) == 16 + 2270271272def test_digest_auth_no_specified_qop():273    url = "https://example.org/"274    auth = DigestAuth(username="tomchristie", password="password123")275276    with Client(dispatch=MockDigestAuthDispatch(qop=None)) as client:277        response = client.get(url, auth=auth)278279    assert response.status_code == 200280    auth = response.json()["auth"]281    assert auth.startswith("Digest ")282283    response_fields = [field.strip() for field in auth[auth.find(" ") :].split(",")]284    digest_data = dict(field.split("=") for field in response_fields)285286    assert "qop" not in digest_data287    assert "nc" not in digest_data288    assert "cnonce" not in digest_data289    assert digest_data["username"] == '"tomchristie"'290    assert digest_data["realm"] == '"httpx@example.org"'291    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes292    assert digest_data["uri"] == '"/"'293    assert len(digest_data["response"]) == 64 + 2294    assert len(digest_data["opaque"]) == 64 + 2295    assert digest_data["algorithm"] == "SHA-256"296297298@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))299def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str):300    url = "https://example.org/"301    auth = DigestAuth(username="tomchristie", password="password123")302303    with Client(dispatch=MockDigestAuthDispatch(qop=qop)) as client:304        client.get(url, auth=auth)305306307def test_digest_auth_qop_auth_int_not_implemented():308    url = "https://example.org/"309    auth = DigestAuth(username="tomchristie", password="password123")310311    with pytest.raises(NotImplementedError):312        with Client(dispatch=MockDigestAuthDispatch(qop="auth-int")) as client:313            client.get(url, auth=auth)314315316def test_digest_auth_qop_must_be_auth_or_auth_int():317    url = "https://example.org/"318    auth = DigestAuth(username="tomchristie", password="password123")319320    with pytest.raises(ProtocolError):321        with Client(dispatch=MockDigestAuthDispatch(qop="not-auth")) as client:322            client.get(url, auth=auth)323324325def test_digest_auth_incorrect_credentials():326    url = "https://example.org/"327    auth = DigestAuth(username="tomchristie", password="password123")328329    with Client(330        dispatch=MockDigestAuthDispatch(send_response_after_attempt=2)331    ) as client:332        response = client.get(url, auth=auth)333334    assert response.status_code == 401335336337@pytest.mark.parametrize(338    "auth_header",339    [340        'Digest realm="httpx@example.org", qop="auth"',  # missing fields341        'realm="httpx@example.org", qop="auth"',  # not starting with Digest342        'DigestZ realm="httpx@example.org", qop="auth"'343        'qop="auth,auth-int",nonce="abc",opaque="xyz"',344        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list345    ],346)347def test_digest_auth_raises_protocol_error_on_malformed_header(auth_header: str):348    url = "https://example.org/"349    auth = DigestAuth(username="tomchristie", password="password123")350351    with pytest.raises(ProtocolError):352        with Client(353            dispatch=MockDispatch(auth_header=auth_header, status_code=401)354        ) as client:355            client.get(url, auth=auth)