~james/core

core/migrator/git/runner.go -rw-r--r-- 8.1 KiB
452f17b7 — james chore(import): snapshot james.dad.town/core at f70c71c7696a 15 hours ago
                                                                                
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
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
package git

import (
	"bytes"
	"context"
	"errors"
	"fmt"
	"io"
	"io/fs"
	"net/url"
	"os"
	"os/exec"
	"path/filepath"
	"regexp"
	"slices"
	"strings"
	"sync"
	"syscall"
	"time"
)

var (
	ErrDiskLimitExceeded = errors.New("scratch disk limit exceeded")
	ErrPackLimitExceeded = errors.New("git pack limit exceeded")
	ErrAuthRequired      = errors.New("authorization required")
	ErrRepoNotFound      = errors.New("repository not found")
)

type CommandRunner interface {
	Run(ctx context.Context, dir string, env []string, name string, args ...string) (string, error)
	LookPath(file string) (string, error)
}

type RealCommandRunner struct {
	MaxOutputBytes   int
	MaxDiskBytes     int64
	WatchDir         string
	DiskPollInterval time.Duration
}

func (r RealCommandRunner) LookPath(file string) (string, error) {
	return exec.LookPath(file)
}

func (r RealCommandRunner) Run(ctx context.Context, dir string, env []string, name string, args ...string) (string, error) {
	cmdCtx, cmdCancel := context.WithCancel(ctx)
	defer cmdCancel()

	cmd := exec.CommandContext(cmdCtx, name, args...)
	cmd.Dir = dir
	cmd.Env = env
	// git spawns child helpers like git-remote-https, kill the process group
	cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true}
	cmd.Cancel = func() error {
		if cmd.Process == nil {
			return nil
		}
		return syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
	}

	maxOut := r.MaxOutputBytes
	if maxOut <= 0 {
		maxOut = 256 * 1024
	}

	var stdoutBuf, stderrBuf bytes.Buffer
	cmd.Stdout = &boundedWriter{w: &stdoutBuf, limit: maxOut}
	cmd.Stderr = &boundedWriter{w: &stderrBuf, limit: maxOut}

	var stopMonitor chan struct{}
	var monitorDone chan struct{}
	var diskMu sync.Mutex
	var diskErr error

	if r.WatchDir != "" && r.MaxDiskBytes > 0 {
		stopMonitor = make(chan struct{})
		monitorDone = make(chan struct{})
		baseUsed, baseErr := fsUsedBytes(r.WatchDir)
		go func() {
			defer close(monitorDone)
			interval := r.DiskPollInterval
			if interval <= 0 {
				interval = time.Second
			}
			ticker := time.NewTicker(interval)
			defer ticker.Stop()
			ticks := diskSweepEvery - 1
			for {
				select {
				case <-stopMonitor:
					return
				case <-cmdCtx.Done():
					return
				case <-ticker.C:
					ticks++
					grown := baseErr == nil
					if used, err := fsUsedBytes(r.WatchDir); err != nil || used-baseUsed <= r.MaxDiskBytes {
						grown = false
					}
					if !grown && ticks%diskSweepEvery != 0 {
						continue
					}
					size, err := dirSize(r.WatchDir)
					if err == nil && size > r.MaxDiskBytes {
						diskMu.Lock()
						diskErr = fmt.Errorf("%w: current %d bytes > max %d bytes", ErrDiskLimitExceeded, size, r.MaxDiskBytes)
						diskMu.Unlock()
						cmdCancel()
						return
					}
				}
			}
		}()
	}

	err := cmd.Run()

	if stopMonitor != nil {
		close(stopMonitor)
		<-monitorDone
	}

	diskMu.Lock()
	capturedDiskErr := diskErr
	diskMu.Unlock()

	outStr := stdoutBuf.String()
	if stderr := stderrBuf.String(); stderr != "" {
		outStr += stderr
	}

	if capturedDiskErr != nil {
		return outStr, capturedDiskErr
	}

	if err != nil {
		return outStr, fmt.Errorf("command %s failed: %w (output: %s)", name, err, sanitizeOutput(outStr))
	}

	return outStr, nil
}

type boundedWriter struct {
	w     io.Writer
	limit int
	total int
}

func (b *boundedWriter) Write(p []byte) (int, error) {
	if b.total >= b.limit {
		return len(p), nil
	}
	remaining := b.limit - b.total
	toWrite := p
	if len(toWrite) > remaining {
		toWrite = toWrite[:remaining]
	}
	n, err := b.w.Write(toWrite)
	b.total += n
	return len(p), err
}

const diskSweepEvery = 15

func fsUsedBytes(path string) (int64, error) {
	var st syscall.Statfs_t
	if err := syscall.Statfs(path, &st); err != nil {
		return 0, err
	}
	return int64(st.Blocks-st.Bavail) * int64(st.Bsize), nil
}

func dirSize(path string) (int64, error) {
	var size int64
	err := filepath.WalkDir(path, func(_ string, d fs.DirEntry, err error) error {
		if err != nil {
			return nil
		}
		if !d.IsDir() {
			info, err := d.Info()
			if err == nil {
				size += info.Size()
			}
		}
		return nil
	})
	return size, err
}

func RedactSecrets(s string, secrets ...string) string {
	res := s
	for _, sec := range secrets {
		if sec == "" || len(sec) < 4 {
			continue
		}
		res = strings.ReplaceAll(res, sec, "[REDACTED]")
		if encoded := url.QueryEscape(sec); encoded != sec {
			res = strings.ReplaceAll(res, encoded, "[REDACTED]")
		}
		if encoded := url.PathEscape(sec); encoded != sec {
			res = strings.ReplaceAll(res, encoded, "[REDACTED]")
		}
	}
	return res
}

var credentialPattern = regexp.MustCompile(`(Bearer|Basic)\s+[A-Za-z0-9._~+/-]+=*`)

func sanitizeOutput(s string) string {
	return credentialPattern.ReplaceAllString(s, "$1 [REDACTED]")
}

var authErrorMarkers = []string{
	"401",
	"403",
	"authentication failed",
	"invalid username or password",
	"could not read username",
	"device not configured",
	"terminal prompts disabled",
}

func ClassifyGitError(output string, exitErr error) error {
	outLower := strings.ToLower(output)
	// github answers a missing repository (and one the token cannot see)
	// with "repository not found"; that is not proof of a bad credential,
	// so it stays retryable instead of ending the job as authorization
	// required and scrubbing the batch token
	if strings.Contains(outLower, "repository not found") {
		return fmt.Errorf("%w: %s", ErrRepoNotFound, strings.TrimSpace(output))
	}
	if slices.ContainsFunc(authErrorMarkers, func(m string) bool { return strings.Contains(outLower, m) }) {
		return fmt.Errorf("%w: %s", ErrAuthRequired, strings.TrimSpace(output))
	}
	return exitErr
}

func HardenedGitEnv(proxyAddr, askpassBin, homeDir string, askpassHost, askpassToken string) []string {
	env := []string{
		"PATH=" + os.Getenv("PATH"),
		"HOME=" + homeDir,
		"GIT_CONFIG_NOSYSTEM=1",
		"GIT_CONFIG_GLOBAL=/dev/null",
		"GIT_TERMINAL_PROMPT=0",
		// without this a source url of file:///etc/passwd is a readable repository
		"GIT_ALLOW_PROTOCOL=https",
		"GIT_PROTOCOL_FROM_USER=0",
	}

	if proxyAddr != "" {
		proxyURL := "http://" + proxyAddr
		env = append(env,
			"http_proxy="+proxyURL,
			"HTTP_PROXY="+proxyURL,
			"https_proxy="+proxyURL,
			"HTTPS_PROXY="+proxyURL,
			"all_proxy="+proxyURL,
			"ALL_PROXY="+proxyURL,
			"NO_PROXY=",
			"no_proxy=",
		)
	}

	// git gets none of our env, but a trust store set for the whole process is the operator's
	if ca := os.Getenv("SSL_CERT_FILE"); ca != "" {
		env = append(env, "GIT_SSL_CAINFO="+ca)
	}

	if askpassBin != "" {
		env = append(env,
			"GIT_ASKPASS="+askpassBin,
			"MIGRATOR_ASKPASS_HOST="+askpassHost,
			"MIGRATOR_ASKPASS_TOKEN="+askpassToken,
		)
	}

	return env
}

var quotedURLRegex = regexp.MustCompile(`'([^']+)'`)

func ExtractHostFromPrompt(prompt string) string {
	matches := quotedURLRegex.FindStringSubmatch(prompt)
	if len(matches) > 1 {
		u, err := url.Parse(matches[1])
		if err == nil {
			return strings.ToLower(u.Hostname())
		}
	}
	re := regexp.MustCompile(`https?://(?:[^@/\s]+@)?([^/':@\s]+)`)
	m := re.FindStringSubmatch(prompt)
	if len(m) > 1 {
		return strings.ToLower(m[1])
	}
	return ""
}

func HandleAskpass(prompt, expectedHost, token string) (string, error) {
	promptHost := ExtractHostFromPrompt(prompt)
	if promptHost == "" {
		return "", fmt.Errorf("no host found in askpass prompt %q", prompt)
	}

	expectedHost = strings.ToLower(expectedHost)
	if !strings.EqualFold(promptHost, expectedHost) {
		return "", fmt.Errorf("host mismatch: prompt host %q != expected host %q", promptHost, expectedHost)
	}

	promptLower := strings.ToLower(prompt)
	if strings.Contains(promptLower, "username") {
		return "x-access-token", nil
	}
	if strings.Contains(promptLower, "password") {
		return token, nil
	}

	return "", fmt.Errorf("unknown askpass prompt: %q", prompt)
}

func CreateAskpassScript(dir string) (string, error) {
	migratorBin, err := os.Executable()
	if err != nil {
		return "", fmt.Errorf("getting migrator executable path: %w", err)
	}

	scriptPath := filepath.Join(dir, "askpass.sh")
	content := fmt.Sprintf(`#!/bin/sh
exec "%s" askpass "$@"
`, migratorBin)

	if err := os.WriteFile(scriptPath, []byte(content), 0700); err != nil {
		return "", fmt.Errorf("writing askpass script: %w", err)
	}

	return scriptPath, nil
}