gunk-dev/the-valley

main_test.go

sourceb39557ff3f00main's published tip history
46.8 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// with the flags given after --state and --listen, and returns where it
496// listens.
497func (e *edge) valleyWeb(more ...string) string {
498 e.t.Helper()
499 bin := os.Getenv("VALLEY_WEB")
500 if bin == "" {
501 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
502 e.t.Fatal("VALLEY_WEB names no valley-web, and VALLEY_TEST_TOOLS=required")
503 }
504 e.t.Skip("VALLEY_WEB names no valley-web; the nix check provides one")
505 }
506 return start(e.t, command(bin, append([]string{"--state", e.store, "--listen", "127.0.0.1:0"}, more...)...), "valley-web").addr
507}
508
509// serves checks that valley-web at addr answers every page of the
510// fixture's export.
511func (e *edge) serves(addr string) {
512 e.t.Helper()
513 tip := e.f.Export.Projects[0].SourceTip
514 for target, status := range map[string]int{
515 "/": http.StatusOK,
516 "/-/knots": http.StatusOK,
517 "/app/knots/oc-a000002": http.StatusOK,
518 "/app/source/tree/" + tip + "/": http.StatusOK,
519 "/app/source/log/" + tip: http.StatusOK,
520 "/site/source/": http.StatusNotFound,
521 } {
522 res, err := client.Get("http://" + addr + target)
523 if err != nil {
524 e.t.Fatal(err)
525 }
526 page, _ := io.ReadAll(res.Body)
527 res.Body.Close()
528 if res.StatusCode != status {
529 e.t.Errorf("valley-web answered GET %s with %d, want %d:\n%s", target, res.StatusCode, status, page)
530 }
531 }
532}
533
534// An upload of the three steps activates the export, and valley-web, as a
535// process of its own over the same state directory, serves it. The
536// manifest posted again, and the commit made again, are refused as
537// replayed, with the high-water mark.
538func TestAnUploadActivatesAndValleyWebServesIt(t *testing.T) {
539 e := newEdge(t, exporttest.New(t))
540 signed, m := e.signedNow()
541 inv := e.post(signed)
542 if inv.Active != nil || len(inv.Needs) != 2 || inv.Needs[0].Name != export.ExportFile || inv.Needs[1].Name != "app" {
543 t.Fatalf("the first inventory is %+v, want no active export and both bodies needed, export.json first", inv)
544 }
545 again := e.post(signed)
546 if len(again.Needs) != 2 {
547 t.Errorf("the manifest posted again needs %+v, want both bodies still", again.Needs)
548 }
549 e.put(m, export.ExportFile)
550 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != "app" {
551 t.Errorf("the manifest posted after export.json needs %+v, want app's bundle alone", needs)
552 }
553 e.put(m, "app")
554 e.put(m, "app") // a body already staged is accepted again
555 e.commit(m)
556 if hw := e.highWater(); hw != m.Sequence {
557 t.Errorf("high-water is %d after the commit, want %d", hw, m.Sequence)
558 }
559 e.serves(e.valleyWeb())
560
561 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
562 if r := refused(t, "the manifest posted after its commit", status, reply, export.CodeReplayed); r.HighWater != m.Sequence {
563 t.Errorf("the replayed refusal gives high-water %d, want %d", r.HighWater, m.Sequence)
564 }
565 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
566 refused(t, "the commit made again", status, reply, export.CodeReplayed)
567
568 // The next upload carries app's repository over, and needs export.json
569 // alone.
570 signed, m = e.signedNow()
571 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != export.ExportFile {
572 t.Errorf("the next upload needs %+v, want export.json alone", needs)
573 }
574 e.put(m, export.ExportFile)
575 e.commit(m)
576}
577
578// A request without the token is refused as unauthenticated, whatever it
579// asks, and stages nothing. So is one with another token, or with the
580// token twice.
581func TestAnUnauthenticatedRequestIsRefused(t *testing.T) {
582 e := newEdge(t, exporttest.New(t))
583 signed, m := e.signedNow()
584 send := func(what, method, path string, body []byte, auth []string) {
585 t.Helper()
586 req, err := http.NewRequest(method, "http://"+e.addr+path, bytes.NewReader(body))
587 if err != nil {
588 t.Fatal(err)
589 }
590 req.Header["Authorization"] = auth
591 res, err := client.Do(req)
592 if err != nil {
593 t.Fatal(err)
594 }
595 reply, _ := io.ReadAll(res.Body)
596 res.Body.Close()
597 refused(t, what, res.StatusCode, reply, export.CodeUnauthenticated)
598 if !strings.HasPrefix(res.Header.Get("WWW-Authenticate"), "Bearer ") {
599 t.Errorf("%s: the refusal names no scheme to authenticate with", what)
600 }
601 }
602 send("a manifest with no token", http.MethodPost, export.ManifestPath, signed, nil)
603 send("a manifest with another token", http.MethodPost, export.ManifestPath, signed, []string{export.BearerHeader(token + "x")})
604 send("a manifest with the token in another scheme", http.MethodPost, export.ManifestPath, signed, []string{"Basic " + token})
605 send("a manifest with the token twice", http.MethodPost, export.ManifestPath, signed,
606 []string{export.BearerHeader(token), export.BearerHeader(token)})
607 send("a body with no token", http.MethodPut, export.BodyPath(m.Sequence, m.File.SHA256), e.f.ExportJSON, nil)
608 send("a commit with no token", http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
609 send("a path the upload does not use", http.MethodGet, "/", nil, nil)
610 if staged := e.staged(); len(staged) != 0 || e.highWater() != 0 {
611 t.Errorf("unauthenticated requests left %v staged and high-water %d", staged, e.highWater())
612 }
613}
614
615// A manifest is refused when it is stale, signed ahead of the receiver's
616// clock, signed by another key, or for another receiver; and an older
617// manifest than the one staged is superseded. None of them is staged.
618func TestAManifestIsAdmittedOnlyWhenFresh(t *testing.T) {
619 e := newEdge(t, exporttest.New(t))
620 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
621 now := time.Now()
622 for _, c := range []struct {
623 what string
624 at time.Time
625 key ed25519.PrivateKey
626 destination string
627 code export.Code
628 }{
629 {"a manifest signed four days ago", now.Add(-96 * time.Hour), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
630 {"a manifest signed two minutes ahead", now.Add(2 * time.Minute), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
631 {"a manifest signed by another key", now, other, exporttest.Destination, export.CodeBadSignature},
632 {"a manifest for another receiver", now, exporttest.Key(), "elsewhere.example.org", export.CodeWrongDestination},
633 } {
634 signed, _ := e.manifest(c.at.UnixNano(), c.key, c.destination)
635 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
636 refused(t, c.what, status, reply, c.code)
637 }
638 if staged := e.staged(); len(staged) != 0 {
639 t.Errorf("refused manifests left %v staged", staged)
640 }
641
642 older, om := e.manifest(now.Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
643 newer, _ := e.signedNow()
644 e.post(newer)
645 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, older, nil)
646 refused(t, "a manifest older than the one staged", status, reply, export.CodeSuperseded)
647 status, reply, _ = e.request(http.MethodPut, export.BodyPath(om.Sequence, om.File.SHA256), e.f.ExportJSON, nil)
648 refused(t, "a body of the older upload", status, reply, export.CodeSuperseded)
649 status, reply, _ = e.request(http.MethodPost, export.CommitPath(om.Sequence+1e12), nil, nil)
650 refused(t, "a commit of an upload never staged", status, reply, export.CodeNoManifest)
651}
652
653// A body is refused when its bytes are not what the manifest declares: a
654// hash mismatch, a size mismatch whether or not the length is given, a
655// Content-Encoding, or a hash the manifest does not declare. An upload
656// cut off part way through a body is refused at the commit as incomplete,
657// and the active export stays as it was until the body is sent whole.
658func TestABodyIsKeptOnlyWhenItVerifies(t *testing.T) {
659 e := newEdge(t, exporttest.New(t))
660 first := e.upload()
661 signed, m := e.signedNow()
662 // A second upload of the same export needs export.json again, staged
663 // for it, and no bundle: app's repository is carried over.
664 if needs := e.post(signed).Needs; len(needs) != 1 {
665 t.Fatalf("the second upload needs %+v, want export.json alone", needs)
666 }
667 file := body(t, m, export.ExportFile)
668 path := export.BodyPath(m.Sequence, file.SHA256)
669 wrong := append([]byte{}, e.f.ExportJSON...)
670 wrong[0] ^= 1
671
672 status, reply, _ := e.request(http.MethodPut, path, wrong, nil)
673 refused(t, "a body with other bytes of the same size", status, reply, export.CodeHashMismatch)
674 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON[1:], nil)
675 refused(t, "a body one byte short", status, reply, export.CodeSizeMismatch)
676 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON, http.Header{"Content-Encoding": {"gzip"}})
677 refused(t, "a body with a Content-Encoding", status, reply, export.CodeEncoding)
678 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, strings.Repeat("0", 64)), e.f.ExportJSON, nil)
679 refused(t, "a body the manifest does not declare", status, reply, export.CodeNotDeclared)
680
681 // Sent with no length, one byte long.
682 req, err := http.NewRequest(http.MethodPut, "http://"+e.addr+path, io.MultiReader(bytes.NewReader(e.f.ExportJSON), strings.NewReader("x")))
683 if err != nil {
684 t.Fatal(err)
685 }
686 req.Header.Set("Authorization", export.BearerHeader(token))
687 res, err := client.Do(req)
688 if err != nil {
689 t.Fatal(err)
690 }
691 reply, _ = io.ReadAll(res.Body)
692 res.Body.Close()
693 refused(t, "a body one byte long, sent with no length", res.StatusCode, reply, export.CodeSizeMismatch)
694
695 // Sent while another request is staging it: staging holds one partial
696 // file of each body.
697 stalled := e.stall(http.MethodPut, path, e.f.ExportJSON)
698 if stalled == nil {
699 t.Fatal("the receiver answered a stalled body at once")
700 }
701 status, reply, header := e.request(http.MethodPut, path, e.f.ExportJSON, nil)
702 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
703 t.Errorf("a body sent while another request stages it was answered %d %s, want 503 with Retry-After", status, reply)
704 }
705 stalled.Close()
706
707 // Cut off half way.
708 c := e.dial()
709 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)
710 c.Write(e.f.ExportJSON[:file.Size/2])
711 c.Close()
712
713 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
714 r := refused(t, "a commit after the body was cut off", status, reply, export.CodeIncomplete)
715 if len(r.Needs) != 1 || r.Needs[0].SHA256 != file.SHA256 {
716 t.Errorf("the incomplete refusal needs %+v, want export.json", r.Needs)
717 }
718 if hw := e.highWater(); hw != first.Sequence {
719 t.Errorf("high-water moved to %d on refused bodies, want %d", hw, first.Sequence)
720 }
721 // The receiver removes what it read of the cut-off body once it sees
722 // the connection close.
723 waitFor(t, "no body left in staging", func(context.Context) bool {
724 partial, _ := filepath.Glob(filepath.Join(e.state, "staging", "*", "bodies", "*"))
725 return len(partial) == 0
726 })
727 e.put(m, export.ExportFile)
728 e.commit(m)
729}
730
731// A manifest whose body is larger than --max-body, or whose bodies
732// together are larger than --max-upload, is refused as too-large and
733// staged not at all.
734func TestAnOversizedUploadIsRefused(t *testing.T) {
735 f := exporttest.New(t)
736 size := func(name string) int64 { return int64(len(f.BodyBytes(t, name))) }
737 for _, c := range []struct {
738 what string
739 flags []string
740 }{
741 {"a body over --max-body", []string{"--max-body", strconv.FormatInt(size(export.ExportFile)-1, 10)}},
742 {"bodies over --max-upload", []string{"--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app")-1, 10)}},
743 } {
744 e := newEdge(t, f, c.flags...)
745 signed, _ := e.signedNow()
746 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
747 refused(t, c.what, status, reply, export.CodeTooLarge)
748 if staged := e.staged(); len(staged) != 0 {
749 t.Errorf("%s: the refused manifest left %v staged", c.what, staged)
750 }
751 }
752 // At the caps exactly, the upload is accepted.
753 e := newEdge(t, f, "--max-body", strconv.FormatInt(max(size(export.ExportFile), size("app")), 10),
754 "--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app"), 10))
755 e.upload()
756}
757
758// A saturated receiver answers 503 to a request past its slots, and
759// valley-web, a process of its own over the same state directory, keeps
760// serving every page. A request without the token is still refused as
761// unauthenticated, taking no slot. Once the stalled requests go away, the
762// receiver takes uploads again.
763//
764// Then every connection the receiver takes is held by a client that sends
765// part of a request's headers and stops. valley-web keeps serving. A body
766// sent meanwhile waits in the listen queue until the header timeout closes
767// those connections, and no longer.
768func TestASaturatedUploadLeavesValleyWebServing(t *testing.T) {
769 e := newEdge(t, exporttest.New(t))
770 e.upload()
771 web := e.valleyWeb()
772 signed, m := e.signedNow()
773 e.post(signed)
774 probe := export.BodyPath(m.Sequence, strings.Repeat("0", 64))
775
776 stalled := e.stallAll(signed)
777 status, _, header := e.request(http.MethodPut, probe, []byte("x"), nil)
778 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
779 t.Errorf("a request past every slot was answered %d, want 503 with Retry-After", status)
780 }
781 res, err := client.Post("http://"+e.addr+export.ManifestPath, "", bytes.NewReader(signed))
782 if err != nil {
783 t.Fatal(err)
784 }
785 reply, _ := io.ReadAll(res.Body)
786 res.Body.Close()
787 refused(t, "a manifest with no token while the receiver is saturated", res.StatusCode, reply, export.CodeUnauthenticated)
788 e.serves(web)
789 // Authorizations have slots of their own, and take no activation
790 // lock, so one is stored while uploads hold every upload slot.
791 if status, reply := e.authorize(2, "app"); status != http.StatusOK {
792 t.Errorf("an authorization while uploads hold every slot was answered %d: %s", status, reply)
793 }
794
795 for _, c := range stalled {
796 c.Close()
797 }
798 waitFor(t, "the receiver to take requests again", func(ctx context.Context) bool {
799 status, _, _, err := e.do(ctx, http.MethodPut, probe, []byte("x"), nil)
800 return err == nil && status == http.StatusNotFound
801 })
802
803 for range maxConns {
804 fmt.Fprintf(e.dial(), "PUT %s HTTP/1.1\r\nHost: %s\r\n", probe, e.addr)
805 }
806 began := time.Now()
807 e.serves(web)
808 e.put(m, export.ExportFile)
809 if took := time.Since(began); took < headerTimeout/2 || took > headerTimeout+5*time.Second {
810 t.Errorf("a body sent behind a connection on every slot was answered after %v, want about the header timeout, %v", took, headerTimeout)
811 }
812 e.commit(m)
813 e.serves(web)
814}
815
816// OPTIONS * is the receiver's to answer, as any other request is: refused
817// as unauthenticated without the token, and 404 with it. Either is
818// answered at once, without reading the body it declares, and its
819// connection is closed. So OPTIONS * requests that withhold their bodies,
820// one on every connection the receiver takes, hold none of them, and an
821// upload goes through.
822func TestOptionsStarHoldsNoConnection(t *testing.T) {
823 e := newEdge(t, exporttest.New(t))
824 conns := make([]net.Conn, maxConns)
825 for i := range conns {
826 auth := ""
827 if i%2 == 1 {
828 auth = "Authorization: " + export.BearerHeader(token) + "\r\n"
829 }
830 conns[i] = e.dial()
831 fmt.Fprintf(conns[i], "OPTIONS * HTTP/1.1\r\nHost: %s\r\n%sContent-Length: 1\r\n\r\n", e.addr, auth)
832 }
833 e.upload()
834 for i, c := range conns {
835 c.SetReadDeadline(time.Now().Add(requestTimeout))
836 res, err := http.ReadResponse(bufio.NewReader(c), nil)
837 if err != nil {
838 t.Fatalf("OPTIONS * on connection %d was not answered: %v", i, err)
839 }
840 reply, _ := io.ReadAll(res.Body)
841 res.Body.Close()
842 if i%2 == 0 {
843 refused(t, "OPTIONS * with no token", res.StatusCode, reply, export.CodeUnauthenticated)
844 } else if res.StatusCode != http.StatusNotFound {
845 t.Errorf("OPTIONS * with the token was answered %d, want 404", res.StatusCode)
846 }
847 if !res.Close {
848 t.Errorf("the receiver kept the connection of OPTIONS * open")
849 }
850 }
851}
852
853// A manifest waits for the store's lock, which a commit holds throughout,
854// and stages nothing once its client goes away. Here the test holds the
855// lock, as a commit does.
856func TestAManifestStopsWaitingWhenItsClientGoesAway(t *testing.T) {
857 e := newEdge(t, exporttest.New(t))
858 e.upload()
859 lock, err := os.OpenFile(filepath.Join(e.state, "lock"), os.O_RDWR, 0)
860 if err != nil {
861 t.Fatal(err)
862 }
863 defer lock.Close()
864 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
865 t.Fatal(err)
866 }
867 signed, _ := e.signedNow()
868 c := e.dial()
869 fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n%s",
870 export.ManifestPath, e.addr, export.BearerHeader(token), len(signed), signed)
871 if answered(c, time.Second) {
872 t.Fatal("the manifest was answered while the store's lock was held")
873 }
874 c.Close()
875 waitFor(t, "the receiver to give the manifest up", func(context.Context) bool {
876 return e.logged(export.ManifestPath, "waiting for the lock", "context canceled")
877 })
878 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_UN); err != nil {
879 t.Fatal(err)
880 }
881 if staged := e.staged(); len(staged) != 0 {
882 t.Errorf("a manifest whose client went away left %v staged", staged)
883 }
884 e.upload()
885}
886
887// A manifest whose upload would take the state directory past
888// --max-storage is refused as too-large, and nothing is staged. The cap
889// counts a repository for every project, so a manifest that names one
890// bundle for many projects, which --max-upload counts once, is held to it
891// too. An upload within the cap is accepted.
892func TestAnUploadPastTheStorageCapIsRefused(t *testing.T) {
893 e := newEdge(t, exporttest.New(t), "--max-storage", "4M")
894 x := *e.f.Export
895 x.Projects = append([]export.Project{}, x.Projects...)
896 bundles := map[string]export.Body{}
897 for _, p := range e.f.Manifest.Projects {
898 bundles[p.Name] = p.Bundle
899 }
900 for i := range 6 {
901 p := x.Projects[0]
902 p.Name = fmt.Sprintf("%s-%d", p.Name, i)
903 x.Projects = append(x.Projects, p)
904 bundles[p.Name] = bundles[x.Projects[0].Name]
905 }
906 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, time.Now().UnixNano(), &x, e.f.ExportJSON, bundles)
907 if err != nil {
908 t.Fatal(err)
909 }
910 if err := m.CheckSizes(1<<30, 2<<30); err != nil {
911 t.Fatalf("the manifest is not within --max-upload: %v", err)
912 }
913 signed, err := m.Sign(exporttest.SignerName, exporttest.Key())
914 if err != nil {
915 t.Fatal(err)
916 }
917 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
918 refused(t, "a manifest naming one bundle for eight projects", status, reply, export.CodeTooLarge)
919 if staged := e.staged(); len(staged) != 0 {
920 t.Errorf("the refused manifest left %v staged", staged)
921 }
922 e.upload()
923 e.upload()
924}
925
926// openPartials are the partial body files the receiver holds open, as
927// /proc names them. A file deleted while it is open keeps its name there.
928func (e *edge) openPartials() []string {
929 e.t.Helper()
930 fds, err := filepath.Glob(fmt.Sprintf("/proc/%d/fd/*", e.proc.cmd.Process.Pid))
931 if err != nil {
932 e.t.Fatal(err)
933 }
934 var open []string
935 for _, fd := range fds {
936 if target, err := os.Readlink(fd); err == nil && strings.Contains(target, "/.partial-") {
937 open = append(open, target)
938 }
939 }
940 return open
941}
942
943// A newer manifest stops the older upload's body requests before it
944// deletes the older upload. Each is answered as superseded, and once the
945// newer manifest is answered the receiver holds no partial file of the
946// older upload open, where the disk it takes would be counted by nothing.
947// The newer upload's request for the same body is then accepted, not
948// answered 503 as a body another request is staging.
949func TestANewerManifestStopsTheOlderUploadsBodies(t *testing.T) {
950 e := newEdge(t, exporttest.New(t))
951 older, om := e.manifest(time.Now().Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
952 e.post(older)
953 file := body(t, om, export.ExportFile)
954 stalled := e.stall(http.MethodPut, export.BodyPath(om.Sequence, file.SHA256), e.f.ExportJSON)
955 if stalled == nil {
956 t.Fatal("the receiver answered a stalled body at once")
957 }
958 waitFor(t, "the receiver to open the stalled body's partial file", func(context.Context) bool {
959 return len(e.openPartials()) == 1
960 })
961
962 newer, nm := e.signedNow()
963 e.post(newer)
964 if open := e.openPartials(); len(open) != 0 {
965 t.Errorf("once the newer manifest was answered, the receiver holds %q open", open)
966 }
967 stalled.SetReadDeadline(time.Now().Add(requestTimeout))
968 res, err := http.ReadResponse(bufio.NewReader(stalled), nil)
969 if err != nil {
970 t.Fatalf("the older upload's stalled body was not answered: %v", err)
971 }
972 reply, _ := io.ReadAll(res.Body)
973 res.Body.Close()
974 refused(t, "the older upload's stalled body", res.StatusCode, reply, export.CodeSuperseded)
975 if staged := e.staged(); len(staged) != 1 || staged[0] != strconv.FormatInt(nm.Sequence, 10) {
976 t.Errorf("staging holds %v, want the newer upload alone", staged)
977 }
978 status, reply, _ := e.request(http.MethodPut, export.BodyPath(nm.Sequence, file.SHA256), e.f.ExportJSON, nil)
979 if status != http.StatusNoContent {
980 t.Errorf("the newer upload's export.json was answered %d %s, want 204", status, reply)
981 }
982 for _, n := range e.post(newer).Needs {
983 e.put(nm, n.Name)
984 }
985 e.commit(nm)
986}
987
988// A generation a reader holds is kept past the activation that replaces
989// it, and counts against --max-storage. While a reader holds a large one,
990// a manifest whose upload would pass the cap is refused as too-large. Once
991// the reader lets it go, the next manifest finds the room: the receiver
992// deletes the generation before it refuses anything for space.
993func TestAReleasedGenerationMakesRoomForAnUpload(t *testing.T) {
994 e := newEdge(t, exporttest.New(t), "--max-storage", "6M")
995 first := e.upload()
996 reader, err := export.OpenReadOnly(e.store)
997 if err != nil {
998 t.Fatal(err)
999 }
1000 g, release, err := reader.Open()
1001 defer release()
1002 if err != nil || g.Sequence != first.Sequence {
1003 t.Fatalf("the reader opened %v, %v; want the first generation", g, err)
1004 }
1005 second := e.upload()
1006 // A sparse file makes the held generation large: the cap counts a
1007 // file at its size, whatever blocks it takes.
1008 pad, err := os.Create(filepath.Join(g.Dir, "padding"))
1009 if err != nil {
1010 t.Fatal(err)
1011 }
1012 if err := errors.Join(pad.Truncate(8<<20), pad.Close()); err != nil {
1013 t.Fatal(err)
1014 }
1015
1016 signed, _ := e.signedNow()
1017 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
1018 refused(t, "a manifest while a reader holds a large generation", status, reply, export.CodeTooLarge)
1019 if hw := e.highWater(); hw != second.Sequence {
1020 t.Errorf("high-water is %d, want %d", hw, second.Sequence)
1021 }
1022 release()
1023 third := e.upload()
1024 if gens, _ := filepath.Glob(filepath.Join(e.state, "generations", "*")); len(gens) != 1 || filepath.Base(gens[0]) != strconv.FormatInt(third.Sequence, 10) {
1025 t.Errorf("the state directory holds the generations %v, want the third alone", gens)
1026 }
1027}
1028
1029// waitFor polls done until it reports true, and fails the test unless it
1030// does within waitTimeout. done is given a context that ends then, which
1031// bounds whatever request it makes.
1032func waitFor(t *testing.T, what string, done func(ctx context.Context) bool) {
1033 t.Helper()
1034 ctx, cancel := context.WithTimeout(context.Background(), waitTimeout)
1035 defer cancel()
1036 for ctx.Err() == nil {
1037 if done(ctx) {
1038 return
1039 }
1040 select {
1041 case <-ctx.Done():
1042 case <-time.After(20 * time.Millisecond):
1043 }
1044 }
1045 t.Fatalf("timed out waiting for %s", what)
1046}
1047
1048// The receiver stops on SIGTERM within its stop and drain timeouts, even
1049// with every connection it takes held: four by manifests stalled part
1050// way, which hold every request slot, and the rest by idle connections. A
1051// further connection waits in the listen queue.
1052func TestStopsOnSIGTERM(t *testing.T) {
1053 e := newEdge(t, exporttest.New(t))
1054 for range maxConns - maxRequests {
1055 e.idle()
1056 }
1057 signed, _ := e.signedNow()
1058 e.stallAll(signed)
1059 fmt.Fprintf(e.dial(), "OPTIONS * HTTP/1.1\r\nHost: %s\r\nContent-Length: 1\r\n\r\n", e.addr)
1060 began := time.Now()
1061 if err := e.proc.cmd.Process.Signal(syscall.SIGTERM); err != nil {
1062 t.Fatal(err)
1063 }
1064 select {
1065 case <-e.proc.done:
1066 case <-time.After(stopTimeout + drainTimeout + 10*time.Second):
1067 t.Fatalf("valley-web-receive did not stop within %v of SIGTERM", stopTimeout+drainTimeout+10*time.Second)
1068 }
1069 if e.proc.err != nil {
1070 t.Errorf("valley-web-receive stopped with %v", e.proc.err)
1071 }
1072 if took := time.Since(began); took > stopTimeout+drainTimeout+5*time.Second {
1073 t.Errorf("valley-web-receive took %v to stop, past its stop and drain timeouts of %v and %v", took, stopTimeout, drainTimeout)
1074 }
1075}
1076
1077// stallingGit is a git that stalls the first time it is asked to write a
1078// commit-graph, once it has fetched the bundle, and is the real git
1079// otherwise. The git that stalls is a shell that starts a child and waits
1080// for it. The child holds git's output open, so the receiver reads git's
1081// output to its end only once the child is gone too. stalled waits for the
1082// stall and returns the shell's process ID and the child's.
1083func stallingGit(t *testing.T) (git string, stalled func() (shell, child int)) {
1084 t.Helper()
1085 real, err := exec.LookPath(export.GitProgram)
1086 if err != nil {
1087 t.Fatal(err)
1088 }
1089 if real, err = filepath.Abs(real); err != nil {
1090 t.Fatal(err)
1091 }
1092 dir := t.TempDir()
1093 pids, once, git := filepath.Join(dir, "pids"), filepath.Join(dir, "stalled"), filepath.Join(dir, "git")
1094 script := `#!/bin/sh
1095for a; do
1096 if [ "$a" = commit-graph ] && mkdir '` + once + `' 2> /dev/null; then
1097 sleep 600 &
1098 echo $$ $! > '` + pids + `.tmp' && mv '` + pids + `.tmp' '` + pids + `'
1099 wait
1100 fi
1101done
1102exec '` + real + `' "$@"
1103`
1104 if err := os.WriteFile(git, []byte(script), 0o755); err != nil {
1105 t.Fatal(err)
1106 }
1107 return git, func() (shell, child int) {
1108 t.Helper()
1109 waitFor(t, "the commit's git to stall", func(context.Context) bool {
1110 data, err := os.ReadFile(pids)
1111 _, scanErr := fmt.Sscan(string(data), &shell, &child)
1112 return err == nil && scanErr == nil
1113 })
1114 return shell, child
1115 }
1116}
1117
1118// running reports whether the process pid has not exited. A zombie, which
1119// has exited and is not yet reaped, is not running.
1120func running(pid int) bool {
1121 data, err := os.ReadFile(fmt.Sprintf("/proc/%d/stat", pid))
1122 if err != nil {
1123 return false
1124 }
1125 i := bytes.LastIndexByte(data, ')')
1126 state := strings.Fields(string(data[i+1:]))
1127 return len(state) > 0 && state[0] != "Z" && state[0] != "X"
1128}
1129
1130// A commit whose client goes away stops the git it runs, with every
1131// process that git started, even one that holds git's output open. The
1132// request then ends: it gives back the store's lock and its request slot,
1133// and keeps the bundle it was sent. So the manifest posted again needs
1134// nothing, and the commit made again activates the upload.
1135func TestACommitWhoseClientGoesAwayStopsItsGit(t *testing.T) {
1136 git, stalled := stallingGit(t)
1137 e := newEdgeWithGit(t, exporttest.New(t), git)
1138 signed, m := e.signedNow()
1139 for _, n := range e.post(signed).Needs {
1140 e.put(m, n.Name)
1141 }
1142 ctx, cancel := context.WithCancel(context.Background())
1143 defer cancel()
1144 committed := make(chan error, 1)
1145 go func() {
1146 _, _, _, err := e.do(ctx, http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
1147 committed <- err
1148 }()
1149 shell, child := stalled()
1150 cancel()
1151 if err := <-committed; err == nil {
1152 t.Error("the commit was answered, though its client went away")
1153 }
1154 waitFor(t, "the commit's git and its child to be killed", func(context.Context) bool {
1155 return !running(shell) && !running(child)
1156 })
1157 waitFor(t, "the receiver to give the commit up", func(context.Context) bool {
1158 return e.logged(export.CommitPath(m.Sequence), "git commit-graph")
1159 })
1160 if needs := e.post(signed).Needs; len(needs) != 0 {
1161 t.Errorf("once the commit was given up the upload needs %+v, want nothing", needs)
1162 }
1163 e.commit(m)
1164}
1165
1166// A stop that ends a commit waits for the commit's git to stop before the
1167// receiver exits, so neither git nor any process git started outlives
1168// it, even one that holds git's output open.
1169func TestAStopWaitsForTheGitACommitRuns(t *testing.T) {
1170 git, stalled := stallingGit(t)
1171 e := newEdgeWithGit(t, exporttest.New(t), git)
1172 signed, m := e.signedNow()
1173 for _, n := range e.post(signed).Needs {
1174 e.put(m, n.Name)
1175 }
1176 committed := make(chan error, 1)
1177 go func() {
1178 _, _, _, err := e.do(context.Background(), http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
1179 committed <- err
1180 }()
1181 shell, child := stalled()
1182
1183 if err := e.proc.cmd.Process.Signal(syscall.SIGTERM); err != nil {
1184 t.Fatal(err)
1185 }
1186 select {
1187 case <-e.proc.done:
1188 case <-time.After(stopTimeout + drainTimeout + 10*time.Second):
1189 t.Fatalf("valley-web-receive did not stop within %v of SIGTERM", stopTimeout+drainTimeout+10*time.Second)
1190 }
1191 if e.proc.err != nil {
1192 t.Errorf("valley-web-receive stopped with %v", e.proc.err)
1193 }
1194 if running(shell) || running(child) {
1195 t.Errorf("the commit's git, process %d, or its child, process %d, outlived the receiver", shell, child)
1196 }
1197 if e.logged("requests were still running") {
1198 t.Error("the receiver exited before the commit it stopped had finished")
1199 }
1200 if err := <-committed; err == nil {
1201 t.Error("the commit was answered, though the receiver stopped during it")
1202 }
1203 if hw := e.highWater(); hw != 0 {
1204 t.Errorf("high-water is %d after a commit the stop ended, want 0", hw)
1205 }
1206}
1207
1208// A command line it cannot run with gets the usage and exit status 2; a
1209// token file it cannot use, or verifiers it cannot read, exit status 1;
1210// --help gets the usage alone.
1211func TestUsage(t *testing.T) {
1212 tokenFile, verifiers := files(t)
1213 state := t.TempDir()
1214 base := []string{"--state", state, "--listen", "127.0.0.1:0", "--instance", "valley-host", "--destination", "example.org"}
1215 for _, args := range [][]string{
1216 {},
1217 append(base, "--verifiers", verifiers),
1218 append(base, "--token-file", tokenFile),
1219 {"--state", state, "--listen", "127.0.0.1:0", "--instance", "a b", "--destination", "example.org", "--verifiers", verifiers, "--token-file", tokenFile},
1220 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "--max-body", "0"),
1221 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "extra"),
1222 } {
1223 out, err := output(t, receiveCmd(args...))
1224 exit, ok := err.(*exec.ExitError)
1225 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web-receive") {
1226 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
1227 }
1228 }
1229 short := filepath.Join(t.TempDir(), "short")
1230 if err := os.WriteFile(short, []byte("too-short\n"), 0o600); err != nil {
1231 t.Fatal(err)
1232 }
1233 for _, args := range [][]string{
1234 append(base, "--verifiers", verifiers, "--token-file", short),
1235 append(base, "--verifiers", tokenFile, "--token-file", tokenFile),
1236 } {
1237 out, err := output(t, receiveCmd(args...))
1238 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
1239 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
1240 }
1241 if bytes.Contains(out, []byte(token)) {
1242 t.Errorf("valley-web-receive %q printed the token", args)
1243 }
1244 }
1245 out, err := output(t, receiveCmd("--help"))
1246 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web-receive") {
1247 t.Errorf("valley-web-receive --help gave %v:\n%s", err, out)
1248 }
1249}
1250
1251// The receiver admits an authorization by its sequence alone: one checked
1252// long ago, with a sequence above the stored one's, is stored, and the
1253// same one posted again is refused as replayed. Its reply says what the
1254// receiver serves. A path of the first protocol is refused with
1255// unsupported-version.
1256func TestAnAuthorizationIsAdmittedBySequence(t *testing.T) {
1257 e := newEdge(t, exporttest.New(t))
1258 e.upload()
1259 old := exporttest.Authorization(7, "app")
1260 old.Checked = time.Date(2001, 1, 1, 0, 0, 0, 0, time.UTC)
1261 signed := exporttest.SignAuthorization(t, old)
1262 status, reply, _ := e.request(http.MethodPost, export.AuthorizationPath, signed, nil)
1263 var got export.AuthorizationReply
1264 if err := json.Unmarshal(reply, &got); status != http.StatusOK || err != nil || got.Schema != export.AuthorizedSchema ||
1265 got.Sequence != 7 || got.Active == nil || len(got.Missing) != 0 {
1266 t.Errorf("an old-dated authorization above the stored one was answered %d: %s", status, reply)
1267 }
1268 status, reply, _ = e.request(http.MethodPost, export.AuthorizationPath, signed, nil)
1269 refused(t, "the same authorization again", status, reply, export.CodeReplayed)
1270 status, reply, _ = e.request(http.MethodPost, "/web-export/v1/manifest", e.f.Signed, nil)
1271 refused(t, "a manifest of the first protocol", status, reply, export.CodeUnsupportedVersion)
1272 if !strings.Contains(string(reply), "upgrade valley-web-publish") {
1273 t.Errorf("the refusal of the first protocol does not say what to upgrade: %s", reply)
1274 }
1275}