gunk-dev/the-valley

main_test.go

source0a8b441c9e0dmain'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 "/app/knots/oc-a000002": http.StatusOK,
102 "/app/source/tree/" + tip + "/": http.StatusOK,
103 "/app/source/blob/" + tip + "/docs/guide.md": http.StatusOK,
104 "/app/source/log/" + tip: http.StatusOK,
105 "/site/source/": http.StatusNotFound,
106 }
107}
108
109// get checks that each target answers its status, with the policy.
110func get(t *testing.T, addr string, targets map[string]int) {
111 t.Helper()
112 for target, status := range targets {
113 res, err := http.Get("http://" + addr + target)
114 if err != nil {
115 t.Fatal(err)
116 }
117 body, _ := io.ReadAll(res.Body)
118 res.Body.Close()
119 if res.StatusCode != status {
120 t.Errorf("GET %s answered %d, not %d:\n%s", target, res.StatusCode, status, body)
121 }
122 if !strings.HasPrefix(res.Header.Get("Content-Security-Policy"), "default-src 'self';") {
123 t.Errorf("GET %s answered with no policy", target)
124 }
125 }
126}
127
128// valley-web serves a state directory the fixture's export was uploaded
129// to, on the address it prints, and stops cleanly on SIGTERM.
130func TestServesTheStateDirectory(t *testing.T) {
131 f, state := uploaded(t)
132 cmd := valleyWeb("--state", state, "--listen", "127.0.0.1:0")
133 get(t, start(t, cmd), routes(f))
134
135 if err := cmd.Process.Signal(syscall.SIGTERM); err != nil {
136 t.Fatal(err)
137 }
138 stopped := make(chan error, 1)
139 go func() { stopped <- cmd.Wait() }()
140 select {
141 case err := <-stopped:
142 if err != nil {
143 t.Errorf("valley-web stopped with %v", err)
144 }
145 case <-time.After(30 * time.Second):
146 t.Fatal("valley-web did not stop within 30 seconds of SIGTERM")
147 }
148}
149
150// valley-web serves every page from a state directory it can only read,
151// as a user other than the receiver's: no file or directory in it is
152// writable, and git holds its repositories to be another user's. The
153// receiver wrote it under umask 0077, so what it reads is readable by
154// others because the receiver made it so. The deployment gives the server
155// the state directory itself, here mode 0755. The test cannot become
156// another user, so it makes the directory read as one does: each entry's
157// owner and group bits are set to its bits for others, less write. git is
158// told the repositories are another user's with
159// GIT_TEST_ASSUME_DIFFERENT_OWNER, as git's own tests tell it, through a
160// git that sets it and runs the real one, since valley-web passes git none
161// of its own GIT_ variables.
162func TestServesAReadOnlyStateDirectory(t *testing.T) {
163 umask := syscall.Umask(0o077)
164 f, state := uploaded(t)
165 syscall.Umask(umask)
166 if err := os.Chmod(filepath.Dir(state), 0o755); err != nil {
167 t.Fatal(err)
168 }
169 asOthers(t, filepath.Dir(state))
170 real, err := exec.LookPath(export.GitProgram)
171 if err != nil {
172 t.Fatal(err)
173 }
174 if real, err = filepath.Abs(real); err != nil {
175 t.Fatal(err)
176 }
177 wrapper := filepath.Join(t.TempDir(), "git")
178 script := "#!/bin/sh\nGIT_TEST_ASSUME_DIFFERENT_OWNER=1 exec '" + real + "' \"$@\"\n"
179 if err := os.WriteFile(wrapper, []byte(script), 0o755); err != nil {
180 t.Fatal(err)
181 }
182
183 cmd := valleyWeb("--state", state, "--listen", "127.0.0.1:0")
184 cmd.Env = append(cmd.Env, "VALLEY_WEB_TEST_GIT="+wrapper)
185 get(t, start(t, cmd), routes(f))
186
187 out, err := output(t, valleyWeb("--state", filepath.Join(filepath.Dir(state), "missing"), "--listen", "127.0.0.1:0"))
188 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
189 t.Errorf("valley-web on a store that does not exist gave %v:\n%s", err, out)
190 }
191 // The directory the store is in is what the first layout took as its
192 // state. valley-web refuses it, rather than serve anything from it.
193 out, err = output(t, valleyWeb("--state", filepath.Dir(state), "--listen", "127.0.0.1:0"))
194 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 || !strings.Contains(string(out), "is a directory") {
195 t.Errorf("valley-web on a directory gave %v:\n%s", err, out)
196 }
197}
198
199// asOthers makes every file and directory under root, root too, read by
200// its owner as a user who is neither its owner nor in its group reads it,
201// and writable by none. The test's cleanup makes it writable again, so it
202// can be removed.
203func asOthers(t *testing.T, root string) {
204 t.Helper()
205 var paths []string
206 err := filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
207 if err == nil && d.Type()&fs.ModeSymlink == 0 {
208 paths = append(paths, path)
209 }
210 return err
211 })
212 if err != nil {
213 t.Fatal(err)
214 }
215 t.Cleanup(func() {
216 filepath.WalkDir(root, func(path string, d fs.DirEntry, err error) error {
217 if err == nil && d.IsDir() {
218 os.Chmod(path, 0o755)
219 }
220 return nil
221 })
222 })
223 // Children first, so each directory can still be read while its
224 // entries change.
225 for i := len(paths) - 1; i >= 0; i-- {
226 info, err := os.Lstat(paths[i])
227 if err != nil {
228 t.Fatal(err)
229 }
230 others := info.Mode().Perm() & 0o005
231 if err := os.Chmod(paths[i], others<<6|others<<3|others); err != nil {
232 t.Fatal(err)
233 }
234 }
235 if f, err := os.Create(filepath.Join(root, "probe")); err == nil {
236 f.Close()
237 t.Skip("the test runs as a user every file is writable by, such as root")
238 }
239}
240
241// A command line it cannot run with gets the usage and exit status 2;
242// --help gets the usage alone.
243func TestUsage(t *testing.T) {
244 state := t.TempDir()
245 for _, args := range [][]string{
246 {},
247 {"--state", state},
248 {"--listen", "127.0.0.1:0"},
249 {"--state", state, "--listen", "127.0.0.1:0", "extra"},
250 {"--no-such-flag"},
251 } {
252 out, err := output(t, valleyWeb(args...))
253 exit, ok := err.(*exec.ExitError)
254 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web --state FILE --listen ADDR") {
255 t.Errorf("valley-web %q gave %v:\n%s", args, err, out)
256 }
257 }
258 out, err := output(t, valleyWeb("--help"))
259 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web") {
260 t.Errorf("valley-web --help gave %v:\n%s", err, out)
261 }
262}