cmd/gitbay-runner/env_test.go
76 lines · 2213 bytes
1package main
2
3import (
4 "os"
5 "strings"
6 "testing"
7)
8
9// A step's environment is constructed, not inherited: repository content
10// must not see what the operator set on the runner service (#144).
11func TestStepEnvDoesNotInherit(t *testing.T) {
12 t.Setenv("GITBAY_RUNNER_TOKEN", "a-secret-the-service-was-given")
13 t.Setenv("AWS_SECRET_ACCESS_KEY", "also-not-for-builds")
14
15 env := stepEnv(job{Repo: "alice/app", SHA: "abc", Ref: "main", Job: "test"}, "/tmp/ws")
16
17 for _, e := range env {
18 if strings.HasPrefix(e, "GITBAY_RUNNER_TOKEN=") || strings.HasPrefix(e, "AWS_SECRET_ACCESS_KEY=") {
19 t.Errorf("the runner's own environment reached a build step: %q", e)
20 }
21 }
22 want := map[string]string{
23 "CI": "true", "GITBAY_REPO": "alice/app", "GITBAY_SHA": "abc",
24 "GITBAY_REF": "main", "GITBAY_JOB": "test",
25 // HOME is the workspace so a build cannot read the runner's
26 // dotfiles, where tools keep credentials.
27 "HOME": "/tmp/ws",
28 }
29 got := map[string]string{}
30 for _, e := range env {
31 k, v, _ := strings.Cut(e, "=")
32 got[k] = v
33 }
34 for k, v := range want {
35 if got[k] != v {
36 t.Errorf("%s = %q, want %q", k, got[k], v)
37 }
38 }
39 if got["PATH"] == "" {
40 t.Error("PATH is empty; a step could not find any tool")
41 }
42}
43
44// Secrets are passed through when the server sent them, which it does
45// only for a trusted build.
46func TestStepEnvCarriesSecrets(t *testing.T) {
47 env := stepEnv(job{Secrets: map[string]string{"TOKEN": "s3cret"}}, "/tmp/ws")
48 if !containsEnv(env, "TOKEN=s3cret") {
49 t.Error("a trusted build's secret did not reach the step")
50 }
51 env = stepEnv(job{}, "/tmp/ws")
52 for _, e := range env {
53 if strings.HasPrefix(e, "TOKEN=") {
54 t.Errorf("a secret appeared with none sent: %q", e)
55 }
56 }
57}
58
59// PATH falls back rather than leaving a step unable to find anything.
60func TestStepEnvPathFallback(t *testing.T) {
61 old := os.Getenv("PATH")
62 os.Unsetenv("PATH")
63 defer os.Setenv("PATH", old)
64 if env := stepEnv(job{}, "/tmp/ws"); !containsEnv(env, "PATH=/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin") {
65 t.Errorf("no PATH fallback: %v", env)
66 }
67}
68
69func containsEnv(env []string, want string) bool {
70 for _, e := range env {
71 if e == want {
72 return true
73 }
74 }
75 return false
76}