Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

693 lines · 21.7 KiB · Python

Last changed by

Refactor test_auth.py to use `MockTransport` class. (#1288)Tom Christiebefore adoption2d6c30d

History of this file

Take it

1"""2Integration tests for authentication.34Unit tests for auth classes also exist in tests/test_auth.py5"""6import asyncio7import hashlib8import json9import os10import threading11import typing1213import pytest1415import httpx16from httpx import (17    URL,18    Auth,19    BasicAuth,20    DigestAuth,21    ProtocolError,22    Request,23    RequestBodyUnavailable,24    Response,25)26from tests.utils import AsyncMockTransport, MockTransport2728from ..common import FIXTURES_DIR293031class App:32    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:33        self.auth_header = auth_header34        self.status_code = status_code3536    def __call__(self, request: httpx.Request) -> httpx.Response:37        headers = {"www-authenticate": self.auth_header} if self.auth_header else {}38        data = {"auth": request.headers.get("Authorization")}39        content = json.dumps(data).encode("utf-8")40        return httpx.Response(self.status_code, headers=headers, content=content)414243class DigestApp:44    def __init__(45        self,46        algorithm: str = "SHA-256",47        send_response_after_attempt: int = 1,48        qop: str = "auth",49        regenerate_nonce: bool = True,50    ) -> None:51        self.algorithm = algorithm52        self.send_response_after_attempt = send_response_after_attempt53        self.qop = qop54        self._regenerate_nonce = regenerate_nonce55        self._response_count = 05657    def __call__(self, request: httpx.Request) -> httpx.Response:58        if self._response_count < self.send_response_after_attempt:59            return self.challenge_send(request)6061        data = {"auth": request.headers.get("Authorization")}62        content = json.dumps(data).encode("utf-8")63        return httpx.Response(200, content=content)6465    def challenge_send(self, request: httpx.Request) -> httpx.Response:66        self._response_count += 167        nonce = (68            hashlib.sha256(os.urandom(8)).hexdigest()69            if self._regenerate_nonce70            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"71        )72        challenge_data = {73            "nonce": nonce,74            "qop": self.qop,75            "opaque": (76                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"77            ),78            "algorithm": self.algorithm,79            "stale": "FALSE",80        }81        challenge_str = ", ".join(82            '{}="{}"'.format(key, value)83            for key, value in challenge_data.items()84            if value85        )8687        headers = {88            "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',89        }90        return Response(401, headers=headers)919293class RepeatAuth(Auth):94    """95    A mock authentication scheme that requires clients to send96    the request a fixed number of times, and then send a last request containing97    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers98    of intermediate responses.99    """100101    requires_request_body = True102103    def __init__(self, repeat: int):104        self.repeat = repeat105106    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:107        nonces = []108109        for index in range(self.repeat):110            request.headers["Authorization"] = f"Repeat {index}"111            response = yield request112            nonces.append(response.headers["www-authenticate"])113114        key = ".".join(nonces)115        request.headers["Authorization"] = f"Repeat {key}"116        yield request117118119class ResponseBodyAuth(Auth):120    """121    A mock authentication scheme that requires clients to send an 'Authorization'122    header, then send back the contents of the response in the 'Authorization'123    header.124    """125126    requires_response_body = True127128    def __init__(self, token):129        self.token = token130131    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:132        request.headers["Authorization"] = self.token133        response = yield request134        data = response.text135        request.headers["Authorization"] = data136        yield request137138139class SyncOrAsyncAuth(Auth):140    """141    A mock authentication scheme that uses a different implementation for the142    sync and async cases.143    """144145    def __init__(self) -> None:146        self._lock = threading.Lock()147        self._async_lock = asyncio.Lock()148149    def sync_auth_flow(150        self, request: Request151    ) -> typing.Generator[Request, Response, None]:152        with self._lock:153            request.headers["Authorization"] = "sync-auth"154        yield request155156    async def async_auth_flow(157        self, request: Request158    ) -> typing.AsyncGenerator[Request, Response]:159        async with self._async_lock:160            request.headers["Authorization"] = "async-auth"161        yield request162163164@pytest.mark.asyncio165async def test_basic_auth() -> None:166    url = "https://example.org/"167    auth = ("tomchristie", "password123")168    app = App()169170    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:171        response = await client.get(url, auth=auth)172173    assert response.status_code == 200174    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}175176177@pytest.mark.asyncio178async def test_basic_auth_in_url() -> None:179    url = "https://tomchristie:password123@example.org/"180    app = App()181182    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:183        response = await client.get(url)184185    assert response.status_code == 200186    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}187188189@pytest.mark.asyncio190async def test_basic_auth_on_session() -> None:191    url = "https://example.org/"192    auth = ("tomchristie", "password123")193    app = App()194195    async with httpx.AsyncClient(196        transport=AsyncMockTransport(app), auth=auth197    ) as client:198        response = await client.get(url)199200    assert response.status_code == 200201    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}202203204@pytest.mark.asyncio205async def test_custom_auth() -> None:206    url = "https://example.org/"207    app = App()208209    def auth(request: Request) -> Request:210        request.headers["Authorization"] = "Token 123"211        return request212213    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:214        response = await client.get(url, auth=auth)215216    assert response.status_code == 200217    assert response.json() == {"auth": "Token 123"}218219220@pytest.mark.asyncio221async def test_netrc_auth() -> None:222    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")223    url = "http://netrcexample.org"224    app = App()225226    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:227        response = await client.get(url)228229    assert response.status_code == 200230    assert response.json() == {231        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"232    }233234235@pytest.mark.asyncio236async def test_auth_header_has_priority_over_netrc() -> None:237    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")238    url = "http://netrcexample.org"239    app = App()240241    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:242        response = await client.get(url, headers={"Authorization": "Override"})243244    assert response.status_code == 200245    assert response.json() == {"auth": "Override"}246247248@pytest.mark.asyncio249async def test_trust_env_auth() -> None:250    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")251    url = "http://netrcexample.org"252    app = App()253254    async with httpx.AsyncClient(255        transport=AsyncMockTransport(app), trust_env=False256    ) as client:257        response = await client.get(url)258259    assert response.status_code == 200260    assert response.json() == {"auth": None}261262    async with httpx.AsyncClient(263        transport=AsyncMockTransport(app), trust_env=True264    ) as client:265        response = await client.get(url)266267    assert response.status_code == 200268    assert response.json() == {269        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"270    }271272273@pytest.mark.asyncio274async def test_auth_disable_per_request() -> None:275    url = "https://example.org/"276    auth = ("tomchristie", "password123")277    app = App()278279    async with httpx.AsyncClient(280        transport=AsyncMockTransport(app), auth=auth281    ) as client:282        response = await client.get(url, auth=None)283284    assert response.status_code == 200285    assert response.json() == {"auth": None}286287288def test_auth_hidden_url() -> None:289    url = "http://example-username:example-password@example.org/"290    expected = "URL('http://example-username:[secure]@example.org/')"291    assert url == URL(url)292    assert expected == repr(URL(url))293294295@pytest.mark.asyncio296async def test_auth_hidden_header() -> None:297    url = "https://example.org/"298    auth = ("example-username", "example-password")299    app = App()300301    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:302        response = await client.get(url, auth=auth)303304    assert "'authorization': '[secure]'" in str(response.request.headers)305306307@pytest.mark.asyncio308async def test_auth_property() -> None:309    app = App()310311    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:312        assert client.auth is None313314        client.auth = ("tomchristie", "password123")  # type: ignore315        assert isinstance(client.auth, BasicAuth)316317        url = "https://example.org/"318        response = await client.get(url)319        assert response.status_code == 200320        assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}321322323@pytest.mark.asyncio324async def test_auth_invalid_type() -> None:325    app = App()326327    with pytest.raises(TypeError):328        client = httpx.AsyncClient(329            transport=AsyncMockTransport(app),330            auth="not a tuple, not a callable",  # type: ignore331        )332333    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:334        with pytest.raises(TypeError):335            await client.get(auth="not a tuple, not a callable")  # type: ignore336337        with pytest.raises(TypeError):338            client.auth = "not a tuple, not a callable"  # type: ignore339340341@pytest.mark.asyncio342async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:343    url = "https://example.org/"344    auth = DigestAuth(username="tomchristie", password="password123")345    app = App()346347    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:348        response = await client.get(url, auth=auth)349350    assert response.status_code == 200351    assert response.json() == {"auth": None}352    assert len(response.history) == 0353354355def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:356    url = "https://example.org/"357    auth = DigestAuth(username="tomchristie", password="password123")358    auth_header = "Token ..."359    app = App(auth_header=auth_header, status_code=401)360361    client = httpx.Client(transport=MockTransport(app))362    response = client.get(url, auth=auth)363364    assert response.status_code == 401365    assert response.json() == {"auth": None}366    assert len(response.history) == 0367368369@pytest.mark.asyncio370async def test_digest_auth_200_response_including_digest_auth_header() -> None:371    url = "https://example.org/"372    auth = DigestAuth(username="tomchristie", password="password123")373    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'374    app = App(auth_header=auth_header, status_code=200)375376    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:377        response = await client.get(url, auth=auth)378379    assert response.status_code == 200380    assert response.json() == {"auth": None}381    assert len(response.history) == 0382383384@pytest.mark.asyncio385async def test_digest_auth_401_response_without_digest_auth_header() -> None:386    url = "https://example.org/"387    auth = DigestAuth(username="tomchristie", password="password123")388    app = App(auth_header="", status_code=401)389390    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:391        response = await client.get(url, auth=auth)392393    assert response.status_code == 401394    assert response.json() == {"auth": None}395    assert len(response.history) == 0396397398@pytest.mark.parametrize(399    "algorithm,expected_hash_length,expected_response_length",400    [401        ("MD5", 64, 32),402        ("MD5-SESS", 64, 32),403        ("SHA", 64, 40),404        ("SHA-SESS", 64, 40),405        ("SHA-256", 64, 64),406        ("SHA-256-SESS", 64, 64),407        ("SHA-512", 64, 128),408        ("SHA-512-SESS", 64, 128),409    ],410)411@pytest.mark.asyncio412async def test_digest_auth(413    algorithm: str, expected_hash_length: int, expected_response_length: int414) -> None:415    url = "https://example.org/"416    auth = DigestAuth(username="tomchristie", password="password123")417    app = DigestApp(algorithm=algorithm)418419    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:420        response = await client.get(url, auth=auth)421422    assert response.status_code == 200423    assert len(response.history) == 1424425    authorization = typing.cast(dict, response.json())["auth"]426    scheme, _, fields = authorization.partition(" ")427    assert scheme == "Digest"428429    response_fields = [field.strip() for field in fields.split(",")]430    digest_data = dict(field.split("=") for field in response_fields)431432    assert digest_data["username"] == '"tomchristie"'433    assert digest_data["realm"] == '"httpx@example.org"'434    assert "nonce" in digest_data435    assert digest_data["uri"] == '"/"'436    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes437    assert len(digest_data["opaque"]) == expected_hash_length + 2438    assert digest_data["algorithm"] == algorithm439    assert digest_data["qop"] == "auth"440    assert digest_data["nc"] == "00000001"441    assert len(digest_data["cnonce"]) == 16 + 2442443444@pytest.mark.asyncio445async def test_digest_auth_no_specified_qop() -> None:446    url = "https://example.org/"447    auth = DigestAuth(username="tomchristie", password="password123")448    app = DigestApp(qop="")449450    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:451        response = await client.get(url, auth=auth)452453    assert response.status_code == 200454    assert len(response.history) == 1455456    authorization = typing.cast(dict, response.json())["auth"]457    scheme, _, fields = authorization.partition(" ")458    assert scheme == "Digest"459460    response_fields = [field.strip() for field in fields.split(",")]461    digest_data = dict(field.split("=") for field in response_fields)462463    assert "qop" not in digest_data464    assert "nc" not in digest_data465    assert "cnonce" not in digest_data466    assert digest_data["username"] == '"tomchristie"'467    assert digest_data["realm"] == '"httpx@example.org"'468    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes469    assert digest_data["uri"] == '"/"'470    assert len(digest_data["response"]) == 64 + 2471    assert len(digest_data["opaque"]) == 64 + 2472    assert digest_data["algorithm"] == "SHA-256"473474475@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))476@pytest.mark.asyncio477async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:478    url = "https://example.org/"479    auth = DigestAuth(username="tomchristie", password="password123")480    app = DigestApp(qop=qop)481482    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:483        response = await client.get(url, auth=auth)484485    assert response.status_code == 200486    assert len(response.history) == 1487488489@pytest.mark.asyncio490async def test_digest_auth_qop_auth_int_not_implemented() -> None:491    url = "https://example.org/"492    auth = DigestAuth(username="tomchristie", password="password123")493    app = DigestApp(qop="auth-int")494495    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:496        with pytest.raises(NotImplementedError):497            await client.get(url, auth=auth)498499500@pytest.mark.asyncio501async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:502    url = "https://example.org/"503    auth = DigestAuth(username="tomchristie", password="password123")504    app = DigestApp(qop="not-auth")505506    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:507        with pytest.raises(ProtocolError):508            await client.get(url, auth=auth)509510511@pytest.mark.asyncio512async def test_digest_auth_incorrect_credentials() -> None:513    url = "https://example.org/"514    auth = DigestAuth(username="tomchristie", password="password123")515    app = DigestApp(send_response_after_attempt=2)516517    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:518        response = await client.get(url, auth=auth)519520    assert response.status_code == 401521    assert len(response.history) == 1522523524@pytest.mark.parametrize(525    "auth_header",526    [527        'Digest realm="httpx@example.org", qop="auth"',  # missing fields528        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list529    ],530)531@pytest.mark.asyncio532async def test_async_digest_auth_raises_protocol_error_on_malformed_header(533    auth_header: str,534) -> None:535    url = "https://example.org/"536    auth = DigestAuth(username="tomchristie", password="password123")537    app = App(auth_header=auth_header, status_code=401)538539    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:540        with pytest.raises(ProtocolError):541            await client.get(url, auth=auth)542543544@pytest.mark.parametrize(545    "auth_header",546    [547        'Digest realm="httpx@example.org", qop="auth"',  # missing fields548        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list549    ],550)551def test_sync_digest_auth_raises_protocol_error_on_malformed_header(552    auth_header: str,553) -> None:554    url = "https://example.org/"555    auth = DigestAuth(username="tomchristie", password="password123")556    app = App(auth_header=auth_header, status_code=401)557558    with httpx.Client(transport=MockTransport(app)) as client:559        with pytest.raises(ProtocolError):560            client.get(url, auth=auth)561562563@pytest.mark.asyncio564async def test_async_auth_history() -> None:565    """566    Test that intermediate requests sent as part of an authentication flow567    are recorded in the response history.568    """569    url = "https://example.org/"570    auth = RepeatAuth(repeat=2)571    app = App(auth_header="abc")572573    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:574        response = await client.get(url, auth=auth)575576    assert response.status_code == 200577    assert response.json() == {"auth": "Repeat abc.abc"}578579    assert len(response.history) == 2580    resp1, resp2 = response.history581    assert resp1.json() == {"auth": "Repeat 0"}582    assert resp2.json() == {"auth": "Repeat 1"}583584    assert len(resp2.history) == 1585    assert resp2.history == [resp1]586587    assert len(resp1.history) == 0588589590def test_sync_auth_history() -> None:591    """592    Test that intermediate requests sent as part of an authentication flow593    are recorded in the response history.594    """595    url = "https://example.org/"596    auth = RepeatAuth(repeat=2)597    app = App(auth_header="abc")598599    with httpx.Client(transport=MockTransport(app)) as client:600        response = client.get(url, auth=auth)601602    assert response.status_code == 200603    assert response.json() == {"auth": "Repeat abc.abc"}604605    assert len(response.history) == 2606    resp1, resp2 = response.history607    assert resp1.json() == {"auth": "Repeat 0"}608    assert resp2.json() == {"auth": "Repeat 1"}609610    assert len(resp2.history) == 1611    assert resp2.history == [resp1]612613    assert len(resp1.history) == 0614615616@pytest.mark.asyncio617async def test_digest_auth_unavailable_streaming_body():618    url = "https://example.org/"619    auth = DigestAuth(username="tomchristie", password="password123")620    app = App()621622    async def streaming_body():623        yield b"Example request body"  # pragma: nocover624625    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:626        with pytest.raises(RequestBodyUnavailable):627            await client.post(url, data=streaming_body(), auth=auth)628629630@pytest.mark.asyncio631async def test_async_auth_reads_response_body() -> None:632    """633    Test that we can read the response body in an auth flow if `requires_response_body`634    is set.635    """636    url = "https://example.org/"637    auth = ResponseBodyAuth("xyz")638    app = App()639640    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:641        response = await client.get(url, auth=auth)642643    assert response.status_code == 200644    assert response.json() == {"auth": '{"auth": "xyz"}'}645646647def test_sync_auth_reads_response_body() -> None:648    """649    Test that we can read the response body in an auth flow if `requires_response_body`650    is set.651    """652    url = "https://example.org/"653    auth = ResponseBodyAuth("xyz")654    app = App()655656    with httpx.Client(transport=MockTransport(app)) as client:657        response = client.get(url, auth=auth)658659    assert response.status_code == 200660    assert response.json() == {"auth": '{"auth": "xyz"}'}661662663@pytest.mark.asyncio664async def test_async_auth() -> None:665    """666    Test that we can use an auth implementation specific to the async case, to667    support cases that require performing I/O or using concurrency primitives (such668    as checking a disk-based cache or fetching a token from a remote auth server).669    """670    url = "https://example.org/"671    auth = SyncOrAsyncAuth()672    app = App()673674    async with httpx.AsyncClient(transport=AsyncMockTransport(app)) as client:675        response = await client.get(url, auth=auth)676677    assert response.status_code == 200678    assert response.json() == {"auth": "async-auth"}679680681def test_sync_auth() -> None:682    """683    Test that we can use an auth implementation specific to the sync case.684    """685    url = "https://example.org/"686    auth = SyncOrAsyncAuth()687    app = App()688689    with httpx.Client(transport=MockTransport(app)) as client:690        response = client.get(url, auth=auth)691692    assert response.status_code == 200693    assert response.json() == {"auth": "sync-auth"}