File: git-credential-lfstest.go

package info (click to toggle)
git-lfs 3.6.1-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid, trixie
  • size: 4,808 kB
  • sloc: sh: 21,256; makefile: 507; ruby: 417
file content (262 lines) | stat: -rw-r--r-- 7,284 bytes parent folder | download
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
//go:build testtools
// +build testtools

package main

import (
	"bufio"
	"errors"
	"fmt"
	"os"
	"path/filepath"
	"slices"
	"strings"
)

var (
	commands = map[string]func(){
		"get":   fill,
		"store": log,
		"erase": log,
	}

	delim    = '\n'
	credsDir = ""
)

type credential struct {
	authtype   string
	username   string
	password   string
	credential string
	matchState string
	state      string
	multistage bool
	skip       bool
}

func (c *credential) Serialize(capabilities map[string]struct{}, state []string, username []string) map[string][]string {
	formattedState := fmt.Sprintf("lfstest:%s", c.state)
	formattedMatchState := fmt.Sprintf("lfstest:%s", c.matchState)
	creds := make(map[string][]string)
	if c.skip {
		// Do nothing.
	} else if _, ok := capabilities["authtype"]; ok && len(c.authtype) != 0 && len(c.credential) != 0 {
		if _, ok := capabilities["state"]; len(c.matchState) == 0 || (ok && slices.Contains(state, formattedMatchState)) {
			creds["authtype"] = []string{c.authtype}
			creds["credential"] = []string{c.credential}
			if ok {
				creds["state[]"] = []string{formattedState}
				if c.multistage {
					creds["continue"] = []string{"1"}
				}
			}
		}
	} else if len(c.authtype) == 0 && (len(username) == 0 || username[0] == c.username) {
		if len(username) == 0 {
			creds["username"] = []string{c.username}
		}
		creds["password"] = []string{c.password}
	}
	return creds
}

func init() {
	if len(credsDir) == 0 {
		credsDir = os.Getenv("CREDSDIR")
	}
}

func main() {
	if argsize := len(os.Args); argsize != 2 {
		fmt.Fprintf(os.Stderr, "wrong number of args: %d\n", argsize)
		os.Exit(1)
	}

	arg := os.Args[1]
	cmd := commands[arg]

	if cmd == nil {
		fmt.Fprintf(os.Stderr, "bad cmd: %s\n", arg)
		os.Exit(1)
	}

	cmd()
}

func fill() {
	scanner := bufio.NewScanner(os.Stdin)
	creds := map[string][]string{}
	for scanner.Scan() {
		line := scanner.Text()
		parts := strings.SplitN(line, "=", 2)
		if len(parts) != 2 {
			fmt.Fprintf(os.Stderr, "bad line: %s\n", line)
			os.Exit(1)
		}

		fmt.Fprintf(os.Stderr, "CREDS RECV: %s\n", line)
		if _, ok := creds[parts[0]]; ok {
			creds[parts[0]] = append(creds[parts[0]], strings.TrimSpace(parts[1]))
		} else {
			creds[parts[0]] = []string{strings.TrimSpace(parts[1])}
		}
	}

	if err := scanner.Err(); err != nil {
		fmt.Fprintf(os.Stderr, "reading standard input: %v", err)
		os.Exit(1)
	}

	hostPieces := strings.SplitN(firstEntryForKey(creds, "host"), ":", 2)
	credentials, err := credsForHostAndPath(hostPieces[0], firstEntryForKey(creds, "path"))
	if err != nil {
		fmt.Fprintln(os.Stderr, err.Error())
		os.Exit(1)
	}

	result := map[string][]string{}
	capas := discoverCapabilities(creds)
	for _, cred := range credentials {
		result = cred.Serialize(capas, creds["state[]"], creds["username"])
		if len(result) != 0 {
			break
		}
	}

	mode := os.Getenv("LFS_TEST_CREDS_WWWAUTH")
	wwwauth := firstEntryForKey(creds, "wwwauth[]")
	if mode == "required" && !strings.HasPrefix(wwwauth, "Basic ") {
		fmt.Fprintf(os.Stderr, "Missing required 'wwwauth[]' key in credentials\n")
		os.Exit(1)
	} else if mode == "forbidden" && wwwauth != "" {
		fmt.Fprintf(os.Stderr, "Unexpected 'wwwauth[]' key in credentials\n")
		os.Exit(1)
	}

	if len(result) == 0 {
		os.Exit(0)
	}

	// Send capabilities first to all for one-pass parsing, but only if
	// client advertised capabilities matching those of the per-host data.
	key := "capability[]"
	for entry, _ := range capas {
		fmt.Fprintf(os.Stderr, "CREDS SEND: %s=%s\n", key, entry)
		fmt.Fprintf(os.Stdout, "%s=%s\n", key, entry)
	}
	for key, value := range result {
		for _, entry := range value {
			fmt.Fprintf(os.Stderr, "CREDS SEND: %s=%s\n", key, entry)
			fmt.Fprintf(os.Stdout, "%s=%s\n", key, entry)
		}
	}
}

func discoverCapabilities(creds map[string][]string) map[string]struct{} {
	capas := make(map[string]struct{})
	supportedCapas := map[string]struct{}{
		"authtype": struct{}{},
		"state":    struct{}{},
	}
	for _, capa := range creds["capability[]"] {
		// Only pass on capabilities we support.
		if _, ok := supportedCapas[capa]; ok {
			capas[capa] = struct{}{}
		}
	}
	return capas
}

func credsForHostAndPath(host, path string) ([]credential, error) {
	if len(path) > 0 {
		pathFilename := fmt.Sprintf("%s--%s", host, strings.Replace(path, "/", "-", -1))
		cred, err := credsFromFilename(filepath.Join(credsDir, pathFilename))
		if err == nil {
			return cred, err
		}

		// Ideally we might run cygpath to convert paths like D:/...
		// to /d/... paths, but we only need to do this to support
		// one test of the deprecated git-lfs-clone command in our
		// CI suite, so for simplicity we just do basic rewriting.
		if len(path) > 2 && path[0] >= 'A' && path[0] <= 'Z' && path[1] == ':' {
			path = "/" + strings.ToLower(string(path[0])) + path[2:]
			pathFilename := fmt.Sprintf("%s--%s", host, strings.Replace(path, "/", "-", -1))
			cred, err := credsFromFilename(filepath.Join(credsDir, pathFilename))
			if err == nil {
				return cred, err
			}
		}
	}

	if len(host) == 0 {
		return nil, errors.New("No file available; empty 'host' key in credentials")
	}

	return credsFromFilename(filepath.Join(credsDir, host))
}

func parseOneCredential(s, file string) (credential, error) {
	// Each line in a file is of the following form:
	//
	// skip::
	//	The literal word "skip" means to skip emitting credentials.
	// AUTHTYPE::CREDENTIAL
	//	If the authtype is not empty, then this is an authtype and
	//	credential.
	// AUTHTYPE::CREDENTIAL:MATCH:STATE:MULTISTAGE
	//	Like above, but this matches only if MATCH is empty or if the
	//	state[] entry is present and matches "lfstest:MATCH".  If so,
	//	the value "lfstest:STATE" is emitted as the new state[] entry.
	//	If MULTISTAGE is set to "true", then the multistage flag is set.
	// :USERNAME:PASSWORD
	//	This is a normal username and password.
	credsPieces := strings.Split(strings.TrimSpace(s), ":")
	if len(credsPieces) != 3 && len(credsPieces) != 6 {
		return credential{}, fmt.Errorf("Invalid data %q while reading %q", string(s), file)
	}
	if credsPieces[0] == "skip" {
		return credential{skip: true}, nil
	} else if len(credsPieces[0]) == 0 {
		return credential{username: credsPieces[1], password: credsPieces[2]}, nil
	} else if len(credsPieces) == 3 {
		return credential{authtype: credsPieces[0], credential: credsPieces[2]}, nil
	} else {
		return credential{
			authtype:   credsPieces[0],
			credential: credsPieces[2],
			matchState: credsPieces[3],
			state:      credsPieces[4],
			multistage: credsPieces[5] == "true",
		}, nil
	}
}

func credsFromFilename(file string) ([]credential, error) {
	fileContents, err := os.ReadFile(file)
	if err != nil {
		return nil, fmt.Errorf("Error opening %q: %s", file, err)
	}
	lines := strings.Split(strings.TrimSpace(string(fileContents)), "\n")
	creds := make([]credential, 0, len(lines))
	for _, line := range lines {
		cred, err := parseOneCredential(line, file)
		if err != nil {
			return nil, err
		}
		creds = append(creds, cred)
	}
	return creds, nil
}

func log() {
	fmt.Fprintf(os.Stderr, "CREDS received command: %s (ignored)\n", os.Args[1])
}

func firstEntryForKey(input map[string][]string, key string) string {
	if val, ok := input[key]; ok && len(val) > 0 {
		return val[0]
	}
	return ""
}