Add `NetRCAuth()` class. (#2535)
Before adoption: this commit came in with the history the project adopted, so no landing records it.
* NetRCAuth class * Add docs for httpx.NetRCAuth() * Drop failing cross-domain test for NetRCAuth() * Update tests * Update httpx/_auth.py * Add tests for netrc file with no password
authored by Tom Christie · committed by GitHub · parent 7947b56 · Browse files · 10 files·+126 added−126 removed
This commit
State
Before adoption: this commit came in with the history the project adopted, so no landing records it.
Diff stats
10 files+126 added−126 removed
- tests:+66 added−49 removed
- other:+60 added−77 removed
Provenance
- Commit
59914c7- Tree
418fd62- Author
Tom Christie <tom@tomchristie.com>- Committer
GitHub <noreply@github.com>- Parent
7947b56
10 files changed+126 added−126 removed
modified:docs/advanced.md+29 added-24 removed
426 unmodified lines427 428 429 ## .netrc Support430 431-HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is432-not defined, HTTPX tries to add auth into request's header from .netrc file.431+HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.432 434-!!! note435- The NETRC file is cached across requests made by a client.436- If you need to refresh the cache (e.g. because the NETRC file has changed),437- you should create a new client or restart the interpreter.433+The `.netrc` config file allows authentication credentials to be associated with specified hosts. When a request is made to a host that is found in the netrc file, the username and password will be included using HTTP basic auth.434 439-As default `trust_env` is true. To set false:440-```pycon441->>> httpx.get('https://example.org/', trust_env=False)435+Example `.netrc` file:436+437 ```438+machine example.org439+login example-username440+password example-password441 444-If `NETRC` environment is empty, HTTPX tries to use default files.445-(`~/.netrc`, `~/_netrc`)442+machine python-httpx.org443+login other-username444+password other-password445+```446 447-To change `NETRC` environment:447+Some examples of configuring `.netrc` authentication with `httpx`.448+449+Use the default `.netrc` file in the users home directory:450+451 ```pycon449->>> import os450->>> os.environ["NETRC"] = "my_default_folder/.my_netrc"452+>>> auth = httpx.NetRCAuth()453+>>> client = httpx.Client(auth=auth)454 ```455 453-.netrc file content example:454-```455-machine netrcexample.org456-login example-username457-password example-password456+Use an explicit path to a `.netrc` file:457 459-...458+```pycon459+>>> auth = httpx.NetRCAuth(file="/path/to/.netrc")460+>>> client = httpx.Client(auth=auth)461 ```462 462-When using `Client` instances, `trust_env` should be set on the client itself, rather than on the request methods:463+Use the `NETRC` environment variable to configure a path to the `.netrc` file,464+or fallback to the default.465 464-```python465-client = httpx.Client(trust_env=False)466+```pycon467+>>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))468+>>> client = httpx.Client(auth=auth)469 ```470 471+The `NetRCAuth()` class uses [the `netrc.netrc()` function from the Python standard library](https://docs.python.org/3/library/netrc.html). See the documentation there for more details on exceptions that may be raised if the netrc file is not found, or cannot be parsed.472+473 ## HTTP Proxying474 475 HTTPX supports setting up [HTTP proxies](https://en.wikipedia.org/wiki/Proxy_server#Web_proxy_servers) via the `proxies` parameter to be passed on client initialization or top-level API functions like `httpx.get(..., proxies=...)`.476 355 unmodified lines832 833 When issuing requests or instantiating a client, the `auth` argument can be used to pass an authentication scheme to use. The `auth` argument may be one of the following...834 835 * A two-tuple of `username`/`password`, to be used with basic authentication.831-* An instance of `httpx.BasicAuth()` or `httpx.DigestAuth()`.836+* An instance of `httpx.BasicAuth()`, `httpx.DigestAuth()`, or `httpx.NetRCAuth()`.837 * A callable, accepting a request and returning an authenticated request instance.838 * An instance of subclasses of `httpx.Auth`.839 840 The most involved of these is the last, which allows you to create authentication flows involving one or more requests. A subclass of `httpx.Auth` should implement `def auth_flow(request)`, and yield any requests that need to be made...424 unmodified linesmodified:docs/environment_variables.md-13 removed
130 unmodified lines131 ```console132 SSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"133 ```134 135-## `NETRC`136-137-Valid values: a filename138-139-If this environment variable is set but auth parameter is not defined, HTTPX will add auth information stored in the .netrc file into the request's header. If you do not provide NETRC environment either, HTTPX will use default files. (~/.netrc, ~/_netrc)140-141-Example:142-143-```console144-NETRC=/path/to/netrcfile/.my_netrc python -c "import httpx; httpx.get('https://example.com')"145-```146-135 ## Proxies136 137 The environment variables documented below are used as a convention by various HTTP tooling, including:138 35 unmodified lines174 # These requests will be sent directly, bypassing the proxy175 python -c "import httpx; httpx.get('http://127.0.0.1:5000/my-api')"176 python -c "import httpx; httpx.get('https://www.python-httpx.org')"177 ```190-modified:httpx/__init__.py+2 added-1 removed
1 from .__version__ import __description__, __title__, __version__2 from ._api import delete, get, head, options, patch, post, put, request, stream3-from ._auth import Auth, BasicAuth, DigestAuth3+from ._auth import Auth, BasicAuth, DigestAuth, NetRCAuth4 from ._client import USE_CLIENT_DEFAULT, AsyncClient, Client5 from ._config import Limits, Proxy, Timeout, create_ssl_context6 from ._content import ByteStream7 from ._exceptions import (85 unmodified lines93 "Limits",94 "LocalProtocolError",95 "main",96 "MockTransport",97+ "NetRCAuth",98 "NetworkError",99 "options",100 "patch",101 "PoolTimeout",37 unmodified linesmodified:httpx/_auth.py+29 added
1 import hashlib2+import netrc3 import os4 import re5 import time6 import typing134 unmodified lines141 token = b64encode(userpass).decode()142 return f"Basic {token}"143 144 145+class NetRCAuth(Auth):146+ """147+ Use a 'netrc' file to lookup basic auth credentials based on the url host.148+ """149+150+ def __init__(self, file: typing.Optional[str]):151+ self._netrc_info = netrc.netrc(file)152+153+ def auth_flow(self, request: Request) -> typing.Generator[Request, Response, None]:154+ auth_info = self._netrc_info.authenticators(request.url.host)155+ if auth_info is None or not auth_info[2]:156+ # The netrc file did not have authentication credentials for this host.157+ yield request158+ else:159+ # Build a basic auth header with credentials from the netrc file.160+ request.headers["Authorization"] = self._build_auth_header(161+ username=auth_info[0], password=auth_info[2]162+ )163+ yield request164+165+ def _build_auth_header(166+ self, username: typing.Union[str, bytes], password: typing.Union[str, bytes]167+ ) -> str:168+ userpass = b":".join((to_bytes(username), to_bytes(password)))169+ token = b64encode(userpass).decode()170+ return f"Basic {token}"171+172+173 class DigestAuth(Auth):174 _ALGORITHM_TO_HASH_FUNCTION: typing.Dict[str, typing.Callable[[bytes], "_Hash"]] = {175 "MD5": hashlib.md5,176 "MD5-SESS": hashlib.md5,171 unmodified linesmodified:httpx/_client.py-7 removed
45 unmodified lines46 VerifyTypes,47 )48 from ._urls import URL, QueryParams49 from ._utils import (50- NetRCInfo,50 Timer,51 URLPattern,52 get_environment_proxies,53 get_logger,135 unmodified lines189 "response": list(event_hooks.get("response", [])),190 }191 self._trust_env = trust_env192 self._default_encoding = default_encoding194- self._netrc = NetRCInfo()193 self._state = ClientState.UNOPENED194 195 @property196 def is_closed(self) -> bool:256 unmodified lines453 username, password = request.url.username, request.url.password454 if username or password:455 return BasicAuth(username=username, password=password)456 459- if self.trust_env and "Authorization" not in request.headers:460- credentials = self._netrc.get_credentials(request.url.host)461- if credentials is not None:462- return BasicAuth(username=credentials[0], password=credentials[1])463-457 return Auth()458 459 def _build_redirect_request(self, request: Request, response: Response) -> Request:460 """1539 unmodified linesmodified:httpx/_utils.py-32 removed
1 import codecs2 import email.message3 import logging4 import mimetypes5-import netrc5 import os6 import re7 import sys8 import time117 unmodified lines126 # Did not detect a valid UTF-32 ascii-range character127 return None128 129 131-class NetRCInfo:132- def __init__(self, files: typing.Optional[typing.List[str]] = None) -> None:133- if files is None:134- files = [os.getenv("NETRC", ""), "~/.netrc", "~/_netrc"]135- self.netrc_files = files136-137- @property138- def netrc_info(self) -> typing.Optional[netrc.netrc]:139- if not hasattr(self, "_netrc_info"):140- self._netrc_info = None141- for file_path in self.netrc_files:142- expanded_path = Path(file_path).expanduser()143- try:144- if expanded_path.is_file():145- self._netrc_info = netrc.netrc(str(expanded_path))146- break147- except (netrc.NetrcParseError, IOError): # pragma: no cover148- # Issue while reading the netrc file, ignore...149- pass150- return self._netrc_info151-152- def get_credentials(self, host: str) -> typing.Optional[typing.Tuple[str, str]]:153- if self.netrc_info is None:154- return None155-156- auth_info = self.netrc_info.authenticators(host)157- if auth_info is None or auth_info[2] is None:158- return None159- return (auth_info[0], auth_info[2])160-161-130 def get_ca_bundle_from_env() -> typing.Optional[str]:131 if "SSL_CERT_FILE" in os.environ:132 ssl_file = Path(os.environ["SSL_CERT_FILE"])133 if ssl_file.is_file():364 unmodified linesmodified:tests/client/test_auth.py+55 added-28 removed
2 unmodified lines3 4 Unit tests for auth classes also exist in tests/test_auth.py5 """6 import hashlib7+import netrc8 import os9+import sys10 import threading11 import typing12 from urllib.request import parse_keqv_list13 5 unmodified lines19 from ..common import FIXTURES_DIR20 21 22 class App:23+ """24+ A mock app to test auth credentials.25+ """26+27 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:28 self.auth_header = auth_header29 self.status_code = status_code30 201 unmodified lines232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234 235 230-@pytest.mark.anyio231-async def test_netrc_auth() -> None:232- os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")236+def test_netrc_auth_credentials_exist() -> None:237+ """238+ When netrc auth is being used and a request is made to a host that is239+ in the netrc file, then the relevant credentials should be applied.240+ """241+ netrc_file = str(FIXTURES_DIR / ".netrc")242 url = "http://netrcexample.org"243 app = App()244+ auth = httpx.NetRCAuth(netrc_file)245 236- async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:237- response = await client.get(url)246+ with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:247+ response = client.get(url)248 249 assert response.status_code == 200250 assert response.json() == {251 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"252 }253 254 245-@pytest.mark.anyio246-async def test_auth_header_has_priority_over_netrc() -> None:247- os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")248- url = "http://netrcexample.org"255+def test_netrc_auth_credentials_do_not_exist() -> None:256+ """257+ When netrc auth is being used and a request is made to a host that is258+ not in the netrc file, then no credentials should be applied.259+ """260+ netrc_file = str(FIXTURES_DIR / ".netrc")261+ url = "http://example.org"262 app = App()263+ auth = httpx.NetRCAuth(netrc_file)264 251- async with httpx.AsyncClient(transport=httpx.MockTransport(app)) as client:252- response = await client.get(url, headers={"Authorization": "Override"})265+ with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:266+ response = client.get(url)267 268 assert response.status_code == 200255- assert response.json() == {"auth": "Override"}269+ assert response.json() == {"auth": None}270 271 258-@pytest.mark.anyio259-async def test_trust_env_auth() -> None:260- os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")261- url = "http://netrcexample.org"272+@pytest.mark.skipif(273+ sys.version_info < (3, 11),274+ reason="netrc files without a password are invalid with Python < 3.11",275+)276+def test_netrc_auth_nopassword() -> None: # pragma: no cover277+ """278+ Python has different netrc parsing behaviours with different versions.279+ For Python 3.11+ a netrc file with no password is valid. In this case280+ we want to check that we allow the netrc auth, and simply don't provide281+ any credentials in the request.282+ """283+ netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")284+ url = "http://example.org"285 app = App()286+ auth = httpx.NetRCAuth(netrc_file)287 264- async with httpx.AsyncClient(265- transport=httpx.MockTransport(app), trust_env=False266- ) as client:267- response = await client.get(url)288+ with httpx.Client(transport=httpx.MockTransport(app), auth=auth) as client:289+ response = client.get(url)290 291 assert response.status_code == 200292 assert response.json() == {"auth": None}293 272- async with httpx.AsyncClient(273- transport=httpx.MockTransport(app), trust_env=True274- ) as client:275- response = await client.get(url)294 277- assert response.status_code == 200278- assert response.json() == {279- "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"280- }295+@pytest.mark.skipif(296+ sys.version_info >= (3, 11),297+ reason="netrc files without a password are valid from Python >= 3.11",298+)299+def test_netrc_auth_nopassword_parse_error() -> None: # pragma: no cover300+ """301+ Python has different netrc parsing behaviours with different versions.302+ For Python < 3.11 a netrc file with no password is invalid. In this case303+ we want to allow the parse error to be raised.304+ """305+ netrc_file = str(FIXTURES_DIR / ".netrc-nopassword")306+ with pytest.raises(netrc.NetrcParseError):307+ httpx.NetRCAuth(netrc_file)308 309 310 @pytest.mark.anyio311 async def test_auth_disable_per_request() -> None:482 unmodified linesmodified:tests/client/test_properties.py+8 added
56 unmodified lines57 58 client = httpx.Client()59 client.event_hooks = {"request": [on_request]}60 assert client.event_hooks == {"request": [on_request], "response": []}61+62+63+def test_client_trust_env():64+ client = httpx.Client()65+ assert client.trust_env66+67+ client = httpx.Client(trust_env=False)68+ assert not client.trust_envadded:tests/fixtures/.netrc-nopassword+2 added
1+machine netrcexample.org2+login example-usernamemodified:tests/test_utils.py+1 added-21 removed
3 unmodified lines4 import pytest5 6 import httpx7 from httpx._utils import (8- NetRCInfo,8 URLPattern,9 get_ca_bundle_from_env,10 get_environment_proxies,11 guess_json_utf,3 unmodified lines15 same_origin,16 )17 from tests.utils import override_log_level18 20-from .common import FIXTURES_DIR, TESTS_DIR19+from .common import TESTS_DIR20 21 22 @pytest.mark.parametrize(23 "encoding",30 unmodified lines54 data = "\ufeff{}".encode(encoding)55 assert guess_json_utf(data) == expected56 57 59-def test_bad_get_netrc_login():60- netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])61- assert netrc_info.get_credentials("netrcexample.org") is None62-63-64-def test_get_netrc_login():65- netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])66- expected_credentials = (67- "example-username",68- "example-password",69- )70- assert netrc_info.get_credentials("netrcexample.org") == expected_credentials71-72-73-def test_get_netrc_unknown():74- netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])75- assert netrc_info.get_credentials("nonexistent.org") is None76-77-58 @pytest.mark.parametrize(59 "value, expected",60 (61 (197 unmodified lines