Skip to content

Commit

Permalink
docs(advanced): document new netrc behavior
Browse files Browse the repository at this point in the history
BREAKING CHANGE: python-gitlab now explicitly passes auth to requests, meaning
it will only read netrc credentials if no token is provided, fixing a bug where
netrc credentials took precedence over OAuth tokens. This also affects the CLI,
where all environment variables now take precedence over netrc files.
  • Loading branch information
nejch committed Oct 12, 2023
1 parent 5f46cfd commit 45b8930
Show file tree
Hide file tree
Showing 2 changed files with 38 additions and 4 deletions.
8 changes: 4 additions & 4 deletions docs/api-usage-advanced.rst
Expand Up @@ -44,11 +44,11 @@ properly closed when you exit a ``with`` block:
netrc authentication
--------------------

python-gitlab reads credentials from ``.netrc`` files via the ``requests`` backend by default,
which may override authentication headers you set on your client.
python-gitlab reads credentials from ``.netrc`` files via the ``requests`` backend
only if you do not provide any other type of authentication yourself.

For more granular control, you can disable this `Using a custom session`_
and explicitly setting ``trust_env=False`` as described in the ``requests`` documentation.
If you'd like to disable reading netrc files altogether, you can follow `Using a custom session`_
and explicitly set ``trust_env=False`` as described in the ``requests`` documentation.

.. code-block:: python
Expand Down
34 changes: 34 additions & 0 deletions tests/unit/test_gitlab_auth.py
@@ -1,12 +1,22 @@
import pathlib

import pytest
import requests
import responses
from requests import PreparedRequest

from gitlab import Gitlab
from gitlab._backends import JobTokenAuth, OAuthTokenAuth, PrivateTokenAuth
from gitlab.config import GitlabConfigParser


@pytest.fixture
def netrc(monkeypatch: pytest.MonkeyPatch, tmp_path: pathlib.Path):
netrc_file = tmp_path / ".netrc"
netrc_file.write_text("machine localhost login test password test")
monkeypatch.setenv("NETRC", str(netrc_file))


def test_invalid_auth_args():
with pytest.raises(ValueError):
Gitlab(
Expand Down Expand Up @@ -101,6 +111,30 @@ def test_http_auth():
assert "JOB-TOKEN" not in p.headers


@responses.activate
def test_with_no_auth_uses_netrc_file(netrc):
responses.get(
url="http://localhost/api/v4/test",
match=[
responses.matchers.header_matcher({"Authorization": "Basic dGVzdDp0ZXN0"})
],
)

gl = Gitlab("http://localhost")
gl.http_get("/test")


@responses.activate
def test_with_auth_ignores_netrc_file(netrc):
responses.get(
url="http://localhost/api/v4/test",
match=[responses.matchers.header_matcher({"Authorization": "Bearer test"})],
)

gl = Gitlab("http://localhost", oauth_token="test")
gl.http_get("/test")


@pytest.mark.parametrize(
"options,config,expected_private_token,expected_oauth_token,expected_job_token",
[
Expand Down

0 comments on commit 45b8930

Please sign in to comment.