Skip to content

fix: pass auth via Request constructor instead of calling HTTPBasicAuth on unprepared Request#10748

Open
Affanmir wants to merge 2 commits intopython-poetry:mainfrom
Affanmir:fix/authenticator-basic-auth-request-preparation
Open

fix: pass auth via Request constructor instead of calling HTTPBasicAuth on unprepared Request#10748
Affanmir wants to merge 2 commits intopython-poetry:mainfrom
Affanmir:fix/authenticator-basic-auth-request-preparation

Conversation

@Affanmir
Copy link

@Affanmir Affanmir commented Feb 24, 2026

Summary

  • Fixes a bug where HTTPBasicAuth().__call__() was invoked on an unprepared requests.Request object, setting the Authorization header directly on request.headers. When session.prepare_request() subsequently processed this request, the header could be corrupted during header merging — specifically, Base64-encoded credentials were truncated (e.g., from 260 to 230 characters), causing 401 Unauthorized errors.
  • The fix passes auth=HTTPBasicAuth(...) to the Request() constructor instead, so the auth callable is properly applied during prepare_request() via prepare_auth(). This is the idiomatic requests library pattern.
  • This primarily affected users authenticating to Google Artifact Registry with OAuth2 access tokens, where the long token values were susceptible to header corruption during preparation.

Reproduction

import requests
import requests.auth

token = "ya29.<long_oauth2_access_token>"  # ~260 chars
url = "https://us-central1-python.pkg.dev/<project>/<repo>/simple/<package>/"

session = requests.Session()

# BEFORE (broken): call HTTPBasicAuth on unprepared Request
req = requests.Request("GET", url)
req = requests.auth.HTTPBasicAuth("oauth2accesstoken", token)(req)
prep = session.prepare_request(req)
resp = session.send(prep)  # → 401

# AFTER (fixed): pass auth= to Request constructor
req = requests.Request("GET", url, auth=("oauth2accesstoken", token))
prep = session.prepare_request(req)
resp = session.send(prep)  # → 200

Related Issues

Test plan

  • All 42 existing tests in tests/utils/test_authenticator.py pass
  • Verified manually against a live Google Artifact Registry with OAuth2 access tokens

Summary by Sourcery

Bug Fixes:

  • Resolve truncated Authorization headers that caused 401 responses when authenticating with long credentials, such as OAuth2 tokens against Google Artifact Registry.

…th on unprepared Request

Previously, `HTTPBasicAuth(username, password)(request)` was called on an
unprepared `requests.Request` object, which set the Authorization header
directly on `request.headers`. When `session.prepare_request()` subsequently
processed this request, the Authorization header could be corrupted during
header merging — specifically, Base64-encoded credentials were being
truncated (e.g., from 260 to 230 characters), causing 401 errors from
registries that validate the full token.

The fix passes `auth=HTTPBasicAuth(...)` to the `Request()` constructor
instead, so the auth callable is properly applied during `prepare_request()`
via `prepare_auth()`. This is the idiomatic `requests` library pattern and
ensures credentials are correctly encoded in the final prepared request.

This primarily affected users authenticating to Google Artifact Registry
with OAuth2 access tokens, where the long token values were susceptible
to the header corruption during preparation.

Co-Authored-By: Claude Opus 4.6 <noreply@anthropic.com>
@sourcery-ai
Copy link

sourcery-ai bot commented Feb 24, 2026

Reviewer's guide (collapsed on small PRs)

Reviewer's Guide

Adjusts how HTTP basic auth is applied to outgoing requests by passing the auth callable into the requests.Request constructor instead of mutating an unprepared Request, preventing Authorization header corruption during prepare_request().

Sequence diagram for applying HTTPBasicAuth via Request constructor

sequenceDiagram
    participant Client as ClientCode
    participant Auth as Authenticator
    participant Req as requests_Request
    participant HBA as HTTPBasicAuth
    participant Sess as requests_Session

    Client->>Auth: request(method, url, headers, kwargs)
    Auth->>Auth: credential = get_credentials_for_url(url)
    alt username_or_password_present
        Auth->>HBA: create HTTPBasicAuth(credential.username, credential.password)
        HBA-->>Auth: auth
    else no_credentials
        Auth-->>Auth: auth = None
    end
    Auth->>Req: new Request(method, url, headers, auth)
    Auth->>Sess: get_session(url)
    Sess-->>Auth: session
    Auth->>Sess: prepare_request(Request)
    Sess-->>Auth: PreparedRequest (Authorization set via prepare_auth)
    Auth->>Sess: send(PreparedRequest)
    Sess-->>Auth: Response
    Auth-->>Client: Response
Loading

Class diagram for updated Authenticator.request authentication flow

classDiagram
    class Authenticator {
        +request(method: str, url: str, raise_for_status: bool, kwargs: Any) requests_Response
        +get_credentials_for_url(url: str) Credential
        +get_session(url: str) requests_Session
    }

    class Credential {
        +username: Optional~str~
        +password: Optional~str~
    }

    class requests_Request {
        +method: str
        +url: str
        +headers: Optional~dict~
        +auth: Optional~HTTPBasicAuth~
    }

    class HTTPBasicAuth {
        +username: str
        +password: str
        +__call__(request: requests_Request) requests_Request
    }

    class requests_Session {
        +prepare_request(request: requests_Request) PreparedRequest
        +send(request: PreparedRequest) requests_Response
    }

    class PreparedRequest {
        +headers: dict
        +body: Any
    }

    Authenticator --> Credential : uses
    Authenticator --> requests_Request : constructs
    Authenticator --> HTTPBasicAuth : constructs
    Authenticator --> requests_Session : uses
    requests_Session --> PreparedRequest : prepares
    HTTPBasicAuth --> requests_Request : configures_auth_on
    PreparedRequest --> requests_Request : prepared_from
Loading

File-Level Changes

Change Details Files
Apply HTTPBasicAuth via the Request constructor so auth is prepared correctly and long Authorization headers are not corrupted.
  • Stop constructing a bare Request and then calling HTTPBasicAuth on the unprepared request object.
  • Introduce an auth variable that is conditionally set when credentials are available.
  • Construct the requests.Request with headers and the auth parameter, letting prepare_request/prepare_auth handle header injection.
src/poetry/utils/authenticator.py

Possibly linked issues

  • Authentication to private registry fails #9910: PR changes how auth is passed to requests so prepare_request uses correct credentials, resolving the 401 auth failures.
  • #unknown: PR fixes broken HTTP basic auth request preparation, which likely causes the CI private registry authorization failures described.

Tips and commands

Interacting with Sourcery

  • Trigger a new review: Comment @sourcery-ai review on the pull request.
  • Continue discussions: Reply directly to Sourcery's review comments.
  • Generate a GitHub issue from a review comment: Ask Sourcery to create an
    issue from a review comment by replying to it. You can also reply to a
    review comment with @sourcery-ai issue to create an issue from it.
  • Generate a pull request title: Write @sourcery-ai anywhere in the pull
    request title to generate a title at any time. You can also comment
    @sourcery-ai title on the pull request to (re-)generate the title at any time.
  • Generate a pull request summary: Write @sourcery-ai summary anywhere in
    the pull request body to generate a PR summary at any time exactly where you
    want it. You can also comment @sourcery-ai summary on the pull request to
    (re-)generate the summary at any time.
  • Generate reviewer's guide: Comment @sourcery-ai guide on the pull
    request to (re-)generate the reviewer's guide at any time.
  • Resolve all Sourcery comments: Comment @sourcery-ai resolve on the
    pull request to resolve all Sourcery comments. Useful if you've already
    addressed all the comments and don't want to see them anymore.
  • Dismiss all Sourcery reviews: Comment @sourcery-ai dismiss on the pull
    request to dismiss all existing Sourcery reviews. Especially useful if you
    want to start fresh with a new review - don't forget to comment
    @sourcery-ai review to trigger a new review!

Customizing Your Experience

Access your dashboard to:

  • Enable or disable review features such as the Sourcery-generated pull request
    summary, the reviewer's guide, and others.
  • Change the review language.
  • Add, remove or edit custom review instructions.
  • Adjust other review settings.

Getting Help

Copy link

@sourcery-ai sourcery-ai bot left a comment

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

Hey - I've reviewed your changes and they look great!


Sourcery is free for open source - if you like our reviews please consider sharing them ✨
Help me be more useful! Please click 👍 or 👎 on each comment and I'll use the feedback to improve your reviews.

@Affanmir
Copy link
Author

@sdispater @abn @radoering Hello, hope you're doing well. Would it be possible to get a review on this PR? I have tested the changes locally and they work. Was facing an issue with Auth w.r.t GCP Artifact Registry, have highlighted the issue as well. Let me know if anything else is needed from my side

@Affanmir
Copy link
Author

@Secrus Are you the correct person to ask for a review for this PR? Having a difficult time identifying who has write access

@Secrus
Copy link
Member

Secrus commented Feb 27, 2026

@Affanmir patience please, we will get to reviewing your PR when we have time.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

None yet

Projects

None yet

Development

Successfully merging this pull request may close these issues.

2 participants