Skip to content
Myr

test_auth.py

This file

Path

tests/client/test_auth.py

677 lines · 21.3 KiB · Python

Last changed by

Version 0.15.0 (#1301)Tom Christiebefore adoptionf932af9

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 os9import threading10import typing1112import pytest1314import httpx15from httpx import URL, Auth, BasicAuth, DigestAuth, ProtocolError, Request, Response16from tests.utils import MockTransport1718from ..common import FIXTURES_DIR192021class App:22    def __init__(self, auth_header: str = "", status_code: int = 200) -> None:23        self.auth_header = auth_header24        self.status_code = status_code2526    def __call__(self, request: httpx.Request) -> httpx.Response:27        headers = {"www-authenticate": self.auth_header} if self.auth_header else {}28        data = {"auth": request.headers.get("Authorization")}29        return httpx.Response(self.status_code, headers=headers, json=data)303132class DigestApp: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    def __call__(self, request: httpx.Request) -> httpx.Response:47        if self._response_count < self.send_response_after_attempt:48            return self.challenge_send(request)4950        data = {"auth": request.headers.get("Authorization")}51        return httpx.Response(200, json=data)5253    def challenge_send(self, request: httpx.Request) -> httpx.Response:54        self._response_count += 155        nonce = (56            hashlib.sha256(os.urandom(8)).hexdigest()57            if self._regenerate_nonce58            else "ee96edced2a0b43e4869e96ebe27563f369c1205a049d06419bb51d8aeddf3d3"59        )60        challenge_data = {61            "nonce": nonce,62            "qop": self.qop,63            "opaque": (64                "ee6378f3ee14ebfd2fff54b70a91a7c9390518047f242ab2271380db0e14bda1"65            ),66            "algorithm": self.algorithm,67            "stale": "FALSE",68        }69        challenge_str = ", ".join(70            '{}="{}"'.format(key, value)71            for key, value in challenge_data.items()72            if value73        )7475        headers = {76            "www-authenticate": f'Digest realm="httpx@example.org", {challenge_str}',77        }78        return Response(401, headers=headers)798081class RepeatAuth(Auth):82    """83    A mock authentication scheme that requires clients to send84    the request a fixed number of times, and then send a last request containing85    an aggregation of nonces that the server sent in 'WWW-Authenticate' headers86    of intermediate responses.87    """8889    requires_request_body = True9091    def __init__(self, repeat: int):92        self.repeat = repeat9394    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:95        nonces = []9697        for index in range(self.repeat):98            request.headers["Authorization"] = f"Repeat {index}"99            response = yield request100            nonces.append(response.headers["www-authenticate"])101102        key = ".".join(nonces)103        request.headers["Authorization"] = f"Repeat {key}"104        yield request105106107class ResponseBodyAuth(Auth):108    """109    A mock authentication scheme that requires clients to send an 'Authorization'110    header, then send back the contents of the response in the 'Authorization'111    header.112    """113114    requires_response_body = True115116    def __init__(self, token):117        self.token = token118119    def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:120        request.headers["Authorization"] = self.token121        response = yield request122        data = response.text123        request.headers["Authorization"] = data124        yield request125126127class SyncOrAsyncAuth(Auth):128    """129    A mock authentication scheme that uses a different implementation for the130    sync and async cases.131    """132133    def __init__(self) -> None:134        self._lock = threading.Lock()135        self._async_lock = asyncio.Lock()136137    def sync_auth_flow(138        self, request: Request139    ) -> typing.Generator[Request, Response, None]:140        with self._lock:141            request.headers["Authorization"] = "sync-auth"142        yield request143144    async def async_auth_flow(145        self, request: Request146    ) -> typing.AsyncGenerator[Request, Response]:147        async with self._async_lock:148            request.headers["Authorization"] = "async-auth"149        yield request150151152@pytest.mark.asyncio153async def test_basic_auth() -> None:154    url = "https://example.org/"155    auth = ("tomchristie", "password123")156    app = App()157158    async with httpx.AsyncClient(transport=MockTransport(app)) as client:159        response = await client.get(url, auth=auth)160161    assert response.status_code == 200162    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}163164165@pytest.mark.asyncio166async def test_basic_auth_in_url() -> None:167    url = "https://tomchristie:password123@example.org/"168    app = App()169170    async with httpx.AsyncClient(transport=MockTransport(app)) as client:171        response = await client.get(url)172173    assert response.status_code == 200174    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}175176177@pytest.mark.asyncio178async def test_basic_auth_on_session() -> None:179    url = "https://example.org/"180    auth = ("tomchristie", "password123")181    app = App()182183    async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:184        response = await client.get(url)185186    assert response.status_code == 200187    assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}188189190@pytest.mark.asyncio191async def test_custom_auth() -> None:192    url = "https://example.org/"193    app = App()194195    def auth(request: Request) -> Request:196        request.headers["Authorization"] = "Token 123"197        return request198199    async with httpx.AsyncClient(transport=MockTransport(app)) as client:200        response = await client.get(url, auth=auth)201202    assert response.status_code == 200203    assert response.json() == {"auth": "Token 123"}204205206@pytest.mark.asyncio207async def test_netrc_auth() -> None:208    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")209    url = "http://netrcexample.org"210    app = App()211212    async with httpx.AsyncClient(transport=MockTransport(app)) as client:213        response = await client.get(url)214215    assert response.status_code == 200216    assert response.json() == {217        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"218    }219220221@pytest.mark.asyncio222async def test_auth_header_has_priority_over_netrc() -> None:223    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")224    url = "http://netrcexample.org"225    app = App()226227    async with httpx.AsyncClient(transport=MockTransport(app)) as client:228        response = await client.get(url, headers={"Authorization": "Override"})229230    assert response.status_code == 200231    assert response.json() == {"auth": "Override"}232233234@pytest.mark.asyncio235async def test_trust_env_auth() -> None:236    os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")237    url = "http://netrcexample.org"238    app = App()239240    async with httpx.AsyncClient(241        transport=MockTransport(app), trust_env=False242    ) as client:243        response = await client.get(url)244245    assert response.status_code == 200246    assert response.json() == {"auth": None}247248    async with httpx.AsyncClient(249        transport=MockTransport(app), trust_env=True250    ) as client:251        response = await client.get(url)252253    assert response.status_code == 200254    assert response.json() == {255        "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"256    }257258259@pytest.mark.asyncio260async def test_auth_disable_per_request() -> None:261    url = "https://example.org/"262    auth = ("tomchristie", "password123")263    app = App()264265    async with httpx.AsyncClient(transport=MockTransport(app), auth=auth) as client:266        response = await client.get(url, auth=None)267268    assert response.status_code == 200269    assert response.json() == {"auth": None}270271272def test_auth_hidden_url() -> None:273    url = "http://example-username:example-password@example.org/"274    expected = "URL('http://example-username:[secure]@example.org/')"275    assert url == URL(url)276    assert expected == repr(URL(url))277278279@pytest.mark.asyncio280async def test_auth_hidden_header() -> None:281    url = "https://example.org/"282    auth = ("example-username", "example-password")283    app = App()284285    async with httpx.AsyncClient(transport=MockTransport(app)) as client:286        response = await client.get(url, auth=auth)287288    assert "'authorization': '[secure]'" in str(response.request.headers)289290291@pytest.mark.asyncio292async def test_auth_property() -> None:293    app = App()294295    async with httpx.AsyncClient(transport=MockTransport(app)) as client:296        assert client.auth is None297298        client.auth = ("tomchristie", "password123")  # type: ignore299        assert isinstance(client.auth, BasicAuth)300301        url = "https://example.org/"302        response = await client.get(url)303        assert response.status_code == 200304        assert response.json() == {"auth": "Basic dG9tY2hyaXN0aWU6cGFzc3dvcmQxMjM="}305306307@pytest.mark.asyncio308async def test_auth_invalid_type() -> None:309    app = App()310311    with pytest.raises(TypeError):312        client = httpx.AsyncClient(313            transport=MockTransport(app),314            auth="not a tuple, not a callable",  # type: ignore315        )316317    async with httpx.AsyncClient(transport=MockTransport(app)) as client:318        with pytest.raises(TypeError):319            await client.get(auth="not a tuple, not a callable")  # type: ignore320321        with pytest.raises(TypeError):322            client.auth = "not a tuple, not a callable"  # type: ignore323324325@pytest.mark.asyncio326async def test_digest_auth_returns_no_auth_if_no_digest_header_in_response() -> None:327    url = "https://example.org/"328    auth = DigestAuth(username="tomchristie", password="password123")329    app = App()330331    async with httpx.AsyncClient(transport=MockTransport(app)) as client:332        response = await client.get(url, auth=auth)333334    assert response.status_code == 200335    assert response.json() == {"auth": None}336    assert len(response.history) == 0337338339def test_digest_auth_returns_no_auth_if_alternate_auth_scheme() -> None:340    url = "https://example.org/"341    auth = DigestAuth(username="tomchristie", password="password123")342    auth_header = "Token ..."343    app = App(auth_header=auth_header, status_code=401)344345    client = httpx.Client(transport=MockTransport(app))346    response = client.get(url, auth=auth)347348    assert response.status_code == 401349    assert response.json() == {"auth": None}350    assert len(response.history) == 0351352353@pytest.mark.asyncio354async def test_digest_auth_200_response_including_digest_auth_header() -> None:355    url = "https://example.org/"356    auth = DigestAuth(username="tomchristie", password="password123")357    auth_header = 'Digest realm="realm@host.com",qop="auth",nonce="abc",opaque="xyz"'358    app = App(auth_header=auth_header, status_code=200)359360    async with httpx.AsyncClient(transport=MockTransport(app)) as client:361        response = await client.get(url, auth=auth)362363    assert response.status_code == 200364    assert response.json() == {"auth": None}365    assert len(response.history) == 0366367368@pytest.mark.asyncio369async def test_digest_auth_401_response_without_digest_auth_header() -> None:370    url = "https://example.org/"371    auth = DigestAuth(username="tomchristie", password="password123")372    app = App(auth_header="", status_code=401)373374    async with httpx.AsyncClient(transport=MockTransport(app)) as client:375        response = await client.get(url, auth=auth)376377    assert response.status_code == 401378    assert response.json() == {"auth": None}379    assert len(response.history) == 0380381382@pytest.mark.parametrize(383    "algorithm,expected_hash_length,expected_response_length",384    [385        ("MD5", 64, 32),386        ("MD5-SESS", 64, 32),387        ("SHA", 64, 40),388        ("SHA-SESS", 64, 40),389        ("SHA-256", 64, 64),390        ("SHA-256-SESS", 64, 64),391        ("SHA-512", 64, 128),392        ("SHA-512-SESS", 64, 128),393    ],394)395@pytest.mark.asyncio396async def test_digest_auth(397    algorithm: str, expected_hash_length: int, expected_response_length: int398) -> None:399    url = "https://example.org/"400    auth = DigestAuth(username="tomchristie", password="password123")401    app = DigestApp(algorithm=algorithm)402403    async with httpx.AsyncClient(transport=MockTransport(app)) as client:404        response = await client.get(url, auth=auth)405406    assert response.status_code == 200407    assert len(response.history) == 1408409    authorization = typing.cast(dict, response.json())["auth"]410    scheme, _, fields = authorization.partition(" ")411    assert scheme == "Digest"412413    response_fields = [field.strip() for field in fields.split(",")]414    digest_data = dict(field.split("=") for field in response_fields)415416    assert digest_data["username"] == '"tomchristie"'417    assert digest_data["realm"] == '"httpx@example.org"'418    assert "nonce" in digest_data419    assert digest_data["uri"] == '"/"'420    assert len(digest_data["response"]) == expected_response_length + 2  # extra quotes421    assert len(digest_data["opaque"]) == expected_hash_length + 2422    assert digest_data["algorithm"] == algorithm423    assert digest_data["qop"] == "auth"424    assert digest_data["nc"] == "00000001"425    assert len(digest_data["cnonce"]) == 16 + 2426427428@pytest.mark.asyncio429async def test_digest_auth_no_specified_qop() -> None:430    url = "https://example.org/"431    auth = DigestAuth(username="tomchristie", password="password123")432    app = DigestApp(qop="")433434    async with httpx.AsyncClient(transport=MockTransport(app)) as client:435        response = await client.get(url, auth=auth)436437    assert response.status_code == 200438    assert len(response.history) == 1439440    authorization = typing.cast(dict, response.json())["auth"]441    scheme, _, fields = authorization.partition(" ")442    assert scheme == "Digest"443444    response_fields = [field.strip() for field in fields.split(",")]445    digest_data = dict(field.split("=") for field in response_fields)446447    assert "qop" not in digest_data448    assert "nc" not in digest_data449    assert "cnonce" not in digest_data450    assert digest_data["username"] == '"tomchristie"'451    assert digest_data["realm"] == '"httpx@example.org"'452    assert len(digest_data["nonce"]) == 64 + 2  # extra quotes453    assert digest_data["uri"] == '"/"'454    assert len(digest_data["response"]) == 64 + 2455    assert len(digest_data["opaque"]) == 64 + 2456    assert digest_data["algorithm"] == "SHA-256"457458459@pytest.mark.parametrize("qop", ("auth, auth-int", "auth,auth-int", "unknown,auth"))460@pytest.mark.asyncio461async def test_digest_auth_qop_including_spaces_and_auth_returns_auth(qop: str) -> None:462    url = "https://example.org/"463    auth = DigestAuth(username="tomchristie", password="password123")464    app = DigestApp(qop=qop)465466    async with httpx.AsyncClient(transport=MockTransport(app)) as client:467        response = await client.get(url, auth=auth)468469    assert response.status_code == 200470    assert len(response.history) == 1471472473@pytest.mark.asyncio474async def test_digest_auth_qop_auth_int_not_implemented() -> None:475    url = "https://example.org/"476    auth = DigestAuth(username="tomchristie", password="password123")477    app = DigestApp(qop="auth-int")478479    async with httpx.AsyncClient(transport=MockTransport(app)) as client:480        with pytest.raises(NotImplementedError):481            await client.get(url, auth=auth)482483484@pytest.mark.asyncio485async def test_digest_auth_qop_must_be_auth_or_auth_int() -> None:486    url = "https://example.org/"487    auth = DigestAuth(username="tomchristie", password="password123")488    app = DigestApp(qop="not-auth")489490    async with httpx.AsyncClient(transport=MockTransport(app)) as client:491        with pytest.raises(ProtocolError):492            await client.get(url, auth=auth)493494495@pytest.mark.asyncio496async def test_digest_auth_incorrect_credentials() -> None:497    url = "https://example.org/"498    auth = DigestAuth(username="tomchristie", password="password123")499    app = DigestApp(send_response_after_attempt=2)500501    async with httpx.AsyncClient(transport=MockTransport(app)) as client:502        response = await client.get(url, auth=auth)503504    assert response.status_code == 401505    assert len(response.history) == 1506507508@pytest.mark.parametrize(509    "auth_header",510    [511        'Digest realm="httpx@example.org", qop="auth"',  # missing fields512        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list513    ],514)515@pytest.mark.asyncio516async def test_async_digest_auth_raises_protocol_error_on_malformed_header(517    auth_header: str,518) -> None:519    url = "https://example.org/"520    auth = DigestAuth(username="tomchristie", password="password123")521    app = App(auth_header=auth_header, status_code=401)522523    async with httpx.AsyncClient(transport=MockTransport(app)) as client:524        with pytest.raises(ProtocolError):525            await client.get(url, auth=auth)526527528@pytest.mark.parametrize(529    "auth_header",530    [531        'Digest realm="httpx@example.org", qop="auth"',  # missing fields532        'Digest realm="httpx@example.org", qop="auth,au',  # malformed fields list533    ],534)535def test_sync_digest_auth_raises_protocol_error_on_malformed_header(536    auth_header: str,537) -> None:538    url = "https://example.org/"539    auth = DigestAuth(username="tomchristie", password="password123")540    app = App(auth_header=auth_header, status_code=401)541542    with httpx.Client(transport=MockTransport(app)) as client:543        with pytest.raises(ProtocolError):544            client.get(url, auth=auth)545546547@pytest.mark.asyncio548async def test_async_auth_history() -> None:549    """550    Test that intermediate requests sent as part of an authentication flow551    are recorded in the response history.552    """553    url = "https://example.org/"554    auth = RepeatAuth(repeat=2)555    app = App(auth_header="abc")556557    async with httpx.AsyncClient(transport=MockTransport(app)) as client:558        response = await client.get(url, auth=auth)559560    assert response.status_code == 200561    assert response.json() == {"auth": "Repeat abc.abc"}562563    assert len(response.history) == 2564    resp1, resp2 = response.history565    assert resp1.json() == {"auth": "Repeat 0"}566    assert resp2.json() == {"auth": "Repeat 1"}567568    assert len(resp2.history) == 1569    assert resp2.history == [resp1]570571    assert len(resp1.history) == 0572573574def test_sync_auth_history() -> None:575    """576    Test that intermediate requests sent as part of an authentication flow577    are recorded in the response history.578    """579    url = "https://example.org/"580    auth = RepeatAuth(repeat=2)581    app = App(auth_header="abc")582583    with httpx.Client(transport=MockTransport(app)) as client:584        response = client.get(url, auth=auth)585586    assert response.status_code == 200587    assert response.json() == {"auth": "Repeat abc.abc"}588589    assert len(response.history) == 2590    resp1, resp2 = response.history591    assert resp1.json() == {"auth": "Repeat 0"}592    assert resp2.json() == {"auth": "Repeat 1"}593594    assert len(resp2.history) == 1595    assert resp2.history == [resp1]596597    assert len(resp1.history) == 0598599600@pytest.mark.asyncio601async def test_digest_auth_unavailable_streaming_body():602    url = "https://example.org/"603    auth = DigestAuth(username="tomchristie", password="password123")604    app = DigestApp()605606    async def streaming_body():607        yield b"Example request body"  # pragma: nocover608609    async with httpx.AsyncClient(transport=MockTransport(app)) as client:610        with pytest.raises(httpx.StreamConsumed):611            await client.post(url, data=streaming_body(), auth=auth)612613614@pytest.mark.asyncio615async def test_async_auth_reads_response_body() -> None:616    """617    Test that we can read the response body in an auth flow if `requires_response_body`618    is set.619    """620    url = "https://example.org/"621    auth = ResponseBodyAuth("xyz")622    app = App()623624    async with httpx.AsyncClient(transport=MockTransport(app)) as client:625        response = await client.get(url, auth=auth)626627    assert response.status_code == 200628    assert response.json() == {"auth": '{"auth": "xyz"}'}629630631def test_sync_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    with httpx.Client(transport=MockTransport(app)) as client:641        response = client.get(url, auth=auth)642643    assert response.status_code == 200644    assert response.json() == {"auth": '{"auth": "xyz"}'}645646647@pytest.mark.asyncio648async def test_async_auth() -> None:649    """650    Test that we can use an auth implementation specific to the async case, to651    support cases that require performing I/O or using concurrency primitives (such652    as checking a disk-based cache or fetching a token from a remote auth server).653    """654    url = "https://example.org/"655    auth = SyncOrAsyncAuth()656    app = App()657658    async with httpx.AsyncClient(transport=MockTransport(app)) as client:659        response = await client.get(url, auth=auth)660661    assert response.status_code == 200662    assert response.json() == {"auth": "async-auth"}663664665def test_sync_auth() -> None:666    """667    Test that we can use an auth implementation specific to the sync case.668    """669    url = "https://example.org/"670    auth = SyncOrAsyncAuth()671    app = App()672673    with httpx.Client(transport=MockTransport(app)) as client:674        response = client.get(url, auth=auth)675676    assert response.status_code == 200677    assert response.json() == {"auth": "sync-auth"}