Skip to content
Myr

test_auth.py

This file

Path

tests/test_auth.py

308 lines · 11.3 KiB · Python

Last changed by

format (#3131)T-256before adoption0006ed0

History of this file

Take it

1"""2Unit tests for auth classes.34Integration tests also exist in tests/client/test_auth.py5"""67from urllib.request import parse_keqv_list89import pytest1011import httpx121314def test_basic_auth():15    auth = httpx.BasicAuth(username="user", password="pass")16    request = httpx.Request("GET", "https://www.example.com")1718    # The initial request should include a basic auth header.19    flow = auth.sync_auth_flow(request)20    request = next(flow)21    assert request.headers["Authorization"].startswith("Basic")2223    # No other requests are made.24    response = httpx.Response(content=b"Hello, world!", status_code=200)25    with pytest.raises(StopIteration):26        flow.send(response)272829def test_digest_auth_with_200():30    auth = httpx.DigestAuth(username="user", password="pass")31    request = httpx.Request("GET", "https://www.example.com")3233    # The initial request should not include an auth header.34    flow = auth.sync_auth_flow(request)35    request = next(flow)36    assert "Authorization" not in request.headers3738    # If a 200 response is returned, then no other requests are made.39    response = httpx.Response(content=b"Hello, world!", status_code=200)40    with pytest.raises(StopIteration):41        flow.send(response)424344def test_digest_auth_with_401():45    auth = httpx.DigestAuth(username="user", password="pass")46    request = httpx.Request("GET", "https://www.example.com")4748    # The initial request should not include an auth header.49    flow = auth.sync_auth_flow(request)50    request = next(flow)51    assert "Authorization" not in request.headers5253    # If a 401 response is returned, then a digest auth request is made.54    headers = {55        "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'56    }57    response = httpx.Response(58        content=b"Auth required", status_code=401, headers=headers, request=request59    )60    request = flow.send(response)61    assert request.headers["Authorization"].startswith("Digest")6263    # No other requests are made.64    response = httpx.Response(content=b"Hello, world!", status_code=200)65    with pytest.raises(StopIteration):66        flow.send(response)676869def test_digest_auth_with_401_nonce_counting():70    auth = httpx.DigestAuth(username="user", password="pass")71    request = httpx.Request("GET", "https://www.example.com")7273    # The initial request should not include an auth header.74    flow = auth.sync_auth_flow(request)75    request = next(flow)76    assert "Authorization" not in request.headers7778    # If a 401 response is returned, then a digest auth request is made.79    headers = {80        "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'81    }82    response = httpx.Response(83        content=b"Auth required", status_code=401, headers=headers, request=request84    )85    first_request = flow.send(response)86    assert first_request.headers["Authorization"].startswith("Digest")8788    # Each subsequent request contains the digest header by default...89    request = httpx.Request("GET", "https://www.example.com")90    flow = auth.sync_auth_flow(request)91    second_request = next(flow)92    assert second_request.headers["Authorization"].startswith("Digest")9394    # ... and the client nonce count (nc) is increased95    first_nc = parse_keqv_list(first_request.headers["Authorization"].split(", "))["nc"]96    second_nc = parse_keqv_list(second_request.headers["Authorization"].split(", "))[97        "nc"98    ]99    assert int(first_nc, 16) + 1 == int(second_nc, 16)100101    # No other requests are made.102    response = httpx.Response(content=b"Hello, world!", status_code=200)103    with pytest.raises(StopIteration):104        flow.send(response)105106107def set_cookies(request: httpx.Request) -> httpx.Response:108    headers = {109        "Set-Cookie": "session=.session_value...",110        "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."',111    }112    if request.url.path == "/auth":113        return httpx.Response(114            content=b"Auth required", status_code=401, headers=headers115        )116    else:117        raise NotImplementedError()  # pragma: no cover118119120def test_digest_auth_setting_cookie_in_request():121    url = "https://www.example.com/auth"122    client = httpx.Client(transport=httpx.MockTransport(set_cookies))123    request = client.build_request("GET", url)124125    auth = httpx.DigestAuth(username="user", password="pass")126    flow = auth.sync_auth_flow(request)127    request = next(flow)128    assert "Authorization" not in request.headers129130    response = client.get(url)131    assert len(response.cookies) > 0132    assert response.cookies["session"] == ".session_value..."133134    request = flow.send(response)135    assert request.headers["Authorization"].startswith("Digest")136    assert request.headers["Cookie"] == "session=.session_value..."137138    # No other requests are made.139    response = httpx.Response(140        content=b"Hello, world!", status_code=200, request=request141    )142    with pytest.raises(StopIteration):143        flow.send(response)144145146def test_digest_auth_rfc_2069():147    # Example from https://datatracker.ietf.org/doc/html/rfc2069#section-2.4148    # with corrected response from https://www.rfc-editor.org/errata/eid749149150    auth = httpx.DigestAuth(username="Mufasa", password="CircleOfLife")151    request = httpx.Request("GET", "https://www.example.com/dir/index.html")152153    # The initial request should not include an auth header.154    flow = auth.sync_auth_flow(request)155    request = next(flow)156    assert "Authorization" not in request.headers157158    # If a 401 response is returned, then a digest auth request is made.159    headers = {160        "WWW-Authenticate": (161            'Digest realm="testrealm@host.com", '162            'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '163            'opaque="5ccc069c403ebaf9f0171e9517f40e41"'164        )165    }166    response = httpx.Response(167        content=b"Auth required", status_code=401, headers=headers, request=request168    )169    request = flow.send(response)170    assert request.headers["Authorization"].startswith("Digest")171    assert 'username="Mufasa"' in request.headers["Authorization"]172    assert 'realm="testrealm@host.com"' in request.headers["Authorization"]173    assert (174        'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"' in request.headers["Authorization"]175    )176    assert 'uri="/dir/index.html"' in request.headers["Authorization"]177    assert (178        'opaque="5ccc069c403ebaf9f0171e9517f40e41"' in request.headers["Authorization"]179    )180    assert (181        'response="1949323746fe6a43ef61f9606e7febea"'182        in request.headers["Authorization"]183    )184185    # No other requests are made.186    response = httpx.Response(content=b"Hello, world!", status_code=200)187    with pytest.raises(StopIteration):188        flow.send(response)189190191def test_digest_auth_rfc_7616_md5(monkeypatch):192    # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1193194    def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:195        return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode()196197    auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life")198    monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce)199200    request = httpx.Request("GET", "https://www.example.com/dir/index.html")201202    # The initial request should not include an auth header.203    flow = auth.sync_auth_flow(request)204    request = next(flow)205    assert "Authorization" not in request.headers206207    # If a 401 response is returned, then a digest auth request is made.208    headers = {209        "WWW-Authenticate": (210            'Digest realm="http-auth@example.org", '211            'qop="auth, auth-int", '212            "algorithm=MD5, "213            'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", '214            'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'215        )216    }217    response = httpx.Response(218        content=b"Auth required", status_code=401, headers=headers, request=request219    )220    request = flow.send(response)221    assert request.headers["Authorization"].startswith("Digest")222    assert 'username="Mufasa"' in request.headers["Authorization"]223    assert 'realm="http-auth@example.org"' in request.headers["Authorization"]224    assert 'uri="/dir/index.html"' in request.headers["Authorization"]225    assert "algorithm=MD5" in request.headers["Authorization"]226    assert (227        'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"'228        in request.headers["Authorization"]229    )230    assert "nc=00000001" in request.headers["Authorization"]231    assert (232        'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"'233        in request.headers["Authorization"]234    )235    assert "qop=auth" in request.headers["Authorization"]236    assert (237        'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'238        in request.headers["Authorization"]239    )240    assert (241        'response="8ca523f5e9506fed4657c9700eebdbec"'242        in request.headers["Authorization"]243    )244245    # No other requests are made.246    response = httpx.Response(content=b"Hello, world!", status_code=200)247    with pytest.raises(StopIteration):248        flow.send(response)249250251def test_digest_auth_rfc_7616_sha_256(monkeypatch):252    # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1253254    def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:255        return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode()256257    auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life")258    monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce)259260    request = httpx.Request("GET", "https://www.example.com/dir/index.html")261262    # The initial request should not include an auth header.263    flow = auth.sync_auth_flow(request)264    request = next(flow)265    assert "Authorization" not in request.headers266267    # If a 401 response is returned, then a digest auth request is made.268    headers = {269        "WWW-Authenticate": (270            'Digest realm="http-auth@example.org", '271            'qop="auth, auth-int", '272            "algorithm=SHA-256, "273            'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", '274            'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'275        )276    }277    response = httpx.Response(278        content=b"Auth required", status_code=401, headers=headers, request=request279    )280    request = flow.send(response)281    assert request.headers["Authorization"].startswith("Digest")282    assert 'username="Mufasa"' in request.headers["Authorization"]283    assert 'realm="http-auth@example.org"' in request.headers["Authorization"]284    assert 'uri="/dir/index.html"' in request.headers["Authorization"]285    assert "algorithm=SHA-256" in request.headers["Authorization"]286    assert (287        'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"'288        in request.headers["Authorization"]289    )290    assert "nc=00000001" in request.headers["Authorization"]291    assert (292        'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"'293        in request.headers["Authorization"]294    )295    assert "qop=auth" in request.headers["Authorization"]296    assert (297        'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'298        in request.headers["Authorization"]299    )300    assert (301        'response="753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"'302        in request.headers["Authorization"]303    )304305    # No other requests are made.306    response = httpx.Response(content=b"Hello, world!", status_code=200)307    with pytest.raises(StopIteration):308        flow.send(response)