gunk-dev/the-valley

main_test.go

sourcea54b7fd5249bmain's published tip history
23.1 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "crypto/ed25519"
7 "encoding/json"
8 "fmt"
9 "io"
10 "net"
11 "net/http"
12 "os"
13 "os/exec"
14 "path/filepath"
15 "strconv"
16 "strings"
17 "syscall"
18 "testing"
19 "time"
20
21 "the-valley/web/export"
22 "the-valley/web/export/exporttest"
23)
24
25// The tests run the receiver as a process of its own: the test binary is
26// valley-web-receive when VALLEY_WEB_RECEIVE_TEST_MAIN is set. Uploads are
27// the shared fixture's export, under manifests signed now with the
28// fixture's key, and they are accepted with real git. valley-web is the
29// real program, which VALLEY_WEB names.
30func TestMain(m *testing.M) {
31 if os.Getenv("VALLEY_WEB_RECEIVE_TEST_MAIN") == "1" {
32 main()
33 os.Exit(0)
34 }
35 os.Exit(m.Run())
36}
37
38const token = "receiver-test-token-0123456789abcdef"
39
40// edge is a receiver running over a state directory, and the fixture it
41// is sent.
42type edge struct {
43 t *testing.T
44 f *exporttest.Fixture
45 state string
46 addr string
47 cmd *exec.Cmd
48}
49
50// files writes the token file and the verifier file a receiver is given.
51func files(t *testing.T) (tokenFile, verifiers string) {
52 t.Helper()
53 dir := t.TempDir()
54 tokenFile, verifiers = filepath.Join(dir, "token"), filepath.Join(dir, "verifiers")
55 if err := os.WriteFile(tokenFile, []byte(token+"\n"), 0o600); err != nil {
56 t.Fatal(err)
57 }
58 if err := os.WriteFile(verifiers, []byte(exporttest.Verifier().String()+"\n"), 0o644); err != nil {
59 t.Fatal(err)
60 }
61 return tokenFile, verifiers
62}
63
64func receiveCmd(args ...string) *exec.Cmd {
65 cmd := exec.Command(os.Args[0], args...)
66 cmd.Env = append(os.Environ(), "VALLEY_WEB_RECEIVE_TEST_MAIN=1")
67 return cmd
68}
69
70// newEdge starts a receiver over a new state directory, with the flags
71// given after the ones every receiver here needs.
72func newEdge(t *testing.T, f *exporttest.Fixture, more ...string) *edge {
73 t.Helper()
74 tokenFile, verifiers := files(t)
75 state := filepath.Join(t.TempDir(), "state")
76 cmd := receiveCmd(append([]string{"--state", state, "--listen", "127.0.0.1:0",
77 "--instance", exporttest.Instance, "--destination", exporttest.Destination,
78 "--verifiers", verifiers, "--token-file", tokenFile}, more...)...)
79 return &edge{t: t, f: f, state: state, cmd: cmd, addr: start(t, cmd, "valley-web-receive")}
80}
81
82// start runs cmd and waits for it to say where it listens.
83func start(t *testing.T, cmd *exec.Cmd, name string) string {
84 t.Helper()
85 stderr, err := cmd.StderrPipe()
86 if err != nil {
87 t.Fatal(err)
88 }
89 if err := cmd.Start(); err != nil {
90 t.Fatal(err)
91 }
92 t.Cleanup(func() { cmd.Process.Kill(); cmd.Wait() })
93 lines := make(chan string, 1)
94 go func() {
95 r := bufio.NewReader(stderr)
96 line, _ := r.ReadString('\n')
97 lines <- line
98 io.Copy(io.Discard, r)
99 }()
100 select {
101 case line := <-lines:
102 addr, ok := strings.CutPrefix(strings.TrimSpace(line), name+": listening on ")
103 if !ok {
104 t.Fatalf("%s printed %q", name, line)
105 }
106 return addr
107 case <-time.After(30 * time.Second):
108 t.Fatalf("%s did not say where it listens", name)
109 }
110 return ""
111}
112
113// manifest is the fixture's export under a manifest with sequence, signed
114// with key, and the manifest itself.
115func (e *edge) manifest(sequence int64, key ed25519.PrivateKey, destination string) ([]byte, *export.Manifest) {
116 e.t.Helper()
117 bundles := map[string]export.Body{}
118 for _, p := range e.f.Manifest.Projects {
119 bundles[p.Name] = p.Bundle
120 }
121 m, err := export.NewManifest(exporttest.Instance, destination, sequence, e.f.Export, e.f.ExportJSON, bundles)
122 if err != nil {
123 e.t.Fatal(err)
124 }
125 signed, err := m.Sign(exporttest.SignerName, key)
126 if err != nil {
127 e.t.Fatal(err)
128 }
129 return signed, m
130}
131
132// signedNow is the fixture's export under a manifest signed now.
133func (e *edge) signedNow() ([]byte, *export.Manifest) {
134 return e.manifest(time.Now().UnixNano(), exporttest.Key(), exporttest.Destination)
135}
136
137// request makes one request with the token, and returns the status and the
138// reply.
139func (e *edge) request(method, path string, body []byte, header http.Header) (int, []byte, http.Header) {
140 e.t.Helper()
141 req, err := http.NewRequest(method, "http://"+e.addr+path, bytes.NewReader(body))
142 if err != nil {
143 e.t.Fatal(err)
144 }
145 req.Header.Set("Authorization", export.Authorization(token))
146 for k, v := range header {
147 req.Header[k] = v
148 }
149 res, err := http.DefaultClient.Do(req)
150 if err != nil {
151 e.t.Fatal(err)
152 }
153 defer res.Body.Close()
154 reply, err := io.ReadAll(res.Body)
155 if err != nil {
156 e.t.Fatal(err)
157 }
158 return res.StatusCode, reply, res.Header
159}
160
161// refused checks that a reply is the refusal with code, and returns it.
162func refused(t *testing.T, what string, status int, reply []byte, code export.Code) export.ErrorReply {
163 t.Helper()
164 var r export.ErrorReply
165 if err := json.Unmarshal(reply, &r); err != nil || r.Schema != export.ErrorSchema || r.Code != code || status != code.Status() {
166 t.Errorf("%s: the receiver replied %d %s, want %d and %s", what, status, reply, code.Status(), code)
167 }
168 return r
169}
170
171// post posts the signed manifest, and returns its inventory.
172func (e *edge) post(signed []byte) export.Inventory {
173 e.t.Helper()
174 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
175 var inv export.Inventory
176 if err := json.Unmarshal(reply, &inv); status != http.StatusOK || err != nil || inv.Schema != export.InventorySchema {
177 e.t.Fatalf("the manifest was answered %d %s", status, reply)
178 }
179 return inv
180}
181
182// put sends one body the manifest declares, and fails the test unless it
183// is accepted.
184func (e *edge) put(m *export.Manifest, name string) {
185 e.t.Helper()
186 b := body(e.t, m, name)
187 status, reply, _ := e.request(http.MethodPut, export.BodyPath(m.Sequence, b.SHA256), e.f.BodyBytes(e.t, name), nil)
188 if status != http.StatusNoContent {
189 e.t.Fatalf("body %s was answered %d %s", name, status, reply)
190 }
191}
192
193func body(t *testing.T, m *export.Manifest, name string) export.Body {
194 t.Helper()
195 for _, b := range m.Bodies() {
196 if b.Name == name {
197 return b
198 }
199 }
200 t.Fatalf("the manifest declares no body %s", name)
201 return export.Body{}
202}
203
204// commit commits the upload, and fails the test unless it is activated.
205func (e *edge) commit(m *export.Manifest) {
206 e.t.Helper()
207 status, reply, _ := e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
208 var c export.Committed
209 if err := json.Unmarshal(reply, &c); status != http.StatusOK || err != nil || c.Sequence != m.Sequence {
210 e.t.Fatalf("the commit was answered %d %s", status, reply)
211 }
212}
213
214// upload runs the three steps for a manifest signed now, and returns it.
215func (e *edge) upload() *export.Manifest {
216 e.t.Helper()
217 signed, m := e.signedNow()
218 for _, n := range e.post(signed).Needs {
219 e.put(m, n.Name)
220 }
221 e.commit(m)
222 return m
223}
224
225// highWater is the state directory's high-water mark, 0 for none.
226func (e *edge) highWater() int64 {
227 e.t.Helper()
228 data, err := os.ReadFile(filepath.Join(e.state, "high-water"))
229 if os.IsNotExist(err) {
230 return 0
231 }
232 n, perr := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
233 if err != nil || perr != nil {
234 e.t.Fatalf("high-water: %v %v", err, perr)
235 }
236 return n
237}
238
239// staged are the entries of the state directory's staging area.
240func (e *edge) staged() []string {
241 e.t.Helper()
242 entries, err := os.ReadDir(filepath.Join(e.state, "staging"))
243 if err != nil {
244 e.t.Fatal(err)
245 }
246 var names []string
247 for _, d := range entries {
248 names = append(names, d.Name())
249 }
250 return names
251}
252
253// valleyWeb starts the real valley-web over the edge's state directory,
254// and returns where it listens.
255func (e *edge) valleyWeb() string {
256 e.t.Helper()
257 bin := os.Getenv("VALLEY_WEB")
258 if bin == "" {
259 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
260 e.t.Fatal("VALLEY_WEB names no valley-web, and VALLEY_TEST_TOOLS=required")
261 }
262 e.t.Skip("VALLEY_WEB names no valley-web; the nix check provides one")
263 }
264 return start(e.t, exec.Command(bin, "--state", e.state, "--listen", "127.0.0.1:0"), "valley-web")
265}
266
267// serves checks that valley-web at addr answers every page of the
268// fixture's export.
269func (e *edge) serves(addr string) {
270 e.t.Helper()
271 tip := e.f.Export.Projects[0].SourceTip
272 for target, status := range map[string]int{
273 "/": http.StatusOK,
274 "/app/knots/oc-a000002": http.StatusOK,
275 "/app/source/tree/" + tip + "/": http.StatusOK,
276 "/app/source/log/" + tip: http.StatusOK,
277 "/site/source/": http.StatusNotFound,
278 } {
279 res, err := http.Get("http://" + addr + target)
280 if err != nil {
281 e.t.Fatal(err)
282 }
283 page, _ := io.ReadAll(res.Body)
284 res.Body.Close()
285 if res.StatusCode != status {
286 e.t.Errorf("valley-web answered GET %s with %d, want %d:\n%s", target, res.StatusCode, status, page)
287 }
288 }
289}
290
291// An upload of the three steps activates the export, and valley-web, as a
292// process of its own over the same state directory, serves it. The
293// manifest posted again, and the commit made again, are refused as
294// replayed, with the high-water mark.
295func TestAnUploadActivatesAndValleyWebServesIt(t *testing.T) {
296 e := newEdge(t, exporttest.New(t))
297 signed, m := e.signedNow()
298 inv := e.post(signed)
299 if inv.Active != nil || len(inv.Needs) != 2 || inv.Needs[0].Name != export.ExportFile || inv.Needs[1].Name != "app" {
300 t.Fatalf("the first inventory is %+v, want no active export and both bodies needed, export.json first", inv)
301 }
302 again := e.post(signed)
303 if len(again.Needs) != 2 {
304 t.Errorf("the manifest posted again needs %+v, want both bodies still", again.Needs)
305 }
306 e.put(m, export.ExportFile)
307 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != "app" {
308 t.Errorf("the manifest posted after export.json needs %+v, want app's bundle alone", needs)
309 }
310 e.put(m, "app")
311 e.put(m, "app") // a body already staged is accepted again
312 e.commit(m)
313 if hw := e.highWater(); hw != m.Sequence {
314 t.Errorf("high-water is %d after the commit, want %d", hw, m.Sequence)
315 }
316 e.serves(e.valleyWeb())
317
318 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
319 if r := refused(t, "the manifest posted after its commit", status, reply, export.CodeReplayed); r.HighWater != m.Sequence {
320 t.Errorf("the replayed refusal gives high-water %d, want %d", r.HighWater, m.Sequence)
321 }
322 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
323 refused(t, "the commit made again", status, reply, export.CodeReplayed)
324
325 // The next upload carries app's repository over, and needs export.json
326 // alone.
327 signed, m = e.signedNow()
328 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != export.ExportFile {
329 t.Errorf("the next upload needs %+v, want export.json alone", needs)
330 }
331 e.put(m, export.ExportFile)
332 e.commit(m)
333}
334
335// A request without the token is refused as unauthenticated, whatever it
336// asks, and stages nothing. So is one with another token, or with the
337// token twice.
338func TestAnUnauthenticatedRequestIsRefused(t *testing.T) {
339 e := newEdge(t, exporttest.New(t))
340 signed, m := e.signedNow()
341 send := func(what, method, path string, body []byte, auth []string) {
342 t.Helper()
343 req, err := http.NewRequest(method, "http://"+e.addr+path, bytes.NewReader(body))
344 if err != nil {
345 t.Fatal(err)
346 }
347 req.Header["Authorization"] = auth
348 res, err := http.DefaultClient.Do(req)
349 if err != nil {
350 t.Fatal(err)
351 }
352 reply, _ := io.ReadAll(res.Body)
353 res.Body.Close()
354 refused(t, what, res.StatusCode, reply, export.CodeUnauthenticated)
355 if !strings.HasPrefix(res.Header.Get("WWW-Authenticate"), "Bearer ") {
356 t.Errorf("%s: the refusal names no scheme to authenticate with", what)
357 }
358 }
359 send("a manifest with no token", http.MethodPost, export.ManifestPath, signed, nil)
360 send("a manifest with another token", http.MethodPost, export.ManifestPath, signed, []string{export.Authorization(token + "x")})
361 send("a manifest with the token in another scheme", http.MethodPost, export.ManifestPath, signed, []string{"Basic " + token})
362 send("a manifest with the token twice", http.MethodPost, export.ManifestPath, signed,
363 []string{export.Authorization(token), export.Authorization(token)})
364 send("a body with no token", http.MethodPut, export.BodyPath(m.Sequence, m.File.SHA256), e.f.ExportJSON, nil)
365 send("a commit with no token", http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
366 send("a path the upload does not use", http.MethodGet, "/", nil, nil)
367 if staged := e.staged(); len(staged) != 0 || e.highWater() != 0 {
368 t.Errorf("unauthenticated requests left %v staged and high-water %d", staged, e.highWater())
369 }
370}
371
372// A manifest is refused when it is stale, signed ahead of the receiver's
373// clock, signed by another key, or for another receiver; and an older
374// manifest than the one staged is superseded. None of them is staged.
375func TestAManifestIsAdmittedOnlyWhenFresh(t *testing.T) {
376 e := newEdge(t, exporttest.New(t))
377 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
378 now := time.Now()
379 for _, c := range []struct {
380 what string
381 at time.Time
382 key ed25519.PrivateKey
383 destination string
384 code export.Code
385 }{
386 {"a manifest signed four days ago", now.Add(-96 * time.Hour), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
387 {"a manifest signed two minutes ahead", now.Add(2 * time.Minute), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
388 {"a manifest signed by another key", now, other, exporttest.Destination, export.CodeBadSignature},
389 {"a manifest for another receiver", now, exporttest.Key(), "elsewhere.example.org", export.CodeWrongDestination},
390 } {
391 signed, _ := e.manifest(c.at.UnixNano(), c.key, c.destination)
392 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
393 refused(t, c.what, status, reply, c.code)
394 }
395 if staged := e.staged(); len(staged) != 0 {
396 t.Errorf("refused manifests left %v staged", staged)
397 }
398
399 older, om := e.manifest(now.Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
400 newer, _ := e.signedNow()
401 e.post(newer)
402 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, older, nil)
403 refused(t, "a manifest older than the one staged", status, reply, export.CodeSuperseded)
404 status, reply, _ = e.request(http.MethodPut, export.BodyPath(om.Sequence, om.File.SHA256), e.f.ExportJSON, nil)
405 refused(t, "a body of the older upload", status, reply, export.CodeSuperseded)
406 status, reply, _ = e.request(http.MethodPost, export.CommitPath(om.Sequence+1e12), nil, nil)
407 refused(t, "a commit of an upload never staged", status, reply, export.CodeNoManifest)
408}
409
410// A body is refused when its bytes are not what the manifest declares: a
411// hash mismatch, a size mismatch whether or not the length is given, a
412// Content-Encoding, or a hash the manifest does not declare. An upload
413// cut off part way through a body is refused at the commit as incomplete,
414// and the active export stays as it was until the body is sent whole.
415func TestABodyIsKeptOnlyWhenItVerifies(t *testing.T) {
416 e := newEdge(t, exporttest.New(t))
417 first := e.upload()
418 signed, m := e.signedNow()
419 // A second upload of the same export needs export.json again, staged
420 // for it, and no bundle: app's repository is carried over.
421 if needs := e.post(signed).Needs; len(needs) != 1 {
422 t.Fatalf("the second upload needs %+v, want export.json alone", needs)
423 }
424 file := body(t, m, export.ExportFile)
425 path := export.BodyPath(m.Sequence, file.SHA256)
426 wrong := append([]byte{}, e.f.ExportJSON...)
427 wrong[0] ^= 1
428
429 status, reply, _ := e.request(http.MethodPut, path, wrong, nil)
430 refused(t, "a body with other bytes of the same size", status, reply, export.CodeHashMismatch)
431 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON[1:], nil)
432 refused(t, "a body one byte short", status, reply, export.CodeSizeMismatch)
433 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON, http.Header{"Content-Encoding": {"gzip"}})
434 refused(t, "a body with a Content-Encoding", status, reply, export.CodeEncoding)
435 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, strings.Repeat("0", 64)), e.f.ExportJSON, nil)
436 refused(t, "a body the manifest does not declare", status, reply, export.CodeNotDeclared)
437
438 // Sent with no length, one byte long.
439 req, err := http.NewRequest(http.MethodPut, "http://"+e.addr+path, io.MultiReader(bytes.NewReader(e.f.ExportJSON), strings.NewReader("x")))
440 if err != nil {
441 t.Fatal(err)
442 }
443 req.Header.Set("Authorization", export.Authorization(token))
444 res, err := http.DefaultClient.Do(req)
445 if err != nil {
446 t.Fatal(err)
447 }
448 reply, _ = io.ReadAll(res.Body)
449 res.Body.Close()
450 refused(t, "a body one byte long, sent with no length", res.StatusCode, reply, export.CodeSizeMismatch)
451
452 // Cut off half way.
453 c, err := net.Dial("tcp", e.addr)
454 if err != nil {
455 t.Fatal(err)
456 }
457 fmt.Fprintf(c, "PUT %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n", path, e.addr, export.Authorization(token), file.Size)
458 c.Write(e.f.ExportJSON[:file.Size/2])
459 c.Close()
460
461 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
462 r := refused(t, "a commit after the body was cut off", status, reply, export.CodeIncomplete)
463 if len(r.Needs) != 1 || r.Needs[0].SHA256 != file.SHA256 {
464 t.Errorf("the incomplete refusal needs %+v, want export.json", r.Needs)
465 }
466 if hw := e.highWater(); hw != first.Sequence {
467 t.Errorf("high-water moved to %d on refused bodies, want %d", hw, first.Sequence)
468 }
469 // The receiver removes what it read of the cut-off body once it sees
470 // the connection close.
471 waitFor(t, "no body left in staging", func() bool {
472 partial, _ := filepath.Glob(filepath.Join(e.state, "staging", "*", "bodies", "*"))
473 return len(partial) == 0
474 })
475 e.put(m, export.ExportFile)
476 e.commit(m)
477}
478
479// A manifest whose body is larger than --max-body, or whose bodies
480// together are larger than --max-upload, is refused as too-large and
481// staged not at all.
482func TestAnOversizedUploadIsRefused(t *testing.T) {
483 f := exporttest.New(t)
484 size := func(name string) int64 { return int64(len(f.BodyBytes(t, name))) }
485 for _, c := range []struct {
486 what string
487 flags []string
488 }{
489 {"a body over --max-body", []string{"--max-body", strconv.FormatInt(size(export.ExportFile)-1, 10)}},
490 {"bodies over --max-upload", []string{"--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app")-1, 10)}},
491 } {
492 e := newEdge(t, f, c.flags...)
493 signed, _ := e.signedNow()
494 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
495 refused(t, c.what, status, reply, export.CodeTooLarge)
496 if staged := e.staged(); len(staged) != 0 {
497 t.Errorf("%s: the refused manifest left %v staged", c.what, staged)
498 }
499 }
500 // At the caps exactly, the upload is accepted.
501 e := newEdge(t, f, "--max-body", strconv.FormatInt(max(size(export.ExportFile), size("app")), 10),
502 "--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app"), 10))
503 e.upload()
504}
505
506// A saturated receiver answers 503 to a request past its slots, and
507// valley-web, a process of its own over the same state directory, keeps
508// serving every page. A request without the token is still refused as
509// unauthenticated, taking no slot. Once the stalled uploads go away, the
510// receiver takes uploads again.
511func TestASaturatedUploadLeavesValleyWebServing(t *testing.T) {
512 e := newEdge(t, exporttest.New(t))
513 e.upload()
514 web := e.valleyWeb()
515 signed, m := e.signedNow()
516 e.post(signed)
517 file := body(t, m, export.ExportFile)
518 probe := export.BodyPath(m.Sequence, strings.Repeat("0", 64))
519
520 // Each stalled upload sends its headers and one byte of its body, and
521 // holds a slot while the receiver waits for the rest. One answered at
522 // once found no slot free, and another takes its place.
523 var stalled []net.Conn
524 for len(stalled) < maxRequests {
525 c, err := net.Dial("tcp", e.addr)
526 if err != nil {
527 t.Fatal(err)
528 }
529 fmt.Fprintf(c, "PUT %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n",
530 export.BodyPath(m.Sequence, file.SHA256), e.addr, export.Authorization(token), file.Size)
531 c.Write(e.f.ExportJSON[:1])
532 c.SetReadDeadline(time.Now().Add(200 * time.Millisecond))
533 if _, err := c.Read(make([]byte, 1)); err == nil {
534 c.Close()
535 continue
536 }
537 stalled = append(stalled, c)
538 }
539 waitFor(t, "the receiver to answer 503", func() bool {
540 status, _, header := e.request(http.MethodPut, probe, []byte("x"), nil)
541 return status == http.StatusServiceUnavailable && header.Get("Retry-After") != ""
542 })
543 req, err := http.NewRequest(http.MethodPost, "http://"+e.addr+export.ManifestPath, bytes.NewReader(signed))
544 if err != nil {
545 t.Fatal(err)
546 }
547 res, err := http.DefaultClient.Do(req)
548 if err != nil {
549 t.Fatal(err)
550 }
551 reply, _ := io.ReadAll(res.Body)
552 res.Body.Close()
553 refused(t, "a manifest with no token while the receiver is saturated", res.StatusCode, reply, export.CodeUnauthenticated)
554 e.serves(web)
555
556 for _, c := range stalled {
557 c.Close()
558 }
559 waitFor(t, "the receiver to take requests again", func() bool {
560 status, _, _ := e.request(http.MethodPut, probe, []byte("x"), nil)
561 return status == http.StatusNotFound
562 })
563 e.put(m, export.ExportFile)
564 e.commit(m)
565 e.serves(web)
566}
567
568func waitFor(t *testing.T, what string, done func() bool) {
569 t.Helper()
570 for deadline := time.Now().Add(20 * time.Second); time.Now().Before(deadline); time.Sleep(20 * time.Millisecond) {
571 if done() {
572 return
573 }
574 }
575 t.Fatalf("timed out waiting for %s", what)
576}
577
578// The receiver stops cleanly on SIGTERM.
579func TestStopsOnSIGTERM(t *testing.T) {
580 e := newEdge(t, exporttest.New(t))
581 if err := e.cmd.Process.Signal(syscall.SIGTERM); err != nil {
582 t.Fatal(err)
583 }
584 if err := e.cmd.Wait(); err != nil {
585 t.Errorf("valley-web-receive stopped with %v", err)
586 }
587}
588
589// A command line it cannot run with gets the usage and exit status 2; a
590// token file it cannot use, or verifiers it cannot read, exit status 1;
591// --help gets the usage alone.
592func TestUsage(t *testing.T) {
593 tokenFile, verifiers := files(t)
594 state := t.TempDir()
595 base := []string{"--state", state, "--listen", "127.0.0.1:0", "--instance", "valley-host", "--destination", "example.org"}
596 for _, args := range [][]string{
597 {},
598 append(base, "--verifiers", verifiers),
599 append(base, "--token-file", tokenFile),
600 {"--state", state, "--listen", "127.0.0.1:0", "--instance", "a b", "--destination", "example.org", "--verifiers", verifiers, "--token-file", tokenFile},
601 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "--max-body", "0"),
602 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "extra"),
603 } {
604 out, err := receiveCmd(args...).CombinedOutput()
605 exit, ok := err.(*exec.ExitError)
606 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web-receive") {
607 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
608 }
609 }
610 short := filepath.Join(t.TempDir(), "short")
611 if err := os.WriteFile(short, []byte("too-short\n"), 0o600); err != nil {
612 t.Fatal(err)
613 }
614 for _, args := range [][]string{
615 append(base, "--verifiers", verifiers, "--token-file", short),
616 append(base, "--verifiers", tokenFile, "--token-file", tokenFile),
617 } {
618 out, err := receiveCmd(args...).CombinedOutput()
619 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
620 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
621 }
622 if bytes.Contains(out, []byte(token)) {
623 t.Errorf("valley-web-receive %q printed the token", args)
624 }
625 }
626 out, err := receiveCmd("--help").CombinedOutput()
627 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web-receive") {
628 t.Errorf("valley-web-receive --help gave %v:\n%s", err, out)
629 }
630}