| 1 | package lfsapi |
| 2 | |
| 3 | import ( |
| 4 | "encoding/base64" |
| 5 | "fmt" |
| 6 | "net/http" |
| 7 | "net/url" |
| 8 | "os" |
| 9 | "strings" |
| 10 | |
| 11 | "github.com/git-lfs/git-lfs/v3/creds" |
| 12 | "github.com/git-lfs/git-lfs/v3/errors" |
| 13 | "github.com/git-lfs/git-lfs/v3/lfshttp" |
| 14 | "github.com/git-lfs/git-lfs/v3/tr" |
| 15 | "github.com/rubyist/tracerx" |
| 16 | ) |
| 17 | |
| 18 | var ( |
| 19 | defaultEndpointFinder = NewEndpointFinder(nil) |
| 20 | defaultMaxAuthAttempts = 3 |
| 21 | ) |
| 22 | |
| 23 | // DoWithAuth sends an HTTP request to get an HTTP response. It attempts to add |
| 24 | // authentication from netrc or git's credential helpers if necessary, |
| 25 | // supporting basic authentication. |
| 26 | func (c *Client) DoWithAuth(remote string, access creds.Access, req *http.Request) (*http.Response, error) { |
| 27 | maxAuthAttempts := defaultMaxAuthAttempts |
| 28 | if access.Mode() == creds.NoneAccess { |
| 29 | maxAuthAttempts++ |
| 30 | } |
| 31 | |
| 32 | for i := range maxAuthAttempts { |
| 33 | res, err := c.doWithAuth(remote, access, req, nil) |
| 34 | if err == nil || !errors.IsAuthError(err) { |
| 35 | return res, err |
| 36 | } |
| 37 | |
| 38 | // We expect this condition should occur only when an |
| 39 | // Authorization header was already set for the request |
| 40 | // and the request was rejected. Otherwise, after a 401 |
| 41 | // status code is received, doWithAuth() will remove any |
| 42 | // Authorization header that it added to the request. |
| 43 | if len(req.Header.Get("Authorization")) != 0 { |
| 44 | return res, err |
| 45 | } |
| 46 | |
| 47 | // This case represents a rejected request that |
| 48 | // should have been authenticated but wasn't, possibly because |
| 49 | // it is part of a multi-stage authentication sequence. |
| 50 | if res != nil && res.Body != nil { |
| 51 | res.Body.Close() |
| 52 | } |
| 53 | |
| 54 | // If at least one more attempt is still permitted, we update |
| 55 | // the access mode and retry the request. |
| 56 | if i < maxAuthAttempts-1 { |
| 57 | access = c.Endpoints.AccessFor(access.URL()) |
| 58 | tracerx.Printf("api: http response indicates %q authentication. Resubmitting...", access.Mode()) |
| 59 | } |
| 60 | } |
| 61 | |
| 62 | c.credContext.SetStateFields(nil) |
| 63 | |
| 64 | tracerx.Printf("api: too many authentication attempts") |
| 65 | return nil, fmt.Errorf("too many authentication attempts") |
| 66 | } |
| 67 | |
| 68 | // DoWithAuthNoRetry sends an HTTP request to get an HTTP response. It works in |
| 69 | // the same way as DoWithAuth, but will not retry the request if it fails with |
| 70 | // an authorization error. |
| 71 | func (c *Client) DoWithAuthNoRetry(remote string, access creds.Access, req *http.Request) (*http.Response, error) { |
| 72 | return c.doWithAuth(remote, access, req, nil) |
| 73 | } |
| 74 | |
| 75 | // DoAPIRequestWithAuth sends an HTTP request to get an HTTP response similarly |
| 76 | // to DoWithAuth, but using the LFS API endpoint for the provided remote and |
| 77 | // operation to determine the access mode. |
| 78 | func (c *Client) DoAPIRequestWithAuth(remote string, req *http.Request) (*http.Response, error) { |
| 79 | operation := getReqOperation(req) |
| 80 | apiEndpoint := c.Endpoints.Endpoint(operation, remote) |
| 81 | access := c.Endpoints.AccessFor(apiEndpoint.Url) |
| 82 | return c.DoWithAuth(remote, access, req) |
| 83 | } |
| 84 | |
| 85 | func (c *Client) doWithAuth(remote string, access creds.Access, req *http.Request, via []*http.Request) (*http.Response, error) { |
| 86 | req.Header = c.client.ExtraHeadersFor(req) |
| 87 | |
| 88 | credWrapper, err := c.getCreds(remote, access, req) |
| 89 | if err != nil { |
| 90 | return nil, err |
| 91 | } |
| 92 | c.credContext.SetStateFields(credWrapper.Creds["state[]"]) |
| 93 | |
| 94 | res, err := c.doWithCreds(req, credWrapper, access, via) |
| 95 | if err != nil && errors.IsAuthError(err) { |
| 96 | multistage := credWrapper.Creds.IsMultistage() |
| 97 | newMode, newModes, headers := getAuthAccess(res, access.Mode(), c.access, multistage) |
| 98 | newAccess := access.Upgrade(newMode) |
| 99 | if newAccess.Mode() != access.Mode() { |
| 100 | c.Endpoints.SetAccess(newAccess) |
| 101 | c.access = newModes |
| 102 | } |
| 103 | |
| 104 | if credWrapper.Creds != nil { |
| 105 | req.Header.Del("Authorization") |
| 106 | if !multistage { |
| 107 | credWrapper.CredentialHelper.Reject(credWrapper.Creds) |
| 108 | } |
| 109 | } |
| 110 | c.credContext.SetWWWAuthHeaders(headers) |
| 111 | } |
| 112 | |
| 113 | if res != nil && res.StatusCode < 300 && res.StatusCode > 199 { |
| 114 | credWrapper.CredentialHelper.Approve(credWrapper.Creds) |
| 115 | } |
| 116 | |
| 117 | return res, err |
| 118 | } |
| 119 | |
| 120 | func (c *Client) doWithCreds(req *http.Request, credWrapper creds.CredentialHelperWrapper, access creds.Access, via []*http.Request) (*http.Response, error) { |
| 121 | if access.Mode() == creds.NegotiateAccess { |
| 122 | return c.doWithNegotiate(req, credWrapper) |
| 123 | } |
| 124 | |
| 125 | req.Header.Set("User-Agent", lfshttp.UserAgent) |
| 126 | |
| 127 | client, err := c.client.HttpClient(req.URL, access.Mode()) |
| 128 | if err != nil { |
| 129 | return nil, err |
| 130 | } |
| 131 | |
| 132 | redirectedReq, res, err := c.client.DoWithRedirect(client, req, "", via) |
| 133 | if err != nil || res != nil { |
| 134 | return res, err |
| 135 | } |
| 136 | |
| 137 | if redirectedReq == nil { |
| 138 | return res, errors.New(tr.Tr.Get("failed to redirect request")) |
| 139 | } |
| 140 | |
| 141 | return c.doWithAuth("", access, redirectedReq, via) |
| 142 | } |
| 143 | |
| 144 | // getCreds fills the authorization header for the given request if possible, |
| 145 | // from the following sources: |
| 146 | // |
| 147 | // 1. NTLM access is handled elsewhere. |
| 148 | // 2. Existing Authorization or ?token query tells LFS that the request is ready. |
| 149 | // 3. Netrc based on the hostname. |
| 150 | // 4. URL authentication on the Endpoint URL or the Git Remote URL. |
| 151 | // 5. Git Credential Helper, potentially prompting the user. |
| 152 | // |
| 153 | // There are three URLs in play, that make this a little confusing. |
| 154 | // |
| 155 | // 1. The request URL, which should be something like "https://git.com/repo.git/info/lfs/objects/batch" |
| 156 | // 2. The LFS API URL, which should be something like "https://git.com/repo.git/info/lfs" |
| 157 | // This URL used for the "lfs.URL.access" git config key, which determines |
| 158 | // what kind of auth the LFS server expects. Could be BasicAccess, |
| 159 | // NTLMAccess, NegotiateAccess, or NoneAccess, in which the Git Credential |
| 160 | // Helper step is skipped. We do not want to prompt the user for a password |
| 161 | // to fetch public repository data. |
| 162 | // 3. The Git Remote URL, which should be something like "https://git.com/repo.git" |
| 163 | // This URL is used for the Git Credential Helper. This way existing https |
| 164 | // Git remote credentials can be re-used for LFS. |
| 165 | func (c *Client) getCreds(remote string, access creds.Access, req *http.Request) (creds.CredentialHelperWrapper, error) { |
| 166 | ef := c.Endpoints |
| 167 | if ef == nil { |
| 168 | ef = defaultEndpointFinder |
| 169 | } |
| 170 | |
| 171 | operation := getReqOperation(req) |
| 172 | apiEndpoint := ef.Endpoint(operation, remote) |
| 173 | |
| 174 | if access.Mode() != creds.NegotiateAccess { |
| 175 | if requestHasAuth(req) || access.Mode() == creds.NoneAccess { |
| 176 | return creds.CredentialHelperWrapper{CredentialHelper: creds.NullCreds, Input: nil, Url: nil, Creds: nil}, nil |
| 177 | } |
| 178 | |
| 179 | credsURL, err := getCredURLForAPI(ef, operation, remote, apiEndpoint, req) |
| 180 | if err != nil { |
| 181 | return creds.CredentialHelperWrapper{CredentialHelper: creds.NullCreds, Input: nil, Url: nil, Creds: nil}, errors.Wrap(err, tr.Tr.Get("credentials")) |
| 182 | } |
| 183 | |
| 184 | if credsURL == nil { |
| 185 | return creds.CredentialHelperWrapper{CredentialHelper: creds.NullCreds, Input: nil, Url: nil, Creds: nil}, nil |
| 186 | } |
| 187 | |
| 188 | credWrapper := c.getGitCredsWrapper(ef, req, credsURL) |
| 189 | err = credWrapper.FillCreds() |
| 190 | if err == nil { |
| 191 | tracerx.Printf("Filled credentials for %s", credsURL) |
| 192 | setRequestAuthWithCreds(req, credWrapper.Creds) |
| 193 | } |
| 194 | return credWrapper, err |
| 195 | } |
| 196 | |
| 197 | // Negotiate only |
| 198 | |
| 199 | credsURL, err := url.Parse(apiEndpoint.Url) |
| 200 | if err != nil { |
| 201 | return creds.CredentialHelperWrapper{CredentialHelper: creds.NullCreds, Input: nil, Url: nil, Creds: nil}, errors.Wrap(err, tr.Tr.Get("credentials")) |
| 202 | } |
| 203 | |
| 204 | // NTLM uses creds to create the session |
| 205 | credWrapper := c.getGitCredsWrapper(ef, req, credsURL) |
| 206 | return credWrapper, err |
| 207 | } |
| 208 | |
| 209 | func (c *Client) getGitCredsWrapper(ef EndpointFinder, req *http.Request, u *url.URL) creds.CredentialHelperWrapper { |
| 210 | return c.credContext.GetCredentialHelper(c.Credentials, u) |
| 211 | } |
| 212 | |
| 213 | func getCredURLForAPI(ef EndpointFinder, operation, remote string, apiEndpoint lfshttp.Endpoint, req *http.Request) (*url.URL, error) { |
| 214 | apiURL, err := url.Parse(apiEndpoint.Url) |
| 215 | if err != nil { |
| 216 | return nil, err |
| 217 | } |
| 218 | |
| 219 | // if the LFS request doesn't match the current LFS url, don't bother |
| 220 | // attempting to set the Authorization header from the LFS or Git remote URLs. |
| 221 | if req.URL.Scheme != apiURL.Scheme || |
| 222 | req.URL.Host != apiURL.Host { |
| 223 | return req.URL, nil |
| 224 | } |
| 225 | |
| 226 | if setRequestAuthFromURL(req, apiURL) { |
| 227 | return nil, nil |
| 228 | } |
| 229 | |
| 230 | if len(remote) > 0 { |
| 231 | if u := ef.GitRemoteURL(remote, operation == "upload"); u != "" { |
| 232 | schemedUrl, _ := fixSchemelessURL(u) |
| 233 | |
| 234 | gitRemoteURL, err := url.Parse(schemedUrl) |
| 235 | if err != nil { |
| 236 | return nil, err |
| 237 | } |
| 238 | |
| 239 | if gitRemoteURL.Scheme == apiURL.Scheme && |
| 240 | gitRemoteURL.Host == apiURL.Host { |
| 241 | |
| 242 | if setRequestAuthFromURL(req, gitRemoteURL) { |
| 243 | return nil, nil |
| 244 | } |
| 245 | |
| 246 | return gitRemoteURL, nil |
| 247 | } |
| 248 | } |
| 249 | } |
| 250 | |
| 251 | return apiURL, nil |
| 252 | } |
| 253 | |
| 254 | // fixSchemelessURL prepends an empty scheme "//" if none was found in |
| 255 | // the URL and replaces the first colon with a slash in order to satisfy RFC |
| 256 | // 3986 §3.3, and `net/url.Parse()`. |
| 257 | // |
| 258 | // It returns a string parse-able with `net/url.Parse()` and a boolean whether |
| 259 | // or not an empty scheme was added. |
| 260 | func fixSchemelessURL(u string) (string, bool) { |
| 261 | if hasScheme(u) { |
| 262 | return u, false |
| 263 | } |
| 264 | |
| 265 | colon := strings.Index(u, ":") |
| 266 | slash := strings.Index(u, "/") |
| 267 | |
| 268 | if colon >= 0 && (slash < 0 || colon < slash) { |
| 269 | // First path segment has a colon, assumed that it's a |
| 270 | // scheme-less URL. Append an empty scheme on top to |
| 271 | // satisfy RFC 3986 §3.3, and `net/url.Parse()`. |
| 272 | // |
| 273 | // In addition, replace the first colon with a slash since |
| 274 | // otherwise the colon looks like it's introducing a port |
| 275 | // number. |
| 276 | return fmt.Sprintf("//%s", strings.Replace(u, ":", "/", 1)), true |
| 277 | } |
| 278 | return u, true |
| 279 | } |
| 280 | |
| 281 | var ( |
| 282 | // supportedSchemes is the list of URL schemes the `lfsapi` package |
| 283 | // supports. |
| 284 | supportedSchemes = []string{"ssh", "http", "https"} |
| 285 | ) |
| 286 | |
| 287 | // hasScheme returns whether or not a given string (taken to represent a RFC |
| 288 | // 3986 URL) has a scheme that is supported by the `lfsapi` package. |
| 289 | func hasScheme(what string) bool { |
| 290 | for _, scheme := range supportedSchemes { |
| 291 | if strings.HasPrefix(what, fmt.Sprintf("%s://", scheme)) { |
| 292 | return true |
| 293 | } |
| 294 | } |
| 295 | |
| 296 | return false |
| 297 | } |
| 298 | |
| 299 | func requestHasAuth(req *http.Request) bool { |
| 300 | // The "Authorization" string constant is safe, since we assume that all |
| 301 | // request headers have been canonicalized. |
| 302 | if len(req.Header.Get("Authorization")) > 0 { |
| 303 | return true |
| 304 | } |
| 305 | |
| 306 | return len(req.URL.Query().Get("token")) > 0 |
| 307 | } |
| 308 | |
| 309 | func setRequestAuthFromURL(req *http.Request, u *url.URL) bool { |
| 310 | if u.User == nil { |
| 311 | return false |
| 312 | } |
| 313 | |
| 314 | if pass, ok := u.User.Password(); ok { |
| 315 | fmt.Fprintln(os.Stderr, tr.Tr.Get("warning: current Git remote contains credentials")) |
| 316 | setRequestAuth(req, u.User.Username(), pass) |
| 317 | return true |
| 318 | } |
| 319 | |
| 320 | return false |
| 321 | } |
| 322 | |
| 323 | func setRequestAuth(req *http.Request, user, pass string) { |
| 324 | if len(user) == 0 && len(pass) == 0 { |
| 325 | return |
| 326 | } |
| 327 | |
| 328 | token := fmt.Sprintf("%s:%s", user, pass) |
| 329 | auth := "Basic " + strings.TrimSpace(base64.StdEncoding.EncodeToString([]byte(token))) |
| 330 | req.Header.Set("Authorization", auth) |
| 331 | } |
| 332 | |
| 333 | func setRequestAuthWithCreds(req *http.Request, c creds.Creds) { |
| 334 | authtype := creds.FirstEntryForKey(c, "authtype") |
| 335 | credential := creds.FirstEntryForKey(c, "credential") |
| 336 | if len(authtype) == 0 && len(credential) == 0 { |
| 337 | user := creds.FirstEntryForKey(c, "username") |
| 338 | pass := creds.FirstEntryForKey(c, "password") |
| 339 | setRequestAuth(req, user, pass) |
| 340 | return |
| 341 | } |
| 342 | |
| 343 | auth := fmt.Sprintf("%s %s", authtype, credential) |
| 344 | req.Header.Set("Authorization", auth) |
| 345 | } |
| 346 | |
| 347 | func getReqOperation(req *http.Request) string { |
| 348 | operation := "download" |
| 349 | if req.Method == "POST" || req.Method == "PUT" { |
| 350 | operation = "upload" |
| 351 | } |
| 352 | return operation |
| 353 | } |
| 354 | |
| 355 | var ( |
| 356 | authenticateHeaders = []string{"Lfs-Authenticate", "Www-Authenticate"} |
| 357 | ) |
| 358 | |
| 359 | func getAuthAccess(res *http.Response, access creds.AccessMode, modes []creds.AccessMode, multistage bool) (creds.AccessMode, []creds.AccessMode, []string) { |
| 360 | newModes := make([]creds.AccessMode, 0, len(modes)) |
| 361 | for _, mode := range modes { |
| 362 | if multistage || access != mode { |
| 363 | newModes = append(newModes, mode) |
| 364 | } |
| 365 | } |
| 366 | headers := make([]string, 0) |
| 367 | if res != nil { |
| 368 | for _, headerName := range authenticateHeaders { |
| 369 | headers = append(headers, res.Header[headerName]...) |
| 370 | } |
| 371 | supportedModes := make(map[creds.AccessMode]struct{}) |
| 372 | for _, headerName := range authenticateHeaders { |
| 373 | for _, auth := range res.Header[headerName] { |
| 374 | pieces := strings.SplitN(strings.ToLower(auth), " ", 2) |
| 375 | if len(pieces) == 0 { |
| 376 | continue |
| 377 | } |
| 378 | |
| 379 | supportedModes[creds.AccessMode(pieces[0])] = struct{}{} |
| 380 | } |
| 381 | } |
| 382 | for _, mode := range newModes { |
| 383 | if _, ok := supportedModes[mode]; ok { |
| 384 | return mode, newModes, headers |
| 385 | } |
| 386 | } |
| 387 | } |
| 388 | |
| 389 | return creds.BasicAccess, newModes, headers |
| 390 | } |