Debian Codegraph @

creds/creds.go

raw symbols SCIP
1 package creds
2
3 import (
4 "bytes"
5 "fmt"
6 "net/url"
7 "os"
8 "os/exec"
9 "slices"
10 "strings"
11 "sync"
12
13 "github.com/git-lfs/git-lfs/v3/config"
14 "github.com/git-lfs/git-lfs/v3/errors"
15 "github.com/git-lfs/git-lfs/v3/subprocess"
16 "github.com/git-lfs/git-lfs/v3/tools"
17 "github.com/git-lfs/git-lfs/v3/tr"
18 "github.com/rubyist/tracerx"
19 )
20
21 // CredentialHelperWrapper is used to contain the encapsulate the information we need for credential handling during auth.
22 type CredentialHelperWrapper struct {
23 CredentialHelper CredentialHelper
24 Input Creds
25 Url *url.URL
26 Creds Creds
27 }
28
29 // CredentialHelper is an interface used by the lfsapi Client to interact with
30 // the 'git credential' command: https://git-scm.com/docs/gitcredentials
31 // Other implementations include ASKPASS support, and an in-memory cache.
32 type CredentialHelper interface {
33 Fill(Creds) (Creds, error)
34 Reject(Creds) error
35 Approve(Creds) error
36 }
37
38 func (credWrapper *CredentialHelperWrapper) FillCreds() error {
39 creds, err := credWrapper.CredentialHelper.Fill(credWrapper.Input)
40 if creds == nil || len(creds) < 1 {
41 errmsg := tr.Tr.Get("Git credentials for %s not found", credWrapper.Url)
42 if err != nil {
43 errmsg = fmt.Sprintf("%s:\n%s", errmsg, err.Error())
44 } else {
45 errmsg = fmt.Sprintf("%s.", errmsg)
46 }
47 err = errors.New(errmsg)
48 }
49 credWrapper.Creds = creds
50 return err
51 }
52
53 // Creds represents a set of key/value pairs that are passed to 'git credential'
54 // as input.
55 type Creds map[string][]string
56
57 func (c Creds) IsMultistage() bool {
58 return slices.Contains([]string{"1", "true"}, FirstEntryForKey(c, "continue"))
59 }
60
61 func (c Creds) buffer(protectProtocol bool) (*bytes.Buffer, error) {
62 buf := new(bytes.Buffer)
63
64 buf.Write([]byte("capability[]=authtype\n"))
65 buf.Write([]byte("capability[]=state\n"))
66 for k, v := range c {
67 for _, item := range v {
68 if strings.Contains(item, "\n") {
69 return nil, errors.New(tr.Tr.Get("credential value for %s contains newline: %q", k, item))
70 }
71 if protectProtocol && strings.Contains(item, "\r") {
72 return nil, errors.New(tr.Tr.Get("credential value for %s contains carriage return: %q\nIf this is intended, set `credential.protectProtocol=false`", k, item))
73 }
74 if strings.Contains(item, string(rune(0))) {
75 return nil, errors.New(tr.Tr.Get("credential value for %s contains null byte: %q", k, item))
76 }
77
78 buf.Write([]byte(k))
79 buf.Write([]byte("="))
80 buf.Write([]byte(item))
81 buf.Write([]byte("\n"))
82 }
83 }
84
85 return buf, nil
86 }
87
88 type CredentialHelperContext struct {
89 netrcCredHelper *netrcCredentialHelper
90 commandCredHelper *commandCredentialHelper
91 askpassCredHelper *AskPassCredentialHelper
92 cachingCredHelper *credentialCacher
93
94 urlConfig *config.URLConfig
95 wwwAuthHeaders []string
96 state []string
97 }
98
99 func NewCredentialHelperContext(gitEnv config.Environment, osEnv config.Environment) *CredentialHelperContext {
100 c := &CredentialHelperContext{urlConfig: config.NewURLConfig(gitEnv)}
101
102 c.netrcCredHelper = newNetrcCredentialHelper(osEnv)
103
104 askpass, ok := osEnv.Get("GIT_ASKPASS")
105 if !ok {
106 askpass, ok = gitEnv.Get("core.askpass")
107 }
108 if !ok {
109 askpass, _ = osEnv.Get("SSH_ASKPASS")
110 }
111 if len(askpass) > 0 {
112 askpassfile, err := tools.TranslateCygwinPath(askpass)
113 if err != nil {
114 tracerx.Printf("Error reading askpass helper %q: %v", askpassfile, err)
115 }
116 if len(askpassfile) > 0 {
117 c.askpassCredHelper = &AskPassCredentialHelper{
118 Program: askpassfile,
119 }
120 }
121 }
122
123 cacheCreds := gitEnv.Bool("lfs.cachecredentials", true)
124 if cacheCreds {
125 c.cachingCredHelper = NewCredentialCacher()
126 }
127
128 c.commandCredHelper = &commandCredentialHelper{
129 SkipPrompt: osEnv.Bool("GIT_TERMINAL_PROMPT", false),
130 }
131
132 return c
133 }
134
135 func (ctxt *CredentialHelperContext) SetWWWAuthHeaders(headers []string) {
136 ctxt.wwwAuthHeaders = headers
137 }
138
139 func (ctxt *CredentialHelperContext) SetStateFields(fields []string) {
140 ctxt.state = fields
141 }
142
143 // getCredentialHelper parses a 'credsConfig' from the git and OS environments,
144 // returning the appropriate CredentialHelper to authenticate requests with.
145 //
146 // It returns an error if any configuration was invalid, or otherwise
147 // un-useable.
148 func (ctxt *CredentialHelperContext) GetCredentialHelper(helper CredentialHelper, u *url.URL) CredentialHelperWrapper {
149 rawurl := fmt.Sprintf("%s://%s%s", u.Scheme, u.Host, u.Path)
150 input := Creds{"protocol": []string{u.Scheme}, "host": []string{u.Host}}
151 if u.User != nil && u.User.Username() != "" {
152 input["username"] = []string{u.User.Username()}
153 }
154 if u.Scheme == "cert" || ctxt.urlConfig.Bool("credential", rawurl, "usehttppath", false) {
155 input["path"] = []string{strings.TrimPrefix(u.Path, "/")}
156 }
157 if len(ctxt.wwwAuthHeaders) != 0 && !ctxt.urlConfig.Bool("credential", rawurl, "skipwwwauth", false) {
158 input["wwwauth[]"] = ctxt.wwwAuthHeaders
159 }
160 if len(ctxt.state) != 0 {
161 input["state[]"] = ctxt.state
162 }
163
164 if helper != nil {
165 return CredentialHelperWrapper{CredentialHelper: helper, Input: input, Url: u}
166 }
167
168 helpers := make([]CredentialHelper, 0, 4)
169 if ctxt.netrcCredHelper != nil {
170 helpers = append(helpers, ctxt.netrcCredHelper)
171 }
172 if ctxt.cachingCredHelper != nil {
173 helpers = append(helpers, ctxt.cachingCredHelper)
174 }
175 if ctxt.askpassCredHelper != nil {
176 helper, _ := ctxt.urlConfig.Get("credential", rawurl, "helper")
177 if len(helper) == 0 {
178 helpers = append(helpers, ctxt.askpassCredHelper)
179 }
180 }
181
182 ctxt.commandCredHelper.protectProtocol = ctxt.urlConfig.Bool("credential", rawurl, "protectProtocol", true)
183
184 return CredentialHelperWrapper{CredentialHelper: NewCredentialHelpers(append(helpers, ctxt.commandCredHelper)), Input: input, Url: u}
185 }
186
187 // AskPassCredentialHelper implements the CredentialHelper type for GIT_ASKPASS
188 // and 'core.askpass' configuration values.
189 type AskPassCredentialHelper struct {
190 // Program is the executable program's absolute or relative name.
191 Program string
192 }
193
194 type credValueType int
195
196 const (
197 credValueTypeUnknown credValueType = iota
198 credValueTypeUsername
199 credValueTypePassword
200 )
201
202 // Fill implements fill by running the ASKPASS program and returning its output
203 // as a password encoded in the Creds type given the key "password".
204 //
205 // It accepts the password as coming from the program's stdout, as when invoked
206 // with the given arguments (see (*AskPassCredentialHelper).args() below)./
207 //
208 // If there was an error running the command, it is returned instead of a set of
209 // filled credentials.
210 //
211 // The ASKPASS program is only queried if a credential was not already
212 // provided, i.e. through the git URL
213 func (a *AskPassCredentialHelper) Fill(what Creds) (Creds, error) {
214 u := &url.URL{
215 Scheme: FirstEntryForKey(what, "protocol"),
216 Host: FirstEntryForKey(what, "host"),
217 Path: FirstEntryForKey(what, "path"),
218 }
219
220 creds := make(Creds)
221
222 username, err := a.getValue(what, credValueTypeUsername, u)
223 if err != nil {
224 return nil, err
225 }
226 creds["username"] = []string{username}
227
228 if len(username) > 0 {
229 // If a non-empty username was given, add it to the URL via func
230 // 'net/url.User()'.
231 u.User = url.User(username)
232 }
233
234 password, err := a.getValue(what, credValueTypePassword, u)
235 if err != nil {
236 return nil, err
237 }
238 creds["password"] = []string{password}
239
240 return creds, nil
241 }
242
243 func (a *AskPassCredentialHelper) getValue(what Creds, valueType credValueType, u *url.URL) (string, error) {
244 var valueString string
245
246 switch valueType {
247 case credValueTypeUsername:
248 valueString = "username"
249 case credValueTypePassword:
250 valueString = "password"
251 default:
252 return "", errors.New(tr.Tr.Get("Invalid Credential type queried from AskPass"))
253 }
254
255 // Return the existing credential if it was already provided, otherwise
256 // query AskPass for it
257 if given, ok := what[valueString]; ok && len(given) > 0 {
258 return given[0], nil
259 }
260 return a.getFromProgram(valueType, u)
261 }
262
263 func (a *AskPassCredentialHelper) getFromProgram(valueType credValueType, u *url.URL) (string, error) {
264 var (
265 value bytes.Buffer
266 err bytes.Buffer
267
268 valueString string
269 )
270
271 switch valueType {
272 case credValueTypeUsername:
273 valueString = "Username"
274 case credValueTypePassword:
275 valueString = "Password"
276 default:
277 return "", errors.New(tr.Tr.Get("Invalid Credential type queried from AskPass"))
278 }
279
280 // 'cmd' will run the GIT_ASKPASS (or core.askpass) command prompting
281 // for the desired valueType (`Username` or `Password`)
282 cmd, errVal := subprocess.ExecCommand(a.Program, a.args(fmt.Sprintf("%s for %q", valueString, u))...)
283 if errVal != nil {
284 tracerx.Printf("creds: failed to find GIT_ASKPASS command: %s", a.Program)
285 return "", errVal
286 }
287 cmd.Stderr = &err
288 cmd.Stdout = &value
289
290 tracerx.Printf("creds: filling with GIT_ASKPASS: %s", strings.Join(cmd.Args, " "))
291 if err := cmd.Run(); err != nil {
292 return "", err
293 }
294
295 if err.Len() > 0 {
296 return "", errors.New(err.String())
297 }
298
299 return strings.TrimSpace(value.String()), nil
300 }
301
302 // Approve implements CredentialHelper.Approve, and returns nil. The ASKPASS
303 // credential helper does not implement credential approval.
304 func (a *AskPassCredentialHelper) Approve(_ Creds) error { return nil }
305
306 // Reject implements CredentialHelper.Reject, and returns nil. The ASKPASS
307 // credential helper does not implement credential rejection.
308 func (a *AskPassCredentialHelper) Reject(_ Creds) error { return nil }
309
310 // args returns the arguments given to the ASKPASS program, if a prompt was
311 // given.
312
313 // See: https://git-scm.com/docs/gitcredentials#_requesting_credentials for
314 // more.
315 func (a *AskPassCredentialHelper) args(prompt string) []string {
316 if len(prompt) == 0 {
317 return nil
318 }
319 return []string{prompt}
320 }
321
322 type commandCredentialHelper struct {
323 SkipPrompt bool
324 protectProtocol bool
325 }
326
327 func (h *commandCredentialHelper) Fill(creds Creds) (Creds, error) {
328 tracerx.Printf("creds: git credential fill (%q, %q, %q)",
329 FirstEntryForKey(creds, "protocol"),
330 FirstEntryForKey(creds, "host"),
331 FirstEntryForKey(creds, "path"))
332 return h.exec("fill", creds)
333 }
334
335 func (h *commandCredentialHelper) Reject(creds Creds) error {
336 _, err := h.exec("reject", creds)
337 return err
338 }
339
340 func (h *commandCredentialHelper) Approve(creds Creds) error {
341 tracerx.Printf("creds: git credential approve (%q, %q, %q)",
342 FirstEntryForKey(creds, "protocol"),
343 FirstEntryForKey(creds, "host"),
344 FirstEntryForKey(creds, "path"))
345 _, err := h.exec("approve", creds)
346 return err
347 }
348
349 func (h *commandCredentialHelper) exec(subcommand string, input Creds) (Creds, error) {
350 output := new(bytes.Buffer)
351 cmd, err := subprocess.ExecCommand("git", "credential", subcommand)
352 if err != nil {
353 return nil, errors.New(tr.Tr.Get("failed to find `git credential %s`: %v", subcommand, err))
354 }
355 cmd.Stdin, err = input.buffer(h.protectProtocol)
356 if err != nil {
357 return nil, errors.New(tr.Tr.Get("invalid input to `git credential %s`: %v", subcommand, err))
358 }
359 cmd.Stdout = output
360 /*
361 There is a reason we don't read from stderr here:
362 Git's credential cache daemon helper does not close its stderr, so if this
363 process is the process that fires up the daemon, it will wait forever
364 (until the daemon exits, really) trying to read from stderr.
365
366 Instead, we simply pass it through to our stderr.
367
368 See https://github.com/git-lfs/git-lfs/issues/117 for more details.
369 */
370 cmd.Stderr = os.Stderr
371
372 err = cmd.Start()
373 if err == nil {
374 err = cmd.Wait()
375 }
376
377 if _, ok := err.(*exec.ExitError); ok {
378 if h.SkipPrompt {
379 return nil, errors.New(tr.Tr.Get("change the GIT_TERMINAL_PROMPT env var to be prompted to enter your credentials for %s://%s",
380 FirstEntryForKey(input, "protocol"), FirstEntryForKey(input, "host")))
381 }
382
383 // 'git credential' exits with 128 if the helper doesn't fill the username
384 // and password values.
385 if subcommand == "fill" && err.Error() == "exit status 128" {
386 return nil, nil
387 }
388 }
389
390 if err != nil {
391 return nil, errors.New(tr.Tr.Get("`git credential %s` error: %s", subcommand, err.Error()))
392 }
393
394 creds := make(Creds)
395 for _, line := range strings.Split(output.String(), "\n") {
396 pieces := strings.SplitN(line, "=", 2)
397 if len(pieces) < 2 || len(pieces[1]) < 1 {
398 continue
399 }
400 if _, ok := creds[pieces[0]]; ok {
401 creds[pieces[0]] = append(creds[pieces[0]], pieces[1])
402 } else {
403 creds[pieces[0]] = []string{pieces[1]}
404 }
405 }
406
407 return creds, nil
408 }
409
410 type credentialCacher struct {
411 creds map[string]Creds
412 mu sync.Mutex
413 }
414
415 func NewCredentialCacher() *credentialCacher {
416 return &credentialCacher{creds: make(map[string]Creds)}
417 }
418
419 func credCacheKey(creds Creds) string {
420 parts := []string{
421 FirstEntryForKey(creds, "protocol"),
422 FirstEntryForKey(creds, "host"),
423 FirstEntryForKey(creds, "path"),
424 }
425 return strings.Join(parts, "//")
426 }
427
428 func (c *credentialCacher) Fill(what Creds) (Creds, error) {
429 key := credCacheKey(what)
430 c.mu.Lock()
431 cached, ok := c.creds[key]
432 c.mu.Unlock()
433
434 if ok {
435 tracerx.Printf("creds: git credential cache (%q, %q, %q)",
436 FirstEntryForKey(what, "protocol"),
437 FirstEntryForKey(what, "host"),
438 FirstEntryForKey(what, "path"))
439 return cached, nil
440 }
441
442 return nil, credHelperNoOp
443 }
444
445 func (c *credentialCacher) Approve(what Creds) error {
446 key := credCacheKey(what)
447
448 c.mu.Lock()
449 defer c.mu.Unlock()
450
451 if _, ok := c.creds[key]; ok {
452 return nil
453 }
454
455 c.creds[key] = what
456 return credHelperNoOp
457 }
458
459 func (c *credentialCacher) Reject(what Creds) error {
460 key := credCacheKey(what)
461 c.mu.Lock()
462 delete(c.creds, key)
463 c.mu.Unlock()
464 return credHelperNoOp
465 }
466
467 // CredentialHelpers iterates through a slice of CredentialHelper objects
468 // CredentialHelpers is a []CredentialHelper that iterates through each
469 // credential helper to fill, reject, or approve credentials. Typically, the
470 // first success returns immediately. Errors are reported to tracerx, unless
471 // all credential helpers return errors. Any erroring credential helpers are
472 // skipped for future calls.
473 //
474 // A CredentialHelper can return a credHelperNoOp error, signaling that the
475 // CredentialHelpers should try the next one.
476 type CredentialHelpers struct {
477 helpers []CredentialHelper
478 skippedHelpers map[int]bool
479 mu sync.Mutex
480 }
481
482 // NewCredentialHelpers initializes a new CredentialHelpers from the given
483 // slice of CredentialHelper instances.
484 func NewCredentialHelpers(helpers []CredentialHelper) CredentialHelper {
485 return &CredentialHelpers{
486 helpers: helpers,
487 skippedHelpers: make(map[int]bool),
488 }
489 }
490
491 var credHelperNoOp = errors.New("no-op!")
492
493 // Fill implements CredentialHelper.Fill by asking each CredentialHelper in
494 // order to fill the credentials.
495 //
496 // If a fill was successful, it is returned immediately, and no other
497 // `CredentialHelper`s are consulted. If any CredentialHelper returns an error,
498 // it is reported to tracerx, and the next one is attempted. If they all error,
499 // then a collection of all the error messages is returned. Erroring credential
500 // helpers are added to the skip list, and never attempted again for the
501 // lifetime of the current Git LFS command.
502 func (s *CredentialHelpers) Fill(what Creds) (Creds, error) {
503 var multiErr error
504 for i, h := range s.helpers {
505 if s.skipped(i) {
506 continue
507 }
508
509 creds, err := h.Fill(what)
510 if err != nil {
511 if err != credHelperNoOp {
512 s.skip(i)
513 tracerx.Printf("credential fill error: %s", err)
514 multiErr = errors.Join(multiErr, err)
515 }
516 continue
517 }
518
519 if creds != nil {
520 return creds, nil
521 }
522 }
523
524 if multiErr != nil {
525 multiErr = errors.Join(errors.New(tr.Tr.Get("credential fill errors:")), multiErr)
526 }
527
528 return nil, multiErr
529 }
530
531 // Reject implements CredentialHelper.Reject and rejects the given Creds "what"
532 // with the first successful attempt.
533 func (s *CredentialHelpers) Reject(what Creds) error {
534 for i, h := range s.helpers {
535 if s.skipped(i) {
536 continue
537 }
538
539 if err := h.Reject(what); err != credHelperNoOp {
540 return err
541 }
542 }
543
544 return errors.New(tr.Tr.Get("no valid credential helpers to reject"))
545 }
546
547 // Approve implements CredentialHelper.Approve and approves the given Creds
548 // "what" with the first successful CredentialHelper. If an error occurs,
549 // it calls Reject() with the same Creds and returns the error immediately. This
550 // ensures a caching credential helper removes the cache, since the Erroring
551 // CredentialHelper never successfully saved it.
552 func (s *CredentialHelpers) Approve(what Creds) error {
553 skipped := make(map[int]bool)
554 for i, h := range s.helpers {
555 if s.skipped(i) {
556 skipped[i] = true
557 continue
558 }
559
560 if err := h.Approve(what); err != credHelperNoOp {
561 if err != nil && i > 0 { // clear any cached approvals
562 for j := 0; j < i; j++ {
563 if !skipped[j] {
564 s.helpers[j].Reject(what)
565 }
566 }
567 }
568 return err
569 }
570 }
571
572 return errors.New(tr.Tr.Get("no valid credential helpers to approve"))
573 }
574
575 func (s *CredentialHelpers) skip(i int) {
576 s.mu.Lock()
577 s.skippedHelpers[i] = true
578 s.mu.Unlock()
579 }
580
581 func (s *CredentialHelpers) skipped(i int) bool {
582 s.mu.Lock()
583 skipped := s.skippedHelpers[i]
584 s.mu.Unlock()
585 return skipped
586 }
587
588 type nullCredentialHelper struct{}
589
590 var (
591 nullCredError = errors.New(tr.Tr.Get("No credential helper configured"))
592 NullCreds = &nullCredentialHelper{}
593 )
594
595 func (h *nullCredentialHelper) Fill(input Creds) (Creds, error) {
596 return nil, nullCredError
597 }
598
599 func (h *nullCredentialHelper) Approve(creds Creds) error {
600 return nil
601 }
602
603 func (h *nullCredentialHelper) Reject(creds Creds) error {
604 return nil
605 }
606
607 // FirstEntryForKey extracts and returns the first entry for a given key, or
608 // returns the empty string if no value for that key is available.
609 func FirstEntryForKey(input Creds, key string) string {
610 if val, ok := input[key]; ok && len(val) > 0 {
611 return val[0]
612 }
613 return ""
614 }