Repository navigation
fall back to guessed endpoint when git-lfs-authenticate is unavailable - #6286
Conversation
…navailable When an SSH remote's server does not provide the git-lfs-authenticate command, a usable LFS endpoint has already been guessed from the remote URL. Previously any non-zero exit from git-lfs-authenticate was treated as fatal, so such servers could not be used over SSH without explicitly configuring lfs.url. Detect the unavailable command in sshAuthClient.Resolve and signal it with a distinct sshAuthenticateUnavailableError. sshResolveWithRetries then falls back to the guessed endpoint (authenticating via the normal Git credential helper) instead of failing, and stops retrying since a missing command will not become available. Detection covers both the conventional command-not-found exit code (127) and servers that return a generic exit code with a 'not found'-style message. Gerrit, for example, runs the command through a restricted shell and responds with exit code 1 and the message: fatal: Gerrit Code Review: git-lfs-authenticate: not found Message matching is anchored to the command name so that unrelated errors such as a missing repository are not misclassified. Any other non-zero exit code remains fatal.
There was a problem hiding this comment.
Hey, thanks very much for this PR and for the analysis of the issue it addresses!
Both the general approach and the specific implementation look good to me.
There's a test failure which will need to be resolved, and I'd recommend renaming and moving one Go test function.
The other recommendation I'd make is that we'll also want an integration test in our shell test suite.
We can easily modify our t/cmd/lfs-ssh-echo.go utility to return a 127 exit code when a certain repository name is provided in its arguments. (We use this utility in our integration tests to simulate an SSH client.)
The challenge we'll run into is that our t/cmd/lfstest-gitserver.go test utility, which simulates remote Git and Git LFS services, starts its HTTP services on non-standard ports, but the fallback URL constructed by the Git LFS client explicitly drops any port number that specified as part of an SSH URL.
For our existing tests, when our lfs-ssh-echo utility returns a JSON response to a git-lfs-authenticate command invocation, it provides an href element whose HTTP URL contains the same port that was used for the SSH command. The Git LFS client then prefers that URL to the fallback one it has constructed.
However, if our lfs-ssh-echo utility returns a 127 exit code and no JSON response, the client will try an HTTP URL without a port, and since our lfstest-gitserver utility doesn't listen on port 443, the test will likely fail (but it depends on whether a "real" Git LFS service happens to be listening on port 443 and accepting requests).
Here's what I'd suggest. First, apply this patch to our t/cmd/lfs-ssh-echo.go utility:
diff --git a/t/cmd/lfs-ssh-echo.go b/t/cmd/lfs-ssh-echo.go
index ecb862e5..4bb9af87 100644
--- a/t/cmd/lfs-ssh-echo.go
+++ b/t/cmd/lfs-ssh-echo.go
@@ -53,8 +53,8 @@ func checkSufficientArgs(offset int) {
func main() {
// expect args:
- // lfs-ssh-echo [-p PORT [--]] [email protected] "git-lfs-authenticate REPO OPERATION"
- // lfs-ssh-echo [-p PORT [--]] [email protected] "git-lfs-transfer REPO OPERATION"
+ // lfs-ssh-echo [-p PORT [--]] [email protected][.invalid] "git-lfs-authenticate REPO OPERATION"
+ // lfs-ssh-echo [-p PORT [--]] [email protected][.invalid] "git-lfs-transfer REPO OPERATION"
// lfs-ssh-echo [email protected] "git-upload-pack REPO"
// lfs-ssh-echo [email protected] "git-receive-pack REPO"
offset := 1
@@ -114,8 +114,9 @@ func main() {
}
checkSufficientArgs(offset)
- if os.Args[offset] != "[email protected]" {
- fmt.Fprintf(os.Stderr, "expected \"[email protected]\", got %q", os.Args[offset])
+
+ if os.Args[offset] != "[email protected]" && os.Args[offset] != "[email protected]" {
+ fmt.Fprintf(os.Stderr, "expected \"[email protected]\" or \"[email protected]\", got %q", os.Args[offset])
os.Exit(1)
}
@@ -137,6 +138,10 @@ func main() {
repo := remoteCmd[1]
+ if repo == "/ssh-unavailable" {
+ os.Exit(127)
+ }
+
r := &sshResponse{
Href: fmt.Sprintf("http://127.0.0.1:%s/%s.git/info/lfs", os.Args[2], repo),
}Next, add this test to our t/t-ssh.sh script:
begin_test "SSH git-lfs-authenticate unavailable (fallback to HTTPS)"
(
set -e
# This repository name announces to the SSH test utility that it should
# exit as if the "git-lfs-authenticate" command was not found.
reponame="ssh-unavailable"
setup_remote_repo "$reponame"
clone_repo "$reponame" "$reponame"
# We construct an invalid host name (127.0.0.1.invalid) to guarantee that
# the HTTPS fallback URL, which will default to port 443, cannot contact
# any local or remote services not controlled by our test suite.
gitserver_hostport="${GITSERVER#http://}"
gitserver_host="${gitserver_hostport/%:*/}"
gitserver_port="${gitserver_hostport/#*:/}"
invalid_host="$gitserver_host.invalid"
git config lfs.url "ssh://git@$invalid_host:$gitserver_port/$reponame"
git lfs track "*.dat"
contents="test"
printf "%s" "$contents" >test.dat
git add .gitattributes test.dat
git commit -m "initial commit"
GIT_TRACE=1 git push origin main 2>&1 | tee push.log
[ 0 -ne "${PIPESTATUS[0]}" ]
# Requests to both the Locking API and the Batch API should fall back to
# an HTTPS URL, which should in turn fail because the host name is invalid.
[ 2 -eq "$(grep -c "exec: lfs-ssh-echo.*git-lfs-authenticate /$reponame upload" push.log)" ]
[ 2 -eq "$(grep -c -F "ssh: git@$invalid_host does not provide git-lfs-authenticate, falling back to guessed LFS endpoint" push.log)" ]
[ 2 -eq "$(grep -c -F "HTTP: POST https://$invalid_host/$reponame/" push.log)" ]
)
end_test
)
end_testOther tests could be added as well, for example to verify that an HTTPS fallback URL is attempted when the lfs-ssh-echo utility returns an exit code of 1 and a message like git-lfs-authenticate: command not found in reply to an SSH URL request for the git-lfs-authenticate command. You would just need to use a different repository name such as ssh-unavailable-not-found and further tweak the lfs-ssh-echo utility to recognize it and exit with the appropriate code and message.
Thanks again for working on this PR and for your help improving the Git LFS client!
| func TestSSHResolveUsesGuessedEndpointWhenAuthenticateUnavailable(t *testing.T) { | ||
| resolver := &countingResolver{ | ||
| err: &sshAuthenticateUnavailableError{ | ||
| err: errors.New("bash: git-lfs-authenticate: command not found"), | ||
| }, | ||
| } | ||
| c := newTestClient(t, resolver) | ||
|
|
||
| req, err := c.NewRequest("GET", testSSHEndpoint(), "objects/batch", nil) | ||
| assert.Nil(t, err) | ||
| assert.Equal(t, | ||
| "https://git-server.com/foo/bar.git/info/lfs/objects/batch", | ||
| req.URL.String()) | ||
| } |
There was a problem hiding this comment.
Although this test function is obviously very closely related to the other TestSSHResolve*() functions added in this PR, it's actually a test of the NewRequest() method rather than the sshResolveWithRetries() method.
Hence I would be inclined to call it TestNewRequestUsesGuessedEndpointWhenSSHAuthenticateUnavailable() or something along those lines.
I'd also be inclined to move it over with the other TestNewRequest*() test functions.
Co-authored-by: Chris Darroch <[email protected]>
Co-Authored-By: Chris Darroch <[email protected]>
|
Thanks for the detailed and substantial comments @chrisd8088. I think I have now implemented them all as requested. I also added a |
chrisd8088
left a comment
There was a problem hiding this comment.
Hey, thanks again for this PR and for adopting my suggestions and adding another test!
This is looking great. I had only a couple of minor suggestions as to how we might simplify the implementation of the two new shell integration tests, but otherwise I think this is ready to go.
I'll let the CI suite run to see how it does (sometimes we have unexpected regressions, so one of those may pop up and have to be fixed separately).
Thanks again for working on this enhancement to Git LFS!
Co-authored-by: Chris Darroch <[email protected]>
In prior commits in this PR we added two new tests to our "t/t-ssh.sh" integration shell test script and then refactored them to use a common test function we named ssh_authenticate_unavailable_test(). We introduced these new tests to help verify that the changes we made in several other prior commits in this PR are effective and cause the Git LFS client to try using a fallback HTTPS URL for its API requests when a remote SSH service indicates that the "git-lfs-authenticate" command is not available. We now revise these new tests slightly to clarify that the second of the tests is intended to simulate the behaviour of certain third-party tools such as the Gerrit Code Review utility, which returns an exit code of 1 and the message "git-lfs-authenticate: not found" rather than returning an exit code of 127. We also take the opportunity to adjust the indentation in our two new tests to match that of our other shell tests.
chrisd8088
left a comment
There was a problem hiding this comment.
Thanks again for all the work on this PR!
I tweaked the names and indentation of the two shell tests with one final commit, and expanded one test's comment to help clarify that it simulates the Gerrit Code Review condition you described.
Once our CI jobs pass, we can merge the PR. Thanks again for all the help!
In commit 72795a3 of PR #404 we expanded Git LFS client's support for SSH configurations, including remotes configured using SSH URLs (i.e., URLs with an "ssh:" scheme) and those configured using an scp(1)-style format (i.e., "<user>@<host>:<path>"). One specific feature we introduced in that commit is that of a fallback HTTP URL which we construct from the SSH configuration of a Git remote. The Git LFS client sends a "git-lfs-authenticate" command to the SSH remote and expects a JSON response which may contain either an HTTP URL or a set of HTTP credentials, or both. If the JSON response to a "git-lfs-authenticate" remote command includes an HTTP URL, then the client uses any provided credentials with that URL. Otherwise, the client makes requests to the fallback URL that was constructed from the SSH configuration. However, the Git LFS client constructs the fallback URL from a given SSH remote configuration without properly encoding the URL's path component. As a result, if an SSH URL or scp(1)-style SSH remote configuration contains characters which should be URL-encoded, these are included in the fallback URL as raw characters rather than as percent-encoded characters. The primary consequence of this behaviour is that the client may attempt to make a request to an invalid HTTP URL if the remote "git-lfs-authenticate" command either does not succeed or does not return an HTTP URL. In addition, even if the remote "git-lfs-authenticate" command does return a valid HTTP URL, the client will still attempt to use the invalid fallback URL to fetch credentials for the API endpoint, should they be required. If the first HTTP response from the API endpoint has a 401 status code, the client will then attempt to invoke a local Git credential helper program to provide the necessary credentials. The helper program requires the host and path of the remote system as input values, so the getCreds() method of the Client structure in our "lfsapi" package calls the getCredURLForAPI() function to provide the appropriate URL, passing the fallback URL that was constructed for the API endpoint as one of the function's parameters. The getCredURLForAPI() function first checks whether the scheme and host components of the given API endpoint's URL match those of the actual request URL and, if not, returns the request URL rather than the endpoint's URL. This helps ensure that credentials for one remote system are never sent to another system. To determine the scheme and host components of the given endpoint URL, the getCredURLForAPI() function passes it to the Parse() function of the "net/url" package from the Go standard library. When the URL contains invalid characters, the Parse() function returns an error, which is then reported by the Git LFS client before it exits without performing any further operations. To resolve these problems, we revise the EndpointFromSshUrl() function in our "lfshttp" package so that when it constructs a fallback HTTP URL from an SSH URL, it uses a URL-encoded version of the SSH URL's path component in the fallback URL. In particular, the fallback URL's path is formed by re-encoding the URL-decoded path from the SSH URL. The decoded path is used in the repository name argument of the remote commands sent via SSH by the Git LFS client, following Git's own handling of SSH URLs. This decoding converts any percent-encoded path separators (i.e., "%2F" or "%2f" in place of a "/" character) into full path separators, as is true for Git as well: https://github.com/git/git/blob/v2.56.0/connect.c#L1467 https://github.com/git/git/blob/v2.56.0/connect.c#L1107 https://github.com/git/git/blob/v2.56.0/connect.c#L1489 When constructing the fallback HTTPS URL, we want to preserve the lack of distinction in the SSH repository path argument between path separators that were originally raw and those that were URL-encoded. For this reason, we do not directly call the EscapedPath() method of the URL structure whose Path field contains the decoded path of the original SSH URL, because under some circumstances it may return percent-encoded path separators from the original URL. Instead, we construct a new, anonymous URL structure with the decoded path as its Path field and then call the EscapedPath() method of the new structure. The difference between these two approaches stems from the inconsistent handling of percent-encoded path separators in the methods of the URL structure type from the "net/url" package of the Go standard library. So long as the original URL's path is considered to have a valid encoding, it is returned unaltered by the EscapedPath() method. This includes many cases in which path separator characters are percent-encoded, so if we called the EscapedPath() method directly, then in these instances the path separators would be decoded in the SSH repository path argument but would remain percent-encoded in the fallback URL. However, when the original URL path is deemed to be improperly encoded by the validEncoded() internal function in the "net/url" package, the EscapedPath() method returns an encoded version of the value in the URL structure's Path field rather than returning the original path stored in the structure's RawPath field. In these cases, all the path separators from the Path field will be returned in raw form, regardless of whether or not they were percent-encoded in the original URL. For reference, see: golang/go#73549 golang/go#14815 (comment) https://github.com/golang/go/blob/go1.27.0/src/net/url/url.go#L678-L724 As we wish to always retain the raw path separators in the URL-decoded path of the SSH repository name argument when we construct a fallback HTTPS URL, we explicitly induce the latter behaviour of the EscapedPath() method when constructing the fallback URL. To do this, we initialize an anonymous URL structure with a defined Path field but an empty RawPath field, which forces the EscapedPath() method to always encode the value in the Path field. We then use the result in the Url field of the Endpoint structure created by the EndpointFromSshUrl() function. Note, though, that the OriginalUrl field of the Endpoint structure created by the EndpointFromSshUrl() function does not actually contain the original SSH URL, and so the field's value may differ from that URL due to the "net/url" package's inconsistency in handling percent-encoded path separators. The EndpointFromSshUrl() function calls the String() method of the "net/url" package's URL structure type, which in turn calls the EscapedPath() method to generate the path of the URL the String() method returns. Hence, when the original URL's path contains both percent-encoded path separators and certain unencoded raw characters, the path of the URL returned by the String() method will differ from the path of the original URL. https://github.com/golang/go/blob/go1.27.0/src/net/url/url.go#L839 The OriginalUrl field is only used to read the value of an "lfs.<url>.sshTransfer" configuration option, should one exist. (We introduced the field for that purpose in commit 2c04884 of PR #5555.) We should likely refactor our API endpoint URL parsing code so the OriginalUrl field is populated with an unaltered copy of the original URL, but that change falls outside of the scope of the present work and so we defer it to a future PR. To confirm that our revisions to the EndpointFromSshUrl() function behave as we expect and that the URL constructed by the function is always properly encoded, we expand the set of test cases checked by the TestEndpointParsing() Go test function in our "lfsapi" package. These test cases cover a range of possible SSH remote configurations, including URLs with "ssh:", "git+ssh:", and "ssh+git:" schemes as well as a configuration with an scp(1)-style format. Note that the configuration in the scp(1)-style format, which we term a "bare" SSH configuration, is first parsed by the EndpointFromBareSshUrl() function in our "lfshttp" package. This constructs an SSH URL and passes it to the EndpointFromSshUrl() function, unless the "net/url" package's Parse() function returns an error while parsing the constructed URL. As a consequence, we do not support the same range of characters in scp(1)-style format SSH configurations which we now fully support in SSH URL configurations. In addition to our expanded Go test cases, we also add a new shell integration test to accompany the two tests we introduced recently in PR #6286. These tests all simulate the condition in which an SSH remote is configured but the "git-lfs-authenticate" command is not available. Since the changes in PR #6286, we now expect that in these circumstances the Git LFS client will proceed to make an HTTP request to the fallback URL it constructed from the configured SSH URL. Like the two existing tests, our new "SSH git-lfs-authenticate unavailable (fallback to HTTPS, URL-encoded newline)" test also invokes the ssh_authenticate_unavailable_test() function, which then establishes the requested test conditions and confirms that the Git LFS client behaves as expected. We update this function so that it recognizes the "ssh-unavailable-newline" repository name passed by our new test and inserts a percent-encoded line feed (LF) character into the URL used to configure the SSH remote. We also update our "lfs-ssh-echo" test utility to recognize the repository name argument sent by the Git LFS client during our new test and exit with status code 127. This argument contains a line feed character which appears in raw form because the repository name argument of the "git-lfs-authenticate" remote command is not URL-encoded. Finally, we revise the ssh_authenticate_unavailable_test() function so that in the case of our new test, it checks only the first portion of the trace log message which records the contents of the remote SSH command, because the log message is truncated by the raw line feed character in the repository name argument. We expect to revise the format of these trace log messages in subsequent commits, at which time we can expand the ssh_authenticate_unavailable_test() function to also check the second portion of the log message with the remainder of the repository name argument following the line feed character. In subsequent commit, we also expect to add another shell test which will validate the behaviour of the Git LFS client when a URL-encoded line feed character appears in an SSH URL. In the case of this test, the "lfs-ssh-echo" utility will not exit with a non-zero status code, as it does during the new test we are adding in this commit. Instead, the utility will simulate a valid JSON response to the "git-lfs-authenticate" remote command. Under these conditions, the client should proceed to make HTTP requests (using URLs with percent-encoded LF characters) and ultimately successfully upload an object. However, this future test will only be possible if the client does not fail when it attempts to fetch credentials for the HTTP requests, as it would without the changes from this commit.
When an SSH remote's server does not provide the git-lfs-authenticate command, a usable LFS endpoint has already been guessed from the remote URL. Previously any non-zero exit from git-lfs-authenticate was treated as fatal, so such servers could not be used over SSH without explicitly configuring lfs.url.
Detect the unavailable command in sshAuthClient.Resolve and signal it with a distinct sshAuthenticateUnavailableError. sshResolveWithRetries then falls back to the guessed endpoint (authenticating via the normal Git credential helper) instead of failing, and stops retrying since a missing command will not become available.
Detection covers both the conventional command-not-found exit code (127) and servers that return a generic exit code with a 'not found'-style message. Gerrit, for example, runs the command through a restricted shell and responds with exit code 1 and the message:
fatal: Gerrit Code Review: git-lfs-authenticate: not found
Message matching is anchored to the command name so that unrelated errors such as a missing repository are not misclassified. Any other non-zero exit code remains fatal.