gunk-dev/the-valley

main_test.go

sourced8836c968fcfmain's published tip history
28.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. Uploads are
30// the shared fixture's export, under manifests signed now with the
31// fixture's key, and they are accepted with real git. valley-web is the
32// real program, which VALLEY_WEB names.
33func TestMain(m *testing.M) {
34 if os.Getenv("VALLEY_WEB_RECEIVE_TEST_MAIN") == "1" {
35 main()
36 os.Exit(0)
37 }
38 os.Exit(m.Run())
39}
40
41const token = "receiver-test-token-0123456789abcdef"
42
43// How long a test waits for a request, a dial, or anything it polls for.
44// Every wait here is bounded, so a receiver that stops answering fails the
45// test rather than hanging it.
46const (
47 requestTimeout = 30 * time.Second
48 dialTimeout = 5 * time.Second
49 waitTimeout = 20 * time.Second
50)
51
52// client makes every request the tests make, each within requestTimeout,
53// on a connection of its own that it closes after the reply. A connection
54// kept for the next request would hold one of the receiver's, which the
55// tests that fill them count on being free.
56var client = &http.Client{
57 Timeout: requestTimeout,
58 Transport: &http.Transport{
59 DisableKeepAlives: true,
60 DialContext: (&net.Dialer{Timeout: dialTimeout}).DialContext,
61 },
62}
63
64// edge is a receiver running over a state directory, and the fixture it
65// is sent.
66type edge struct {
67 t *testing.T
68 f *exporttest.Fixture
69 state string
70 addr string
71 proc *proc
72}
73
74// files writes the token file and the verifier file a receiver is given.
75func files(t *testing.T) (tokenFile, verifiers string) {
76 t.Helper()
77 dir := t.TempDir()
78 tokenFile, verifiers = filepath.Join(dir, "token"), filepath.Join(dir, "verifiers")
79 if err := os.WriteFile(tokenFile, []byte(token+"\n"), 0o600); err != nil {
80 t.Fatal(err)
81 }
82 if err := os.WriteFile(verifiers, []byte(exporttest.Verifier().String()+"\n"), 0o644); err != nil {
83 t.Fatal(err)
84 }
85 return tokenFile, verifiers
86}
87
88// command is a program the tests run. It runs in a process group of its
89// own, which start kills when the test ends, with every git it started.
90// The kernel kills it when the test process dies first, as on a timeout
91// or an external kill, so a test run leaves no receiver behind.
92func command(name string, args ...string) *exec.Cmd {
93 cmd := exec.Command(name, args...)
94 cmd.SysProcAttr = &syscall.SysProcAttr{Setpgid: true, Pdeathsig: syscall.SIGKILL}
95 cmd.WaitDelay = 5 * time.Second
96 return cmd
97}
98
99func receiveCmd(args ...string) *exec.Cmd {
100 cmd := command(os.Args[0], args...)
101 cmd.Env = append(os.Environ(), "VALLEY_WEB_RECEIVE_TEST_MAIN=1")
102 return cmd
103}
104
105// newEdge starts a receiver over a new state directory, with the flags
106// given after the ones every receiver here needs.
107func newEdge(t *testing.T, f *exporttest.Fixture, more ...string) *edge {
108 t.Helper()
109 tokenFile, verifiers := files(t)
110 state := filepath.Join(t.TempDir(), "state")
111 p := start(t, receiveCmd(append([]string{"--state", state, "--listen", "127.0.0.1:0",
112 "--instance", exporttest.Instance, "--destination", exporttest.Destination,
113 "--verifiers", verifiers, "--token-file", tokenFile}, more...)...), "valley-web-receive")
114 return &edge{t: t, f: f, state: state, proc: p, addr: p.addr}
115}
116
117// proc is a program start runs: where it listens, what it writes to
118// stderr, and how it exits.
119type proc struct {
120 cmd *exec.Cmd
121 addr string
122 log *stderrLog
123 // done is closed once the program has exited, and err is then how.
124 done chan struct{}
125 err error
126}
127
128// stderrLog keeps what a program writes to stderr, and hands on its first
129// line.
130type stderrLog struct {
131 mu sync.Mutex
132 buf bytes.Buffer
133 first chan string
134}
135
136func (l *stderrLog) Write(p []byte) (int, error) {
137 l.mu.Lock()
138 defer l.mu.Unlock()
139 l.buf.Write(p)
140 if line, _, ok := strings.Cut(l.buf.String(), "\n"); ok && l.first != nil {
141 l.first <- line
142 l.first = nil
143 }
144 return len(p), nil
145}
146
147func (l *stderrLog) String() string {
148 l.mu.Lock()
149 defer l.mu.Unlock()
150 return l.buf.String()
151}
152
153// start runs cmd and waits for it to say where it listens. The cleanup is
154// registered as soon as cmd starts: it kills cmd's process group unless
155// cmd has exited, and logs what cmd wrote when the test failed.
156func start(t *testing.T, cmd *exec.Cmd, name string) *proc {
157 t.Helper()
158 p := &proc{cmd: cmd, log: &stderrLog{first: make(chan string, 1)}, done: make(chan struct{})}
159 first := p.log.first
160 cmd.Stderr = p.log
161 if err := cmd.Start(); err != nil {
162 t.Fatal(err)
163 }
164 go func() {
165 p.err = cmd.Wait()
166 close(p.done)
167 }()
168 t.Cleanup(func() {
169 select {
170 case <-p.done:
171 default:
172 syscall.Kill(-cmd.Process.Pid, syscall.SIGKILL)
173 <-p.done
174 }
175 if t.Failed() {
176 t.Logf("%s wrote:\n%s", name, p.log)
177 }
178 })
179 select {
180 case line := <-first:
181 addr, ok := strings.CutPrefix(line, name+": listening on ")
182 if !ok {
183 t.Fatalf("%s printed %q", name, line)
184 }
185 p.addr = addr
186 return p
187 case <-p.done:
188 t.Fatalf("%s exited with %v before it listened", name, p.err)
189 case <-time.After(waitTimeout):
190 t.Fatalf("%s did not say where it listens", name)
191 }
192 return nil
193}
194
195// logged reports whether the receiver has logged a line that holds every
196// one of parts.
197func (e *edge) logged(parts ...string) bool {
198 for _, line := range strings.Split(e.proc.log.String(), "\n") {
199 all := true
200 for _, part := range parts {
201 all = all && strings.Contains(line, part)
202 }
203 if all {
204 return true
205 }
206 }
207 return false
208}
209
210// manifest is the fixture's export under a manifest with sequence, signed
211// with key, and the manifest itself.
212func (e *edge) manifest(sequence int64, key ed25519.PrivateKey, destination string) ([]byte, *export.Manifest) {
213 e.t.Helper()
214 bundles := map[string]export.Body{}
215 for _, p := range e.f.Manifest.Projects {
216 bundles[p.Name] = p.Bundle
217 }
218 m, err := export.NewManifest(exporttest.Instance, destination, sequence, e.f.Export, e.f.ExportJSON, bundles)
219 if err != nil {
220 e.t.Fatal(err)
221 }
222 signed, err := m.Sign(exporttest.SignerName, key)
223 if err != nil {
224 e.t.Fatal(err)
225 }
226 return signed, m
227}
228
229// signedNow is the fixture's export under a manifest signed now.
230func (e *edge) signedNow() ([]byte, *export.Manifest) {
231 return e.manifest(time.Now().UnixNano(), exporttest.Key(), exporttest.Destination)
232}
233
234// do makes one request with the token within ctx, and returns the status,
235// the reply and its header.
236func (e *edge) do(ctx context.Context, method, path string, body []byte, header http.Header) (int, []byte, http.Header, error) {
237 req, err := http.NewRequestWithContext(ctx, method, "http://"+e.addr+path, bytes.NewReader(body))
238 if err != nil {
239 return 0, nil, nil, err
240 }
241 req.Header.Set("Authorization", export.Authorization(token))
242 for k, v := range header {
243 req.Header[k] = v
244 }
245 res, err := client.Do(req)
246 if err != nil {
247 return 0, nil, nil, err
248 }
249 defer res.Body.Close()
250 reply, err := io.ReadAll(res.Body)
251 return res.StatusCode, reply, res.Header, err
252}
253
254// request makes one request with the token, and returns the status and the
255// reply. A request not answered within requestTimeout fails the test.
256func (e *edge) request(method, path string, body []byte, header http.Header) (int, []byte, http.Header) {
257 e.t.Helper()
258 status, reply, h, err := e.do(context.Background(), method, path, body, header)
259 if err != nil {
260 e.t.Fatal(err)
261 }
262 return status, reply, h
263}
264
265// dial opens a connection to the receiver, which the test closes when it
266// ends if nothing has before.
267func (e *edge) dial() net.Conn {
268 e.t.Helper()
269 c, err := net.DialTimeout("tcp", e.addr, dialTimeout)
270 if err != nil {
271 e.t.Fatal(err)
272 }
273 e.t.Cleanup(func() { c.Close() })
274 return c
275}
276
277// idle makes one request with the token on a connection of its own, a
278// commit of an upload never staged, which the receiver refuses and keeps
279// the connection open after. It returns the connection, which then holds
280// one of the receiver's connections until it is closed or the receiver's
281// idle timeout.
282func (e *edge) idle() net.Conn {
283 e.t.Helper()
284 for range 100 {
285 c := e.dial()
286 fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: 0\r\n\r\n",
287 export.CommitPath(1), e.addr, export.Authorization(token))
288 c.SetReadDeadline(time.Now().Add(requestTimeout))
289 res, err := http.ReadResponse(bufio.NewReader(c), nil)
290 if err != nil {
291 e.t.Fatal(err)
292 }
293 io.Copy(io.Discard, res.Body)
294 res.Body.Close()
295 c.SetReadDeadline(time.Time{})
296 switch {
297 case res.StatusCode == http.StatusServiceUnavailable:
298 // A request just answered had not yet given its slot back.
299 c.Close()
300 time.Sleep(20 * time.Millisecond)
301 case res.Close:
302 e.t.Fatalf("the receiver closed the connection after a %d", res.StatusCode)
303 default:
304 return c
305 }
306 }
307 e.t.Fatal("the receiver never had a request slot free")
308 return nil
309}
310
311// stall sends the headers of a request with content, and one byte of it,
312// on a connection of its own. The request then holds one of the
313// receiver's request slots while the receiver waits for the rest. stall
314// returns nil when the receiver answered at once: it had no slot free, or
315// it refused the request.
316func (e *edge) stall(method, path string, content []byte) net.Conn {
317 e.t.Helper()
318 c := e.dial()
319 fmt.Fprintf(c, "%s %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n",
320 method, path, e.addr, export.Authorization(token), len(content))
321 c.Write(content[:1])
322 if answered(c, 200*time.Millisecond) {
323 c.Close()
324 return nil
325 }
326 return c
327}
328
329// stallAll holds every request slot with a stalled manifest, signed.
330func (e *edge) stallAll(signed []byte) []net.Conn {
331 e.t.Helper()
332 var stalled []net.Conn
333 for range 100 {
334 if c := e.stall(http.MethodPost, export.ManifestPath, signed); c != nil {
335 stalled = append(stalled, c)
336 }
337 if len(stalled) == maxRequests {
338 return stalled
339 }
340 }
341 e.t.Fatalf("only %d of %d stalled manifests held a request slot", len(stalled), maxRequests)
342 return nil
343}
344
345// answered reports whether anything arrives on c within d, or c is closed.
346// It reads nothing when nothing arrives.
347func answered(c net.Conn, d time.Duration) bool {
348 c.SetReadDeadline(time.Now().Add(d))
349 defer c.SetReadDeadline(time.Time{})
350 _, err := c.Read(make([]byte, 1))
351 var ne net.Error
352 return !(errors.As(err, &ne) && ne.Timeout())
353}
354
355// refused checks that a reply is the refusal with code, and returns it.
356func refused(t *testing.T, what string, status int, reply []byte, code export.Code) export.ErrorReply {
357 t.Helper()
358 var r export.ErrorReply
359 if err := json.Unmarshal(reply, &r); err != nil || r.Schema != export.ErrorSchema || r.Code != code || status != code.Status() {
360 t.Errorf("%s: the receiver replied %d %s, want %d and %s", what, status, reply, code.Status(), code)
361 }
362 return r
363}
364
365// post posts the signed manifest, and returns its inventory.
366func (e *edge) post(signed []byte) export.Inventory {
367 e.t.Helper()
368 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
369 var inv export.Inventory
370 if err := json.Unmarshal(reply, &inv); status != http.StatusOK || err != nil || inv.Schema != export.InventorySchema {
371 e.t.Fatalf("the manifest was answered %d %s", status, reply)
372 }
373 return inv
374}
375
376// put sends one body the manifest declares, and fails the test unless it
377// is accepted.
378func (e *edge) put(m *export.Manifest, name string) {
379 e.t.Helper()
380 b := body(e.t, m, name)
381 status, reply, _ := e.request(http.MethodPut, export.BodyPath(m.Sequence, b.SHA256), e.f.BodyBytes(e.t, name), nil)
382 if status != http.StatusNoContent {
383 e.t.Fatalf("body %s was answered %d %s", name, status, reply)
384 }
385}
386
387func body(t *testing.T, m *export.Manifest, name string) export.Body {
388 t.Helper()
389 for _, b := range m.Bodies() {
390 if b.Name == name {
391 return b
392 }
393 }
394 t.Fatalf("the manifest declares no body %s", name)
395 return export.Body{}
396}
397
398// commit commits the upload, and fails the test unless it is activated.
399func (e *edge) commit(m *export.Manifest) {
400 e.t.Helper()
401 status, reply, _ := e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
402 var c export.Committed
403 if err := json.Unmarshal(reply, &c); status != http.StatusOK || err != nil || c.Sequence != m.Sequence {
404 e.t.Fatalf("the commit was answered %d %s", status, reply)
405 }
406}
407
408// upload runs the three steps for a manifest signed now, and returns it.
409func (e *edge) upload() *export.Manifest {
410 e.t.Helper()
411 signed, m := e.signedNow()
412 for _, n := range e.post(signed).Needs {
413 e.put(m, n.Name)
414 }
415 e.commit(m)
416 return m
417}
418
419// highWater is the state directory's high-water mark, 0 for none.
420func (e *edge) highWater() int64 {
421 e.t.Helper()
422 data, err := os.ReadFile(filepath.Join(e.state, "high-water"))
423 if os.IsNotExist(err) {
424 return 0
425 }
426 n, perr := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
427 if err != nil || perr != nil {
428 e.t.Fatalf("high-water: %v %v", err, perr)
429 }
430 return n
431}
432
433// staged are the entries of the state directory's staging area.
434func (e *edge) staged() []string {
435 e.t.Helper()
436 entries, err := os.ReadDir(filepath.Join(e.state, "staging"))
437 if err != nil {
438 e.t.Fatal(err)
439 }
440 var names []string
441 for _, d := range entries {
442 names = append(names, d.Name())
443 }
444 return names
445}
446
447// valleyWeb starts the real valley-web over the edge's state directory,
448// and returns where it listens.
449func (e *edge) valleyWeb() string {
450 e.t.Helper()
451 bin := os.Getenv("VALLEY_WEB")
452 if bin == "" {
453 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
454 e.t.Fatal("VALLEY_WEB names no valley-web, and VALLEY_TEST_TOOLS=required")
455 }
456 e.t.Skip("VALLEY_WEB names no valley-web; the nix check provides one")
457 }
458 return start(e.t, command(bin, "--state", e.state, "--listen", "127.0.0.1:0"), "valley-web").addr
459}
460
461// serves checks that valley-web at addr answers every page of the
462// fixture's export.
463func (e *edge) serves(addr string) {
464 e.t.Helper()
465 tip := e.f.Export.Projects[0].SourceTip
466 for target, status := range map[string]int{
467 "/": http.StatusOK,
468 "/app/knots/oc-a000002": http.StatusOK,
469 "/app/source/tree/" + tip + "/": http.StatusOK,
470 "/app/source/log/" + tip: http.StatusOK,
471 "/site/source/": http.StatusNotFound,
472 } {
473 res, err := client.Get("http://" + addr + target)
474 if err != nil {
475 e.t.Fatal(err)
476 }
477 page, _ := io.ReadAll(res.Body)
478 res.Body.Close()
479 if res.StatusCode != status {
480 e.t.Errorf("valley-web answered GET %s with %d, want %d:\n%s", target, res.StatusCode, status, page)
481 }
482 }
483}
484
485// An upload of the three steps activates the export, and valley-web, as a
486// process of its own over the same state directory, serves it. The
487// manifest posted again, and the commit made again, are refused as
488// replayed, with the high-water mark.
489func TestAnUploadActivatesAndValleyWebServesIt(t *testing.T) {
490 e := newEdge(t, exporttest.New(t))
491 signed, m := e.signedNow()
492 inv := e.post(signed)
493 if inv.Active != nil || len(inv.Needs) != 2 || inv.Needs[0].Name != export.ExportFile || inv.Needs[1].Name != "app" {
494 t.Fatalf("the first inventory is %+v, want no active export and both bodies needed, export.json first", inv)
495 }
496 again := e.post(signed)
497 if len(again.Needs) != 2 {
498 t.Errorf("the manifest posted again needs %+v, want both bodies still", again.Needs)
499 }
500 e.put(m, export.ExportFile)
501 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != "app" {
502 t.Errorf("the manifest posted after export.json needs %+v, want app's bundle alone", needs)
503 }
504 e.put(m, "app")
505 e.put(m, "app") // a body already staged is accepted again
506 e.commit(m)
507 if hw := e.highWater(); hw != m.Sequence {
508 t.Errorf("high-water is %d after the commit, want %d", hw, m.Sequence)
509 }
510 e.serves(e.valleyWeb())
511
512 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
513 if r := refused(t, "the manifest posted after its commit", status, reply, export.CodeReplayed); r.HighWater != m.Sequence {
514 t.Errorf("the replayed refusal gives high-water %d, want %d", r.HighWater, m.Sequence)
515 }
516 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
517 refused(t, "the commit made again", status, reply, export.CodeReplayed)
518
519 // The next upload carries app's repository over, and needs export.json
520 // alone.
521 signed, m = e.signedNow()
522 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != export.ExportFile {
523 t.Errorf("the next upload needs %+v, want export.json alone", needs)
524 }
525 e.put(m, export.ExportFile)
526 e.commit(m)
527}
528
529// A request without the token is refused as unauthenticated, whatever it
530// asks, and stages nothing. So is one with another token, or with the
531// token twice.
532func TestAnUnauthenticatedRequestIsRefused(t *testing.T) {
533 e := newEdge(t, exporttest.New(t))
534 signed, m := e.signedNow()
535 send := func(what, method, path string, body []byte, auth []string) {
536 t.Helper()
537 req, err := http.NewRequest(method, "http://"+e.addr+path, bytes.NewReader(body))
538 if err != nil {
539 t.Fatal(err)
540 }
541 req.Header["Authorization"] = auth
542 res, err := client.Do(req)
543 if err != nil {
544 t.Fatal(err)
545 }
546 reply, _ := io.ReadAll(res.Body)
547 res.Body.Close()
548 refused(t, what, res.StatusCode, reply, export.CodeUnauthenticated)
549 if !strings.HasPrefix(res.Header.Get("WWW-Authenticate"), "Bearer ") {
550 t.Errorf("%s: the refusal names no scheme to authenticate with", what)
551 }
552 }
553 send("a manifest with no token", http.MethodPost, export.ManifestPath, signed, nil)
554 send("a manifest with another token", http.MethodPost, export.ManifestPath, signed, []string{export.Authorization(token + "x")})
555 send("a manifest with the token in another scheme", http.MethodPost, export.ManifestPath, signed, []string{"Basic " + token})
556 send("a manifest with the token twice", http.MethodPost, export.ManifestPath, signed,
557 []string{export.Authorization(token), export.Authorization(token)})
558 send("a body with no token", http.MethodPut, export.BodyPath(m.Sequence, m.File.SHA256), e.f.ExportJSON, nil)
559 send("a commit with no token", http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
560 send("a path the upload does not use", http.MethodGet, "/", nil, nil)
561 if staged := e.staged(); len(staged) != 0 || e.highWater() != 0 {
562 t.Errorf("unauthenticated requests left %v staged and high-water %d", staged, e.highWater())
563 }
564}
565
566// A manifest is refused when it is stale, signed ahead of the receiver's
567// clock, signed by another key, or for another receiver; and an older
568// manifest than the one staged is superseded. None of them is staged.
569func TestAManifestIsAdmittedOnlyWhenFresh(t *testing.T) {
570 e := newEdge(t, exporttest.New(t))
571 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
572 now := time.Now()
573 for _, c := range []struct {
574 what string
575 at time.Time
576 key ed25519.PrivateKey
577 destination string
578 code export.Code
579 }{
580 {"a manifest signed four days ago", now.Add(-96 * time.Hour), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
581 {"a manifest signed two minutes ahead", now.Add(2 * time.Minute), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
582 {"a manifest signed by another key", now, other, exporttest.Destination, export.CodeBadSignature},
583 {"a manifest for another receiver", now, exporttest.Key(), "elsewhere.example.org", export.CodeWrongDestination},
584 } {
585 signed, _ := e.manifest(c.at.UnixNano(), c.key, c.destination)
586 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
587 refused(t, c.what, status, reply, c.code)
588 }
589 if staged := e.staged(); len(staged) != 0 {
590 t.Errorf("refused manifests left %v staged", staged)
591 }
592
593 older, om := e.manifest(now.Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
594 newer, _ := e.signedNow()
595 e.post(newer)
596 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, older, nil)
597 refused(t, "a manifest older than the one staged", status, reply, export.CodeSuperseded)
598 status, reply, _ = e.request(http.MethodPut, export.BodyPath(om.Sequence, om.File.SHA256), e.f.ExportJSON, nil)
599 refused(t, "a body of the older upload", status, reply, export.CodeSuperseded)
600 status, reply, _ = e.request(http.MethodPost, export.CommitPath(om.Sequence+1e12), nil, nil)
601 refused(t, "a commit of an upload never staged", status, reply, export.CodeNoManifest)
602}
603
604// A body is refused when its bytes are not what the manifest declares: a
605// hash mismatch, a size mismatch whether or not the length is given, a
606// Content-Encoding, or a hash the manifest does not declare. An upload
607// cut off part way through a body is refused at the commit as incomplete,
608// and the active export stays as it was until the body is sent whole.
609func TestABodyIsKeptOnlyWhenItVerifies(t *testing.T) {
610 e := newEdge(t, exporttest.New(t))
611 first := e.upload()
612 signed, m := e.signedNow()
613 // A second upload of the same export needs export.json again, staged
614 // for it, and no bundle: app's repository is carried over.
615 if needs := e.post(signed).Needs; len(needs) != 1 {
616 t.Fatalf("the second upload needs %+v, want export.json alone", needs)
617 }
618 file := body(t, m, export.ExportFile)
619 path := export.BodyPath(m.Sequence, file.SHA256)
620 wrong := append([]byte{}, e.f.ExportJSON...)
621 wrong[0] ^= 1
622
623 status, reply, _ := e.request(http.MethodPut, path, wrong, nil)
624 refused(t, "a body with other bytes of the same size", status, reply, export.CodeHashMismatch)
625 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON[1:], nil)
626 refused(t, "a body one byte short", status, reply, export.CodeSizeMismatch)
627 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON, http.Header{"Content-Encoding": {"gzip"}})
628 refused(t, "a body with a Content-Encoding", status, reply, export.CodeEncoding)
629 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, strings.Repeat("0", 64)), e.f.ExportJSON, nil)
630 refused(t, "a body the manifest does not declare", status, reply, export.CodeNotDeclared)
631
632 // Sent with no length, one byte long.
633 req, err := http.NewRequest(http.MethodPut, "http://"+e.addr+path, io.MultiReader(bytes.NewReader(e.f.ExportJSON), strings.NewReader("x")))
634 if err != nil {
635 t.Fatal(err)
636 }
637 req.Header.Set("Authorization", export.Authorization(token))
638 res, err := client.Do(req)
639 if err != nil {
640 t.Fatal(err)
641 }
642 reply, _ = io.ReadAll(res.Body)
643 res.Body.Close()
644 refused(t, "a body one byte long, sent with no length", res.StatusCode, reply, export.CodeSizeMismatch)
645
646 // Cut off half way.
647 c := e.dial()
648 fmt.Fprintf(c, "PUT %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n", path, e.addr, export.Authorization(token), file.Size)
649 c.Write(e.f.ExportJSON[:file.Size/2])
650 c.Close()
651
652 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
653 r := refused(t, "a commit after the body was cut off", status, reply, export.CodeIncomplete)
654 if len(r.Needs) != 1 || r.Needs[0].SHA256 != file.SHA256 {
655 t.Errorf("the incomplete refusal needs %+v, want export.json", r.Needs)
656 }
657 if hw := e.highWater(); hw != first.Sequence {
658 t.Errorf("high-water moved to %d on refused bodies, want %d", hw, first.Sequence)
659 }
660 // The receiver removes what it read of the cut-off body once it sees
661 // the connection close.
662 waitFor(t, "no body left in staging", func(context.Context) bool {
663 partial, _ := filepath.Glob(filepath.Join(e.state, "staging", "*", "bodies", "*"))
664 return len(partial) == 0
665 })
666 e.put(m, export.ExportFile)
667 e.commit(m)
668}
669
670// A manifest whose body is larger than --max-body, or whose bodies
671// together are larger than --max-upload, is refused as too-large and
672// staged not at all.
673func TestAnOversizedUploadIsRefused(t *testing.T) {
674 f := exporttest.New(t)
675 size := func(name string) int64 { return int64(len(f.BodyBytes(t, name))) }
676 for _, c := range []struct {
677 what string
678 flags []string
679 }{
680 {"a body over --max-body", []string{"--max-body", strconv.FormatInt(size(export.ExportFile)-1, 10)}},
681 {"bodies over --max-upload", []string{"--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app")-1, 10)}},
682 } {
683 e := newEdge(t, f, c.flags...)
684 signed, _ := e.signedNow()
685 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
686 refused(t, c.what, status, reply, export.CodeTooLarge)
687 if staged := e.staged(); len(staged) != 0 {
688 t.Errorf("%s: the refused manifest left %v staged", c.what, staged)
689 }
690 }
691 // At the caps exactly, the upload is accepted.
692 e := newEdge(t, f, "--max-body", strconv.FormatInt(max(size(export.ExportFile), size("app")), 10),
693 "--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app"), 10))
694 e.upload()
695}
696
697// A saturated receiver answers 503 to a request past its slots, and
698// valley-web, a process of its own over the same state directory, keeps
699// serving every page. A request without the token is still refused as
700// unauthenticated, taking no slot. Once the stalled requests go away, the
701// receiver takes uploads again.
702func TestASaturatedUploadLeavesValleyWebServing(t *testing.T) {
703 e := newEdge(t, exporttest.New(t))
704 e.upload()
705 web := e.valleyWeb()
706 signed, m := e.signedNow()
707 e.post(signed)
708 probe := export.BodyPath(m.Sequence, strings.Repeat("0", 64))
709
710 stalled := e.stallAll(signed)
711 status, _, header := e.request(http.MethodPut, probe, []byte("x"), nil)
712 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
713 t.Errorf("a request past every slot was answered %d, want 503 with Retry-After", status)
714 }
715 res, err := client.Post("http://"+e.addr+export.ManifestPath, "", bytes.NewReader(signed))
716 if err != nil {
717 t.Fatal(err)
718 }
719 reply, _ := io.ReadAll(res.Body)
720 res.Body.Close()
721 refused(t, "a manifest with no token while the receiver is saturated", res.StatusCode, reply, export.CodeUnauthenticated)
722 e.serves(web)
723
724 for _, c := range stalled {
725 c.Close()
726 }
727 waitFor(t, "the receiver to take requests again", func(ctx context.Context) bool {
728 status, _, _, err := e.do(ctx, http.MethodPut, probe, []byte("x"), nil)
729 return err == nil && status == http.StatusNotFound
730 })
731
732 e.put(m, export.ExportFile)
733 e.commit(m)
734 e.serves(web)
735}
736
737// waitFor polls done until it reports true, and fails the test unless it
738// does within waitTimeout. done is given a context that ends then, which
739// bounds whatever request it makes.
740func waitFor(t *testing.T, what string, done func(ctx context.Context) bool) {
741 t.Helper()
742 ctx, cancel := context.WithTimeout(context.Background(), waitTimeout)
743 defer cancel()
744 for ctx.Err() == nil {
745 if done(ctx) {
746 return
747 }
748 select {
749 case <-ctx.Done():
750 case <-time.After(20 * time.Millisecond):
751 }
752 }
753 t.Fatalf("timed out waiting for %s", what)
754}
755
756// The receiver stops cleanly on SIGTERM.
757func TestStopsOnSIGTERM(t *testing.T) {
758 e := newEdge(t, exporttest.New(t))
759 if err := e.proc.cmd.Process.Signal(syscall.SIGTERM); err != nil {
760 t.Fatal(err)
761 }
762 select {
763 case <-e.proc.done:
764 case <-time.After(stopTimeout + 10*time.Second):
765 t.Fatalf("valley-web-receive did not stop within %v of SIGTERM", stopTimeout+10*time.Second)
766 }
767 if e.proc.err != nil {
768 t.Errorf("valley-web-receive stopped with %v", e.proc.err)
769 }
770}
771
772// A command line it cannot run with gets the usage and exit status 2; a
773// token file it cannot use, or verifiers it cannot read, exit status 1;
774// --help gets the usage alone.
775func TestUsage(t *testing.T) {
776 tokenFile, verifiers := files(t)
777 state := t.TempDir()
778 base := []string{"--state", state, "--listen", "127.0.0.1:0", "--instance", "valley-host", "--destination", "example.org"}
779 for _, args := range [][]string{
780 {},
781 append(base, "--verifiers", verifiers),
782 append(base, "--token-file", tokenFile),
783 {"--state", state, "--listen", "127.0.0.1:0", "--instance", "a b", "--destination", "example.org", "--verifiers", verifiers, "--token-file", tokenFile},
784 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "--max-body", "0"),
785 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "extra"),
786 } {
787 out, err := receiveCmd(args...).CombinedOutput()
788 exit, ok := err.(*exec.ExitError)
789 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web-receive") {
790 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
791 }
792 }
793 short := filepath.Join(t.TempDir(), "short")
794 if err := os.WriteFile(short, []byte("too-short\n"), 0o600); err != nil {
795 t.Fatal(err)
796 }
797 for _, args := range [][]string{
798 append(base, "--verifiers", verifiers, "--token-file", short),
799 append(base, "--verifiers", tokenFile, "--token-file", tokenFile),
800 } {
801 out, err := receiveCmd(args...).CombinedOutput()
802 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
803 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
804 }
805 if bytes.Contains(out, []byte(token)) {
806 t.Errorf("valley-web-receive %q printed the token", args)
807 }
808 }
809 out, err := receiveCmd("--help").CombinedOutput()
810 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web-receive") {
811 t.Errorf("valley-web-receive --help gave %v:\n%s", err, out)
812 }
813}