gunk-dev/the-valley

main_test.go

source27cc12bbf18fmain's published tip history
44.1 KiB
1package main
2
3import (
4 "bufio"
5 "bytes"
6 "context"
7 "crypto/ed25519"
8 "encoding/json"
9 "errors"
10 "fmt"
11 "io"
12 "net"
13 "net/http"
14 "os"
15 "os/exec"
16 "path/filepath"
17 "strconv"
18 "strings"
19 "sync"
20 "syscall"
21 "testing"
22 "time"
23
24 "the-valley/web/export"
25 "the-valley/web/export/exporttest"
26)
27
28// The tests run the receiver as a process of its own: the test binary is
29// valley-web-receive when VALLEY_WEB_RECEIVE_TEST_MAIN is set, and it runs
30// the git VALLEY_WEB_RECEIVE_TEST_GIT names, when that is set. Uploads are
31// the shared fixture's export, under manifests signed now with the
32// fixture's key, and they are accepted with real git. valley-web is the
33// real program, which VALLEY_WEB names.
34func TestMain(m *testing.M) {
35 if os.Getenv("VALLEY_WEB_RECEIVE_TEST_MAIN") == "1" {
36 if git := os.Getenv("VALLEY_WEB_RECEIVE_TEST_GIT"); git != "" {
37 export.GitProgram = git
38 }
39 main()
40 os.Exit(0)
41 }
42 os.Exit(m.Run())
43}
44
45const token = "receiver-test-token-0123456789abcdef"
46
47// How long a test waits for a request, a dial, or anything it polls for.
48// Every wait here is bounded, so a receiver that stops answering fails the
49// test rather than hanging it.
50const (
51 requestTimeout = 30 * time.Second
52 dialTimeout = 5 * time.Second
53 waitTimeout = 20 * time.Second
54)
55
56// client makes every request the tests make, each within requestTimeout,
57// on a connection of its own that it closes after the reply. A connection
58// kept for the next request would hold one of the receiver's, which the
59// tests that fill them count on being free.
60var client = &http.Client{
61 Timeout: requestTimeout,
62 Transport: &http.Transport{
63 DisableKeepAlives: true,
64 DialContext: (&net.Dialer{Timeout: dialTimeout}).DialContext,
65 },
66}
67
68// edge is a receiver running over a state directory, and the fixture it
69// is sent.
70type edge struct {
71 t *testing.T
72 f *exporttest.Fixture
73 state string
74 addr string
75 proc *proc
76}
77
78// files writes the token file and the verifier file a receiver is given.
79func files(t *testing.T) (tokenFile, verifiers string) {
80 t.Helper()
81 dir := t.TempDir()
82 tokenFile, verifiers = filepath.Join(dir, "token"), filepath.Join(dir, "verifiers")
83 if err := os.WriteFile(tokenFile, []byte(token+"\n"), 0o600); err != nil {
84 t.Fatal(err)
85 }
86 if err := os.WriteFile(verifiers, []byte(exporttest.Verifier().String()+"\n"), 0o644); err != nil {
87 t.Fatal(err)
88 }
89 return tokenFile, verifiers
90}
91
92// command is a program the tests run. start and output run it with
93// exporttest.Start, so neither it nor any git it starts outlives the test,
94// even when the test process dies first, as on a timeout or an external
95// kill.
96func command(name string, args ...string) *exec.Cmd {
97 return exec.Command(name, args...)
98}
99
100// output runs cmd, and returns what it wrote to stdout and stderr
101// together. A cmd that has not exited within requestTimeout fails the
102// test.
103func output(t *testing.T, cmd *exec.Cmd) ([]byte, error) {
104 t.Helper()
105 var out bytes.Buffer
106 cmd.Stdout, cmd.Stderr = &out, &out
107 err := exporttest.Run(t, cmd, requestTimeout)
108 return out.Bytes(), err
109}
110
111func receiveCmd(args ...string) *exec.Cmd {
112 cmd := command(os.Args[0], args...)
113 cmd.Env = append(os.Environ(), "VALLEY_WEB_RECEIVE_TEST_MAIN=1")
114 return cmd
115}
116
117// newEdge starts a receiver over a new state directory, with the flags
118// given after the ones every receiver here needs.
119func newEdge(t *testing.T, f *exporttest.Fixture, more ...string) *edge {
120 t.Helper()
121 return newEdgeWithGit(t, f, "", more...)
122}
123
124// newEdgeWithGit starts a receiver that runs git, or the default git when
125// git is "".
126func newEdgeWithGit(t *testing.T, f *exporttest.Fixture, git string, more ...string) *edge {
127 t.Helper()
128 tokenFile, verifiers := files(t)
129 state := filepath.Join(t.TempDir(), "state")
130 cmd := receiveCmd(append([]string{"--state", state, "--listen", "127.0.0.1:0",
131 "--instance", exporttest.Instance, "--destination", exporttest.Destination,
132 "--verifiers", verifiers, "--token-file", tokenFile}, more...)...)
133 if git != "" {
134 cmd.Env = append(cmd.Env, "VALLEY_WEB_RECEIVE_TEST_GIT="+git)
135 }
136 p := start(t, cmd, "valley-web-receive")
137 return &edge{t: t, f: f, state: state, proc: p, addr: p.addr}
138}
139
140// proc is a program start runs: where it listens, what it writes to
141// stderr, and how it exits.
142type proc struct {
143 cmd *exec.Cmd
144 addr string
145 log *stderrLog
146 // done is closed once the program has exited, and err is then how.
147 done chan struct{}
148 err error
149}
150
151// stderrLog keeps what a program writes to stderr, and hands on its first
152// line.
153type stderrLog struct {
154 mu sync.Mutex
155 buf bytes.Buffer
156 first chan string
157}
158
159func (l *stderrLog) Write(p []byte) (int, error) {
160 l.mu.Lock()
161 defer l.mu.Unlock()
162 l.buf.Write(p)
163 if line, _, ok := strings.Cut(l.buf.String(), "\n"); ok && l.first != nil {
164 l.first <- line
165 l.first = nil
166 }
167 return len(p), nil
168}
169
170func (l *stderrLog) String() string {
171 l.mu.Lock()
172 defer l.mu.Unlock()
173 return l.buf.String()
174}
175
176// start runs cmd with exporttest.Start and waits for it to say where it
177// listens. The cleanup is registered as soon as cmd starts: it kills every
178// process in cmd's session, even once cmd has exited, since a git cmd
179// started may outlive it. It logs what cmd wrote when the test failed.
180func start(t *testing.T, cmd *exec.Cmd, name string) *proc {
181 t.Helper()
182 p := &proc{cmd: cmd, log: &stderrLog{first: make(chan string, 1)}, done: make(chan struct{})}
183 first := p.log.first
184 cmd.Stderr = p.log
185 kill, err := exporttest.Start(t, cmd)
186 if err != nil {
187 t.Fatal(err)
188 }
189 go func() {
190 p.err = cmd.Wait()
191 close(p.done)
192 }()
193 t.Cleanup(func() {
194 kill()
195 <-p.done
196 if t.Failed() {
197 t.Logf("%s wrote:\n%s", name, p.log)
198 }
199 })
200 select {
201 case line := <-first:
202 addr, ok := strings.CutPrefix(line, name+": listening on ")
203 if !ok {
204 t.Fatalf("%s printed %q", name, line)
205 }
206 p.addr = addr
207 return p
208 case <-p.done:
209 t.Fatalf("%s exited with %v before it listened", name, p.err)
210 case <-time.After(waitTimeout):
211 t.Fatalf("%s did not say where it listens", name)
212 }
213 return nil
214}
215
216// logged reports whether the receiver has logged a line that holds every
217// one of parts.
218func (e *edge) logged(parts ...string) bool {
219 for _, line := range strings.Split(e.proc.log.String(), "\n") {
220 all := true
221 for _, part := range parts {
222 all = all && strings.Contains(line, part)
223 }
224 if all {
225 return true
226 }
227 }
228 return false
229}
230
231// manifest is the fixture's export under a manifest with sequence, signed
232// with key, and the manifest itself.
233func (e *edge) manifest(sequence int64, key ed25519.PrivateKey, destination string) ([]byte, *export.Manifest) {
234 e.t.Helper()
235 bundles := map[string]export.Body{}
236 for _, p := range e.f.Manifest.Projects {
237 bundles[p.Name] = p.Bundle
238 }
239 m, err := export.NewManifest(exporttest.Instance, destination, sequence, e.f.Export, e.f.ExportJSON, bundles)
240 if err != nil {
241 e.t.Fatal(err)
242 }
243 signed, err := m.Sign(exporttest.SignerName, key)
244 if err != nil {
245 e.t.Fatal(err)
246 }
247 return signed, m
248}
249
250// signedNow is the fixture's export under a manifest signed now.
251func (e *edge) signedNow() ([]byte, *export.Manifest) {
252 return e.manifest(time.Now().UnixNano(), exporttest.Key(), exporttest.Destination)
253}
254
255// do makes one request with the token within ctx, and returns the status,
256// the reply and its header.
257func (e *edge) do(ctx context.Context, method, path string, body []byte, header http.Header) (int, []byte, http.Header, error) {
258 req, err := http.NewRequestWithContext(ctx, method, "http://"+e.addr+path, bytes.NewReader(body))
259 if err != nil {
260 return 0, nil, nil, err
261 }
262 req.Header.Set("Authorization", export.Authorization(token))
263 for k, v := range header {
264 req.Header[k] = v
265 }
266 res, err := client.Do(req)
267 if err != nil {
268 return 0, nil, nil, err
269 }
270 defer res.Body.Close()
271 reply, err := io.ReadAll(res.Body)
272 return res.StatusCode, reply, res.Header, err
273}
274
275// request makes one request with the token, and returns the status and the
276// reply. A request not answered within requestTimeout fails the test.
277func (e *edge) request(method, path string, body []byte, header http.Header) (int, []byte, http.Header) {
278 e.t.Helper()
279 status, reply, h, err := e.do(context.Background(), method, path, body, header)
280 if err != nil {
281 e.t.Fatal(err)
282 }
283 return status, reply, h
284}
285
286// dial opens a connection to the receiver, which the test closes when it
287// ends if nothing has before.
288func (e *edge) dial() net.Conn {
289 e.t.Helper()
290 c, err := net.DialTimeout("tcp", e.addr, dialTimeout)
291 if err != nil {
292 e.t.Fatal(err)
293 }
294 e.t.Cleanup(func() { c.Close() })
295 return c
296}
297
298// idle makes one request with the token on a connection of its own, a
299// commit of an upload never staged, which the receiver refuses and keeps
300// the connection open after. It returns the connection, which then holds
301// one of the receiver's connections until it is closed or the receiver's
302// idle timeout.
303func (e *edge) idle() net.Conn {
304 e.t.Helper()
305 for range 100 {
306 c := e.dial()
307 fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: 0\r\n\r\n",
308 export.CommitPath(1), e.addr, export.Authorization(token))
309 c.SetReadDeadline(time.Now().Add(requestTimeout))
310 res, err := http.ReadResponse(bufio.NewReader(c), nil)
311 if err != nil {
312 e.t.Fatal(err)
313 }
314 io.Copy(io.Discard, res.Body)
315 res.Body.Close()
316 c.SetReadDeadline(time.Time{})
317 switch {
318 case res.StatusCode == http.StatusServiceUnavailable:
319 // A request just answered had not yet given its slot back.
320 c.Close()
321 time.Sleep(20 * time.Millisecond)
322 case res.Close:
323 e.t.Fatalf("the receiver closed the connection after a %d", res.StatusCode)
324 default:
325 return c
326 }
327 }
328 e.t.Fatal("the receiver never had a request slot free")
329 return nil
330}
331
332// stall sends the headers of a request with content, and one byte of it,
333// on a connection of its own. The request then holds one of the
334// receiver's request slots while the receiver waits for the rest. stall
335// returns nil when the receiver answered at once: it had no slot free, or
336// it refused the request.
337func (e *edge) stall(method, path string, content []byte) net.Conn {
338 e.t.Helper()
339 c := e.dial()
340 fmt.Fprintf(c, "%s %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n",
341 method, path, e.addr, export.Authorization(token), len(content))
342 c.Write(content[:1])
343 if answered(c, 200*time.Millisecond) {
344 c.Close()
345 return nil
346 }
347 return c
348}
349
350// stallAll holds every request slot with a stalled manifest, signed.
351func (e *edge) stallAll(signed []byte) []net.Conn {
352 e.t.Helper()
353 var stalled []net.Conn
354 for range 100 {
355 if c := e.stall(http.MethodPost, export.ManifestPath, signed); c != nil {
356 stalled = append(stalled, c)
357 }
358 if len(stalled) == maxRequests {
359 return stalled
360 }
361 }
362 e.t.Fatalf("only %d of %d stalled manifests held a request slot", len(stalled), maxRequests)
363 return nil
364}
365
366// answered reports whether anything arrives on c within d, or c is closed.
367// It reads nothing when nothing arrives.
368func answered(c net.Conn, d time.Duration) bool {
369 c.SetReadDeadline(time.Now().Add(d))
370 defer c.SetReadDeadline(time.Time{})
371 _, err := c.Read(make([]byte, 1))
372 var ne net.Error
373 return !(errors.As(err, &ne) && ne.Timeout())
374}
375
376// refused checks that a reply is the refusal with code, and returns it.
377func refused(t *testing.T, what string, status int, reply []byte, code export.Code) export.ErrorReply {
378 t.Helper()
379 var r export.ErrorReply
380 if err := json.Unmarshal(reply, &r); err != nil || r.Schema != export.ErrorSchema || r.Code != code || status != code.Status() {
381 t.Errorf("%s: the receiver replied %d %s, want %d and %s", what, status, reply, code.Status(), code)
382 }
383 return r
384}
385
386// post posts the signed manifest, and returns its inventory.
387func (e *edge) post(signed []byte) export.Inventory {
388 e.t.Helper()
389 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
390 var inv export.Inventory
391 if err := json.Unmarshal(reply, &inv); status != http.StatusOK || err != nil || inv.Schema != export.InventorySchema {
392 e.t.Fatalf("the manifest was answered %d %s", status, reply)
393 }
394 return inv
395}
396
397// put sends one body the manifest declares, and fails the test unless it
398// is accepted. A 503 is retried, as the publisher retries it: a request
399// that staged the body may not have given it up yet.
400func (e *edge) put(m *export.Manifest, name string) {
401 e.t.Helper()
402 b := body(e.t, m, name)
403 var status int
404 var reply []byte
405 for range 50 {
406 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, b.SHA256), e.f.BodyBytes(e.t, name), nil)
407 if status != http.StatusServiceUnavailable {
408 break
409 }
410 time.Sleep(20 * time.Millisecond)
411 }
412 if status != http.StatusNoContent {
413 e.t.Fatalf("body %s was answered %d %s", name, status, reply)
414 }
415}
416
417func body(t *testing.T, m *export.Manifest, name string) export.Body {
418 t.Helper()
419 for _, b := range m.Bodies() {
420 if b.Name == name {
421 return b
422 }
423 }
424 t.Fatalf("the manifest declares no body %s", name)
425 return export.Body{}
426}
427
428// commit commits the upload, and fails the test unless it is activated.
429func (e *edge) commit(m *export.Manifest) {
430 e.t.Helper()
431 status, reply, _ := e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
432 var c export.Committed
433 if err := json.Unmarshal(reply, &c); status != http.StatusOK || err != nil || c.Sequence != m.Sequence {
434 e.t.Fatalf("the commit was answered %d %s", status, reply)
435 }
436}
437
438// upload runs the three steps for a manifest signed now, and returns it.
439func (e *edge) upload() *export.Manifest {
440 e.t.Helper()
441 signed, m := e.signedNow()
442 for _, n := range e.post(signed).Needs {
443 e.put(m, n.Name)
444 }
445 e.commit(m)
446 return m
447}
448
449// highWater is the state directory's high-water mark, 0 for none.
450func (e *edge) highWater() int64 {
451 e.t.Helper()
452 data, err := os.ReadFile(filepath.Join(e.state, "high-water"))
453 if os.IsNotExist(err) {
454 return 0
455 }
456 n, perr := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
457 if err != nil || perr != nil {
458 e.t.Fatalf("high-water: %v %v", err, perr)
459 }
460 return n
461}
462
463// staged are the entries of the state directory's staging area.
464func (e *edge) staged() []string {
465 e.t.Helper()
466 entries, err := os.ReadDir(filepath.Join(e.state, "staging"))
467 if err != nil {
468 e.t.Fatal(err)
469 }
470 var names []string
471 for _, d := range entries {
472 names = append(names, d.Name())
473 }
474 return names
475}
476
477// valleyWeb starts the real valley-web over the edge's state directory,
478// and returns where it listens.
479func (e *edge) valleyWeb() string {
480 e.t.Helper()
481 bin := os.Getenv("VALLEY_WEB")
482 if bin == "" {
483 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
484 e.t.Fatal("VALLEY_WEB names no valley-web, and VALLEY_TEST_TOOLS=required")
485 }
486 e.t.Skip("VALLEY_WEB names no valley-web; the nix check provides one")
487 }
488 return start(e.t, command(bin, "--state", e.state, "--listen", "127.0.0.1:0"), "valley-web").addr
489}
490
491// serves checks that valley-web at addr answers every page of the
492// fixture's export.
493func (e *edge) serves(addr string) {
494 e.t.Helper()
495 tip := e.f.Export.Projects[0].SourceTip
496 for target, status := range map[string]int{
497 "/": http.StatusOK,
498 "/app/knots/oc-a000002": http.StatusOK,
499 "/app/source/tree/" + tip + "/": http.StatusOK,
500 "/app/source/log/" + tip: http.StatusOK,
501 "/site/source/": http.StatusNotFound,
502 } {
503 res, err := client.Get("http://" + addr + target)
504 if err != nil {
505 e.t.Fatal(err)
506 }
507 page, _ := io.ReadAll(res.Body)
508 res.Body.Close()
509 if res.StatusCode != status {
510 e.t.Errorf("valley-web answered GET %s with %d, want %d:\n%s", target, res.StatusCode, status, page)
511 }
512 }
513}
514
515// An upload of the three steps activates the export, and valley-web, as a
516// process of its own over the same state directory, serves it. The
517// manifest posted again, and the commit made again, are refused as
518// replayed, with the high-water mark.
519func TestAnUploadActivatesAndValleyWebServesIt(t *testing.T) {
520 e := newEdge(t, exporttest.New(t))
521 signed, m := e.signedNow()
522 inv := e.post(signed)
523 if inv.Active != nil || len(inv.Needs) != 2 || inv.Needs[0].Name != export.ExportFile || inv.Needs[1].Name != "app" {
524 t.Fatalf("the first inventory is %+v, want no active export and both bodies needed, export.json first", inv)
525 }
526 again := e.post(signed)
527 if len(again.Needs) != 2 {
528 t.Errorf("the manifest posted again needs %+v, want both bodies still", again.Needs)
529 }
530 e.put(m, export.ExportFile)
531 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != "app" {
532 t.Errorf("the manifest posted after export.json needs %+v, want app's bundle alone", needs)
533 }
534 e.put(m, "app")
535 e.put(m, "app") // a body already staged is accepted again
536 e.commit(m)
537 if hw := e.highWater(); hw != m.Sequence {
538 t.Errorf("high-water is %d after the commit, want %d", hw, m.Sequence)
539 }
540 e.serves(e.valleyWeb())
541
542 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
543 if r := refused(t, "the manifest posted after its commit", status, reply, export.CodeReplayed); r.HighWater != m.Sequence {
544 t.Errorf("the replayed refusal gives high-water %d, want %d", r.HighWater, m.Sequence)
545 }
546 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
547 refused(t, "the commit made again", status, reply, export.CodeReplayed)
548
549 // The next upload carries app's repository over, and needs export.json
550 // alone.
551 signed, m = e.signedNow()
552 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != export.ExportFile {
553 t.Errorf("the next upload needs %+v, want export.json alone", needs)
554 }
555 e.put(m, export.ExportFile)
556 e.commit(m)
557}
558
559// A request without the token is refused as unauthenticated, whatever it
560// asks, and stages nothing. So is one with another token, or with the
561// token twice.
562func TestAnUnauthenticatedRequestIsRefused(t *testing.T) {
563 e := newEdge(t, exporttest.New(t))
564 signed, m := e.signedNow()
565 send := func(what, method, path string, body []byte, auth []string) {
566 t.Helper()
567 req, err := http.NewRequest(method, "http://"+e.addr+path, bytes.NewReader(body))
568 if err != nil {
569 t.Fatal(err)
570 }
571 req.Header["Authorization"] = auth
572 res, err := client.Do(req)
573 if err != nil {
574 t.Fatal(err)
575 }
576 reply, _ := io.ReadAll(res.Body)
577 res.Body.Close()
578 refused(t, what, res.StatusCode, reply, export.CodeUnauthenticated)
579 if !strings.HasPrefix(res.Header.Get("WWW-Authenticate"), "Bearer ") {
580 t.Errorf("%s: the refusal names no scheme to authenticate with", what)
581 }
582 }
583 send("a manifest with no token", http.MethodPost, export.ManifestPath, signed, nil)
584 send("a manifest with another token", http.MethodPost, export.ManifestPath, signed, []string{export.Authorization(token + "x")})
585 send("a manifest with the token in another scheme", http.MethodPost, export.ManifestPath, signed, []string{"Basic " + token})
586 send("a manifest with the token twice", http.MethodPost, export.ManifestPath, signed,
587 []string{export.Authorization(token), export.Authorization(token)})
588 send("a body with no token", http.MethodPut, export.BodyPath(m.Sequence, m.File.SHA256), e.f.ExportJSON, nil)
589 send("a commit with no token", http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
590 send("a path the upload does not use", http.MethodGet, "/", nil, nil)
591 if staged := e.staged(); len(staged) != 0 || e.highWater() != 0 {
592 t.Errorf("unauthenticated requests left %v staged and high-water %d", staged, e.highWater())
593 }
594}
595
596// A manifest is refused when it is stale, signed ahead of the receiver's
597// clock, signed by another key, or for another receiver; and an older
598// manifest than the one staged is superseded. None of them is staged.
599func TestAManifestIsAdmittedOnlyWhenFresh(t *testing.T) {
600 e := newEdge(t, exporttest.New(t))
601 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
602 now := time.Now()
603 for _, c := range []struct {
604 what string
605 at time.Time
606 key ed25519.PrivateKey
607 destination string
608 code export.Code
609 }{
610 {"a manifest signed four days ago", now.Add(-96 * time.Hour), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
611 {"a manifest signed two minutes ahead", now.Add(2 * time.Minute), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
612 {"a manifest signed by another key", now, other, exporttest.Destination, export.CodeBadSignature},
613 {"a manifest for another receiver", now, exporttest.Key(), "elsewhere.example.org", export.CodeWrongDestination},
614 } {
615 signed, _ := e.manifest(c.at.UnixNano(), c.key, c.destination)
616 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
617 refused(t, c.what, status, reply, c.code)
618 }
619 if staged := e.staged(); len(staged) != 0 {
620 t.Errorf("refused manifests left %v staged", staged)
621 }
622
623 older, om := e.manifest(now.Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
624 newer, _ := e.signedNow()
625 e.post(newer)
626 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, older, nil)
627 refused(t, "a manifest older than the one staged", status, reply, export.CodeSuperseded)
628 status, reply, _ = e.request(http.MethodPut, export.BodyPath(om.Sequence, om.File.SHA256), e.f.ExportJSON, nil)
629 refused(t, "a body of the older upload", status, reply, export.CodeSuperseded)
630 status, reply, _ = e.request(http.MethodPost, export.CommitPath(om.Sequence+1e12), nil, nil)
631 refused(t, "a commit of an upload never staged", status, reply, export.CodeNoManifest)
632}
633
634// A body is refused when its bytes are not what the manifest declares: a
635// hash mismatch, a size mismatch whether or not the length is given, a
636// Content-Encoding, or a hash the manifest does not declare. An upload
637// cut off part way through a body is refused at the commit as incomplete,
638// and the active export stays as it was until the body is sent whole.
639func TestABodyIsKeptOnlyWhenItVerifies(t *testing.T) {
640 e := newEdge(t, exporttest.New(t))
641 first := e.upload()
642 signed, m := e.signedNow()
643 // A second upload of the same export needs export.json again, staged
644 // for it, and no bundle: app's repository is carried over.
645 if needs := e.post(signed).Needs; len(needs) != 1 {
646 t.Fatalf("the second upload needs %+v, want export.json alone", needs)
647 }
648 file := body(t, m, export.ExportFile)
649 path := export.BodyPath(m.Sequence, file.SHA256)
650 wrong := append([]byte{}, e.f.ExportJSON...)
651 wrong[0] ^= 1
652
653 status, reply, _ := e.request(http.MethodPut, path, wrong, nil)
654 refused(t, "a body with other bytes of the same size", status, reply, export.CodeHashMismatch)
655 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON[1:], nil)
656 refused(t, "a body one byte short", status, reply, export.CodeSizeMismatch)
657 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON, http.Header{"Content-Encoding": {"gzip"}})
658 refused(t, "a body with a Content-Encoding", status, reply, export.CodeEncoding)
659 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, strings.Repeat("0", 64)), e.f.ExportJSON, nil)
660 refused(t, "a body the manifest does not declare", status, reply, export.CodeNotDeclared)
661
662 // Sent with no length, one byte long.
663 req, err := http.NewRequest(http.MethodPut, "http://"+e.addr+path, io.MultiReader(bytes.NewReader(e.f.ExportJSON), strings.NewReader("x")))
664 if err != nil {
665 t.Fatal(err)
666 }
667 req.Header.Set("Authorization", export.Authorization(token))
668 res, err := client.Do(req)
669 if err != nil {
670 t.Fatal(err)
671 }
672 reply, _ = io.ReadAll(res.Body)
673 res.Body.Close()
674 refused(t, "a body one byte long, sent with no length", res.StatusCode, reply, export.CodeSizeMismatch)
675
676 // Sent while another request is staging it: staging holds one partial
677 // file of each body.
678 stalled := e.stall(http.MethodPut, path, e.f.ExportJSON)
679 if stalled == nil {
680 t.Fatal("the receiver answered a stalled body at once")
681 }
682 status, reply, header := e.request(http.MethodPut, path, e.f.ExportJSON, nil)
683 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
684 t.Errorf("a body sent while another request stages it was answered %d %s, want 503 with Retry-After", status, reply)
685 }
686 stalled.Close()
687
688 // Cut off half way.
689 c := e.dial()
690 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)
691 c.Write(e.f.ExportJSON[:file.Size/2])
692 c.Close()
693
694 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
695 r := refused(t, "a commit after the body was cut off", status, reply, export.CodeIncomplete)
696 if len(r.Needs) != 1 || r.Needs[0].SHA256 != file.SHA256 {
697 t.Errorf("the incomplete refusal needs %+v, want export.json", r.Needs)
698 }
699 if hw := e.highWater(); hw != first.Sequence {
700 t.Errorf("high-water moved to %d on refused bodies, want %d", hw, first.Sequence)
701 }
702 // The receiver removes what it read of the cut-off body once it sees
703 // the connection close.
704 waitFor(t, "no body left in staging", func(context.Context) bool {
705 partial, _ := filepath.Glob(filepath.Join(e.state, "staging", "*", "bodies", "*"))
706 return len(partial) == 0
707 })
708 e.put(m, export.ExportFile)
709 e.commit(m)
710}
711
712// A manifest whose body is larger than --max-body, or whose bodies
713// together are larger than --max-upload, is refused as too-large and
714// staged not at all.
715func TestAnOversizedUploadIsRefused(t *testing.T) {
716 f := exporttest.New(t)
717 size := func(name string) int64 { return int64(len(f.BodyBytes(t, name))) }
718 for _, c := range []struct {
719 what string
720 flags []string
721 }{
722 {"a body over --max-body", []string{"--max-body", strconv.FormatInt(size(export.ExportFile)-1, 10)}},
723 {"bodies over --max-upload", []string{"--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app")-1, 10)}},
724 } {
725 e := newEdge(t, f, c.flags...)
726 signed, _ := e.signedNow()
727 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
728 refused(t, c.what, status, reply, export.CodeTooLarge)
729 if staged := e.staged(); len(staged) != 0 {
730 t.Errorf("%s: the refused manifest left %v staged", c.what, staged)
731 }
732 }
733 // At the caps exactly, the upload is accepted.
734 e := newEdge(t, f, "--max-body", strconv.FormatInt(max(size(export.ExportFile), size("app")), 10),
735 "--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app"), 10))
736 e.upload()
737}
738
739// A saturated receiver answers 503 to a request past its slots, and
740// valley-web, a process of its own over the same state directory, keeps
741// serving every page. A request without the token is still refused as
742// unauthenticated, taking no slot. Once the stalled requests go away, the
743// receiver takes uploads again.
744//
745// Then every connection the receiver takes is held by a client that sends
746// part of a request's headers and stops. valley-web keeps serving. A body
747// sent meanwhile waits in the listen queue until the header timeout closes
748// those connections, and no longer.
749func TestASaturatedUploadLeavesValleyWebServing(t *testing.T) {
750 e := newEdge(t, exporttest.New(t))
751 e.upload()
752 web := e.valleyWeb()
753 signed, m := e.signedNow()
754 e.post(signed)
755 probe := export.BodyPath(m.Sequence, strings.Repeat("0", 64))
756
757 stalled := e.stallAll(signed)
758 status, _, header := e.request(http.MethodPut, probe, []byte("x"), nil)
759 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
760 t.Errorf("a request past every slot was answered %d, want 503 with Retry-After", status)
761 }
762 res, err := client.Post("http://"+e.addr+export.ManifestPath, "", bytes.NewReader(signed))
763 if err != nil {
764 t.Fatal(err)
765 }
766 reply, _ := io.ReadAll(res.Body)
767 res.Body.Close()
768 refused(t, "a manifest with no token while the receiver is saturated", res.StatusCode, reply, export.CodeUnauthenticated)
769 e.serves(web)
770
771 for _, c := range stalled {
772 c.Close()
773 }
774 waitFor(t, "the receiver to take requests again", func(ctx context.Context) bool {
775 status, _, _, err := e.do(ctx, http.MethodPut, probe, []byte("x"), nil)
776 return err == nil && status == http.StatusNotFound
777 })
778
779 for range maxConns {
780 fmt.Fprintf(e.dial(), "PUT %s HTTP/1.1\r\nHost: %s\r\n", probe, e.addr)
781 }
782 began := time.Now()
783 e.serves(web)
784 e.put(m, export.ExportFile)
785 if took := time.Since(began); took < headerTimeout/2 || took > headerTimeout+5*time.Second {
786 t.Errorf("a body sent behind a connection on every slot was answered after %v, want about the header timeout, %v", took, headerTimeout)
787 }
788 e.commit(m)
789 e.serves(web)
790}
791
792// OPTIONS * is the receiver's to answer, as any other request is: refused
793// as unauthenticated without the token, and 404 with it. Either is
794// answered at once, without reading the body it declares, and its
795// connection is closed. So OPTIONS * requests that withhold their bodies,
796// one on every connection the receiver takes, hold none of them, and an
797// upload goes through.
798func TestOptionsStarHoldsNoConnection(t *testing.T) {
799 e := newEdge(t, exporttest.New(t))
800 conns := make([]net.Conn, maxConns)
801 for i := range conns {
802 auth := ""
803 if i%2 == 1 {
804 auth = "Authorization: " + export.Authorization(token) + "\r\n"
805 }
806 conns[i] = e.dial()
807 fmt.Fprintf(conns[i], "OPTIONS * HTTP/1.1\r\nHost: %s\r\n%sContent-Length: 1\r\n\r\n", e.addr, auth)
808 }
809 e.upload()
810 for i, c := range conns {
811 c.SetReadDeadline(time.Now().Add(requestTimeout))
812 res, err := http.ReadResponse(bufio.NewReader(c), nil)
813 if err != nil {
814 t.Fatalf("OPTIONS * on connection %d was not answered: %v", i, err)
815 }
816 reply, _ := io.ReadAll(res.Body)
817 res.Body.Close()
818 if i%2 == 0 {
819 refused(t, "OPTIONS * with no token", res.StatusCode, reply, export.CodeUnauthenticated)
820 } else if res.StatusCode != http.StatusNotFound {
821 t.Errorf("OPTIONS * with the token was answered %d, want 404", res.StatusCode)
822 }
823 if !res.Close {
824 t.Errorf("the receiver kept the connection of OPTIONS * open")
825 }
826 }
827}
828
829// A manifest waits for the store's lock, which a commit holds throughout,
830// and stages nothing once its client goes away. Here the test holds the
831// lock, as a commit does.
832func TestAManifestStopsWaitingWhenItsClientGoesAway(t *testing.T) {
833 e := newEdge(t, exporttest.New(t))
834 e.upload()
835 lock, err := os.OpenFile(filepath.Join(e.state, "lock"), os.O_RDWR, 0)
836 if err != nil {
837 t.Fatal(err)
838 }
839 defer lock.Close()
840 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
841 t.Fatal(err)
842 }
843 signed, _ := e.signedNow()
844 c := e.dial()
845 fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n%s",
846 export.ManifestPath, e.addr, export.Authorization(token), len(signed), signed)
847 if answered(c, time.Second) {
848 t.Fatal("the manifest was answered while the store's lock was held")
849 }
850 c.Close()
851 waitFor(t, "the receiver to give the manifest up", func(context.Context) bool {
852 return e.logged(export.ManifestPath, "waiting for the lock", "context canceled")
853 })
854 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_UN); err != nil {
855 t.Fatal(err)
856 }
857 if staged := e.staged(); len(staged) != 0 {
858 t.Errorf("a manifest whose client went away left %v staged", staged)
859 }
860 e.upload()
861}
862
863// A manifest whose upload would take the state directory past
864// --max-storage is refused as too-large, and nothing is staged. The cap
865// counts a repository for every project, so a manifest that names one
866// bundle for many projects, which --max-upload counts once, is held to it
867// too. An upload within the cap is accepted.
868func TestAnUploadPastTheStorageCapIsRefused(t *testing.T) {
869 e := newEdge(t, exporttest.New(t), "--max-storage", "4M")
870 x := *e.f.Export
871 x.Projects = append([]export.Project{}, x.Projects...)
872 bundles := map[string]export.Body{}
873 for _, p := range e.f.Manifest.Projects {
874 bundles[p.Name] = p.Bundle
875 }
876 for i := range 6 {
877 p := x.Projects[0]
878 p.Name = fmt.Sprintf("%s-%d", p.Name, i)
879 x.Projects = append(x.Projects, p)
880 bundles[p.Name] = bundles[x.Projects[0].Name]
881 }
882 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, time.Now().UnixNano(), &x, e.f.ExportJSON, bundles)
883 if err != nil {
884 t.Fatal(err)
885 }
886 if err := m.CheckSizes(1<<30, 2<<30); err != nil {
887 t.Fatalf("the manifest is not within --max-upload: %v", err)
888 }
889 signed, err := m.Sign(exporttest.SignerName, exporttest.Key())
890 if err != nil {
891 t.Fatal(err)
892 }
893 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
894 refused(t, "a manifest naming one bundle for eight projects", status, reply, export.CodeTooLarge)
895 if staged := e.staged(); len(staged) != 0 {
896 t.Errorf("the refused manifest left %v staged", staged)
897 }
898 e.upload()
899 e.upload()
900}
901
902// openPartials are the partial body files the receiver holds open, as
903// /proc names them. A file deleted while it is open keeps its name there.
904func (e *edge) openPartials() []string {
905 e.t.Helper()
906 fds, err := filepath.Glob(fmt.Sprintf("/proc/%d/fd/*", e.proc.cmd.Process.Pid))
907 if err != nil {
908 e.t.Fatal(err)
909 }
910 var open []string
911 for _, fd := range fds {
912 if target, err := os.Readlink(fd); err == nil && strings.Contains(target, "/.partial-") {
913 open = append(open, target)
914 }
915 }
916 return open
917}
918
919// A newer manifest stops the older upload's body requests before it
920// deletes the older upload. Each is answered as superseded, and once the
921// newer manifest is answered the receiver holds no partial file of the
922// older upload open, where the disk it takes would be counted by nothing.
923// The newer upload's request for the same body is then accepted, not
924// answered 503 as a body another request is staging.
925func TestANewerManifestStopsTheOlderUploadsBodies(t *testing.T) {
926 e := newEdge(t, exporttest.New(t))
927 older, om := e.manifest(time.Now().Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
928 e.post(older)
929 file := body(t, om, export.ExportFile)
930 stalled := e.stall(http.MethodPut, export.BodyPath(om.Sequence, file.SHA256), e.f.ExportJSON)
931 if stalled == nil {
932 t.Fatal("the receiver answered a stalled body at once")
933 }
934 waitFor(t, "the receiver to open the stalled body's partial file", func(context.Context) bool {
935 return len(e.openPartials()) == 1
936 })
937
938 newer, nm := e.signedNow()
939 e.post(newer)
940 if open := e.openPartials(); len(open) != 0 {
941 t.Errorf("once the newer manifest was answered, the receiver holds %q open", open)
942 }
943 stalled.SetReadDeadline(time.Now().Add(requestTimeout))
944 res, err := http.ReadResponse(bufio.NewReader(stalled), nil)
945 if err != nil {
946 t.Fatalf("the older upload's stalled body was not answered: %v", err)
947 }
948 reply, _ := io.ReadAll(res.Body)
949 res.Body.Close()
950 refused(t, "the older upload's stalled body", res.StatusCode, reply, export.CodeSuperseded)
951 if staged := e.staged(); len(staged) != 1 || staged[0] != strconv.FormatInt(nm.Sequence, 10) {
952 t.Errorf("staging holds %v, want the newer upload alone", staged)
953 }
954 status, reply, _ := e.request(http.MethodPut, export.BodyPath(nm.Sequence, file.SHA256), e.f.ExportJSON, nil)
955 if status != http.StatusNoContent {
956 t.Errorf("the newer upload's export.json was answered %d %s, want 204", status, reply)
957 }
958 for _, n := range e.post(newer).Needs {
959 e.put(nm, n.Name)
960 }
961 e.commit(nm)
962}
963
964// A generation a reader holds is kept past the activation that replaces
965// it, and counts against --max-storage. While a reader holds a large one,
966// a manifest whose upload would pass the cap is refused as too-large. Once
967// the reader lets it go, the next manifest finds the room: the receiver
968// deletes the generation before it refuses anything for space.
969func TestAReleasedGenerationMakesRoomForAnUpload(t *testing.T) {
970 e := newEdge(t, exporttest.New(t), "--max-storage", "6M")
971 first := e.upload()
972 reader, err := export.OpenReadOnly(e.state)
973 if err != nil {
974 t.Fatal(err)
975 }
976 g, release, err := reader.Open()
977 defer release()
978 if err != nil || g.Sequence != first.Sequence {
979 t.Fatalf("the reader opened %v, %v; want the first generation", g, err)
980 }
981 second := e.upload()
982 // A sparse file makes the held generation large: the cap counts a
983 // file at its size, whatever blocks it takes.
984 pad, err := os.Create(filepath.Join(g.Dir, "padding"))
985 if err != nil {
986 t.Fatal(err)
987 }
988 if err := errors.Join(pad.Truncate(8<<20), pad.Close()); err != nil {
989 t.Fatal(err)
990 }
991
992 signed, _ := e.signedNow()
993 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
994 refused(t, "a manifest while a reader holds a large generation", status, reply, export.CodeTooLarge)
995 if hw := e.highWater(); hw != second.Sequence {
996 t.Errorf("high-water is %d, want %d", hw, second.Sequence)
997 }
998 release()
999 third := e.upload()
1000 if gens, _ := filepath.Glob(filepath.Join(e.state, "exports", "*")); len(gens) != 1 || filepath.Base(gens[0]) != strconv.FormatInt(third.Sequence, 10) {
1001 t.Errorf("the state directory holds the generations %v, want the third alone", gens)
1002 }
1003}
1004
1005// waitFor polls done until it reports true, and fails the test unless it
1006// does within waitTimeout. done is given a context that ends then, which
1007// bounds whatever request it makes.
1008func waitFor(t *testing.T, what string, done func(ctx context.Context) bool) {
1009 t.Helper()
1010 ctx, cancel := context.WithTimeout(context.Background(), waitTimeout)
1011 defer cancel()
1012 for ctx.Err() == nil {
1013 if done(ctx) {
1014 return
1015 }
1016 select {
1017 case <-ctx.Done():
1018 case <-time.After(20 * time.Millisecond):
1019 }
1020 }
1021 t.Fatalf("timed out waiting for %s", what)
1022}
1023
1024// The receiver stops on SIGTERM within its stop and drain timeouts, even
1025// with every connection it takes held: four by manifests stalled part
1026// way, which hold every request slot, and the rest by idle connections. A
1027// further connection waits in the listen queue.
1028func TestStopsOnSIGTERM(t *testing.T) {
1029 e := newEdge(t, exporttest.New(t))
1030 for range maxConns - maxRequests {
1031 e.idle()
1032 }
1033 signed, _ := e.signedNow()
1034 e.stallAll(signed)
1035 fmt.Fprintf(e.dial(), "OPTIONS * HTTP/1.1\r\nHost: %s\r\nContent-Length: 1\r\n\r\n", e.addr)
1036 began := time.Now()
1037 if err := e.proc.cmd.Process.Signal(syscall.SIGTERM); err != nil {
1038 t.Fatal(err)
1039 }
1040 select {
1041 case <-e.proc.done:
1042 case <-time.After(stopTimeout + drainTimeout + 10*time.Second):
1043 t.Fatalf("valley-web-receive did not stop within %v of SIGTERM", stopTimeout+drainTimeout+10*time.Second)
1044 }
1045 if e.proc.err != nil {
1046 t.Errorf("valley-web-receive stopped with %v", e.proc.err)
1047 }
1048 if took := time.Since(began); took > stopTimeout+drainTimeout+5*time.Second {
1049 t.Errorf("valley-web-receive took %v to stop, past its stop and drain timeouts of %v and %v", took, stopTimeout, drainTimeout)
1050 }
1051}
1052
1053// stallingGit is a git that stalls the first time it is asked to write a
1054// commit-graph, once it has fetched the bundle, and is the real git
1055// otherwise. The git that stalls is a shell that starts a child and waits
1056// for it. The child holds git's output open, so the receiver reads git's
1057// output to its end only once the child is gone too. stalled waits for the
1058// stall and returns the shell's process ID and the child's.
1059func stallingGit(t *testing.T) (git string, stalled func() (shell, child int)) {
1060 t.Helper()
1061 real, err := exec.LookPath(export.GitProgram)
1062 if err != nil {
1063 t.Fatal(err)
1064 }
1065 if real, err = filepath.Abs(real); err != nil {
1066 t.Fatal(err)
1067 }
1068 dir := t.TempDir()
1069 pids, once, git := filepath.Join(dir, "pids"), filepath.Join(dir, "stalled"), filepath.Join(dir, "git")
1070 script := `#!/bin/sh
1071for a; do
1072 if [ "$a" = commit-graph ] && mkdir '` + once + `' 2> /dev/null; then
1073 sleep 600 &
1074 echo $$ $! > '` + pids + `.tmp' && mv '` + pids + `.tmp' '` + pids + `'
1075 wait
1076 fi
1077done
1078exec '` + real + `' "$@"
1079`
1080 if err := os.WriteFile(git, []byte(script), 0o755); err != nil {
1081 t.Fatal(err)
1082 }
1083 return git, func() (shell, child int) {
1084 t.Helper()
1085 waitFor(t, "the commit's git to stall", func(context.Context) bool {
1086 data, err := os.ReadFile(pids)
1087 _, scanErr := fmt.Sscan(string(data), &shell, &child)
1088 return err == nil && scanErr == nil
1089 })
1090 return shell, child
1091 }
1092}
1093
1094// running reports whether the process pid has not exited. A zombie, which
1095// has exited and is not yet reaped, is not running.
1096func running(pid int) bool {
1097 data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
1098 if err != nil {
1099 return false
1100 }
1101 i := bytes.LastIndexByte(data, ')')
1102 state := strings.Fields(string(data[i+1:]))
1103 return len(state) > 0 && state[0] != "Z" && state[0] != "X"
1104}
1105
1106// A commit whose client goes away stops the git it runs, with every
1107// process that git started, even one that holds git's output open. The
1108// request then ends: it gives back the store's lock and its request slot,
1109// and keeps the bundle it was sent. So the manifest posted again needs
1110// nothing, and the commit made again activates the upload.
1111func TestACommitWhoseClientGoesAwayStopsItsGit(t *testing.T) {
1112 git, stalled := stallingGit(t)
1113 e := newEdgeWithGit(t, exporttest.New(t), git)
1114 signed, m := e.signedNow()
1115 for _, n := range e.post(signed).Needs {
1116 e.put(m, n.Name)
1117 }
1118 ctx, cancel := context.WithCancel(context.Background())
1119 defer cancel()
1120 committed := make(chan error, 1)
1121 go func() {
1122 _, _, _, err := e.do(ctx, http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
1123 committed <- err
1124 }()
1125 shell, child := stalled()
1126 cancel()
1127 if err := <-committed; err == nil {
1128 t.Error("the commit was answered, though its client went away")
1129 }
1130 waitFor(t, "the commit's git and its child to be killed", func(context.Context) bool {
1131 return !running(shell) && !running(child)
1132 })
1133 waitFor(t, "the receiver to give the commit up", func(context.Context) bool {
1134 return e.logged(export.CommitPath(m.Sequence), "git commit-graph")
1135 })
1136 if needs := e.post(signed).Needs; len(needs) != 0 {
1137 t.Errorf("once the commit was given up the upload needs %+v, want nothing", needs)
1138 }
1139 e.commit(m)
1140}
1141
1142// A stop that ends a commit waits for the commit's git to stop before the
1143// receiver exits, so neither git nor any process git started outlives
1144// it, even one that holds git's output open.
1145func TestAStopWaitsForTheGitACommitRuns(t *testing.T) {
1146 git, stalled := stallingGit(t)
1147 e := newEdgeWithGit(t, exporttest.New(t), git)
1148 signed, m := e.signedNow()
1149 for _, n := range e.post(signed).Needs {
1150 e.put(m, n.Name)
1151 }
1152 committed := make(chan error, 1)
1153 go func() {
1154 _, _, _, err := e.do(context.Background(), http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
1155 committed <- err
1156 }()
1157 shell, child := stalled()
1158
1159 if err := e.proc.cmd.Process.Signal(syscall.SIGTERM); err != nil {
1160 t.Fatal(err)
1161 }
1162 select {
1163 case <-e.proc.done:
1164 case <-time.After(stopTimeout + drainTimeout + 10*time.Second):
1165 t.Fatalf("valley-web-receive did not stop within %v of SIGTERM", stopTimeout+drainTimeout+10*time.Second)
1166 }
1167 if e.proc.err != nil {
1168 t.Errorf("valley-web-receive stopped with %v", e.proc.err)
1169 }
1170 if running(shell) || running(child) {
1171 t.Errorf("the commit's git, process %d, or its child, process %d, outlived the receiver", shell, child)
1172 }
1173 if e.logged("requests were still running") {
1174 t.Error("the receiver exited before the commit it stopped had finished")
1175 }
1176 if err := <-committed; err == nil {
1177 t.Error("the commit was answered, though the receiver stopped during it")
1178 }
1179 if hw := e.highWater(); hw != 0 {
1180 t.Errorf("high-water is %d after a commit the stop ended, want 0", hw)
1181 }
1182}
1183
1184// A command line it cannot run with gets the usage and exit status 2; a
1185// token file it cannot use, or verifiers it cannot read, exit status 1;
1186// --help gets the usage alone.
1187func TestUsage(t *testing.T) {
1188 tokenFile, verifiers := files(t)
1189 state := t.TempDir()
1190 base := []string{"--state", state, "--listen", "127.0.0.1:0", "--instance", "valley-host", "--destination", "example.org"}
1191 for _, args := range [][]string{
1192 {},
1193 append(base, "--verifiers", verifiers),
1194 append(base, "--token-file", tokenFile),
1195 {"--state", state, "--listen", "127.0.0.1:0", "--instance", "a b", "--destination", "example.org", "--verifiers", verifiers, "--token-file", tokenFile},
1196 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "--max-body", "0"),
1197 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "extra"),
1198 } {
1199 out, err := output(t, receiveCmd(args...))
1200 exit, ok := err.(*exec.ExitError)
1201 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web-receive") {
1202 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
1203 }
1204 }
1205 short := filepath.Join(t.TempDir(), "short")
1206 if err := os.WriteFile(short, []byte("too-short\n"), 0o600); err != nil {
1207 t.Fatal(err)
1208 }
1209 for _, args := range [][]string{
1210 append(base, "--verifiers", verifiers, "--token-file", short),
1211 append(base, "--verifiers", tokenFile, "--token-file", tokenFile),
1212 } {
1213 out, err := output(t, receiveCmd(args...))
1214 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
1215 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
1216 }
1217 if bytes.Contains(out, []byte(token)) {
1218 t.Errorf("valley-web-receive %q printed the token", args)
1219 }
1220 }
1221 out, err := output(t, receiveCmd("--help"))
1222 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web-receive") {
1223 t.Errorf("valley-web-receive --help gave %v:\n%s", err, out)
1224 }
1225}