gunk-dev/the-valley

main_test.go

source199a804cf927main's published tip history
8.2 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "io"
7 "io/fs"
8 "net/http"
9 "os"
10 "os/exec"
11 "path/filepath"
12 "strings"
13 "syscall"
14 "testing"
15 "time"
16
17 "the-valley/web/export"
18 "the-valley/web/export/exporttest"
19)
20
21// The test binary is valley-web when VALLEY_WEB_TEST_MAIN is set, so the
22// tests run the real program as a process of its own. It runs the git
23// VALLEY_WEB_TEST_GIT names, when that is set.
24func TestMain(m *testing.M) {
25 if os.Getenv("VALLEY_WEB_TEST_MAIN") == "1" {
26 if git := os.Getenv("VALLEY_WEB_TEST_GIT"); git != "" {
27 export.GitProgram = git
28 }
29 main()
30 os.Exit(0)
31 }
32 os.Exit(m.Run())
33}
34
35func valleyWeb(args ...string) *exec.Cmd {
36 cmd := exec.Command(os.Args[0], args...)
37 cmd.Env = append(os.Environ(), "VALLEY_WEB_TEST_MAIN=1")
38 return cmd
39}
40
41// uploaded is the descriptor of a store the fixture's export was uploaded
42// to, as a receiver uploads it.
43func uploaded(t *testing.T) (*exporttest.Fixture, string) {
44 t.Helper()
45 f := exporttest.New(t)
46 state := exporttest.StorePath(t)
47 store, err := export.OpenStore(state, nil)
48 if err != nil {
49 t.Fatal(err)
50 }
51 f.Upload(t, store)
52 return f, state
53}
54
55// output runs cmd, and returns what it wrote to stdout and stderr
56// together. A cmd that has not exited within 30 seconds fails the test.
57func output(t *testing.T, cmd *exec.Cmd) ([]byte, error) {
58 t.Helper()
59 var out bytes.Buffer
60 cmd.Stdout, cmd.Stderr = &out, &out
61 err := exporttest.Run(t, cmd, 30*time.Second)
62 return out.Bytes(), err
63}
64
65// start runs cmd with exporttest.Start, so no process of it outlives the
66// test, and waits for it to say where it listens.
67func start(t *testing.T, cmd *exec.Cmd) (addr string) {
68 t.Helper()
69 stderr, err := cmd.StderrPipe()
70 if err != nil {
71 t.Fatal(err)
72 }
73 if _, err := exporttest.Start(t, cmd); err != nil {
74 t.Fatal(err)
75 }
76 t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
77 lines := make(chan string, 1)
78 go func() {
79 r := bufio.NewReader(stderr)
80 line, _ := r.ReadString('\n')
81 lines <- line
82 io.Copy(io.Discard, r)
83 }()
84 select {
85 case line := <-lines:
86 var ok bool
87 if addr, ok = strings.CutPrefix(strings.TrimSpace(line), "valley-web: listening on "); !ok {
88 t.Fatalf("valley-web printed %q", line)
89 }
90 case <-time.After(30 * time.Second):
91 t.Fatal("valley-web did not say where it listens")
92 }
93 return addr
94}
95
96// routes are a GET of each target, and the status it answers.
97func routes(f *exporttest.Fixture) map[string]int {
98 tip := f.Export.Projects[0].SourceTip
99 return map[string]int{
100 "/": http.StatusOK,
101 "/-/knots": http.StatusOK,
102 "/app/knots/oc-a000002": http.StatusOK,
103 "/app/source/tree/" + tip + "/": http.StatusOK,
104 "/app/source/blob/" + tip + "/docs/guide.md": http.StatusOK,
105 "/app/source/log/" + tip: http.StatusOK,
106 "/site/source/": http.StatusNotFound,
107 }
108}
109
110// get checks that each target answers its status, with the policy.
111func get(t *testing.T, addr string, targets map[string]int) {
112 t.Helper()
113 for target, status := range targets {
114 res, err := http.Get("http://" + addr + target)
115 if err != nil {
116 t.Fatal(err)
117 }
118 body, _ := io.ReadAll(res.Body)
119 res.Body.Close()
120 if res.StatusCode != status {
121 t.Errorf("GET %s answered %d, not %d:\n%s", target, res.StatusCode, status, body)
122 }
123 if !strings.HasPrefix(res.Header.Get("Content-Security-Policy"), "default-src 'self';") {
124 t.Errorf("GET %s answered with no policy", target)
125 }
126 }
127}
128
129// valley-web serves a state directory the fixture's export was uploaded
130// to, on the address it prints, and stops cleanly on SIGTERM.
131func TestServesTheStateDirectory(t *testing.T) {
132 f, state := uploaded(t)
133 cmd := valleyWeb("--state", state, "--listen", "127.0.0.1:0")
134 get(t, start(t, cmd), routes(f))
135
136 if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
137 t.Fatal(err)
138 }
139 stopped := make(chan error, 1)
140 go func() { stopped <- cmd.Wait() }()
141 select {
142 case err := <-stopped:
143 if err != nil {
144 t.Errorf("valley-web stopped with %v", err)
145 }
146 case <-time.After(30 * time.Second):
147 t.Fatal("valley-web did not stop within 30 seconds of SIGTERM")
148 }
149}
150
151// valley-web serves every page from a state directory it can only read,
152// as a user other than the receiver's: no file or directory in it is
153// writable, and git holds its repositories to be another user's. The
154// receiver wrote it under umask 0077, so what it reads is readable by
155// others because the receiver made it so. The deployment gives the server
156// the state directory itself, here mode 0755. The test cannot become
157// another user, so it makes the directory read as one does: each entry's
158// owner and group bits are set to its bits for others, less write. git is
159// told the repositories are another user's with
160// GIT_TEST_ASSUME_DIFFERENT_OWNER, as git's own tests tell it, through a
161// git that sets it and runs the real one, since valley-web passes git none
162// of its own GIT_ variables.
163func TestServesAReadOnlyStateDirectory(t *testing.T) {
164 umask := syscall.Umask(0o077)
165 f, state := uploaded(t)
166 syscall.Umask(umask)
167 if err := os.Chmod(filepath.Dir(state), 0o755); err != nil {
168 t.Fatal(err)
169 }
170 asOthers(t, filepath.Dir(state))
171 real, err := exec.LookPath(export.GitProgram)
172 if err != nil {
173 t.Fatal(err)
174 }
175 if real, err = filepath.Abs(real); err != nil {
176 t.Fatal(err)
177 }
178 wrapper := filepath.Join(t.TempDir(), "git")
179 script := "#!/bin/sh\nGIT_TEST_ASSUME_DIFFERENT_OWNER=1 exec '" + real + "' \"$@\"\n"
180 if err := os.WriteFile(wrapper, []byte(script), 0o755); err != nil {
181 t.Fatal(err)
182 }
183
184 cmd := valleyWeb("--state", state, "--listen", "127.0.0.1:0")
185 cmd.Env = append(cmd.Env, "VALLEY_WEB_TEST_GIT="+wrapper)
186 get(t, start(t, cmd), routes(f))
187
188 out, err := output(t, valleyWeb("--state", filepath.Join(filepath.Dir(state), "missing"), "--listen", "127.0.0.1:0"))
189 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
190 t.Errorf("valley-web on a store that does not exist gave %v:\n%s", err, out)
191 }
192 // The directory the store is in is what the first layout took as its
193 // state. valley-web refuses it, rather than serve anything from it.
194 out, err = output(t, valleyWeb("--state", filepath.Dir(state), "--listen", "127.0.0.1:0"))
195 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || !strings.Contains(string(out), "is a directory") {
196 t.Errorf("valley-web on a directory gave %v:\n%s", err, out)
197 }
198}
199
200// asOthers makes every file and directory under root, root too, read by
201// its owner as a user who is neither its owner nor in its group reads it,
202// and writable by none. The test's cleanup makes it writable again, so it
203// can be removed.
204func asOthers(t *testing.T, root string) {
205 t.Helper()
206 var paths []string
207 err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
208 if err == nil && d.Type()&fs.ModeSymlink == 0 {
209 paths = append(paths, path)
210 }
211 return err
212 })
213 if err != nil {
214 t.Fatal(err)
215 }
216 t.Cleanup(func() {
217 filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
218 if err == nil && d.IsDir() {
219 os.Chmod(path, 0o755)
220 }
221 return nil
222 })
223 })
224 // Children first, so each directory can still be read while its
225 // entries change.
226 for i := len(paths) - 1; i >= 0; i-- {
227 info, err := os.Lstat(paths[i])
228 if err != nil {
229 t.Fatal(err)
230 }
231 others := info.Mode().Perm() & 0o005
232 if err := os.Chmod(paths[i], others<<6|others<<3|others); err != nil {
233 t.Fatal(err)
234 }
235 }
236 if f, err := os.Create(filepath.Join(root, "probe")); err == nil {
237 f.Close()
238 t.Skip("the test runs as a user every file is writable by, such as root")
239 }
240}
241
242// A command line it cannot run with gets the usage and exit status 2;
243// --help gets the usage alone.
244func TestUsage(t *testing.T) {
245 state := t.TempDir()
246 for _, args := range [][]string{
247 {},
248 {"--state", state},
249 {"--listen", "127.0.0.1:0"},
250 {"--state", state, "--listen", "127.0.0.1:0", "extra"},
251 {"--no-such-flag"},
252 } {
253 out, err := output(t, valleyWeb(args...))
254 exit, ok := err.(*exec.ExitError)
255 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web --state FILE --listen ADDR") {
256 t.Errorf("valley-web %q gave %v:\n%s", args, err, out)
257 }
258 }
259 out, err := output(t, valleyWeb("--help"))
260 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web") {
261 t.Errorf("valley-web --help gave %v:\n%s", err, out)
262 }
263}