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