BasicAuth cleared permanently after cross-origin redirect in HTTP transport

Ouverte
#2,136 1 commentaire 0 réactions 0 personnes assignées Voir sur GitHub

Les mainteneurs répondent en général sous 3 jours

Personne n'a encore pris cette issue.

Évaluation

Difficulté
3/5
Temps estimé
1-2 jours
Accessibilité débutants
67/100
Type d'issue
Bug
Clarté
Clairement spécifiée
Activité
Calme
Stack technique
git, go

Piste de recherche

Commencez dans plumbing/transport/http/common.go, au niveau de ModifyEndpointIfRedirect, et suivez la manière dont s.auth est appliqué aux requêtes suivantes. Exécutez ou adaptez la reproduction décrite TestFetch_BasicAuth_ClearedOnRedirect, puis vérifiez qu’une redirection entre hôtes ou entre ports permet toujours au POST upload-pack authentifié de réussir sans affaiblir le comportement de sécurité de la redirection.

Rédigé par le modèle d'indexation à partir du texte de l'issue.

Description

Description

When repo.Fetch() (or any upload-pack session) encounters an HTTP redirect that changes the host or port, ModifyEndpointIfRedirect permanently sets s.auth = nil for the entire session. This means the subsequent POST /git-upload-pack request is sent without any authentication, even though valid credentials were provided via BasicAuth.

CLI git does not have this problem — it re-applies http.extraHeader credentials independently on each new request after updating the remote URL.

Affected code

plumbing/transport/http/common.go, lines ~387-390:

if host != s.endpoint.Host || effectivePort(r.URL.Scheme, port) != effectivePort(s.endpoint.Protocol, s.endpoint.Port) {
    s.endpoint.User = ""
    s.endpoint.Password = ""
    s.auth = nil  // ← clears auth for ALL subsequent requests in the session
}

Steps to reproduce

  1. Set up two HTTP servers on the same host but different ports (e.g., 127.0.0.1:A and 127.0.0.1:B)
  2. Server A redirects GET /info/refs?service=git-upload-pack to Server B (HTTP 307)
  3. Server B allows /info/refs without auth but requires Basic Auth on POST /git-upload-pack
  4. Clone a repo from Server B directly, then set the remote to Server A
  5. Call repo.Fetch() with valid BasicAuth credentials

Expected: Fetch succeeds — auth should be re-applied to the upload-pack POST after the redirect.

Actual: Fetch fails with authentication required. go-git clears s.auth when ModifyEndpointIfRedirect detects the port change, so the upload-pack POST is sent without credentials.

Reproduction test

func TestFetch_BasicAuth_ClearedOnRedirect(t *testing.T) {
    // Server B (backend): serves git protocol, requires auth on upload-pack only
    backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        isDiscovery := strings.Contains(r.URL.Path, "/info/refs")
        if !isDiscovery {
            user, pass, ok := r.BasicAuth()
            if !ok || user != "x-access-token" || pass != "token" {
                w.Header().Set("WWW-Authenticate", `Basic realm="git"`)
                http.Error(w, "authentication required", http.StatusUnauthorized)
                return
            }
        }
        // ... serve git-http-backend
    }))

    // Server A (front): redirects /info/refs to backend (different port)
    front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
        if strings.Contains(r.URL.Path, "/info/refs") {
            http.Redirect(w, r, backend.URL+r.URL.RequestURI(), http.StatusTemporaryRedirect)
            return
        }
        // ... serve other paths directly
    }))

    // Clone from backend, point remote at front, then fetch
    // go-git Fetch with BasicAuth will fail after redirect clears s.auth
    err := repo.Fetch(&git.FetchOptions{
        RemoteName: "origin",
        Auth: &http.BasicAuth{Username: "x-access-token", Password: "token"},
    })
    // err = "authentication required" — auth was cleared by ModifyEndpointIfRedirect
}

Impact

This affects any deployment where the git remote goes through a load balancer, CDN, or proxy that redirects to a different host or port. GitHub's infrastructure can trigger this in production environments.

We discovered this as SOF-953 — ~90 errors/day in production with Fetch failed: Repository not found against private GitHub repos. CLI git from the same pod with the same token worked every time. Our fix was to switch Fetch from go-git to CLI git via exec.Command.

Suggested fix

Instead of clearing s.auth entirely in ModifyEndpointIfRedirect, preserve the auth method so it can be re-applied to subsequent requests at the new endpoint:

// Don't clear s.auth — the caller provided credentials for this session,
// and the redirect just changed where requests go, not whether the caller
// is authorized.
if host != s.endpoint.Host || effectivePort(r.URL.Scheme, port) != effectivePort(s.endpoint.Protocol, s.endpoint.Port) {
    s.endpoint.Host = host
    s.endpoint.Port = effectivePort(r.URL.Scheme, port)
    // s.auth intentionally preserved — re-applied on subsequent requests
}

If there's a security concern about sending credentials to an unexpected host, consider logging a warning rather than silently dropping auth, or making it configurable via a FetchOptions field.

Environment

  • go-git v5.19.0
  • Go 1.25.9
  • GitHub.com (private repos via GitHub App installation tokens)
Langage dominant
Go
Étoiles
7.9k
Forks
1.1k
Merge moyen
4 j 19 h
PR mergées (30 j)
34

Préparer son environnement

Par où commencer

  1. Lisez l'issue en entier, puis le guide de contribution du projet.
  2. Signalez en commentaire que vous la prenez — cela évite que deux personnes fassent le même travail.
  3. Forkez le dépôt et travaillez sur une branche.
  4. Ouvrez une pull request qui référence le numéro de l'issue.

Autres issues de go-git/go-git

Toutes les issues de go-git/go-git

Issues similaires

Plus d'issues Go

Recevez les nouvelles issues par e-mail

Un résumé court des issues GitHub adaptées aux débutants.