Skip to content
Myr

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

10 files+126 added−126 removed

modified:docs/advanced.md+29 added-24 removed
426 unmodified lines
427![rich progress bar](img/rich-progress.gif)428429## .netrc Support430431HTTPX supports .netrc file. In `trust_env=True` cases, if auth parameter is432not defined, HTTPX tries to add auth into request's header from .netrc file.431HTTPX can be configured to use [a `.netrc` config file](https://everything.curl.dev/usingcurl/netrc) for authentication.432434!!! 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.433The `.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.434439As default `trust_env` is true. To set false:440```pycon441>>> httpx.get('https://example.org/', trust_env=False)435Example `.netrc` file:436437```438machine example.org439login example-username440password example-password441444If `NETRC` environment is empty, HTTPX tries to use default files.445(`~/.netrc`, `~/_netrc`)442machine python-httpx.org443login other-username444password other-password445```446447To change `NETRC` environment:447Some examples of configuring `.netrc` authentication with `httpx`.448449Use the default `.netrc` file in the users home directory:450451```pycon449>>> import os450>>> os.environ["NETRC"] = "my_default_folder/.my_netrc"452>>> auth = httpx.NetRCAuth()453>>> client = httpx.Client(auth=auth)454```455453.netrc file content example:454```455machine netrcexample.org456login example-username457password example-password456Use an explicit path to a `.netrc` file:457459...458```pycon459>>> auth = httpx.NetRCAuth(file="/path/to/.netrc")460>>> client = httpx.Client(auth=auth)461```462462When using `Client` instances, `trust_env` should be set on the client itself, rather than on the request methods:463Use the `NETRC` environment variable to configure a path to the `.netrc` file,464or fallback to the default.465464```python465client = httpx.Client(trust_env=False)466```pycon467>>> auth = httpx.NetRCAuth(file=os.environ.get("NETRC"))468>>> client = httpx.Client(auth=auth)469```470471The `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.472473## HTTP Proxying474475HTTPX 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 lines
832833When 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...834835* 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`.839840The 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 lines
modified:docs/environment_variables.md-13 removed
130 unmodified lines
131```console132SSL_CERT_DIR=/path/to/ca-certs/ python -c "import httpx; httpx.get('https://example.com')"133```134135## `NETRC`136137Valid values: a filename138139If 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)140141Example:142143```console144NETRC=/path/to/netrcfile/.my_netrc python -c "import httpx; httpx.get('https://example.com')"145```146135## Proxies136137The environment variables documented below are used as a convention by various HTTP tooling, including:138
35 unmodified lines
174# These requests will be sent directly, bypassing the proxy175python -c "import httpx; httpx.get('http://127.0.0.1:5000/my-api')"176python -c "import httpx; httpx.get('https://www.python-httpx.org')"177```190
modified:httpx/__init__.py+2 added-1 removed
1from .__version__ import __description__, __title__, __version__2from ._api import delete, get, head, options, patch, post, put, request, stream3from ._auth import Auth, BasicAuth, DigestAuth3from ._auth import Auth, BasicAuth, DigestAuth, NetRCAuth4from ._client import USE_CLIENT_DEFAULT, AsyncClient, Client5from ._config import Limits, Proxy, Timeout, create_ssl_context6from ._content import ByteStream7from ._exceptions import (
85 unmodified lines
93 "Limits",94 "LocalProtocolError",95 "main",96 "MockTransport",97 "NetRCAuth",98 "NetworkError",99 "options",100 "patch",101 "PoolTimeout",
37 unmodified lines
modified:httpx/_auth.py+29 added
1import hashlib2import netrc3import os4import re5import time6import typing
134 unmodified lines
141 token = b64encode(userpass).decode()142 return f"Basic {token}"143144145class NetRCAuth(Auth):146 """147 Use a 'netrc' file to lookup basic auth credentials based on the url host.148 """149150 def __init__(self, file: typing.Optional[str]):151 self._netrc_info = netrc.netrc(file)152153 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 request164165 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}"171172173class 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 lines
modified:httpx/_client.py-7 removed
45 unmodified lines
46 VerifyTypes,47)48from ._urls import URL, QueryParams49from ._utils import (50 NetRCInfo,50 Timer,51 URLPattern,52 get_environment_proxies,53 get_logger,
135 unmodified lines
189 "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.UNOPENED194195 @property196 def is_closed(self) -> bool:
256 unmodified lines
453 username, password = request.url.username, request.url.password454 if username or password:455 return BasicAuth(username=username, password=password)456459 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])463457 return Auth()458459 def _build_redirect_request(self, request: Request, response: Response) -> Request:460 """
1539 unmodified lines
modified:httpx/_utils.py-32 removed
1import codecs2import email.message3import logging4import mimetypes5import netrc5import os6import re7import sys8import time
117 unmodified lines
126 # Did not detect a valid UTF-32 ascii-range character127 return None128129131class 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 = files136137 @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_info151152 def get_credentials(self, host: str) -> typing.Optional[typing.Tuple[str, str]]:153 if self.netrc_info is None:154 return None155156 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])160161130def 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 lines
modified:tests/client/test_auth.py+55 added-28 removed
2 unmodified lines
34Unit tests for auth classes also exist in tests/test_auth.py5"""6import hashlib7import netrc8import os9import sys10import threading11import typing12from urllib.request import parse_keqv_list13
5 unmodified lines
19from ..common import FIXTURES_DIR202122class App:23 """24 A mock app to test auth credentials.25 """2627 def __init__(self, auth_header: str = "", status_code: int = 200) -> None:28 self.auth_header = auth_header29 self.status_code = status_code30
201 unmodified lines
232 assert response.status_code == 200233 assert response.json() == {"auth": "Token 123"}234235230@pytest.mark.anyio231async def test_netrc_auth() -> None:232 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")236def 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)245236 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)248249 assert response.status_code == 200250 assert response.json() == {251 "auth": "Basic ZXhhbXBsZS11c2VybmFtZTpleGFtcGxlLXBhc3N3b3Jk"252 }253254245@pytest.mark.anyio246async def test_auth_header_has_priority_over_netrc() -> None:247 os.environ["NETRC"] = str(FIXTURES_DIR / ".netrc")248 url = "http://netrcexample.org"255def 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)264251 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)267268 assert response.status_code == 200255 assert response.json() == {"auth": "Override"}269 assert response.json() == {"auth": None}270271258@pytest.mark.anyio259async 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)276def 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)287264 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)290291 assert response.status_code == 200292 assert response.json() == {"auth": None}293272 async with httpx.AsyncClient(273 transport=httpx.MockTransport(app), trust_env=True274 ) as client:275 response = await client.get(url)294277 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)299def 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)308309310@pytest.mark.anyio311async def test_auth_disable_per_request() -> None:
482 unmodified lines
modified:tests/client/test_properties.py+8 added
56 unmodified lines
5758 client = httpx.Client()59 client.event_hooks = {"request": [on_request]}60 assert client.event_hooks == {"request": [on_request], "response": []}616263def test_client_trust_env():64 client = httpx.Client()65 assert client.trust_env6667 client = httpx.Client(trust_env=False)68 assert not client.trust_env
added:tests/fixtures/.netrc-nopassword+2 added
1machine netrcexample.org2login example-username
modified:tests/test_utils.py+1 added-21 removed
3 unmodified lines
4import pytest56import httpx7from httpx._utils import (8 NetRCInfo,8 URLPattern,9 get_ca_bundle_from_env,10 get_environment_proxies,11 guess_json_utf,
3 unmodified lines
15 same_origin,16)17from tests.utils import override_log_level1820from .common import FIXTURES_DIR, TESTS_DIR19from .common import TESTS_DIR202122@pytest.mark.parametrize(23 "encoding",
30 unmodified lines
54 data = "\ufeff{}".encode(encoding)55 assert guess_json_utf(data) == expected565759def test_bad_get_netrc_login():60 netrc_info = NetRCInfo([str(FIXTURES_DIR / "does-not-exist")])61 assert netrc_info.get_credentials("netrcexample.org") is None626364def 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_credentials717273def test_get_netrc_unknown():74 netrc_info = NetRCInfo([str(FIXTURES_DIR / ".netrc")])75 assert netrc_info.get_credentials("nonexistent.org") is None767758@pytest.mark.parametrize(59 "value, expected",60 (61 (
197 unmodified lines