| 1 | package lfshttp |
| 2 | |
| 3 | import ( |
| 4 | "bytes" |
| 5 | "encoding/json" |
| 6 | goerrors "errors" |
| 7 | "os/exec" |
| 8 | "strings" |
| 9 | "sync" |
| 10 | "time" |
| 11 | |
| 12 | "github.com/git-lfs/git-lfs/v3/config" |
| 13 | "github.com/git-lfs/git-lfs/v3/ssh" |
| 14 | "github.com/git-lfs/git-lfs/v3/subprocess" |
| 15 | "github.com/git-lfs/git-lfs/v3/tools" |
| 16 | "github.com/rubyist/tracerx" |
| 17 | ) |
| 18 | |
| 19 | // sshAuthenticateNotFoundExitCode is the conventional POSIX shell exit code |
| 20 | // returned when a command cannot be found. When the remote `ssh` invocation |
| 21 | // exits with this status, we treat the `git-lfs-authenticate` command as |
| 22 | // unavailable on the server and fall back to the guessed LFS endpoint rather |
| 23 | // than treating the failure as fatal. |
| 24 | const sshAuthenticateNotFoundExitCode = 127 |
| 25 | |
| 26 | // sshAuthenticateNotFoundMessages are case-insensitive substrings of the |
| 27 | // stderr output produced when `git-lfs-authenticate` is not available on the |
| 28 | // server. Not every server uses the conventional 127 exit code: Gerrit, for |
| 29 | // example, runs the command through a restricted shell that returns a generic |
| 30 | // exit code 1 with a "not found"-style message. The substrings are anchored |
| 31 | // to the command name so that unrelated "not found" errors (such as a missing |
| 32 | // repository) are not misclassified. |
| 33 | var sshAuthenticateNotFoundMessages = []string{ |
| 34 | "git-lfs-authenticate: not found", // Gerrit |
| 35 | "git-lfs-authenticate: command not found", // bash, sh |
| 36 | "git-lfs-authenticate: no such file", // direct exec by path |
| 37 | "command not found: git-lfs-authenticate", // zsh |
| 38 | } |
| 39 | |
| 40 | // isSSHAuthenticateUnavailable reports whether the error and captured stderr |
| 41 | // from running `git-lfs-authenticate` over SSH indicate that the command is |
| 42 | // not available on the server, in which case Git LFS should fall back to the |
| 43 | // guessed LFS endpoint instead of failing the request. |
| 44 | func isSSHAuthenticateUnavailable(err error, stderr string) bool { |
| 45 | var exitErr *exec.ExitError |
| 46 | if !goerrors.As(err, &exitErr) { |
| 47 | // The command never ran to completion (e.g. the local ssh |
| 48 | // binary is missing); this is a genuine error, not an |
| 49 | // unavailable git-lfs-authenticate command. |
| 50 | return false |
| 51 | } |
| 52 | |
| 53 | if exitErr.ExitCode() == sshAuthenticateNotFoundExitCode { |
| 54 | return true |
| 55 | } |
| 56 | |
| 57 | if exitErr.ExitCode() != 0 { |
| 58 | msg := strings.ToLower(stderr) |
| 59 | for _, needle := range sshAuthenticateNotFoundMessages { |
| 60 | if strings.Contains(msg, needle) { |
| 61 | return true |
| 62 | } |
| 63 | } |
| 64 | } |
| 65 | return false |
| 66 | } |
| 67 | |
| 68 | // sshAuthenticateUnavailableError indicates that the `git-lfs-authenticate` |
| 69 | // command is not available on the SSH server. Callers should fall back to the |
| 70 | // guessed LFS endpoint per the server discovery specification instead of |
| 71 | // failing the request. |
| 72 | type sshAuthenticateUnavailableError struct { |
| 73 | err error |
| 74 | } |
| 75 | |
| 76 | func (e *sshAuthenticateUnavailableError) Error() string { |
| 77 | return e.err.Error() |
| 78 | } |
| 79 | |
| 80 | func (e *sshAuthenticateUnavailableError) Unwrap() error { |
| 81 | return e.err |
| 82 | } |
| 83 | |
| 84 | type SSHResolver interface { |
| 85 | Resolve(Endpoint, string) (sshAuthResponse, error) |
| 86 | } |
| 87 | |
| 88 | func withSSHCache(ssh SSHResolver) SSHResolver { |
| 89 | return &sshCache{ssh: ssh} |
| 90 | } |
| 91 | |
| 92 | type sshCache struct { |
| 93 | endpoints sync.Map // map[string]*sshAuthResponse |
| 94 | ssh SSHResolver |
| 95 | } |
| 96 | |
| 97 | func (c *sshCache) Resolve(e Endpoint, method string) (sshAuthResponse, error) { |
| 98 | if len(e.SSHMetadata.UserAndHost) == 0 { |
| 99 | return sshAuthResponse{}, nil |
| 100 | } |
| 101 | |
| 102 | key := strings.Join([]string{e.SSHMetadata.UserAndHost, e.SSHMetadata.Port, e.SSHMetadata.Path, method}, "//") |
| 103 | if val, ok := c.endpoints.Load(key); ok { |
| 104 | res := val.(*sshAuthResponse) |
| 105 | if _, expired := res.IsExpiredWithin(5 * time.Second); !expired { |
| 106 | tracerx.Printf("ssh cache: %s git-lfs-authenticate %s %s", |
| 107 | e.SSHMetadata.UserAndHost, e.SSHMetadata.Path, endpointOperation(e, method)) |
| 108 | return *res, nil |
| 109 | } else { |
| 110 | tracerx.Printf("ssh cache expired: %s git-lfs-authenticate %s %s", |
| 111 | e.SSHMetadata.UserAndHost, e.SSHMetadata.Path, endpointOperation(e, method)) |
| 112 | } |
| 113 | } |
| 114 | |
| 115 | res, err := c.ssh.Resolve(e, method) |
| 116 | if err == nil { |
| 117 | c.endpoints.Store(key, &res) |
| 118 | } |
| 119 | return res, err |
| 120 | } |
| 121 | |
| 122 | type sshAuthResponse struct { |
| 123 | Message string `json:"-"` |
| 124 | Href string `json:"href"` |
| 125 | Header map[string]string `json:"header"` |
| 126 | ExpiresAt time.Time `json:"expires_at"` |
| 127 | ExpiresIn time.Duration `json:"expires_in"` |
| 128 | |
| 129 | createdAt time.Time |
| 130 | } |
| 131 | |
| 132 | func (r *sshAuthResponse) IsExpiredWithin(d time.Duration) (time.Time, bool) { |
| 133 | return tools.IsExpiredAtOrIn(r.createdAt, d, r.ExpiresAt, |
| 134 | time.Duration(r.ExpiresIn)*time.Second) |
| 135 | } |
| 136 | |
| 137 | type sshAuthClient struct { |
| 138 | os config.Environment |
| 139 | git config.Environment |
| 140 | } |
| 141 | |
| 142 | func (c *sshAuthClient) Resolve(e Endpoint, method string) (sshAuthResponse, error) { |
| 143 | res := sshAuthResponse{} |
| 144 | if len(e.SSHMetadata.UserAndHost) == 0 { |
| 145 | return res, nil |
| 146 | } |
| 147 | |
| 148 | exe, args, _, _ := ssh.GetLFSExeAndArgs(c.os, c.git, &e.SSHMetadata, "git-lfs-authenticate", endpointOperation(e, method), false, "") |
| 149 | cmd, err := subprocess.ExecCommand(exe, args...) |
| 150 | if err != nil { |
| 151 | return res, err |
| 152 | } |
| 153 | |
| 154 | // Save stdout and stderr in separate buffers |
| 155 | var outbuf, errbuf bytes.Buffer |
| 156 | cmd.Stdout = &outbuf |
| 157 | cmd.Stderr = &errbuf |
| 158 | |
| 159 | now := time.Now() |
| 160 | |
| 161 | // Execute command |
| 162 | err = cmd.Start() |
| 163 | if err == nil { |
| 164 | err = cmd.Wait() |
| 165 | } |
| 166 | |
| 167 | // Processing result |
| 168 | if err != nil { |
| 169 | res.Message = strings.TrimSpace(errbuf.String()) |
| 170 | |
| 171 | // If the git-lfs-authenticate command is not available on the |
| 172 | // server, signal this distinctly so the caller can fall back to |
| 173 | // the guessed LFS endpoint instead of failing outright. This |
| 174 | // covers both the conventional command-not-found exit code (127) |
| 175 | // and servers such as Gerrit that return a generic exit code |
| 176 | // with a "not found"-style message. |
| 177 | if isSSHAuthenticateUnavailable(err, res.Message) { |
| 178 | err = &sshAuthenticateUnavailableError{err: err} |
| 179 | } |
| 180 | } else { |
| 181 | err = json.Unmarshal(outbuf.Bytes(), &res) |
| 182 | if res.ExpiresIn == 0 && res.ExpiresAt.IsZero() { |
| 183 | ttl := c.git.Int64("lfs.defaulttokenttl", 0) |
| 184 | if ttl < 0 { |
| 185 | ttl = 0 |
| 186 | } |
| 187 | res.ExpiresIn = time.Duration(ttl) |
| 188 | } |
| 189 | res.createdAt = now |
| 190 | } |
| 191 | |
| 192 | return res, err |
| 193 | } |