Files
tailscale/derp/derphttp/derphttp_client_test.go
Pawel Rutkowski 73b4c49b88 derp/derphttp: bound response body read on non-101 upgrade response (#21980)
connect read a non-101 response body with an unbounded io.ReadAll and
inlined it into the returned error.

* Cap the read, format resp.Status instead of the always-nil err, and use %q.
* Add a regression test for the bound

Updates: tailscale/corp#50441

Change-Id: Ie35fada982ccda4328fd4e9adb795947dee3a283
Signed-off-by: Pawel Rutkowski <[email protected]>
2026-10-26 19:47:59 -05:00

63 lines
1.8 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
package derphttp
import (
"bytes"
"context"
"net/http"
"net/http/httptest"
"strings"
"testing"
"tailscale.com/net/netmon"
"tailscale.com/types/key"
)
func TestConnectNon101ResponseBodyBounded(t *testing.T) {
const (
serverResponseBodySize = 1 << 20
// The error wraps the %q-quoted body in a fixed prefix: caller, target URL,
// and HTTP status. That's 102 bytes for an IPv4 loopback URL with a 5-digit
// ephemeral port; an [::1] fallback or a shorter port only shrink it, so 102
// is an upper bound.
maxErrPrefixLen = 102
maxWantLen = maxErrBodyBytes + maxErrPrefixLen
)
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusBadRequest)
// Write far more than the client's cap, to test that it bounds the read.
w.Write(bytes.Repeat([]byte("A"), serverResponseBodySize))
}))
defer srv.Close()
c, err := NewClient(key.NewNode(), srv.URL+"/derp", t.Logf, netmon.NewStatic())
if err != nil {
t.Fatal(err)
}
defer c.Close()
err = c.Connect(context.Background())
if err == nil {
t.Fatal("Connect succeeded against a server that never sent 101; want error")
}
msg := err.Error()
msgLen := len(msg)
if msgLen > maxWantLen {
t.Errorf("error string is %d bytes (server sent a %d byte body); want <= %d. "+
"Is the io.LimitReader around the response body still there?",
msgLen, serverResponseBodySize, maxWantLen)
}
// The server sends far more than the cap, so a short message means the read was truncated too aggressively.
if msgLen < maxErrBodyBytes {
t.Errorf("error string is too short: %d bytes; want >= %d", msgLen, maxErrBodyBytes)
}
if !strings.Contains(msg, "400 Bad Request") {
t.Errorf("error %q does not include the HTTP status", msg)
}
}