gunk-dev/the-valley

main_test.go

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