gunk-dev/the-valley

main_test.go

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