gunk-dev/the-valley

main_test.go

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