cmd/gitbay-runner/main.go
697 lines · 24833 bytes
22 symbols in this file
1// gitbay-runner executes CI builds queued by a gitbay server. It polls over
2// SSH — the same authenticated channel everything else uses — claims one
3// build at a time, clones the repo, runs each step with `sh -c`, streams the
4// combined output back, and reports success or failure.
5//
6// The account behind the runner's key must be an instance admin: a runner
7// executes arbitrary repo code, so handing out jobs is the operator's call.
8// v1 runs steps directly on the host under this process's user; run it as a
9// dedicated unprivileged user.
10package main
11
12import (
13 "encoding/json"
14 "errors"
15 "flag"
16 "fmt"
17 "io"
18 "io/fs"
19 "log"
20 "net"
21 "os"
22 "os/exec"
23 "os/signal"
24 "path/filepath"
25 "slices"
26 "strings"
27 "sync"
28 "syscall"
29 "time"
30
31 "gitbay.org/gitbay/internal/buildinfo"
32 "gitbay.org/gitbay/internal/toolpath"
33)
34
35type job struct {
36 ID int64 `json:"id"`
37 Repo string `json:"repo"`
38 Number int64 `json:"number"`
39 Job string `json:"job"`
40 SHA string `json:"sha"`
41 Ref string `json:"ref"`
42 Steps []string `json:"steps"`
43 Image string `json:"image"`
44 // Trusted is false for a merge request head from a fork, and when the
45 // server did not say: such a build gets no secrets and a home of its
46 // own (#255).
47 Trusted bool `json:"trusted"`
48 // SSH is the instance's public ssh destination; a runner polling
49 // over loopback takes its port for its builds (#260).
50 SSH string `json:"ssh"`
51 Secrets map[string]string `json:"secrets"`
52 // Results asks for the SARIF the steps leave in $GITBAY_RESULTS to be
53 // uploaded once they succeed. Only the instance's code scan sets it.
54 Results bool `json:"results"`
55}
56
57type runner struct {
58 remote string // ssh destination, e.g. git@gitbay.org
59 sshOpts []string
60 cloneBase string // e.g. ssh://git@gitbay.org
61 workdir string
62 timeout time.Duration
63 // image is the container image for a job that names none, and
64 // isolation selects how steps run: "podman" or "none".
65 image string
66 isolation string
67 // memory and cpus cap one build's cgroup; empty means no cap.
68 memory string
69 cpus string
70 // cgroups is the runner's build cgroup subtree, nil where the unit
71 // is not delegated and builds run unconfined in the service cgroup.
72 cgroups *buildCgroups
73 // stepFn is step, replaceable by tests.
74 stepFn func() (bool, error)
75 // repos limits which repositories this runner claims builds for. Empty
76 // means any, which is what a runner on the server itself wants; a runner
77 // somewhere that should not execute every repository's steps names them.
78 repos []string
79 // untrusted also claims merge request heads from forks.
80 untrusted bool
81}
82
83func main() {
84 if len(os.Args) > 1 && os.Args[1] == "init" {
85 os.Exit(runInit(os.Args[2:]))
86 }
87 var (
88 configPath = flag.String("config", defaultConfigPath(), "config file; keys are these flag names, flags override it")
89 identity = flag.String("identity", "", "ssh private key to poll and clone with (default: the key gitbay-runner init generated, if present)")
90 untrusted = flag.Bool("untrusted", false, "also claim untrusted builds: merge request heads from forks (needs -isolation podman to be safe)")
91 remote = flag.String("remote", "git@gitbay.org", "ssh destination of the gitbay server")
92 sshOpts = flag.String("ssh-opts", "", "extra ssh options, space-separated (also used for git clone)")
93 cloneBase = flag.String("clone-base", "", "clone URL prefix (default ssh://<remote>)")
94 workdir = flag.String("workdir", defaultWorkdir(), "build workspace root")
95 poll = flag.Duration("poll", 5*time.Second, "idle poll interval")
96 timeout = flag.Duration("timeout", 30*time.Minute, "per-build time limit")
97 repos = flag.String("repos", "", "only claim builds for these repositories, comma-separated owner/name (default: any)")
98 once = flag.Bool("once", false, "process at most one build, then exit")
99 jobs = flag.Int("jobs", 1, "builds to run at once")
100 image = flag.String("image", "", "default container image for jobs that name none")
101 isolation = flag.String("isolation", "podman", "how steps run: podman, or none for no container")
102 memory = flag.String("memory", "", "memory limit per build, e.g. 4g (podman only, needs a delegated cgroup; default unlimited)")
103 cpus = flag.String("cpus", "", "CPU limit per build, e.g. 2 (podman only, needs a delegated cgroup; default unlimited)")
104 version = flag.Bool("version", false, "print the commit this binary was built from, then exit")
105 )
106 path := configPathFromArgs(os.Args[1:], *configPath)
107 if values, found, err := loadConfig(path); err != nil {
108 log.Fatal(err)
109 } else if found {
110 if err := applyConfig(flag.CommandLine, values); err != nil {
111 log.Fatal(err)
112 }
113 log.Printf("config: %s", path)
114 }
115 flag.Parse()
116 if *version {
117 fmt.Println(buildinfo.String())
118 return
119 }
120 // The runner links internal/store, so it goes stale on changes that never
121 // touch cmd/gitbay-runner. Say which commit is running.
122 log.Printf("gitbay-runner %s", buildinfo.String())
123 r := &runner{
124 remote: *remote,
125 cloneBase: *cloneBase,
126 workdir: *workdir,
127 timeout: *timeout,
128 image: *image,
129 isolation: *isolation,
130 memory: *memory,
131 cpus: *cpus,
132 }
133 var cgErr error
134 if r.isolation == isolationPodman {
135 // Before podman runs anything: its pause process lands in the
136 // cgroup of the first invocation, and that must be the runner's
137 // leaf, not a build's.
138 r.cgroups, cgErr = prepareBuildCgroups()
139 }
140 if err := r.checkIsolation(); err != nil {
141 // Refusing to start is the point. A runner that quietly fell back
142 // to running repository code on the host would drop isolation
143 // with nothing to surface it, which is worse than a stopped
144 // runner: the operator sees a failed unit either way, but only
145 // one of them is honest about why (#144).
146 log.Fatalf("isolation: %v", err)
147 }
148 if cgErr != nil {
149 // After checkIsolation, so a missing image or podman is reported
150 // as that rather than as the cgroups it would also lack.
151 if why := buildCgroupsRequired(r.memory, r.cpus, *untrusted, r.loopbackRemote()); why != "" {
152 log.Fatalf("%s: build cgroups unavailable: %v", why, cgErr)
153 }
154 log.Printf("build cgroups unavailable (%v); builds run unconfined in the service cgroup", cgErr)
155 }
156 if *sshOpts != "" {
157 r.sshOpts = strings.Fields(*sshOpts)
158 }
159 if *identity == "" {
160 if p := filepath.Join(configDir(), "id_ed25519"); fileExists(p) {
161 *identity = p
162 }
163 }
164 // Clipped: the later appends run from concurrent workers, and spare
165 // capacity here would have them writing the same backing array.
166 r.sshOpts = slices.Clip(sshOptions(*identity, r.sshOpts))
167 r.untrusted = *untrusted
168 for _, name := range strings.Split(*repos, ",") {
169 if name = strings.TrimSpace(name); name != "" {
170 r.repos = append(r.repos, name)
171 }
172 }
173 if r.cloneBase == "" {
174 r.cloneBase = "ssh://" + *remote
175 }
176 // 0o700, not 0o755: a build's checkout and its secrets-bearing
177 // environment are this user's business alone, and the default sits
178 // beside other users' data on a shared host.
179 if err := os.MkdirAll(r.workdir, 0o700); err != nil {
180 log.Fatal(err)
181 }
182 if err := checkWorkdir(r.workdir); err != nil {
183 log.Fatal(err)
184 }
185 n := *jobs
186 if n < 1 {
187 log.Fatal("-jobs must be at least 1")
188 }
189 if *once {
190 // "at most one build" is one build, whatever -jobs says.
191 n = 1
192 }
193 // `runner next` claims inside one transaction, so several workers
194 // claiming at once is already safe; the runner just never used that.
195 // Each build works in its own build-<id> directory, so they do not
196 // meet on disk either.
197 // A stop signal drains: no build is claimed after it, and each build
198 // already in flight runs to completion and is reported. The old
199 // behaviour was to die mid-build, which left the build "running" on
200 // the server with nothing executing (#179). The unit's
201 // TimeoutStopSec bounds the drain; a second signal ends it now.
202 stop := make(chan struct{})
203 go func() {
204 sigs := make(chan os.Signal, 2)
205 signal.Notify(sigs, syscall.SIGTERM, syscall.SIGINT)
206 <-sigs
207 log.Printf("draining: finishing builds in flight, claiming no more")
208 close(stop)
209 <-sigs
210 log.Printf("second signal: exiting without draining")
211 os.Exit(1)
212 }()
213 r.serve(n, *once, *poll, stop)
214}
215
216// serve runs n workers until stop closes. A worker checks stop only
217// between builds, so closing it never interrupts one.
218func (r *runner) serve(n int, once bool, poll time.Duration, stop <-chan struct{}) {
219 if r.stepFn == nil {
220 r.stepFn = r.step
221 }
222 var wg sync.WaitGroup
223 for i := 0; i < n; i++ {
224 wg.Add(1)
225 go func(i int) {
226 defer wg.Done()
227 if n > 1 {
228 time.Sleep(time.Duration(i) * poll / time.Duration(n))
229 }
230 for {
231 select {
232 case <-stop:
233 return
234 default:
235 }
236 ran, err := r.stepFn()
237 if err != nil {
238 log.Printf("runner: %v", err)
239 }
240 if once {
241 return
242 }
243 if !ran {
244 select {
245 case <-stop:
246 return
247 case <-time.After(poll):
248 }
249 }
250 }
251 }(i)
252 }
253 wg.Wait()
254}
255
256// step claims and executes at most one build. ran reports whether there was
257// one, so the caller knows when to idle.
258func (r *runner) step() (bool, error) {
259 args := []string{"runner", "next"}
260 if r.untrusted {
261 args = append(args, "--untrusted")
262 }
263 args = append(append(args, r.repos...), "--json")
264 out, err := r.ssh(nil, args...)
265 if err != nil {
266 return false, fmt.Errorf("claiming build: %w (%s)", err, out)
267 }
268 var env struct {
269 Data job `json:"data"`
270 }
271 if err := json.Unmarshal([]byte(out), &env); err != nil {
272 return false, fmt.Errorf("parsing job: %w", err)
273 }
274 if env.Data.ID == 0 {
275 return false, nil
276 }
277 j := env.Data
278 log.Printf("build %d: %s %s @ %.10s", j.ID, j.Repo, j.Job, j.SHA)
279 f := r.run(j)
280 status := "success"
281 if f != nil {
282 status = "failure"
283 }
284 if err := r.reportDone(j.ID, status, f); err != nil {
285 return true, err
286 }
287 log.Printf("build %d: %s", j.ID, status)
288 return true, nil
289}
290
291// logSink forwards a build's output to the server and swallows any error
292// doing so. os/exec surfaces a write failure on a step's stdout through
293// cmd.Wait(), so a sink that can fail is a sink that can fail the build it
294// was only recording — a restart or a dropped session used to turn a green
295// suite red, with the explaining line written to the same dead pipe. Losing
296// log lines is the acceptable failure here; losing the build is not.
297type logSink struct {
298 mu sync.Mutex
299 w io.Writer // nil once a write has failed
300}
301
302func (s *logSink) Write(p []byte) (int, error) {
303 s.mu.Lock()
304 defer s.mu.Unlock()
305 if s.w != nil {
306 if _, err := s.w.Write(p); err != nil {
307 s.w = nil
308 }
309 }
310 return len(p), nil
311}
312
313// broken reports whether the stream was lost, so a build can say its log is
314// incomplete rather than appear to have simply stopped.
315func (s *logSink) broken() bool {
316 s.mu.Lock()
317 defer s.mu.Unlock()
318 return s.w == nil
319}
320
321// failure says where a build stopped: Step is the 1-based step that
322// failed, 0 when the build stopped before its first step (the clone, the
323// container), and Reason is one short line (#266).
324type failure struct {
325 Step int
326 Reason string
327}
328
329// exitReason is how a finished command's failure reads in a build's log
330// and on the build: "exit 1" for a command that exited, the error
331// otherwise (a signal, a start failure).
332func exitReason(err error) string {
333 var ee *exec.ExitError
334 if errors.As(err, &ee) && ee.ExitCode() >= 0 {
335 return fmt.Sprintf("exit %d", ee.ExitCode())
336 }
337 return err.Error()
338}
339
340// run clones, checks out, and executes the steps, streaming output to the
341// server. Returns nil when every step succeeded, else where the build
342// stopped.
343func (r *runner) run(j job) *failure {
344 dir := filepath.Join(r.workdir, fmt.Sprintf("build-%d", j.ID))
345 defer os.RemoveAll(dir)
346
347 home, doneHome, err := buildHome(r.workdir, j)
348 if err != nil {
349 log.Printf("build %d: build home: %v", j.ID, err)
350 return &failure{Reason: "preparing the build home failed"}
351 }
352 defer doneHome()
353
354 // One long-lived `runner log` session receives the whole stream.
355 logCmd := exec.Command(toolpath.Look("ssh"), append(r.sshOpts, r.remote, "runner", "log", fmt.Sprint(j.ID))...)
356 pipe, err := logCmd.StdinPipe()
357 if err != nil {
358 log.Printf("build %d: log pipe: %v", j.ID, err)
359 return &failure{Reason: "opening the log stream failed"}
360 }
361 sink := &logSink{w: pipe}
362 logCmd.Stdout, logCmd.Stderr = io.Discard, io.Discard
363 if err := logCmd.Start(); err != nil {
364 log.Printf("build %d: log stream: %v", j.ID, err)
365 return &failure{Reason: "opening the log stream failed"}
366 }
367 // The server ends the log session with exit 3 when the build is
368 // cancelled; any other end is a lost stream, which the sink absorbs.
369 cancelled := make(chan struct{})
370 logExited := make(chan struct{})
371 go func() {
372 defer close(logExited)
373 err := logCmd.Wait()
374 if ee, ok := err.(*exec.ExitError); ok && ee.ExitCode() == 3 {
375 close(cancelled)
376 return
377 }
378 if err != nil {
379 log.Printf("build %d: log session ended: %v", j.ID, err)
380 }
381 }()
382 // runStep starts cmd and waits for it, the cancel signal, or the
383 // deadline. Every phase goes through it, so a cancel during the clone
384 // lands as fast as one during a step.
385 runStep := func(cmd *exec.Cmd, deadline time.Time) (bool, string) {
386 select {
387 case <-cancelled:
388 return false, "cancelled"
389 default:
390 }
391 ownProcessGroup(cmd)
392 if err := cmd.Start(); err != nil {
393 return false, fmt.Sprintf("start: %v", err)
394 }
395 done := make(chan error, 1)
396 go func() { done <- cmd.Wait() }()
397 // After a kill, Wait returns once every holder of the log pipe is
398 // gone; the group kill makes that prompt, and the cap makes sure a
399 // straggler cannot hold the build open.
400 reap := func() {
401 killTree(cmd)
402 select {
403 case <-done:
404 case <-time.After(10 * time.Second):
405 }
406 }
407 select {
408 case err := <-done:
409 if err != nil {
410 return false, exitReason(err)
411 }
412 return true, ""
413 case <-cancelled:
414 reap()
415 return false, "cancelled"
416 case <-time.After(time.Until(deadline)):
417 reap()
418 return false, fmt.Sprintf("build timed out after %s", r.timeout)
419 }
420 }
421 defer func() {
422 select {
423 case <-cancelled:
424 log.Printf("build %d: cancelled", j.ID)
425 default:
426 if sink.broken() {
427 log.Printf("build %d: log stream lost; stored log is incomplete", j.ID)
428 }
429 }
430 pipe.Close()
431 <-logExited
432 }()
433
434 gitSSH := strings.TrimSpace("ssh " + strings.Join(r.sshOpts, " "))
435 cloneURL := r.cloneBase + "/" + j.Repo + ".git"
436 deadline := time.Now().Add(r.timeout)
437 fmt.Fprintf(sink, "$ git clone %s (%.10s)\n", cloneURL, j.SHA)
438 // A merge request head lives under refs/merge-requests/, which a
439 // clone does not fetch; ask for the ref before checking out.
440 steps := [][]string{{"clone", "-q", cloneURL, dir}}
441 if strings.HasPrefix(j.Ref, "refs/") {
442 steps = append(steps, []string{"-C", dir, "fetch", "-q", "origin", j.Ref})
443 }
444 steps = append(steps, []string{"-C", dir, "checkout", "-q", j.SHA})
445 for _, args := range steps {
446 cmd := exec.Command(toolpath.Look("git"), args...)
447 cmd.Env = append(os.Environ(), "GIT_SSH_COMMAND="+gitSSH, "GIT_TERMINAL_PROMPT=0")
448 cmd.Stdout, cmd.Stderr = sink, sink
449 if ok, why := runStep(cmd, deadline); !ok {
450 fmt.Fprintf(sink, "git %s: %s\n", args[0], why)
451 return &failure{Reason: "git " + args[0] + ": " + why}
452 }
453 }
454
455 env := stepEnv(j, home, r.buildSSH(j.SSH))
456 if !j.Results {
457 return r.runSteps(j, dir, env, sink, deadline, runStep)
458 }
459 // Cleared first: the checkout is the repository's, and a results
460 // directory committed to it would otherwise be uploaded as the scan's.
461 results := filepath.Join(dir, resultsDir)
462 if err := os.RemoveAll(results); err != nil {
463 fmt.Fprintf(sink, "preparing %s: %v\n", resultsDir, err)
464 return &failure{Reason: "preparing the results directory failed"}
465 }
466 inBuild := results
467 if r.isolation == isolationPodman {
468 inBuild = "/workspace/" + resultsDir
469 }
470 if f := r.runSteps(j, dir, append(env, "GITBAY_RESULTS="+inBuild), sink, deadline, runStep); f != nil {
471 return f
472 }
473 if err := r.uploadResults(j.ID, results); err != nil {
474 fmt.Fprintf(sink, "uploading results: %v\n", err)
475 return &failure{Reason: "uploading results failed"}
476 }
477 fmt.Fprintln(sink, "results uploaded")
478 return nil
479}
480
481// buildHome is a build's HOME and what to do with it when the build ends.
482//
483// Not the workspace, which is removed after every build: the Go module
484// cache and every other tool cache live under HOME. Not the runner's own
485// home either, where its SSH key and credential dotfiles are.
486//
487// A trusted build gets its repository's home,
488// <workdir>/trusted-home/<owner>/<name>, kept between builds so the
489// caches survive. One per repository: shared across repositories, a step
490// could poison a cache or plant a .gitconfig that another repository's
491// build would honour (#184). The root is not <workdir>/home, where homes
492// that untrusted builds could write were kept before #255, so none of
493// those is read again.
494//
495// An untrusted build gets <workdir>/build-<id>-home, new and empty,
496// removed when the build ends. The container mounts HOME read-write, so
497// a home a fork's build could write is a cache a stranger controls
498// (#255).
499func buildHome(workdir string, j job) (string, func(), error) {
500 if !j.Trusted {
501 dir := filepath.Join(workdir, fmt.Sprintf("build-%d-home", j.ID))
502 if err := os.Mkdir(dir, 0o700); err != nil {
503 return "", nil, err
504 }
505 return dir, func() {
506 if err := removeTree(dir); err != nil {
507 log.Printf("build %d: removing its home: %v", j.ID, err)
508 }
509 }, nil
510 }
511 root := filepath.Join(workdir, "trusted-home")
512 dir := filepath.Join(root, filepath.FromSlash(j.Repo))
513 if rel, err := filepath.Rel(root, dir); err != nil || rel == "." || strings.HasPrefix(rel, "..") {
514 return "", nil, fmt.Errorf("repository path %q escapes the build home root", j.Repo)
515 }
516 if err := os.MkdirAll(dir, 0o700); err != nil {
517 return "", nil, err
518 }
519 return dir, func() {}, nil
520}
521
522// removeTree deletes dir and everything under it. os.RemoveAll alone
523// fails on a directory without write permission, and the Go module cache
524// makes every directory it fills read-only.
525func removeTree(dir string) error {
526 filepath.WalkDir(dir, func(p string, d fs.DirEntry, err error) error {
527 if err == nil && d.IsDir() {
528 os.Chmod(p, 0o700)
529 }
530 return nil
531 })
532 return os.RemoveAll(dir)
533}
534
535// loopbackRemote reports whether the runner polls the daemon on its own
536// host over loopback.
537func (r *runner) loopbackRemote() bool {
538 _, host, ok := strings.Cut(r.remote, "@")
539 if !ok {
540 host = r.remote
541 }
542 return host == "127.0.0.1" || host == "localhost" || host == "::1"
543}
544
545// hostAddr is the address a podman build under pasta reaches the host
546// at: pasta's --map-guest-addr, which podman sets to this address and
547// which pasta translates to the host's public address.
548const hostAddr = "169.254.1.2"
549
550// buildSSH is the instance's ssh destination as a build reaches it.
551// Under pasta a podman build holds the host's own public address, so the
552// instance's public name resolves to the container itself. A runner
553// polling over loopback runs on the daemon's host, and its podman builds
554// get hostAddr with the user from -remote and the port from the claim's
555// destination when it is not 22. Any other runner's -remote is the path
556// that reaches the forge from where it runs, so its builds get that.
557func (r *runner) buildSSH(public string) string {
558 if r.isolation == isolationPodman && r.loopbackRemote() {
559 user, _, ok := strings.Cut(r.remote, "@")
560 if !ok || user == "" {
561 user = "git"
562 }
563 dest := hostAddr
564 _, hostport, ok := strings.Cut(public, "@")
565 if !ok {
566 hostport = public
567 }
568 if _, port, err := net.SplitHostPort(hostport); err == nil && port != "" && port != "22" {
569 dest = net.JoinHostPort(hostAddr, port)
570 }
571 return user + "@" + dest
572 }
573 return r.remote
574}
575
576// buildNetwork is the podman network option for a build on the daemon's
577// host. A build reaches the host at hostAddr, which pasta translates to
578// the host's public address, and cannot reach the host's loopback, so
579// none of its connections arrive from 127.0.0.1, the address the runner
580// polls from; the SSH auth limiter counts failures per source address
581// (#260). podman passes --no-map-gw to pasta by default; it is stated
582// here so the build's view of the host does not depend on that default.
583// The host's nftables tables (deploy/gitbay-runner-egress.nft and
584// gitbay-runner-builds.nft) limit what a build reaches on the host to
585// 22, 80 and 443, and an untrusted build to nothing but DNS.
586func (r *runner) buildNetwork() []string {
587 if !r.loopbackRemote() {
588 return nil
589 }
590 return []string{"--network", "pasta:--no-map-gw"}
591}
592
593// stepEnv builds the environment a build step runs with. It is
594// constructed, not inherited: os.Environ() would hand repository content
595// the runner's entire environment, including anything an operator set on
596// the service (#144).
597//
598// HOME is the build's home (buildHome), not the runner's own: tools read
599// credentials out of dotfiles — .netrc, .npmrc, .gitconfig — and a build
600// has no business finding the runner's.
601//
602// PATH is the one thing carried over: without it a step cannot find the
603// tools the host was provisioned with.
604func stepEnv(j job, home, sshDest string) []string {
605 path := os.Getenv("PATH")
606 if path == "" {
607 path = "/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin"
608 }
609 env := []string{
610 "PATH=" + path,
611 "HOME=" + home,
612 "LANG=C.UTF-8",
613 "CI=true",
614 "GITBAY_REPO=" + j.Repo,
615 "GITBAY_SHA=" + j.SHA,
616 "GITBAY_REF=" + j.Ref,
617 "GITBAY_JOB=" + j.Job,
618 "GITBAY_SSH=" + sshDest,
619 }
620 // The server sends secrets only for a trusted build. The claim's
621 // trust flag decides here as well, not whether any arrived (#255).
622 if j.Trusted {
623 for name, value := range j.Secrets {
624 env = append(env, name+"="+value)
625 }
626 }
627 return env
628}
629
630// ssh runs one control command against the server and returns stdout.// ssh runs one control command against the server and returns stdout.
631func (r *runner) ssh(stdin io.Reader, args ...string) (string, error) {
632 cmd := exec.Command(toolpath.Look("ssh"), append(append(r.sshOpts, r.remote), args...)...)
633 if stdin != nil {
634 cmd.Stdin = stdin
635 }
636 var out, errOut strings.Builder
637 cmd.Stdout, cmd.Stderr = &out, &errOut
638 if err := cmd.Run(); err != nil {
639 return out.String() + errOut.String(), err
640 }
641 return out.String(), nil
642}
643
644func fileExists(p string) bool { _, err := os.Stat(p); return err == nil }
645
646// defaultWorkdir picks a build workspace that another local user cannot
647// have created first.
648//
649// The default used to be <tmp>/gitbay-runner: a fixed name inside a
650// world-writable directory, created with MkdirAll, which succeeds against
651// an existing directory whoever owns it. On a shared host another user
652// could have made it — or symlinked it — before the runner started, and
653// this is the process that clones repositories and exports build secrets
654// into step environments (go:S5445, #153).
655//
656// The user's cache directory is not world-writable and is per-user by
657// construction. Falling back to tmp keeps a runner working where HOME is
658// unset, and checkWorkdir refuses the unsafe cases there.
659func defaultWorkdir() string {
660 if cache, err := os.UserCacheDir(); err == nil && cache != "" {
661 return filepath.Join(cache, "gitbay-runner")
662 }
663 return filepath.Join(os.TempDir(), "gitbay-runner")
664}
665
666// checkWorkdir makes sure the workspace is a directory this user owns
667// privately. MkdirAll is happy with one that already exists, so being
668// able to create it proves nothing about who made it.
669//
670// A directory we own that is merely too permissive is tightened rather
671// than refused: every runner before this one created its workspace 0755,
672// so refusing would take the runner down on upgrade to fix a permission
673// we are entitled to change. What cannot be repaired — a symlink, or
674// something owned by someone else — is refused, because those are what an
675// attacker leaves behind and neither is ours to correct.
676func checkWorkdir(dir string) error {
677 fi, err := os.Lstat(dir)
678 if err != nil {
679 return err
680 }
681 if fi.Mode()&os.ModeSymlink != 0 {
682 return fmt.Errorf("workdir %s is a symlink; point -workdir at a real directory", dir)
683 }
684 if !fi.IsDir() {
685 return fmt.Errorf("workdir %s is not a directory", dir)
686 }
687 if st, ok := fi.Sys().(*syscall.Stat_t); ok && int(st.Uid) != os.Getuid() {
688 return fmt.Errorf("workdir %s is owned by uid %d, not this process's %d", dir, st.Uid, os.Getuid())
689 }
690 if perm := fi.Mode().Perm(); perm&0o077 != 0 {
691 log.Printf("workdir %s was mode %04o; tightening to 0700 (builds and their secrets are this user's alone)", dir, perm)
692 if err := os.Chmod(dir, 0o700); err != nil {
693 return fmt.Errorf("tightening workdir %s: %w", dir, err)
694 }
695 }
696 return nil
697}