Debian Codegraph @

lfsapi/endpoint_finder.go

raw symbols SCIP
1 package lfsapi
2
3 import (
4 "bufio"
5 "fmt"
6 "net/url"
7 "os"
8 "path"
9 "regexp"
10 "strings"
11 "sync"
12
13 "github.com/git-lfs/git-lfs/v3/config"
14 "github.com/git-lfs/git-lfs/v3/creds"
15 "github.com/git-lfs/git-lfs/v3/git"
16 "github.com/git-lfs/git-lfs/v3/lfshttp"
17 "github.com/git-lfs/git-lfs/v3/tr"
18 "github.com/rubyist/tracerx"
19 )
20
21 const (
22 defaultRemote = "origin"
23 )
24
25 type EndpointFinder interface {
26 NewEndpointFromCloneURL(operation, rawurl string) lfshttp.Endpoint
27 NewEndpoint(operation, rawurl string) lfshttp.Endpoint
28 Endpoint(operation, remote string) lfshttp.Endpoint
29 RemoteEndpoint(operation, remote string) lfshttp.Endpoint
30 GitRemoteURL(remote string, forpush bool) string
31 AccessFor(rawurl string) creds.Access
32 SetAccess(access creds.Access)
33 GitProtocol() string
34 }
35
36 type endpointGitFinder struct {
37 gitConfig *git.Configuration
38 gitEnv config.Environment
39 gitProtocol string
40 gitDir string
41
42 aliasMu sync.Mutex
43 aliases map[string]string
44 pushAliases map[string]string
45 remoteList []string
46
47 accessMu sync.Mutex
48 urlAccess map[string]creds.AccessMode
49 urlConfig *config.URLConfig
50 }
51
52 func NewEndpointFinder(ctx lfshttp.Context) EndpointFinder {
53 if ctx == nil {
54 ctx = lfshttp.NewContext(nil, nil, nil)
55 }
56
57 var gitDir string
58 cfg := ctx.GitConfig()
59 if cfg != nil && cfg.GitDir != "" {
60 gitDir = cfg.GitDir
61 } else if dir, err := git.GitDir(); err == nil {
62 gitDir = dir
63 }
64
65 e := &endpointGitFinder{
66 gitConfig: ctx.GitConfig(),
67 gitEnv: ctx.GitEnv(),
68 gitProtocol: "https",
69 gitDir: gitDir,
70 aliases: make(map[string]string),
71 pushAliases: make(map[string]string),
72 urlAccess: make(map[string]creds.AccessMode),
73 }
74
75 remotes, _ := git.RemoteList()
76 e.remoteList = remotes
77
78 e.urlConfig = config.NewURLConfig(e.gitEnv)
79 if v, ok := e.gitEnv.Get("lfs.gitprotocol"); ok {
80 e.gitProtocol = v
81 }
82 initAliases(e, e.gitEnv)
83
84 return e
85 }
86
87 func (e *endpointGitFinder) Endpoint(operation, remote string) lfshttp.Endpoint {
88 ep := e.getEndpoint(operation, remote)
89 ep.Operation = operation
90 return ep
91 }
92
93 func (e *endpointGitFinder) getEndpoint(operation, remote string) lfshttp.Endpoint {
94 if e.gitEnv == nil {
95 return lfshttp.Endpoint{}
96 }
97
98 if operation == "upload" {
99 if url, ok := e.gitEnv.Get("lfs.pushurl"); ok {
100 return e.NewEndpoint(operation, url)
101 }
102 }
103
104 if url, ok := e.gitEnv.Get("lfs.url"); ok {
105 return e.NewEndpoint(operation, url)
106 }
107
108 if len(remote) > 0 && remote != defaultRemote {
109 if e := e.RemoteEndpoint(operation, remote); len(e.Url) > 0 {
110 return e
111 }
112 }
113
114 return e.RemoteEndpoint(operation, defaultRemote)
115 }
116
117 func (e *endpointGitFinder) RemoteEndpoint(operation, remote string) lfshttp.Endpoint {
118 if e.gitEnv == nil {
119 return lfshttp.Endpoint{}
120 }
121
122 if len(remote) == 0 {
123 remote = defaultRemote
124 }
125
126 // Support separate push URL if specified and pushing
127 if operation == "upload" {
128 if url, ok := e.gitEnv.Get("remote." + remote + ".lfspushurl"); ok {
129 return e.NewEndpoint(operation, url)
130 }
131 }
132 if url, ok := e.gitEnv.Get("remote." + remote + ".lfsurl"); ok {
133 return e.NewEndpoint(operation, url)
134 }
135
136 // fall back on git remote url (also supports pushurl)
137 if url := e.GitRemoteURL(remote, operation == "upload"); url != "" {
138 return e.NewEndpointFromCloneURL(operation, url)
139 }
140
141 // Finally, fall back on .git/FETCH_HEAD but only if it exists and no specific remote was requested
142 // We can't know which remote FETCH_HEAD is pointing to
143 if e.gitDir != "" && remote == defaultRemote {
144 url, err := parseFetchHead(strings.Join([]string{e.gitDir, "FETCH_HEAD"}, "/"))
145 if err == nil {
146 endpoint := e.NewEndpointFromCloneURL("download", url)
147 return endpoint
148 } else {
149 tracerx.Printf("failed parsing FETCH_HEAD: %s", err)
150 }
151 }
152
153 return lfshttp.Endpoint{}
154 }
155
156 func parseFetchHead(filePath string) (string, error) {
157 file, err := os.Open(filePath)
158 if err != nil {
159 return "", err
160 }
161 defer file.Close()
162
163 scanner := bufio.NewScanner(file)
164 if scanner.Scan() {
165 line := scanner.Text()
166 return ExtractRemoteUrl(line)
167 }
168
169 return "", fmt.Errorf("Failed to read content from %s", filePath)
170 }
171
172 func ExtractRemoteUrl(line string) (string, error) {
173 // see https://regex101.com/r/lYla7c/1
174 re := regexp.MustCompile(`^[a-f0-9]{40,64}\t(not-for-merge)?\t(tag |branch |)'.*' of (?P<url>[\/\.\-\:\_a-zA-Z0-9]+)$`)
175
176 match := re.FindStringSubmatch(line)
177
178 for i, name := range re.SubexpNames() {
179 if name == "url" {
180 if len(match) < i {
181 break
182 }
183 return strings.TrimSpace(match[i]), nil
184 }
185 }
186
187 return "", fmt.Errorf("failed to extract remote URL from \"%s\"", line)
188 }
189
190 func (e *endpointGitFinder) GitRemoteURL(remote string, forpush bool) string {
191 if e.gitEnv != nil {
192 if forpush {
193 if u, ok := e.gitEnv.Get("remote." + remote + ".pushurl"); ok {
194 return u
195 }
196 }
197
198 if u, ok := e.gitEnv.Get("remote." + remote + ".url"); ok {
199 return u
200 }
201 }
202
203 if err := git.ValidateRemoteFromList(e.remoteList, remote); err == nil {
204 return remote
205 }
206
207 return ""
208 }
209
210 func (e *endpointGitFinder) NewEndpointFromCloneURL(operation, rawurl string) lfshttp.Endpoint {
211 ep := e.NewEndpoint(operation, rawurl)
212 if ep.Url == lfshttp.UrlUnknown {
213 return ep
214 }
215
216 if strings.HasSuffix(ep.Url, "/") {
217 ep.Url = ep.Url[0 : len(ep.Url)-1]
218 }
219
220 if strings.HasPrefix(ep.Url, "file://") {
221 return ep
222 }
223
224 // When using main remote URL for HTTP, append info/lfs
225 if path.Ext(ep.Url) == ".git" {
226 ep.Url += "/info/lfs"
227 } else {
228 ep.Url += ".git/info/lfs"
229 }
230
231 return ep
232 }
233
234 func (e *endpointGitFinder) NewEndpoint(operation, rawurl string) lfshttp.Endpoint {
235 rawurl = e.ReplaceUrlAlias(operation, rawurl)
236 if strings.HasPrefix(rawurl, "/") {
237 return lfshttp.EndpointFromLocalPath(rawurl)
238 }
239 u, err := url.Parse(rawurl)
240 if err != nil {
241 return lfshttp.EndpointFromBareSshUrl(rawurl)
242 }
243
244 switch u.Scheme {
245 case "ssh", "git+ssh", "ssh+git":
246 return lfshttp.EndpointFromSshUrl(u)
247 case "http", "https":
248 return lfshttp.EndpointFromHttpUrl(u)
249 case "git":
250 return endpointFromGitUrl(u, e)
251 case "file":
252 return lfshttp.EndpointFromFileUrl(u)
253 case "":
254 // If it looks like a local path, it probably is.
255 if _, err := os.Stat(rawurl); err == nil {
256 return lfshttp.EndpointFromLocalPath(rawurl)
257 }
258 return lfshttp.EndpointFromBareSshUrl(u.String())
259 default:
260 if strings.HasPrefix(rawurl, u.Scheme+"::") {
261 // Looks like a remote helper; just pass it through.
262 return lfshttp.Endpoint{Url: rawurl}
263 }
264 // If it looks like a local path, it probably is.
265 if _, err := os.Stat(rawurl); err == nil {
266 return lfshttp.EndpointFromLocalPath(rawurl)
267 }
268 // We probably got here because the "scheme" that was parsed is
269 // a hostname (whether FQDN or single word) and the URL parser
270 // didn't know what to do with it. Do what Git does and treat
271 // it as an SSH URL. This ensures we handle SSH config aliases
272 // properly.
273 return lfshttp.EndpointFromBareSshUrl(u.String())
274 }
275 }
276
277 func (e *endpointGitFinder) AccessFor(rawurl string) creds.Access {
278 accessurl := urlWithoutAuth(rawurl)
279
280 if e.gitEnv == nil {
281 return creds.NewAccess(creds.NoneAccess, accessurl)
282 }
283
284 e.accessMu.Lock()
285 defer e.accessMu.Unlock()
286
287 if cached, ok := e.urlAccess[accessurl]; ok {
288 return creds.NewAccess(cached, accessurl)
289 }
290
291 e.urlAccess[accessurl] = e.fetchGitAccess(accessurl)
292 return creds.NewAccess(e.urlAccess[accessurl], accessurl)
293 }
294
295 func (e *endpointGitFinder) SetAccess(access creds.Access) {
296 key := fmt.Sprintf("lfs.%s.access", access.URL())
297 tracerx.Printf("setting repository access to %s", access.Mode())
298
299 e.accessMu.Lock()
300 defer e.accessMu.Unlock()
301
302 switch access.Mode() {
303 case creds.EmptyAccess, creds.NoneAccess:
304 e.gitConfig.UnsetLocalKey(key)
305 e.urlAccess[access.URL()] = creds.NoneAccess
306 default:
307 e.gitConfig.SetLocal(key, string(access.Mode()))
308 e.urlAccess[access.URL()] = access.Mode()
309 }
310 }
311
312 func urlWithoutAuth(rawurl string) string {
313 if !strings.Contains(rawurl, "@") {
314 return rawurl
315 }
316
317 u, err := url.Parse(rawurl)
318 if err != nil {
319 fmt.Fprintf(os.Stderr, "Error parsing URL %q: %s", rawurl, err)
320 return rawurl
321 }
322
323 u.User = nil
324 return u.String()
325 }
326
327 func (e *endpointGitFinder) fetchGitAccess(rawurl string) creds.AccessMode {
328 if v, _ := e.urlConfig.Get("lfs", rawurl, "access"); len(v) > 0 {
329 access := creds.AccessMode(strings.ToLower(v))
330 if access == creds.PrivateAccess {
331 return creds.BasicAccess
332 }
333 return access
334 }
335 return creds.NoneAccess
336 }
337
338 func (e *endpointGitFinder) GitProtocol() string {
339 return e.gitProtocol
340 }
341
342 // ReplaceUrlAlias returns a url with a prefix from a `url.*.insteadof` git
343 // config setting. If multiple aliases match, use the longest one.
344 // See https://git-scm.com/docs/git-config for Git's docs.
345 func (e *endpointGitFinder) ReplaceUrlAlias(operation, rawurl string) string {
346 e.aliasMu.Lock()
347 defer e.aliasMu.Unlock()
348
349 if operation == "upload" {
350 if rawurl, replaced := e.replaceUrlAlias(e.pushAliases, rawurl); replaced {
351 return rawurl
352 }
353 }
354 rawurl, _ = e.replaceUrlAlias(e.aliases, rawurl)
355
356 return rawurl
357 }
358
359 // replaceUrlAlias is a helper function for ReplaceUrlAlias. It must only be
360 // called while the e.aliasMu mutex is held.
361 func (e *endpointGitFinder) replaceUrlAlias(aliases map[string]string, rawurl string) (string, bool) {
362 var longestalias string
363 for alias, _ := range aliases {
364 if !strings.HasPrefix(rawurl, alias) {
365 continue
366 }
367
368 if longestalias < alias {
369 longestalias = alias
370 }
371 }
372
373 if len(longestalias) > 0 {
374 return aliases[longestalias] + rawurl[len(longestalias):], true
375 }
376
377 return rawurl, false
378 }
379
380 const (
381 aliasPrefix = "url."
382 )
383
384 func initAliases(e *endpointGitFinder, git config.Environment) {
385 suffix := ".insteadof"
386 pushSuffix := ".pushinsteadof"
387 for gitkey, gitval := range git.All() {
388 if len(gitval) == 0 || !strings.HasPrefix(gitkey, aliasPrefix) {
389 continue
390 }
391 if strings.HasSuffix(gitkey, suffix) {
392 storeAlias(e.aliases, gitkey, gitval, suffix)
393 } else if strings.HasSuffix(gitkey, pushSuffix) {
394 storeAlias(e.pushAliases, gitkey, gitval, pushSuffix)
395 }
396 }
397 }
398
399 func storeAlias(aliases map[string]string, key string, values []string, suffix string) {
400 for _, value := range values {
401 url := key[len(aliasPrefix) : len(key)-len(suffix)]
402 if v, ok := aliases[value]; ok && v != url {
403 fmt.Fprintln(os.Stderr, tr.Tr.Get("warning: Multiple 'url.*.%s' keys with the same alias: %q", suffix, value))
404 }
405 aliases[value] = url
406 }
407 }
408
409 func endpointFromGitUrl(u *url.URL, e *endpointGitFinder) lfshttp.Endpoint {
410 u.Scheme = e.gitProtocol
411 return lfshttp.Endpoint{Url: u.String()}
412 }