Skip to content
Myr

test_auth.py

This file

Path

tests/test_auth.py

307 lines · 11.3 KiB · Python

Last changed by

Fix RFC 2069 mode digest authentication (#3045)Tereza Tomcovabefore adoption99cba6a

History of this file

Take it

1"""2Unit tests for auth classes.34Integration tests also exist in tests/client/test_auth.py5"""6from urllib.request import parse_keqv_list78import pytest910import httpx111213def test_basic_auth():14    auth = httpx.BasicAuth(username="user", password="pass")15    request = httpx.Request("GET", "https://www.example.com")1617    # The initial request should include a basic auth header.18    flow = auth.sync_auth_flow(request)19    request = next(flow)20    assert request.headers["Authorization"].startswith("Basic")2122    # No other requests are made.23    response = httpx.Response(content=b"Hello, world!", status_code=200)24    with pytest.raises(StopIteration):25        flow.send(response)262728def test_digest_auth_with_200():29    auth = httpx.DigestAuth(username="user", password="pass")30    request = httpx.Request("GET", "https://www.example.com")3132    # The initial request should not include an auth header.33    flow = auth.sync_auth_flow(request)34    request = next(flow)35    assert "Authorization" not in request.headers3637    # If a 200 response is returned, then no other requests are made.38    response = httpx.Response(content=b"Hello, world!", status_code=200)39    with pytest.raises(StopIteration):40        flow.send(response)414243def test_digest_auth_with_401():44    auth = httpx.DigestAuth(username="user", password="pass")45    request = httpx.Request("GET", "https://www.example.com")4647    # The initial request should not include an auth header.48    flow = auth.sync_auth_flow(request)49    request = next(flow)50    assert "Authorization" not in request.headers5152    # If a 401 response is returned, then a digest auth request is made.53    headers = {54        "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'55    }56    response = httpx.Response(57        content=b"Auth required", status_code=401, headers=headers, request=request58    )59    request = flow.send(response)60    assert request.headers["Authorization"].startswith("Digest")6162    # No other requests are made.63    response = httpx.Response(content=b"Hello, world!", status_code=200)64    with pytest.raises(StopIteration):65        flow.send(response)666768def test_digest_auth_with_401_nonce_counting():69    auth = httpx.DigestAuth(username="user", password="pass")70    request = httpx.Request("GET", "https://www.example.com")7172    # The initial request should not include an auth header.73    flow = auth.sync_auth_flow(request)74    request = next(flow)75    assert "Authorization" not in request.headers7677    # If a 401 response is returned, then a digest auth request is made.78    headers = {79        "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."'80    }81    response = httpx.Response(82        content=b"Auth required", status_code=401, headers=headers, request=request83    )84    first_request = flow.send(response)85    assert first_request.headers["Authorization"].startswith("Digest")8687    # Each subsequent request contains the digest header by default...88    request = httpx.Request("GET", "https://www.example.com")89    flow = auth.sync_auth_flow(request)90    second_request = next(flow)91    assert second_request.headers["Authorization"].startswith("Digest")9293    # ... and the client nonce count (nc) is increased94    first_nc = parse_keqv_list(first_request.headers["Authorization"].split(", "))["nc"]95    second_nc = parse_keqv_list(second_request.headers["Authorization"].split(", "))[96        "nc"97    ]98    assert int(first_nc, 16) + 1 == int(second_nc, 16)99100    # No other requests are made.101    response = httpx.Response(content=b"Hello, world!", status_code=200)102    with pytest.raises(StopIteration):103        flow.send(response)104105106def set_cookies(request: httpx.Request) -> httpx.Response:107    headers = {108        "Set-Cookie": "session=.session_value...",109        "WWW-Authenticate": 'Digest realm="...", qop="auth", nonce="...", opaque="..."',110    }111    if request.url.path == "/auth":112        return httpx.Response(113            content=b"Auth required", status_code=401, headers=headers114        )115    else:116        raise NotImplementedError()  # pragma: no cover117118119def test_digest_auth_setting_cookie_in_request():120    url = "https://www.example.com/auth"121    client = httpx.Client(transport=httpx.MockTransport(set_cookies))122    request = client.build_request("GET", url)123124    auth = httpx.DigestAuth(username="user", password="pass")125    flow = auth.sync_auth_flow(request)126    request = next(flow)127    assert "Authorization" not in request.headers128129    response = client.get(url)130    assert len(response.cookies) > 0131    assert response.cookies["session"] == ".session_value..."132133    request = flow.send(response)134    assert request.headers["Authorization"].startswith("Digest")135    assert request.headers["Cookie"] == "session=.session_value..."136137    # No other requests are made.138    response = httpx.Response(139        content=b"Hello, world!", status_code=200, request=request140    )141    with pytest.raises(StopIteration):142        flow.send(response)143144145def test_digest_auth_rfc_2069():146    # Example from https://datatracker.ietf.org/doc/html/rfc2069#section-2.4147    # with corrected response from https://www.rfc-editor.org/errata/eid749148149    auth = httpx.DigestAuth(username="Mufasa", password="CircleOfLife")150    request = httpx.Request("GET", "https://www.example.com/dir/index.html")151152    # The initial request should not include an auth header.153    flow = auth.sync_auth_flow(request)154    request = next(flow)155    assert "Authorization" not in request.headers156157    # If a 401 response is returned, then a digest auth request is made.158    headers = {159        "WWW-Authenticate": (160            'Digest realm="testrealm@host.com", '161            'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093", '162            'opaque="5ccc069c403ebaf9f0171e9517f40e41"'163        )164    }165    response = httpx.Response(166        content=b"Auth required", status_code=401, headers=headers, request=request167    )168    request = flow.send(response)169    assert request.headers["Authorization"].startswith("Digest")170    assert 'username="Mufasa"' in request.headers["Authorization"]171    assert 'realm="testrealm@host.com"' in request.headers["Authorization"]172    assert (173        'nonce="dcd98b7102dd2f0e8b11d0f600bfb0c093"' in request.headers["Authorization"]174    )175    assert 'uri="/dir/index.html"' in request.headers["Authorization"]176    assert (177        'opaque="5ccc069c403ebaf9f0171e9517f40e41"' in request.headers["Authorization"]178    )179    assert (180        'response="1949323746fe6a43ef61f9606e7febea"'181        in request.headers["Authorization"]182    )183184    # No other requests are made.185    response = httpx.Response(content=b"Hello, world!", status_code=200)186    with pytest.raises(StopIteration):187        flow.send(response)188189190def test_digest_auth_rfc_7616_md5(monkeypatch):191    # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1192193    def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:194        return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode()195196    auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life")197    monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce)198199    request = httpx.Request("GET", "https://www.example.com/dir/index.html")200201    # The initial request should not include an auth header.202    flow = auth.sync_auth_flow(request)203    request = next(flow)204    assert "Authorization" not in request.headers205206    # If a 401 response is returned, then a digest auth request is made.207    headers = {208        "WWW-Authenticate": (209            'Digest realm="http-auth@example.org", '210            'qop="auth, auth-int", '211            "algorithm=MD5, "212            'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", '213            'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'214        )215    }216    response = httpx.Response(217        content=b"Auth required", status_code=401, headers=headers, request=request218    )219    request = flow.send(response)220    assert request.headers["Authorization"].startswith("Digest")221    assert 'username="Mufasa"' in request.headers["Authorization"]222    assert 'realm="http-auth@example.org"' in request.headers["Authorization"]223    assert 'uri="/dir/index.html"' in request.headers["Authorization"]224    assert "algorithm=MD5" in request.headers["Authorization"]225    assert (226        'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"'227        in request.headers["Authorization"]228    )229    assert "nc=00000001" in request.headers["Authorization"]230    assert (231        'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"'232        in request.headers["Authorization"]233    )234    assert "qop=auth" in request.headers["Authorization"]235    assert (236        'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'237        in request.headers["Authorization"]238    )239    assert (240        'response="8ca523f5e9506fed4657c9700eebdbec"'241        in request.headers["Authorization"]242    )243244    # No other requests are made.245    response = httpx.Response(content=b"Hello, world!", status_code=200)246    with pytest.raises(StopIteration):247        flow.send(response)248249250def test_digest_auth_rfc_7616_sha_256(monkeypatch):251    # Example from https://datatracker.ietf.org/doc/html/rfc7616#section-3.9.1252253    def mock_get_client_nonce(nonce_count: int, nonce: bytes) -> bytes:254        return "f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ".encode()255256    auth = httpx.DigestAuth(username="Mufasa", password="Circle of Life")257    monkeypatch.setattr(auth, "_get_client_nonce", mock_get_client_nonce)258259    request = httpx.Request("GET", "https://www.example.com/dir/index.html")260261    # The initial request should not include an auth header.262    flow = auth.sync_auth_flow(request)263    request = next(flow)264    assert "Authorization" not in request.headers265266    # If a 401 response is returned, then a digest auth request is made.267    headers = {268        "WWW-Authenticate": (269            'Digest realm="http-auth@example.org", '270            'qop="auth, auth-int", '271            "algorithm=SHA-256, "272            'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v", '273            'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'274        )275    }276    response = httpx.Response(277        content=b"Auth required", status_code=401, headers=headers, request=request278    )279    request = flow.send(response)280    assert request.headers["Authorization"].startswith("Digest")281    assert 'username="Mufasa"' in request.headers["Authorization"]282    assert 'realm="http-auth@example.org"' in request.headers["Authorization"]283    assert 'uri="/dir/index.html"' in request.headers["Authorization"]284    assert "algorithm=SHA-256" in request.headers["Authorization"]285    assert (286        'nonce="7ypf/xlj9XXwfDPEoM4URrv/xwf94BcCAzFZH4GiTo0v"'287        in request.headers["Authorization"]288    )289    assert "nc=00000001" in request.headers["Authorization"]290    assert (291        'cnonce="f2/wE4q74E6zIJEtWaHKaf5wv/H5QzzpXusqGemxURZJ"'292        in request.headers["Authorization"]293    )294    assert "qop=auth" in request.headers["Authorization"]295    assert (296        'opaque="FQhe/qaU925kfnzjCev0ciny7QMkPqMAFRtzCUYo5tdS"'297        in request.headers["Authorization"]298    )299    assert (300        'response="753927fa0e85d155564e2e272a28d1802ca10daf4496794697cf8db5856cb6c1"'301        in request.headers["Authorization"]302    )303304    # No other requests are made.305    response = httpx.Response(content=b"Hello, world!", status_code=200)306    with pytest.raises(StopIteration):307        flow.send(response)