| new file mode 100644 |
| index 000000000..b2aad974e |
| --- /dev/null |
| +++ b/internal/edge/demo_api_duplex_test.go |
| @@ -0,0 +1,467 @@ |
| +package edge |
| + |
| +import ( |
| + "bufio" |
| + "crypto/tls" |
| + "errors" |
| + "fmt" |
| + "io" |
| + "log" |
| + "net" |
| + "net/http" |
| + "net/http/httptest" |
| + "slices" |
| + "strings" |
| + "sync" |
| + "sync/atomic" |
| + "syscall" |
| + "testing" |
| + "time" |
| + |
| + "github.com/carlosframework/platform/internal/release" |
| +) |
| + |
| +// #1248: the demo API alias turns on full duplex and leaves the connection |
| +// open for another request. These tests answer a request while its body is |
| +// still arriving, finish the body, and send a second request on the same |
| +// connection. Run them with -race. |
| + |
| +// How the console answers the upload before it has read it. |
| +type demoDuplexConsole int |
| + |
| +const ( |
| + // Answers with Connection: close and returns, with the body unread: how |
| + // a plain net/http handler refuses an upload without waiting for it. |
| + demoConsoleAnswersAndReturns demoDuplexConsole = iota |
| + // Answers, then reads the rest of the body. |
| + demoConsoleAnswersThenReads |
| + // Answers whole on the raw connection, and holds it open unread. |
| + demoConsoleAnswersAndHolds |
| + // Answers with Connection: close and closes. |
| + demoConsoleAnswersAndCloses |
| +) |
| + |
| +func (c demoDuplexConsole) String() string { |
| + return [...]string{"answers-and-returns", "answers-then-reads", "answers-and-holds", "answers-and-closes"}[c] |
| +} |
| + |
| +// A request hidden in the tail of the upload: it is body, and must never be |
| +// parsed as a request of its own. |
| +const demoDuplexSmuggled = "/api/demo/jobs/smuggled" |
| + |
| +const demoDuplexRefusal = "refused" |
| + |
| +type demoDuplexScene struct { |
| + console atomic.Int32 |
| + done atomic.Pointer[chan struct{}] |
| + mu sync.Mutex |
| + seen []string |
| + held []net.Conn |
| +} |
| + |
| +func (s *demoDuplexScene) paths() []string { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + return slices.Clone(s.seen) |
| +} |
| + |
| +func (s *demoDuplexScene) ServeHTTP(w http.ResponseWriter, r *http.Request) { |
| + s.mu.Lock() |
| + s.seen = append(s.seen, r.URL.Path) |
| + s.mu.Unlock() |
| + if r.Method != http.MethodPost { |
| + io.WriteString(w, "second") |
| + return |
| + } |
| + mode := demoDuplexConsole(s.console.Load()) |
| + if mode == demoConsoleAnswersAndHolds || mode == demoConsoleAnswersAndCloses { |
| + conn, _, err := http.NewResponseController(w).Hijack() |
| + if err != nil { |
| + panic(err) |
| + } |
| + head := "HTTP/1.1 403 Forbidden\r\nContent-Length: " + fmt.Sprint(len(demoDuplexRefusal)) + "\r\n" |
| + if mode == demoConsoleAnswersAndCloses { |
| + io.WriteString(conn, head+"Connection: close\r\n\r\n"+demoDuplexRefusal) |
| + conn.Close() |
| + return |
| + } |
| + io.WriteString(conn, head+"\r\n"+demoDuplexRefusal) |
| + s.mu.Lock() |
| + s.held = append(s.held, conn) |
| + s.mu.Unlock() |
| + return |
| + } |
| + rc := http.NewResponseController(w) |
| + if mode == demoConsoleAnswersAndReturns { |
| + w.Header().Set("Connection", "close") |
| + w.WriteHeader(http.StatusForbidden) |
| + io.WriteString(w, demoDuplexRefusal) |
| + return |
| + } |
| + if err := rc.EnableFullDuplex(); err != nil { |
| + panic(err) |
| + } |
| + // A declared length ends the answer for the client while this handler |
| + // is still reading the upload. |
| + w.Header().Set("Content-Length", fmt.Sprint(len(demoDuplexRefusal))) |
| + w.WriteHeader(http.StatusForbidden) |
| + io.WriteString(w, demoDuplexRefusal) |
| + rc.Flush() |
| + if mode == demoConsoleAnswersThenReads { |
| + io.Copy(io.Discard, r.Body) |
| + } |
| +} |
| + |
| +func (s *demoDuplexScene) closeHeld() { |
| + s.mu.Lock() |
| + defer s.mu.Unlock() |
| + for _, c := range s.held { |
| + c.Close() |
| + } |
| + s.held = nil |
| +} |
| + |
| +// When the client sends the rest of the upload. |
| +type demoDuplexTiming int |
| + |
| +const ( |
| + // As soon as it has read the answer. |
| + demoSendsAfterAnswer demoDuplexTiming = iota |
| + // Once the edge's handler has returned. |
| + demoSendsAfterHandler |
| + // As soon as it has read the answer, with the second request in the same |
| + // write. |
| + demoSendsPipelined |
| + // Before any answer: the whole upload and the second request in one |
| + // write, so the transport is still copying the body as the handler ends. |
| + demoSendsWhole |
| +) |
| + |
| +func (d demoDuplexTiming) String() string { |
| + return [...]string{"after-answer", "after-handler", "pipelined", "whole"}[d] |
| +} |
| + |
| +type demoDuplexCase struct { |
| + console demoDuplexConsole |
| + timing demoDuplexTiming |
| + chunked bool |
| + expect bool |
| + // padding is added to the upload's tail, past net/http's post-handler |
| + // read limit when it is large. |
| + padding int |
| +} |
| + |
| +func (c demoDuplexCase) name() string { |
| + name := c.console.String() + "/" + c.timing.String() |
| + if c.chunked { |
| + name += "/chunked" |
| + } |
| + if c.expect { |
| + name += "/expect-continue" |
| + } |
| + if c.padding > 0 { |
| + name += "/large" |
| + } |
| + return name |
| +} |
| + |
| +// demoDuplexGone is whether err is the far side having closed the connection. |
| +func demoDuplexGone(err error) bool { |
| + return errors.Is(err, io.EOF) || errors.Is(err, io.ErrUnexpectedEOF) || errors.Is(err, net.ErrClosed) || |
| + errors.Is(err, syscall.ECONNRESET) || errors.Is(err, syscall.EPIPE) |
| +} |
| + |
| +// runDemoDuplexCase drives one connection and reports whether the edge |
| +// reused it ("reused") or closed it ("closed"). Anything else fails the test: |
| +// a wrong answer, a stall, or the upload's tail parsed as a request. |
| +func runDemoDuplexCase(t *testing.T, conn net.Conn, s *demoDuplexScene, c demoDuplexCase, handlerDone <-chan struct{}) string { |
| + t.Helper() |
| + if err := conn.SetDeadline(time.Now().Add(8 * time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + first := "first-part-" |
| + rest := strings.Repeat("x", c.padding) + "\r\n\r\nGET " + demoDuplexSmuggled + " HTTP/1.1\r\nHost: " + demoAPISite + "\r\n\r\n" |
| + head := "POST /api/demo/apps HTTP/1.1\r\nHost: " + demoAPISite + "\r\nContent-Type: application/json\r\n" |
| + if c.expect { |
| + head += "Expect: 100-continue\r\n" |
| + } |
| + var opening, closing string |
| + if c.chunked { |
| + opening = head + "Transfer-Encoding: chunked\r\n\r\n" + fmt.Sprintf("%x\r\n%s\r\n", len(first), first) |
| + closing = fmt.Sprintf("%x\r\n%s\r\n0\r\n\r\n", len(rest), rest) |
| + } else { |
| + opening = head + fmt.Sprintf("Content-Length: %d\r\n\r\n", len(first)+len(rest)) + first |
| + closing = rest |
| + } |
| + second := "GET /api/demo/jobs/second HTTP/1.1\r\nHost: " + demoAPISite + "\r\n\r\n" |
| + if c.timing == demoSendsWhole { |
| + opening += closing + second |
| + } |
| + |
| + if _, err := io.WriteString(conn, opening); err != nil { |
| + t.Fatalf("sending the start of the upload: %v", err) |
| + } |
| + br := bufio.NewReader(conn) |
| + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost}) |
| + for err == nil && resp.StatusCode < 200 { |
| + resp, err = http.ReadResponse(br, &http.Request{Method: http.MethodPost}) |
| + } |
| + if err != nil { |
| + t.Fatalf("the early answer: %v", err) |
| + } |
| + body, err := io.ReadAll(resp.Body) |
| + if err != nil || resp.StatusCode != http.StatusForbidden || string(body) != demoDuplexRefusal { |
| + t.Fatalf("the early answer: %d %q, %v", resp.StatusCode, body, err) |
| + } |
| + // Sent before the upload ended, the answer must end the connection. |
| + if c.timing != demoSendsWhole && !resp.Close { |
| + t.Fatal("an answer that beat the upload left the connection open") |
| + } |
| + |
| + if c.timing == demoSendsAfterHandler { |
| + select { |
| + case <-handlerDone: |
| + case <-time.After(15 * time.Second): |
| + t.Fatal("the edge's handler did not return after the answer") |
| + } |
| + } |
| + var wrote error |
| + if c.timing == demoSendsWhole { |
| + // Everything is on its way already. |
| + } else if c.timing == demoSendsPipelined { |
| + _, wrote = io.WriteString(conn, closing+second) |
| + } else if _, wrote = io.WriteString(conn, closing); wrote == nil { |
| + _, wrote = io.WriteString(conn, second) |
| + } |
| + if wrote != nil { |
| + if !demoDuplexGone(wrote) { |
| + t.Fatalf("sending the rest: %v", wrote) |
| + } |
| + return "closed" |
| + } |
| + next, err := http.ReadResponse(br, &http.Request{Method: http.MethodGet}) |
| + if err != nil { |
| + if !demoDuplexGone(err) { |
| + t.Fatalf("the second answer: %v", err) |
| + } |
| + return "closed" |
| + } |
| + got, err := io.ReadAll(next.Body) |
| + if err != nil || next.StatusCode != http.StatusOK || string(got) != "second" { |
| + t.Fatalf("the second request was answered %d %q, %v", next.StatusCode, got, err) |
| + } |
| + return "reused" |
| +} |
| + |
| +func checkDemoDuplexPaths(t *testing.T, s *demoDuplexScene, outcome string) { |
| + t.Helper() |
| + paths := s.paths() |
| + if slices.Contains(paths, demoDuplexSmuggled) { |
| + t.Fatalf("the upload's tail reached the console as a request: %v", paths) |
| + } |
| + if outcome == "reused" && !slices.Contains(paths, "/api/demo/jobs/second") { |
| + t.Fatalf("a second answer with no second request at the console: %v", paths) |
| + } |
| +} |
| + |
| +func checkDemoDuplexLog(t *testing.T, who string, logs *lockedBuffer) { |
| + t.Helper() |
| + if text := logs.String(); strings.Contains(text, "panic") { |
| + t.Fatalf("net/http panicked in %s:\n%s", who, text) |
| + } |
| +} |
| + |
| +func demoDuplexCases() []demoDuplexCase { |
| + var cases []demoDuplexCase |
| + for _, console := range []demoDuplexConsole{demoConsoleAnswersAndReturns, demoConsoleAnswersThenReads, demoConsoleAnswersAndHolds, demoConsoleAnswersAndCloses} { |
| + // The handler lingers for its bound here, so one case is enough. |
| + cases = append(cases, demoDuplexCase{console: console, timing: demoSendsAfterHandler}) |
| + for _, timing := range []demoDuplexTiming{demoSendsAfterAnswer, demoSendsPipelined} { |
| + cases = append(cases, |
| + demoDuplexCase{console: console, timing: timing}, |
| + demoDuplexCase{console: console, timing: timing, chunked: true}, |
| + demoDuplexCase{console: console, timing: timing, expect: true}, |
| + // More than net/http will read for a handler that has returned. |
| + demoDuplexCase{console: console, timing: timing, padding: 512 << 10}, |
| + ) |
| + } |
| + // A console closing on an unread upload may reset its own answer away, |
| + // and one holding its connection promised a keep-alive it will not |
| + // serve: with the whole upload written, the transport would reuse it. |
| + if console != demoConsoleAnswersAndCloses && console != demoConsoleAnswersAndHolds { |
| + cases = append(cases, demoDuplexCase{console: console, timing: demoSendsWhole, padding: 128 << 10}) |
| + } |
| + } |
| + return cases |
| +} |
| + |
| +// The console is on this box: the alias's own reverse proxy. |
| +func TestDemoAPIAliasEarlyAnswerKeepAliveLocal(t *testing.T) { |
| + logs := captureLog(t) |
| + demoAPISettings(t) |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + s := &demoDuplexScene{} |
| + t.Cleanup(s.closeHeld) |
| + demoAPIBackend(t, e, s) |
| + front := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + done := s.done.Load() |
| + e.ServeHTTP(w, r) |
| + if r.Method == http.MethodPost && done != nil { |
| + close(*done) |
| + } |
| + })) |
| + // Apart from the console's log: this is the connection under test. |
| + edgeLogs := &lockedBuffer{} |
| + front.Config.ErrorLog = log.New(edgeLogs, "", 0) |
| + front.Start() |
| + t.Cleanup(front.Close) |
| + for _, c := range demoDuplexCases() { |
| + t.Run(c.name(), func(t *testing.T) { |
| + logs.Reset() |
| + edgeLogs.Reset() |
| + // The transport may have pooled a held connection, and the console |
| + // will never answer on it again. |
| + t.Cleanup(s.closeHeld) |
| + s.console.Store(int32(c.console)) |
| + done := make(chan struct{}) |
| + s.done.Store(&done) |
| + conn, err := net.Dial("tcp", front.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + outcome := runDemoDuplexCase(t, conn, s, c, done) |
| + t.Logf("connection %s", outcome) |
| + checkDemoDuplexPaths(t, s, outcome) |
| + checkDemoDuplexLog(t, "the edge's server", edgeLogs) |
| + checkDemoDuplexLog(t, "the console", logs) |
| + }) |
| + } |
| +} |
| + |
| +// The console is on another box: the alias hops to it over the backhaul. |
| +func TestDemoAPIAliasEarlyAnswerKeepAliveHop(t *testing.T) { |
| + logs := captureLog(t) |
| + s := &demoDuplexScene{} |
| + t.Cleanup(s.closeHeld) |
| + scene := NewDemoAPITestIngress(t, s, release.NewDirStore(t.TempDir())) |
| + for _, c := range demoDuplexCases() { |
| + // This ingress offers no signal for its handler returning. |
| + if c.timing == demoSendsAfterHandler { |
| + continue |
| + } |
| + t.Run(c.name(), func(t *testing.T) { |
| + logs.Reset() |
| + // The transport may have pooled a held connection, and the console |
| + // will never answer on it again. |
| + t.Cleanup(s.closeHeld) |
| + s.console.Store(int32(c.console)) |
| + conn, err := tls.Dial("tcp", scene.servers[1].Listener.Addr().String(), &tls.Config{RootCAs: scene.ca.pool, ServerName: demoAPISite, MinVersion: tls.VersionTLS12, NextProtos: []string{"http/1.1"}}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + outcome := runDemoDuplexCase(t, conn, s, c, nil) |
| + t.Logf("connection %s", outcome) |
| + checkDemoDuplexPaths(t, s, outcome) |
| + checkDemoDuplexLog(t, "an edge or the console", logs) |
| + }) |
| + } |
| +} |
| + |
| +// demoDuplexLocalFront is the alias on a real HTTP/1.1 server, with the |
| +// console on this box. |
| +func demoDuplexLocalFront(t *testing.T, s *demoDuplexScene) *httptest.Server { |
| + t.Helper() |
| + demoAPISettings(t) |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + t.Cleanup(s.closeHeld) |
| + demoAPIBackend(t, e, s) |
| + front := httptest.NewServer(e) |
| + t.Cleanup(front.Close) |
| + return front |
| +} |
| + |
| +// A client that stops sending after the early answer does not hold the |
| +// connection: the edge closes it at the linger bound. |
| +func TestDemoAPIAliasEarlyAnswerStalledUploadCloses(t *testing.T) { |
| + s := &demoDuplexScene{} |
| + front := demoDuplexLocalFront(t, s) |
| + conn, err := net.Dial("tcp", front.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + if _, err := io.WriteString(conn, "POST /api/demo/apps HTTP/1.1\r\nHost: "+demoAPISite+"\r\nContent-Length: 100\r\n\r\nstart"); err != nil { |
| + t.Fatal(err) |
| + } |
| + br := bufio.NewReader(conn) |
| + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if body, err := io.ReadAll(resp.Body); err != nil || resp.StatusCode != http.StatusForbidden || string(body) != demoDuplexRefusal || !resp.Close { |
| + t.Fatalf("the early answer: %d %q close=%v, %v", resp.StatusCode, body, resp.Close, err) |
| + } |
| + if _, err := br.ReadByte(); !demoDuplexGone(err) { |
| + t.Fatalf("the stalled connection: %v, want it closed", err) |
| + } |
| +} |
| + |
| +// An upload the console read to its end before answering keeps its |
| +// connection, as every ordinary request does. |
| +func TestDemoAPIAliasWholeUploadKeepsConnection(t *testing.T) { |
| + var calls atomic.Int32 |
| + reader := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { |
| + calls.Add(1) |
| + io.Copy(io.Discard, r.Body) |
| + io.WriteString(w, "ok") |
| + }) |
| + demoAPISettings(t) |
| + e, err := New(openReg(t), nil) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + t.Cleanup(e.probers.Stop) |
| + demoAPIArm(t, e) |
| + demoAPIBackend(t, e, reader) |
| + front := httptest.NewServer(e) |
| + t.Cleanup(front.Close) |
| + conn, err := net.Dial("tcp", front.Listener.Addr().String()) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + defer conn.Close() |
| + if err := conn.SetDeadline(time.Now().Add(10 * time.Second)); err != nil { |
| + t.Fatal(err) |
| + } |
| + br := bufio.NewReader(conn) |
| + for _, framing := range []string{"Content-Length: 5\r\n\r\nhello", "Transfer-Encoding: chunked\r\n\r\n5\r\nhello\r\n0\r\n\r\n"} { |
| + if _, err := io.WriteString(conn, "POST /api/demo/apps HTTP/1.1\r\nHost: "+demoAPISite+"\r\n"+framing); err != nil { |
| + t.Fatal(err) |
| + } |
| + resp, err := http.ReadResponse(br, &http.Request{Method: http.MethodPost}) |
| + if err != nil { |
| + t.Fatal(err) |
| + } |
| + if body, err := io.ReadAll(resp.Body); err != nil || string(body) != "ok" || resp.Close { |
| + t.Fatalf("%q: answer %q close=%v, %v", framing, body, resp.Close, err) |
| + } |
| + } |
| + if calls.Load() != 2 { |
| + t.Fatalf("%d requests reached the console on one connection, want 2", calls.Load()) |
| + } |
| +} |