gunk-dev/the-valley

main_test.go

source06e50fc2f601main's published tip history
34.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. A 503 is retried, as the publisher retries it: a request
378// that staged the body may not have given it up yet.
379func (e *edge) put(m *export.Manifest, name string) {
380 e.t.Helper()
381 b := body(e.t, m, name)
382 var status int
383 var reply []byte
384 for range 50 {
385 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, b.SHA256), e.f.BodyBytes(e.t, name), nil)
386 if status != http.StatusServiceUnavailable {
387 break
388 }
389 time.Sleep(20 * time.Millisecond)
390 }
391 if status != http.StatusNoContent {
392 e.t.Fatalf("body %s was answered %d %s", name, status, reply)
393 }
394}
395
396func body(t *testing.T, m *export.Manifest, name string) export.Body {
397 t.Helper()
398 for _, b := range m.Bodies() {
399 if b.Name == name {
400 return b
401 }
402 }
403 t.Fatalf("the manifest declares no body %s", name)
404 return export.Body{}
405}
406
407// commit commits the upload, and fails the test unless it is activated.
408func (e *edge) commit(m *export.Manifest) {
409 e.t.Helper()
410 status, reply, _ := e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
411 var c export.Committed
412 if err := json.Unmarshal(reply, &c); status != http.StatusOK || err != nil || c.Sequence != m.Sequence {
413 e.t.Fatalf("the commit was answered %d %s", status, reply)
414 }
415}
416
417// upload runs the three steps for a manifest signed now, and returns it.
418func (e *edge) upload() *export.Manifest {
419 e.t.Helper()
420 signed, m := e.signedNow()
421 for _, n := range e.post(signed).Needs {
422 e.put(m, n.Name)
423 }
424 e.commit(m)
425 return m
426}
427
428// highWater is the state directory's high-water mark, 0 for none.
429func (e *edge) highWater() int64 {
430 e.t.Helper()
431 data, err := os.ReadFile(filepath.Join(e.state, "high-water"))
432 if os.IsNotExist(err) {
433 return 0
434 }
435 n, perr := strconv.ParseInt(strings.TrimSpace(string(data)), 10, 64)
436 if err != nil || perr != nil {
437 e.t.Fatalf("high-water: %v %v", err, perr)
438 }
439 return n
440}
441
442// staged are the entries of the state directory's staging area.
443func (e *edge) staged() []string {
444 e.t.Helper()
445 entries, err := os.ReadDir(filepath.Join(e.state, "staging"))
446 if err != nil {
447 e.t.Fatal(err)
448 }
449 var names []string
450 for _, d := range entries {
451 names = append(names, d.Name())
452 }
453 return names
454}
455
456// valleyWeb starts the real valley-web over the edge's state directory,
457// and returns where it listens.
458func (e *edge) valleyWeb() string {
459 e.t.Helper()
460 bin := os.Getenv("VALLEY_WEB")
461 if bin == "" {
462 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
463 e.t.Fatal("VALLEY_WEB names no valley-web, and VALLEY_TEST_TOOLS=required")
464 }
465 e.t.Skip("VALLEY_WEB names no valley-web; the nix check provides one")
466 }
467 return start(e.t, command(bin, "--state", e.state, "--listen", "127.0.0.1:0"), "valley-web").addr
468}
469
470// serves checks that valley-web at addr answers every page of the
471// fixture's export.
472func (e *edge) serves(addr string) {
473 e.t.Helper()
474 tip := e.f.Export.Projects[0].SourceTip
475 for target, status := range map[string]int{
476 "/": http.StatusOK,
477 "/app/knots/oc-a000002": http.StatusOK,
478 "/app/source/tree/" + tip + "/": http.StatusOK,
479 "/app/source/log/" + tip: http.StatusOK,
480 "/site/source/": http.StatusNotFound,
481 } {
482 res, err := client.Get("http://" + addr + target)
483 if err != nil {
484 e.t.Fatal(err)
485 }
486 page, _ := io.ReadAll(res.Body)
487 res.Body.Close()
488 if res.StatusCode != status {
489 e.t.Errorf("valley-web answered GET %s with %d, want %d:\n%s", target, res.StatusCode, status, page)
490 }
491 }
492}
493
494// An upload of the three steps activates the export, and valley-web, as a
495// process of its own over the same state directory, serves it. The
496// manifest posted again, and the commit made again, are refused as
497// replayed, with the high-water mark.
498func TestAnUploadActivatesAndValleyWebServesIt(t *testing.T) {
499 e := newEdge(t, exporttest.New(t))
500 signed, m := e.signedNow()
501 inv := e.post(signed)
502 if inv.Active != nil || len(inv.Needs) != 2 || inv.Needs[0].Name != export.ExportFile || inv.Needs[1].Name != "app" {
503 t.Fatalf("the first inventory is %+v, want no active export and both bodies needed, export.json first", inv)
504 }
505 again := e.post(signed)
506 if len(again.Needs) != 2 {
507 t.Errorf("the manifest posted again needs %+v, want both bodies still", again.Needs)
508 }
509 e.put(m, export.ExportFile)
510 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != "app" {
511 t.Errorf("the manifest posted after export.json needs %+v, want app's bundle alone", needs)
512 }
513 e.put(m, "app")
514 e.put(m, "app") // a body already staged is accepted again
515 e.commit(m)
516 if hw := e.highWater(); hw != m.Sequence {
517 t.Errorf("high-water is %d after the commit, want %d", hw, m.Sequence)
518 }
519 e.serves(e.valleyWeb())
520
521 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
522 if r := refused(t, "the manifest posted after its commit", status, reply, export.CodeReplayed); r.HighWater != m.Sequence {
523 t.Errorf("the replayed refusal gives high-water %d, want %d", r.HighWater, m.Sequence)
524 }
525 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
526 refused(t, "the commit made again", status, reply, export.CodeReplayed)
527
528 // The next upload carries app's repository over, and needs export.json
529 // alone.
530 signed, m = e.signedNow()
531 if needs := e.post(signed).Needs; len(needs) != 1 || needs[0].Name != export.ExportFile {
532 t.Errorf("the next upload needs %+v, want export.json alone", needs)
533 }
534 e.put(m, export.ExportFile)
535 e.commit(m)
536}
537
538// A request without the token is refused as unauthenticated, whatever it
539// asks, and stages nothing. So is one with another token, or with the
540// token twice.
541func TestAnUnauthenticatedRequestIsRefused(t *testing.T) {
542 e := newEdge(t, exporttest.New(t))
543 signed, m := e.signedNow()
544 send := func(what, method, path string, body []byte, auth []string) {
545 t.Helper()
546 req, err := http.NewRequest(method, "http://"+e.addr+path, bytes.NewReader(body))
547 if err != nil {
548 t.Fatal(err)
549 }
550 req.Header["Authorization"] = auth
551 res, err := client.Do(req)
552 if err != nil {
553 t.Fatal(err)
554 }
555 reply, _ := io.ReadAll(res.Body)
556 res.Body.Close()
557 refused(t, what, res.StatusCode, reply, export.CodeUnauthenticated)
558 if !strings.HasPrefix(res.Header.Get("WWW-Authenticate"), "Bearer ") {
559 t.Errorf("%s: the refusal names no scheme to authenticate with", what)
560 }
561 }
562 send("a manifest with no token", http.MethodPost, export.ManifestPath, signed, nil)
563 send("a manifest with another token", http.MethodPost, export.ManifestPath, signed, []string{export.Authorization(token + "x")})
564 send("a manifest with the token in another scheme", http.MethodPost, export.ManifestPath, signed, []string{"Basic " + token})
565 send("a manifest with the token twice", http.MethodPost, export.ManifestPath, signed,
566 []string{export.Authorization(token), export.Authorization(token)})
567 send("a body with no token", http.MethodPut, export.BodyPath(m.Sequence, m.File.SHA256), e.f.ExportJSON, nil)
568 send("a commit with no token", http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
569 send("a path the upload does not use", http.MethodGet, "/", nil, nil)
570 if staged := e.staged(); len(staged) != 0 || e.highWater() != 0 {
571 t.Errorf("unauthenticated requests left %v staged and high-water %d", staged, e.highWater())
572 }
573}
574
575// A manifest is refused when it is stale, signed ahead of the receiver's
576// clock, signed by another key, or for another receiver; and an older
577// manifest than the one staged is superseded. None of them is staged.
578func TestAManifestIsAdmittedOnlyWhenFresh(t *testing.T) {
579 e := newEdge(t, exporttest.New(t))
580 other := ed25519.NewKeyFromSeed(bytes.Repeat([]byte{7}, ed25519.SeedSize))
581 now := time.Now()
582 for _, c := range []struct {
583 what string
584 at time.Time
585 key ed25519.PrivateKey
586 destination string
587 code export.Code
588 }{
589 {"a manifest signed four days ago", now.Add(-96 * time.Hour), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
590 {"a manifest signed two minutes ahead", now.Add(2 * time.Minute), exporttest.Key(), exporttest.Destination, export.CodeOutOfWindow},
591 {"a manifest signed by another key", now, other, exporttest.Destination, export.CodeBadSignature},
592 {"a manifest for another receiver", now, exporttest.Key(), "elsewhere.example.org", export.CodeWrongDestination},
593 } {
594 signed, _ := e.manifest(c.at.UnixNano(), c.key, c.destination)
595 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
596 refused(t, c.what, status, reply, c.code)
597 }
598 if staged := e.staged(); len(staged) != 0 {
599 t.Errorf("refused manifests left %v staged", staged)
600 }
601
602 older, om := e.manifest(now.Add(-time.Minute).UnixNano(), exporttest.Key(), exporttest.Destination)
603 newer, _ := e.signedNow()
604 e.post(newer)
605 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, older, nil)
606 refused(t, "a manifest older than the one staged", status, reply, export.CodeSuperseded)
607 status, reply, _ = e.request(http.MethodPut, export.BodyPath(om.Sequence, om.File.SHA256), e.f.ExportJSON, nil)
608 refused(t, "a body of the older upload", status, reply, export.CodeSuperseded)
609 status, reply, _ = e.request(http.MethodPost, export.CommitPath(om.Sequence+1e12), nil, nil)
610 refused(t, "a commit of an upload never staged", status, reply, export.CodeNoManifest)
611}
612
613// A body is refused when its bytes are not what the manifest declares: a
614// hash mismatch, a size mismatch whether or not the length is given, a
615// Content-Encoding, or a hash the manifest does not declare. An upload
616// cut off part way through a body is refused at the commit as incomplete,
617// and the active export stays as it was until the body is sent whole.
618func TestABodyIsKeptOnlyWhenItVerifies(t *testing.T) {
619 e := newEdge(t, exporttest.New(t))
620 first := e.upload()
621 signed, m := e.signedNow()
622 // A second upload of the same export needs export.json again, staged
623 // for it, and no bundle: app's repository is carried over.
624 if needs := e.post(signed).Needs; len(needs) != 1 {
625 t.Fatalf("the second upload needs %+v, want export.json alone", needs)
626 }
627 file := body(t, m, export.ExportFile)
628 path := export.BodyPath(m.Sequence, file.SHA256)
629 wrong := append([]byte{}, e.f.ExportJSON...)
630 wrong[0] ^= 1
631
632 status, reply, _ := e.request(http.MethodPut, path, wrong, nil)
633 refused(t, "a body with other bytes of the same size", status, reply, export.CodeHashMismatch)
634 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON[1:], nil)
635 refused(t, "a body one byte short", status, reply, export.CodeSizeMismatch)
636 status, reply, _ = e.request(http.MethodPut, path, e.f.ExportJSON, http.Header{"Content-Encoding": {"gzip"}})
637 refused(t, "a body with a Content-Encoding", status, reply, export.CodeEncoding)
638 status, reply, _ = e.request(http.MethodPut, export.BodyPath(m.Sequence, strings.Repeat("0", 64)), e.f.ExportJSON, nil)
639 refused(t, "a body the manifest does not declare", status, reply, export.CodeNotDeclared)
640
641 // Sent with no length, one byte long.
642 req, err := http.NewRequest(http.MethodPut, "http://"+e.addr+path, io.MultiReader(bytes.NewReader(e.f.ExportJSON), strings.NewReader("x")))
643 if err != nil {
644 t.Fatal(err)
645 }
646 req.Header.Set("Authorization", export.Authorization(token))
647 res, err := client.Do(req)
648 if err != nil {
649 t.Fatal(err)
650 }
651 reply, _ = io.ReadAll(res.Body)
652 res.Body.Close()
653 refused(t, "a body one byte long, sent with no length", res.StatusCode, reply, export.CodeSizeMismatch)
654
655 // Sent while another request is staging it: staging holds one partial
656 // file of each body.
657 stalled := e.stall(http.MethodPut, path, e.f.ExportJSON)
658 if stalled == nil {
659 t.Fatal("the receiver answered a stalled body at once")
660 }
661 status, reply, header := e.request(http.MethodPut, path, e.f.ExportJSON, nil)
662 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
663 t.Errorf("a body sent while another request stages it was answered %d %s, want 503 with Retry-After", status, reply)
664 }
665 stalled.Close()
666
667 // Cut off half way.
668 c := e.dial()
669 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)
670 c.Write(e.f.ExportJSON[:file.Size/2])
671 c.Close()
672
673 status, reply, _ = e.request(http.MethodPost, export.CommitPath(m.Sequence), nil, nil)
674 r := refused(t, "a commit after the body was cut off", status, reply, export.CodeIncomplete)
675 if len(r.Needs) != 1 || r.Needs[0].SHA256 != file.SHA256 {
676 t.Errorf("the incomplete refusal needs %+v, want export.json", r.Needs)
677 }
678 if hw := e.highWater(); hw != first.Sequence {
679 t.Errorf("high-water moved to %d on refused bodies, want %d", hw, first.Sequence)
680 }
681 // The receiver removes what it read of the cut-off body once it sees
682 // the connection close.
683 waitFor(t, "no body left in staging", func(context.Context) bool {
684 partial, _ := filepath.Glob(filepath.Join(e.state, "staging", "*", "bodies", "*"))
685 return len(partial) == 0
686 })
687 e.put(m, export.ExportFile)
688 e.commit(m)
689}
690
691// A manifest whose body is larger than --max-body, or whose bodies
692// together are larger than --max-upload, is refused as too-large and
693// staged not at all.
694func TestAnOversizedUploadIsRefused(t *testing.T) {
695 f := exporttest.New(t)
696 size := func(name string) int64 { return int64(len(f.BodyBytes(t, name))) }
697 for _, c := range []struct {
698 what string
699 flags []string
700 }{
701 {"a body over --max-body", []string{"--max-body", strconv.FormatInt(size(export.ExportFile)-1, 10)}},
702 {"bodies over --max-upload", []string{"--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app")-1, 10)}},
703 } {
704 e := newEdge(t, f, c.flags...)
705 signed, _ := e.signedNow()
706 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
707 refused(t, c.what, status, reply, export.CodeTooLarge)
708 if staged := e.staged(); len(staged) != 0 {
709 t.Errorf("%s: the refused manifest left %v staged", c.what, staged)
710 }
711 }
712 // At the caps exactly, the upload is accepted.
713 e := newEdge(t, f, "--max-body", strconv.FormatInt(max(size(export.ExportFile), size("app")), 10),
714 "--max-upload", strconv.FormatInt(size(export.ExportFile)+size("app"), 10))
715 e.upload()
716}
717
718// A saturated receiver answers 503 to a request past its slots, and
719// valley-web, a process of its own over the same state directory, keeps
720// serving every page. A request without the token is still refused as
721// unauthenticated, taking no slot. Once the stalled requests go away, the
722// receiver takes uploads again.
723//
724// Then every connection the receiver takes is held by a client that sends
725// part of a request's headers and stops. valley-web keeps serving. A body
726// sent meanwhile waits in the listen queue until the header timeout closes
727// those connections, and no longer.
728func TestASaturatedUploadLeavesValleyWebServing(t *testing.T) {
729 e := newEdge(t, exporttest.New(t))
730 e.upload()
731 web := e.valleyWeb()
732 signed, m := e.signedNow()
733 e.post(signed)
734 probe := export.BodyPath(m.Sequence, strings.Repeat("0", 64))
735
736 stalled := e.stallAll(signed)
737 status, _, header := e.request(http.MethodPut, probe, []byte("x"), nil)
738 if status != http.StatusServiceUnavailable || header.Get("Retry-After") == "" {
739 t.Errorf("a request past every slot was answered %d, want 503 with Retry-After", status)
740 }
741 res, err := client.Post("http://"+e.addr+export.ManifestPath, "", bytes.NewReader(signed))
742 if err != nil {
743 t.Fatal(err)
744 }
745 reply, _ := io.ReadAll(res.Body)
746 res.Body.Close()
747 refused(t, "a manifest with no token while the receiver is saturated", res.StatusCode, reply, export.CodeUnauthenticated)
748 e.serves(web)
749
750 for _, c := range stalled {
751 c.Close()
752 }
753 waitFor(t, "the receiver to take requests again", func(ctx context.Context) bool {
754 status, _, _, err := e.do(ctx, http.MethodPut, probe, []byte("x"), nil)
755 return err == nil && status == http.StatusNotFound
756 })
757
758 for range maxConns {
759 fmt.Fprintf(e.dial(), "PUT %s HTTP/1.1\r\nHost: %s\r\n", probe, e.addr)
760 }
761 began := time.Now()
762 e.serves(web)
763 e.put(m, export.ExportFile)
764 if took := time.Since(began); took < headerTimeout/2 || took > headerTimeout+5*time.Second {
765 t.Errorf("a body sent behind a connection on every slot was answered after %v, want about the header timeout, %v", took, headerTimeout)
766 }
767 e.commit(m)
768 e.serves(web)
769}
770
771// OPTIONS * is the receiver's to answer, as any other request is: refused
772// as unauthenticated without the token, and 404 with it. Either is
773// answered at once, without reading the body it declares, and its
774// connection is closed. So OPTIONS * requests that withhold their bodies,
775// one on every connection the receiver takes, hold none of them, and an
776// upload goes through.
777func TestOptionsStarHoldsNoConnection(t *testing.T) {
778 e := newEdge(t, exporttest.New(t))
779 conns := make([]net.Conn, maxConns)
780 for i := range conns {
781 auth := ""
782 if i%2 == 1 {
783 auth = "Authorization: " + export.Authorization(token) + "\r\n"
784 }
785 conns[i] = e.dial()
786 fmt.Fprintf(conns[i], "OPTIONS * HTTP/1.1\r\nHost: %s\r\n%sContent-Length: 1\r\n\r\n", e.addr, auth)
787 }
788 e.upload()
789 for i, c := range conns {
790 c.SetReadDeadline(time.Now().Add(requestTimeout))
791 res, err := http.ReadResponse(bufio.NewReader(c), nil)
792 if err != nil {
793 t.Fatalf("OPTIONS * on connection %d was not answered: %v", i, err)
794 }
795 reply, _ := io.ReadAll(res.Body)
796 res.Body.Close()
797 if i%2 == 0 {
798 refused(t, "OPTIONS * with no token", res.StatusCode, reply, export.CodeUnauthenticated)
799 } else if res.StatusCode != http.StatusNotFound {
800 t.Errorf("OPTIONS * with the token was answered %d, want 404", res.StatusCode)
801 }
802 if !res.Close {
803 t.Errorf("the receiver kept the connection of OPTIONS * open")
804 }
805 }
806}
807
808// A manifest waits for the store's lock, which a commit holds throughout,
809// and stages nothing once its client goes away. Here the test holds the
810// lock, as a commit does.
811func TestAManifestStopsWaitingWhenItsClientGoesAway(t *testing.T) {
812 e := newEdge(t, exporttest.New(t))
813 e.upload()
814 lock, err := os.OpenFile(filepath.Join(e.state, "lock"), os.O_RDWR, 0)
815 if err != nil {
816 t.Fatal(err)
817 }
818 defer lock.Close()
819 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_EX); err != nil {
820 t.Fatal(err)
821 }
822 signed, _ := e.signedNow()
823 c := e.dial()
824 fmt.Fprintf(c, "POST %s HTTP/1.1\r\nHost: %s\r\nAuthorization: %s\r\nContent-Length: %d\r\n\r\n%s",
825 export.ManifestPath, e.addr, export.Authorization(token), len(signed), signed)
826 if answered(c, time.Second) {
827 t.Fatal("the manifest was answered while the store's lock was held")
828 }
829 c.Close()
830 waitFor(t, "the receiver to give the manifest up", func(context.Context) bool {
831 return e.logged(export.ManifestPath, "waiting for the lock", "context canceled")
832 })
833 if err := syscall.Flock(int(lock.Fd()), syscall.LOCK_UN); err != nil {
834 t.Fatal(err)
835 }
836 if staged := e.staged(); len(staged) != 0 {
837 t.Errorf("a manifest whose client went away left %v staged", staged)
838 }
839 e.upload()
840}
841
842// A manifest whose upload would take the state directory past
843// --max-storage is refused as too-large, and nothing is staged. The cap
844// counts a repository for every project, so a manifest that names one
845// bundle for many projects, which --max-upload counts once, is held to it
846// too. An upload within the cap is accepted.
847func TestAnUploadPastTheStorageCapIsRefused(t *testing.T) {
848 e := newEdge(t, exporttest.New(t), "--max-storage", "4M")
849 x := *e.f.Export
850 x.Projects = append([]export.Project{}, x.Projects...)
851 bundles := map[string]export.Body{}
852 for _, p := range e.f.Manifest.Projects {
853 bundles[p.Name] = p.Bundle
854 }
855 for i := range 6 {
856 p := x.Projects[0]
857 p.Name = fmt.Sprintf("%s-%d", p.Name, i)
858 x.Projects = append(x.Projects, p)
859 bundles[p.Name] = bundles[x.Projects[0].Name]
860 }
861 m, err := export.NewManifest(exporttest.Instance, exporttest.Destination, time.Now().UnixNano(), &x, e.f.ExportJSON, bundles)
862 if err != nil {
863 t.Fatal(err)
864 }
865 if err := m.CheckSizes(1<<30, 2<<30); err != nil {
866 t.Fatalf("the manifest is not within --max-upload: %v", err)
867 }
868 signed, err := m.Sign(exporttest.SignerName, exporttest.Key())
869 if err != nil {
870 t.Fatal(err)
871 }
872 status, reply, _ := e.request(http.MethodPost, export.ManifestPath, signed, nil)
873 refused(t, "a manifest naming one bundle for eight projects", status, reply, export.CodeTooLarge)
874 if staged := e.staged(); len(staged) != 0 {
875 t.Errorf("the refused manifest left %v staged", staged)
876 }
877 e.upload()
878 e.upload()
879}
880
881// waitFor polls done until it reports true, and fails the test unless it
882// does within waitTimeout. done is given a context that ends then, which
883// bounds whatever request it makes.
884func waitFor(t *testing.T, what string, done func(ctx context.Context) bool) {
885 t.Helper()
886 ctx, cancel := context.WithTimeout(context.Background(), waitTimeout)
887 defer cancel()
888 for ctx.Err() == nil {
889 if done(ctx) {
890 return
891 }
892 select {
893 case <-ctx.Done():
894 case <-time.After(20 * time.Millisecond):
895 }
896 }
897 t.Fatalf("timed out waiting for %s", what)
898}
899
900// The receiver stops on SIGTERM within its stop timeout, even with every
901// connection it takes held: four by manifests stalled part way, which
902// hold every request slot, and the rest by idle connections. A further
903// connection waits in the listen queue.
904func TestStopsOnSIGTERM(t *testing.T) {
905 e := newEdge(t, exporttest.New(t))
906 for range maxConns - maxRequests {
907 e.idle()
908 }
909 signed, _ := e.signedNow()
910 e.stallAll(signed)
911 fmt.Fprintf(e.dial(), "OPTIONS * HTTP/1.1\r\nHost: %s\r\nContent-Length: 1\r\n\r\n", e.addr)
912 began := time.Now()
913 if err := e.proc.cmd.Process.Signal(syscall.SIGTERM); err != nil {
914 t.Fatal(err)
915 }
916 select {
917 case <-e.proc.done:
918 case <-time.After(stopTimeout + 10*time.Second):
919 t.Fatalf("valley-web-receive did not stop within %v of SIGTERM", stopTimeout+10*time.Second)
920 }
921 if e.proc.err != nil {
922 t.Errorf("valley-web-receive stopped with %v", e.proc.err)
923 }
924 if took := time.Since(began); took > stopTimeout+5*time.Second {
925 t.Errorf("valley-web-receive took %v to stop, past its stop timeout of %v", took, stopTimeout)
926 }
927}
928
929// A command line it cannot run with gets the usage and exit status 2; a
930// token file it cannot use, or verifiers it cannot read, exit status 1;
931// --help gets the usage alone.
932func TestUsage(t *testing.T) {
933 tokenFile, verifiers := files(t)
934 state := t.TempDir()
935 base := []string{"--state", state, "--listen", "127.0.0.1:0", "--instance", "valley-host", "--destination", "example.org"}
936 for _, args := range [][]string{
937 {},
938 append(base, "--verifiers", verifiers),
939 append(base, "--token-file", tokenFile),
940 {"--state", state, "--listen", "127.0.0.1:0", "--instance", "a b", "--destination", "example.org", "--verifiers", verifiers, "--token-file", tokenFile},
941 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "--max-body", "0"),
942 append(base, "--verifiers", verifiers, "--token-file", tokenFile, "extra"),
943 } {
944 out, err := receiveCmd(args...).CombinedOutput()
945 exit, ok := err.(*exec.ExitError)
946 if !ok || exit.ExitCode() != 2 || !strings.Contains(string(out), "usage: valley-web-receive") {
947 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
948 }
949 }
950 short := filepath.Join(t.TempDir(), "short")
951 if err := os.WriteFile(short, []byte("too-short\n"), 0o600); err != nil {
952 t.Fatal(err)
953 }
954 for _, args := range [][]string{
955 append(base, "--verifiers", verifiers, "--token-file", short),
956 append(base, "--verifiers", tokenFile, "--token-file", tokenFile),
957 } {
958 out, err := receiveCmd(args...).CombinedOutput()
959 if exit, ok := err.(*exec.ExitError); !ok || exit.ExitCode() != 1 {
960 t.Errorf("valley-web-receive %q gave %v:\n%s", args, err, out)
961 }
962 if bytes.Contains(out, []byte(token)) {
963 t.Errorf("valley-web-receive %q printed the token", args)
964 }
965 }
966 out, err := receiveCmd("--help").CombinedOutput()
967 if err != nil || !strings.HasPrefix(string(out), "usage: valley-web-receive") {
968 t.Errorf("valley-web-receive --help gave %v:\n%s", err, out)
969 }
970}