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

Fix plumbing of env var based Bearer authentication. #148

Merged
merged 3 commits into from
Mar 18, 2025
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
5 changes: 5 additions & 0 deletions CHANGES.md
Original file line number Diff line number Diff line change
@@ -1,5 +1,10 @@
# Release Notes

## 0.12.2

This release fixes a long standing bug in plumbing `SCIENCE_AUTH_<normalized_host>_BEARER` env var
based bearer token auth through to http(s) requests to the host.

## 0.12.1

This release fixes science to support scies where the scie name matches one of the lift file names.
Expand Down
3 changes: 2 additions & 1 deletion pyproject.toml
Original file line number Diff line number Diff line change
Expand Up @@ -46,6 +46,7 @@ dev = [
"myst-parser[linkify]",
"packaging",
"pytest",
"pytest-httpx",
"pytest-xdist",
"ruff",
"shiv",
Expand Down Expand Up @@ -170,7 +171,7 @@ args = ["sphinx-build", "-b", "{-type:html}", "-aEW", "docs", "docs/build/{-type

[tool.dev-cmd.commands.run-zipapp]
env = {"SCIENCE_DOC_LOCAL" = "docs/build/html"}
args = ["dist/science.pyz"]
args = ["python", "dist/science.pyz"]
accepts-extra-args = true
hidden = true

Expand Down
2 changes: 1 addition & 1 deletion science/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -3,6 +3,6 @@

from packaging.version import Version

__version__ = "0.12.1"
__version__ = "0.12.2"

VERSION = Version(__version__)
15 changes: 12 additions & 3 deletions science/fetcher.py
Original file line number Diff line number Diff line change
Expand Up @@ -16,7 +16,7 @@
from netrc import NetrcParseError
from pathlib import Path
from types import TracebackType
from typing import Any, BinaryIO, ClassVar, Iterator, Mapping, Protocol
from typing import Any, BinaryIO, ClassVar, Generator, Iterator, Mapping, Protocol

import click
import httpx
Expand Down Expand Up @@ -75,7 +75,16 @@ class InvalidAuthError(InputError):
"""Indicates the configured authentication for a given URL is invalid."""


def _configure_auth(url: Url) -> httpx.Auth | tuple[str, str] | None:
class BearerAuth(httpx.Auth):
def __init__(self, token: str):
self._token = token

def auth_flow(self, request: Request) -> Generator[Request, Response, None]:
request.headers["Authorization"] = f"Bearer {self._token}"
yield request


def _configure_auth(url: Url) -> httpx.Auth | None:
if not url.info.hostname:
return None

Expand Down Expand Up @@ -105,7 +114,7 @@ def require_password(auth_type: str) -> str:

if bearer := env_auth.pop(f"{env_auth_prefix}_BEARER", None):
check_ambiguous_auth("bearer")
return "Authorization", f"Bearer {bearer}"
return BearerAuth(bearer)

if username := get_username("basic"):
password = require_password("basic")
Expand Down
63 changes: 61 additions & 2 deletions tests/test_fetcher.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,16 @@
# Copyright 2024 Science project contributors.
# Licensed under the Apache License, Version 2.0 (see LICENSE).

import base64
import os
import shutil
from pathlib import Path

import httpx
from pytest import MonkeyPatch
from pytest_httpx import HTTPXMock
from testing import issue

from science.fetcher import fetch_text
from science.fetcher import fetch_json, fetch_text
from science.model import Url


Expand All @@ -32,3 +35,59 @@ def assert_fetch() -> None:
monkeypatch.setenv("HOME", str(home_dir))
(home_dir / ".netrc").mkdir(parents=True)
assert_fetch()


def assert_auth(
monkeypatch: MonkeyPatch,
httpx_mock: HTTPXMock,
cache_dir: Path,
*,
expected_authorization_header_value: str,
**auth_env_vars: str,
) -> None:
# N.B.: Ensure a fresh, un-cached fetch.
shutil.rmtree(cache_dir, ignore_errors=True)

# N.B.: Ensure any ambient auth setup (like we have in CI) is ignored.
for key in os.environ:
if key.startswith("SCIENCE_AUTH_"):
monkeypatch.delenv(key)

for name, value in auth_env_vars.items():
monkeypatch.setenv(name, value)

def reflect_headers(request: httpx.Request) -> httpx.Response:
return httpx.Response(status_code=200, json=dict(request.headers.multi_items()))

httpx_mock.add_callback(reflect_headers)

headers = httpx.Headers(
fetch_json(
Url("https://api.github.com/repos/astral-sh/python-build-standalone/releases/latest")
)
)
assert expected_authorization_header_value == headers.get(
"Authorization"
), f"Got headers: {headers}"


def test_basic_auth(monkeypatch: MonkeyPatch, httpx_mock: HTTPXMock, cache_dir: Path) -> None:
assert_auth(
monkeypatch,
httpx_mock,
cache_dir,
expected_authorization_header_value=f"Basic {base64.b64encode(b'Arthur:Dent').decode()}",
SCIENCE_AUTH_API_GITHUB_COM_BASIC_USER="Arthur",
SCIENCE_AUTH_API_GITHUB_COM_BASIC_PASS="Dent",
)


@issue(127, ignore=True)
def test_bearer_auth(_, monkeypatch: MonkeyPatch, httpx_mock: HTTPXMock, cache_dir: Path) -> None:
assert_auth(
monkeypatch,
httpx_mock,
cache_dir,
expected_authorization_header_value="Bearer Zaphod",
SCIENCE_AUTH_API_GITHUB_COM_BEARER="Zaphod",
)
15 changes: 15 additions & 0 deletions uv.lock

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

Loading