Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
Show all changes
22 commits
Select commit Hold shift + click to select a range
b3ac11b
transform DoWithAuth from recurrent to loop approach to prevent endle…
manturovDan Mar 19, 2025
4332f65
improve DoWithAuth retry loop by removing count variable and unnecess…
tamaracvjetkovic Aug 26, 2025
e87ac8f
use range loop instead of counted loop in DoWithAuth
tamaracvjetkovic Aug 26, 2025
a9f4927
replace := with = for access variable in DoWithAuth loop
tamaracvjetkovic Aug 27, 2025
a775cea
add TestDoWithAuthRetryLimitExceeded to verify DoWithAuth stops after…
tamaracvjetkovic Sep 1, 2025
5ec91bb
set Lfs-Authenticate auth header in TestDoWithAuthRetryLimitExceeded
tamaracvjetkovic Sep 2, 2025
1fe9b17
add TestDoWithAuthNoRetryOn401WhenAuthHeaderPresent in auth_test.go
tamaracvjetkovic Sep 2, 2025
7eed85e
add TestDoWithAuthMultistageRetryLimitExceeded with non-advancing mul…
tamaracvjetkovic Sep 2, 2025
8359673
Merge branch 'main' into fix_endless_authentication_attempts
chrisd8088 Oct 28, 2025
c614460
Merge branch 'main' into fix_endless_authentication_attempts
chrisd8088 Mar 4, 2026
c352a7e
lfsapi: add and fix comments re preset auth header
chrisd8088 Jan 28, 2026
9c78f96
lfsapi/auth_test.go: consistent access mode checks
chrisd8088 Feb 1, 2026
1b9b59b
t: add and update auth tests of bad passwords
chrisd8088 Jan 28, 2026
49f784c
t: add tests of repeated unauth API responses
chrisd8088 Jan 27, 2026
1245cbc
t/t-credentials.sh: add multi-stage auth loop test
chrisd8088 Jan 28, 2026
3c606d2
lfsapi,t: log trace when auth attempts exhausted
chrisd8088 Feb 1, 2026
18290a6
lfsapi,t: reset state when auth attempts exhausted
chrisd8088 Feb 1, 2026
c323f76
lfsapi,t: count only auth attempts toward loop max
chrisd8088 Feb 1, 2026
24bd477
t/cmd/lfstest-gitserver.go: fix debug log message
chrisd8088 Apr 2, 2026
98014b5
lfsapi/auth.go: log trace if auth attempts remain
chrisd8088 Apr 2, 2026
30b3075
lfsapi/auth.go: close unused auth request bodies
chrisd8088 Apr 2, 2026
163dcaa
Merge branch 'main' into fix_endless_authentication_attempts
chrisd8088 Apr 2, 2026
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
94 changes: 54 additions & 40 deletions lfsapi/auth.go
Original file line number Diff line number Diff line change
Expand Up @@ -24,30 +24,52 @@ var (
// authentication from netrc or git's credential helpers if necessary,
// supporting basic authentication.
func (c *Client) DoWithAuth(remote string, access creds.Access, req *http.Request) (*http.Response, error) {
count := 0
res, err := c.doWithAuth(remote, &count, access, req, nil)

if errors.IsAuthError(err) {
if len(req.Header.Get("Authorization")) == 0 {
// This case represents a rejected request that
// should have been authenticated but wasn't. Do
// not count this against our redirection
// maximum.
newAccess := c.Endpoints.AccessFor(access.URL())
tracerx.Printf("api: http response indicates %q authentication. Resubmitting...", newAccess.Mode())
return c.DoWithAuth(remote, newAccess, req)
maxAuthAttempts := defaultMaxAuthAttempts
if access.Mode() == creds.NoneAccess {
maxAuthAttempts++
}

for i := range maxAuthAttempts {
res, err := c.doWithAuth(remote, access, req, nil)
if err == nil || !errors.IsAuthError(err) {
return res, err
}

Comment thread
chrisd8088 marked this conversation as resolved.
Resolved
// We expect this condition should occur only when an
// Authorization header was already set for the request
// and the request was rejected. Otherwise, after a 401
// status code is received, doWithAuth() will remove any
// Authorization header that it added to the request.
if len(req.Header.Get("Authorization")) != 0 {
return res, err
}

// This case represents a rejected request that
// should have been authenticated but wasn't, possibly because
// it is part of a multi-stage authentication sequence.
if res != nil && res.Body != nil {
res.Body.Close()
}

// If at least one more attempt is still permitted, we update
// the access mode and retry the request.
if i < maxAuthAttempts-1 {
access = c.Endpoints.AccessFor(access.URL())
tracerx.Printf("api: http response indicates %q authentication. Resubmitting...", access.Mode())
}
}
Comment thread
chrisd8088 marked this conversation as resolved.
Resolved

return res, err
c.credContext.SetStateFields(nil)

tracerx.Printf("api: too many authentication attempts")
return nil, fmt.Errorf("too many authentication attempts")

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

maybe too many failed authentication attempts?

Copy link
Copy Markdown
Member

Choose a reason for hiding this comment

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

I started to implement this change, but on reflection, I think the message is probably sufficient as it stands, for a few reasons.

First, I would hope that the statement that "too many attempts" have been made should imply to most readers that these attempts have not all been successful.

Second, while each attempt has received a 401 response, they haven't been outright denied with a 403. So in that sense they haven't failed—but they also haven't completely succeeded.

As a concrete example, in a long multi-stage authentication sequence, each stage could "succeed" in the sense that a 401 is returned and so prompt the client to proceed to the next stage, but we might still report this error if the number of stages exceeds our allowed maximum. While this is probably not going to occur in practice for anyone, I think this was the spirit in which the error message was first written, back in commit 6783078 of PR #5803.

In other words, the client has made multiple authentication requests, but hasn't reached a point of either being accepted or denied. Its attempts to authenticate haven't specifically failed or succeeded, just reached an internal limit on the number of attempts.

}

// DoWithAuthNoRetry sends an HTTP request to get an HTTP response. It works in
// the same way as DoWithAuth, but will not retry the request if it fails with
// an authorization error.
func (c *Client) DoWithAuthNoRetry(remote string, access creds.Access, req *http.Request) (*http.Response, error) {
count := 0
return c.doWithAuth(remote, &count, access, req, nil)
return c.doWithAuth(remote, access, req, nil)
}

// DoAPIRequestWithAuth sends an HTTP request to get an HTTP response similarly
Expand All @@ -60,11 +82,7 @@ func (c *Client) DoAPIRequestWithAuth(remote string, req *http.Request) (*http.R
return c.DoWithAuth(remote, access, req)
}

func (c *Client) doWithAuth(remote string, count *int, access creds.Access, req *http.Request, via []*http.Request) (*http.Response, error) {
if *count == defaultMaxAuthAttempts {
return nil, fmt.Errorf("too many authentication attempts")
}

func (c *Client) doWithAuth(remote string, access creds.Access, req *http.Request, via []*http.Request) (*http.Response, error) {
req.Header = c.client.ExtraHeadersFor(req)

credWrapper, err := c.getCreds(remote, access, req)
Expand All @@ -73,27 +91,23 @@ func (c *Client) doWithAuth(remote string, count *int, access creds.Access, req
}
c.credContext.SetStateFields(credWrapper.Creds["state[]"])

res, err := c.doWithCreds(req, count, credWrapper, access, via)
if err != nil {
if errors.IsAuthError(err) {
multistage := credWrapper.Creds.IsMultistage()
newMode, newModes, headers := getAuthAccess(res, access.Mode(), c.access, multistage)
newAccess := access.Upgrade(newMode)
if newAccess.Mode() != access.Mode() {
c.Endpoints.SetAccess(newAccess)
c.access = newModes
}
res, err := c.doWithCreds(req, credWrapper, access, via)
if err != nil && errors.IsAuthError(err) {
multistage := credWrapper.Creds.IsMultistage()
newMode, newModes, headers := getAuthAccess(res, access.Mode(), c.access, multistage)
newAccess := access.Upgrade(newMode)
if newAccess.Mode() != access.Mode() {
c.Endpoints.SetAccess(newAccess)
c.access = newModes
}

if credWrapper.Creds != nil {
req.Header.Del("Authorization")
if multistage && *count < defaultMaxAuthAttempts && res != nil && res.StatusCode == 401 {
*count++
} else {
credWrapper.CredentialHelper.Reject(credWrapper.Creds)
}
if credWrapper.Creds != nil {
req.Header.Del("Authorization")
if !multistage {
credWrapper.CredentialHelper.Reject(credWrapper.Creds)
}
c.credContext.SetWWWAuthHeaders(headers)
}
c.credContext.SetWWWAuthHeaders(headers)
}

if res != nil && res.StatusCode < 300 && res.StatusCode > 199 {
Expand All @@ -103,7 +117,7 @@ func (c *Client) doWithAuth(remote string, count *int, access creds.Access, req
return res, err
}

func (c *Client) doWithCreds(req *http.Request, count *int, credWrapper creds.CredentialHelperWrapper, access creds.Access, via []*http.Request) (*http.Response, error) {
func (c *Client) doWithCreds(req *http.Request, credWrapper creds.CredentialHelperWrapper, access creds.Access, via []*http.Request) (*http.Response, error) {
if access.Mode() == creds.NegotiateAccess {
return c.doWithNegotiate(req, credWrapper)
}
Expand All @@ -124,7 +138,7 @@ func (c *Client) doWithCreds(req *http.Request, count *int, credWrapper creds.Cr
return res, errors.New(tr.Tr.Get("failed to redirect request"))
}

return c.doWithAuth("", count, access, redirectedReq, via)
return c.doWithAuth("", access, redirectedReq, via)
}

// getCreds fills the authorization header for the given request if possible,
Expand Down
152 changes: 146 additions & 6 deletions lfsapi/auth_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -92,7 +92,7 @@ func TestDoWithAuthApprove(t *testing.T) {
c.Credentials = cred

access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.NoneAccess, (&access).Mode())
assert.Equal(t, creds.NoneAccess, access.Mode())

req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
require.Nil(t, err)
Expand All @@ -111,7 +111,7 @@ func TestDoWithAuthApprove(t *testing.T) {
"host": []string{srv.Listener.Addr().String()},
})))
access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.BasicAccess, (&access).Mode())
assert.Equal(t, creds.BasicAccess, access.Mode())
assert.EqualValues(t, 2, called)
}

Expand Down Expand Up @@ -220,7 +220,7 @@ func TestDoWithAuthNoRetry(t *testing.T) {
c.Credentials = cred

access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.NoneAccess, (&access).Mode())
assert.Equal(t, creds.NoneAccess, access.Mode())

req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
require.Nil(t, err)
Expand All @@ -232,10 +232,150 @@ func TestDoWithAuthNoRetry(t *testing.T) {
access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.True(t, errors.IsAuthError(err))
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.Equal(t, creds.BasicAccess, (&access).Mode())
assert.Equal(t, creds.BasicAccess, access.Mode())
assert.EqualValues(t, 1, called)
}

func TestDoWithAuthRetryLimitExceeded(t *testing.T) {
var called uint32

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
atomic.AddUint32(&called, 1)
assert.Equal(t, "POST", req.Method)

body := &authRequest{}
err := json.NewDecoder(req.Body).Decode(body)
assert.Nil(t, err)
assert.Equal(t, "Reject", body.Test)

w.Header().Set("Lfs-Authenticate", "Basic")
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()

cred := newMockCredentialHelper()
c, err := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
nil, map[string]string{
"lfs.url": srv.URL + "/repo/lfs",
},
))
require.Nil(t, err)
c.Credentials = cred

access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.NoneAccess, access.Mode())

req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
require.Nil(t, err)

err = MarshalToRequest(req, &authRequest{Test: "Reject"})
require.Nil(t, err)

res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
require.Error(t, err)
assert.EqualError(t, err, "too many authentication attempts")
require.Nil(t, res)

access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.BasicAccess, access.Mode())
assert.EqualValues(t, defaultMaxAuthAttempts+1, called)
}

func TestDoWithAuthNoRetryOn401WhenAuthHeaderPresent(t *testing.T) {
var called uint32

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
atomic.AddUint32(&called, 1)
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()

cred := newMockCredentialHelper()
c, err := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
nil, map[string]string{
"lfs.url": srv.URL + "/repo/lfs",
},
))
require.Nil(t, err)
c.Credentials = cred

req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
require.Nil(t, err)

// We set the Authorization header explicitly so as to exercise the
// check for an extant Authorization header in DoWithAuth().
//
// Otherwise an Authorization header will be added automatically for
// each request attempt subsequent to the first, since the server
// always returns 401, but the header will then be removed by
// doWithAuth() when it receives another 401, so DoWithAuth() will
// never find an extant Authorization header in any requests.
req.Header.Set("Authorization", basicAuth("user", "pass"))
Comment thread
chrisd8088 marked this conversation as resolved.
Resolved
err = MarshalToRequest(req, &authRequest{Test: "Reject"})
require.Nil(t, err)

res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
require.Error(t, err)
assert.True(t, errors.IsAuthError(err))
assert.NotNil(t, res)
assert.Equal(t, http.StatusUnauthorized, res.StatusCode)
assert.EqualValues(t, 1, called)
}

func TestDoWithAuthMultistageRetryLimitExceeded(t *testing.T) {
var called uint32

srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
atomic.AddUint32(&called, 1)
w.Header().Set("Www-Authenticate", "Multistage type=foo")
w.WriteHeader(http.StatusUnauthorized)
}))
defer srv.Close()

cred := newNonAdvancingMultistageHelper()
c, err := NewClient(lfshttp.NewContext(git.NewReadOnlyConfig("", ""),
nil, map[string]string{
"lfs.url": srv.URL + "/repo/lfs",
},
))
require.Nil(t, err)
c.Credentials = cred

req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
require.Nil(t, err)

err = MarshalToRequest(req, &authRequest{Test: "Reject"})
require.Nil(t, err)

res, err := c.DoWithAuth("", c.Endpoints.AccessFor(srv.URL+"/repo/lfs"), req)
require.Error(t, err)
assert.EqualError(t, err, "too many authentication attempts")
assert.Nil(t, res)

access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.BasicAccess, access.Mode())
assert.EqualValues(t, defaultMaxAuthAttempts+1, called)
}

type nonAdvancingMultistageHelper struct{}

func newNonAdvancingMultistageHelper() *nonAdvancingMultistageHelper {
return &nonAdvancingMultistageHelper{}
}

func (nonAdvancingMultistageHelper) Fill(input creds.Creds) (creds.Creds, error) {
out := make(creds.Creds)
for k, v := range input {
out[k] = v
}
out["authtype"] = []string{"Multistage"}
out["credential"] = []string{"cred1"}
out["state[]"] = []string{"lfstest:state1"}
return out, nil
}
func (nonAdvancingMultistageHelper) Approve(creds.Creds) error { return nil }
func (nonAdvancingMultistageHelper) Reject(creds.Creds) error { return nil }

func TestDoAPIRequestWithAuth(t *testing.T) {
var called uint32

Expand Down Expand Up @@ -272,7 +412,7 @@ func TestDoAPIRequestWithAuth(t *testing.T) {
c.Credentials = cred

access := c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.NoneAccess, (&access).Mode())
assert.Equal(t, creds.NoneAccess, access.Mode())

req, err := http.NewRequest("POST", srv.URL+"/repo/lfs/foo", nil)
require.Nil(t, err)
Expand All @@ -291,7 +431,7 @@ func TestDoAPIRequestWithAuth(t *testing.T) {
"host": []string{srv.Listener.Addr().String()},
})))
access = c.Endpoints.AccessFor(srv.URL + "/repo/lfs")
assert.Equal(t, creds.BasicAccess, (&access).Mode())
assert.Equal(t, creds.BasicAccess, access.Mode())
assert.EqualValues(t, 2, called)
}

Expand Down
26 changes: 17 additions & 9 deletions t/cmd/lfstest-gitserver.go
Original file line number Diff line number Diff line change
Expand Up @@ -69,6 +69,7 @@ var (

reqCookieReposRE = regexp.MustCompile(`\A/require-cookie-`)
dekInfoRE = regexp.MustCompile(`DEK-Info: AES-128-CBC,([a-fA-F0-9]*)`)
multiStageCredRE = regexp.MustCompile(`\Acred(\d+)of(\d+)\z`)
)

func main() {
Expand Down Expand Up @@ -1735,18 +1736,25 @@ func skipIfBadAuth(w http.ResponseWriter, r *http.Request, id string) bool {
return false
}
case "Multistage":
if cred == "cred1" {
wantedAuth = "Multistage type=bar"
w.Header().Add(authHeader, wantedAuth)
w.WriteHeader(401)
debug(id, "auth stage 1 succeeded: %q", auth)
return true
} else if cred == "cred2" {
return false
if matches := multiStageCredRE.FindStringSubmatch(cred); len(matches) == 3 {
if matches[1] == matches[2] {
return false
} else {
wantedAuth = "Multistage type=bar"
w.Header().Add(authHeader, wantedAuth)
w.WriteHeader(401)
debug(id, "auth stage %s of %s succeeded: %q", matches[1], matches[2], auth)
return true
}
}
}

w.WriteHeader(403)
repo, _ := repoFromLfsUrl(r.URL.Path)
if strings.HasSuffix(repo, "-401-unauth") {
w.WriteHeader(401)
} else {
w.WriteHeader(403)
}
debug(id, "Bad auth: %q", auth)
return true
}
Expand Down
Loading
Loading