Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

feat: using token authorization for styles on Github to be able to us… #603

Merged
merged 2 commits into from
Aug 19, 2023
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
12 changes: 4 additions & 8 deletions src/nitpick/style/fetchers/github.py
Original file line number Diff line number Diff line change
Expand Up @@ -50,14 +50,10 @@ def token(self) -> str | None:
return token

@property
def credentials(self) -> tuple[str, str] | tuple[()]:
"""Credentials encoded in this URL.

A tuple of ``(api_token, '')`` if present, or empty tuple otherwise.

"""
def authorization_header(self) -> dict[str, str] | None:
"""Authorization header encoded in this URL."""
token = self.token
return (token, "") if token else ()
return {"Authorization": f"token {token}"} if token else None

@property
def git_reference_or_default(self) -> str:
Expand Down Expand Up @@ -166,5 +162,5 @@ def _normalize_scheme(self, scheme: str) -> str: # pylint: disable=no-self-use

def _download(self, url: furl, **kwargs) -> str:
github_url = GitHubURL.from_furl(url)
kwargs.setdefault("auth", github_url.credentials)
kwargs.setdefault("headers", github_url.authorization_header)
return super()._download(github_url.raw_content_url, **kwargs)
29 changes: 13 additions & 16 deletions tests/test_style.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,5 @@
"""Style tests."""
import warnings
from base64 import b64encode
from pathlib import Path
from textwrap import dedent
from unittest import mock
Expand Down Expand Up @@ -426,8 +425,7 @@ def test_fetch_private_github_urls(tmp_path):
missing = "thing"{SUGGESTION_END}
"""
)
token_on_basic_auth = b64encode(f"{file_token}:".encode()).decode().strip()
assert responses.calls[0].request.headers["Authorization"] == f"Basic {token_on_basic_auth}"
assert responses.calls[0].request.headers["Authorization"] == f"token {file_token}"
project.flake8(offline=True).assert_no_errors()


Expand Down Expand Up @@ -460,8 +458,7 @@ def test_fetch_private_github_urls_no_branch(tmp_path):
"""
)
assert responses.calls[0].request.headers["Authorization"] == f"token {file_token}"
token_on_basic_auth = b64encode(f"{file_token}:".encode()).decode().strip()
assert responses.calls[1].request.headers["Authorization"] == f"Basic {token_on_basic_auth}"
assert responses.calls[1].request.headers["Authorization"] == f"token {file_token}"
project.flake8(offline=True).assert_no_errors()


Expand All @@ -480,10 +477,10 @@ def test_fetch_private_github_urls_no_branch(tmp_path):
"https://raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml",
],
)
def test_github_url_without_token_has_no_credentials(style_url):
def test_github_url_without_token_has_no_authorization_header(style_url):
"""Check private GitHub URLs with a token in various places are parsed correctly."""
parsed = GitHubURL.from_furl(furl(style_url))
assert parsed.credentials == ()
assert parsed.authorization_header is None


@pytest.mark.parametrize(
Expand All @@ -501,10 +498,10 @@ def test_github_url_without_token_has_no_credentials(style_url):
"https://token@raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml",
],
)
def test_github_url_with_fixed_userinfo_token_has_correct_credential(url):
def test_github_url_with_fixed_userinfo_token_has_correct_authorization_header(url):
"""Check private GitHub URLs with a token in various places are parsed correctly."""
parsed = GitHubURL.from_furl(furl(url))
assert parsed.credentials == ("token", "")
assert parsed.authorization_header == {"Authorization": "token token"}


@pytest.mark.parametrize(
Expand All @@ -522,11 +519,11 @@ def test_github_url_with_fixed_userinfo_token_has_correct_credential(url):
"https://$TOKEN@raw.githubusercontent.com/andreoliwa/nitpick/develop/initial.toml",
],
)
def test_github_url_with_variable_userinfo_token_has_correct_credential(url, monkeypatch):
def test_github_url_with_variable_userinfo_token_has_correct_authorization_header(url, monkeypatch):
"""Check private GitHub URLs with a token in various places are parsed correctly."""
monkeypatch.setenv("TOKEN", "envvar-token")
parsed = GitHubURL.from_furl(furl(url))
assert parsed.credentials == ("envvar-token", "")
assert parsed.authorization_header == {"Authorization": "token envvar-token"}


@pytest.mark.parametrize(
Expand All @@ -546,18 +543,18 @@ def test_github_url_with_variable_userinfo_token_has_correct_credential(url, mon
"github://$ENVVAR@andreoliwa/nitpick/initial.toml?token=$NOTUSED",
],
)
def test_github_url_with_variable_query_token_has_correct_credential(url, monkeypatch):
def test_github_url_with_variable_query_token_has_correct_authorization_header(url, monkeypatch):
"""Check private GitHub URLs with a token in various places are parsed correctly."""
monkeypatch.setenv("ENVVAR", "envvar-token")
parsed = GitHubURL.from_furl(furl(url))
assert parsed.credentials == ("envvar-token", "")
assert parsed.authorization_header == {"Authorization": "token envvar-token"}


def test_github_url_with_missing_envvar_has_empty_credential(monkeypatch):
def test_github_url_with_missing_envvar_has_empty_authorization_header(monkeypatch):
"""Environment var that doesn't exist is replaced with empty string."""
monkeypatch.delenv("MISSINGVAR", raising=False)
parsed = GitHubURL.from_furl(furl("https://github.com/foo/bar/blob/branch/filename.toml?token=$MISSINGVAR"))
assert parsed.credentials == ()
assert parsed.authorization_header is None


def test_github_url_query_token_retains_other_queryparams():
Expand All @@ -567,7 +564,7 @@ def test_github_url_query_token_retains_other_queryparams():
parsed = GitHubURL.from_furl(
furl("https://github.com/foo/bar/blob/branch/filename.toml?token=somevar&leavemealone=ok")
)
assert parsed.credentials == ("somevar", "")
assert parsed.authorization_header == {"Authorization": "token somevar"}
assert ("leavemealone", "ok") in parsed.url.query.params.items()


Expand Down