carlos / platform Public

tunnelclient: keep TLS state through the fleet tunnel wrappers

v0.35.0 regression (#511 Plan 4, R26): a fleet tunnel's h2 server served
refusingConn, which wraps the *tls.Conn and hid its ConnectionState.
x/net sets r.TLS only for a conn that has it, so every tunnelled request
reached the box's edge without TLS, SetXForwarded wrote
X-Forwarded-Proto: http, and Rails force_ssl answered every request with
a 301 to its own URL (fleet boxes on v0.35.0).

servedConn and withTLSState give the wrappers (the fleet refusal and the
handshake's over-read replay) the wrapped conn's TLS state; a plain conn
stays plain. Witness: a force_ssl-style app behind a SetXForwarded proxy,
through Loop over a real TLS tunnel and h2, static and fleet; red before
the fix with the reported 301.

Reviewed by Astra, no open P1. Census: internal/tunnelclient envelope
re-pinned, approved on #280.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>

Squashed from fleet-tunnel-tls-state into main.

(cherry picked from commit a32d70bc034c329f3e164ed7760a9d978166d15d)
claude agent, operated by paul@keymail.dev pushed by paul@keymail.dev 7d168df93b0bf24d21bd2e310b6b3b79aa426c69 parent 26272c9
6 files changed, +202 −2
  • docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md +11 −0
  • internal/provision/testdata/plan14-root-reads-chain.tsv +1 −0
  • internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv +3 −0
  • internal/tunnelclient/tlsstate_test.go +145 −0
  • internal/tunnelclient/tunnelclient.go +41 −1
  • internal/tunnelclient/upgrade.go +1 −1

CI cancelled — superseded by a newer push — run details

diff --git a/docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md b/docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md
new file mode 100644
index 000000000..755f68b8a
--- /dev/null
+++ b/docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md
@@ -0,0 +1,11 @@
+# Census approval: fleet-tunnel-tls-state
+
+Ruling `census-ruling-fleet-tunnel-tls-state`. The independent reviewer approves or rejects every change below, 0 with a new disposition; nothing goes to the census owner (Paul, #280, 2026-10-26).
+
+Envelopes re-pinned: `internal/tunnelclient`.
+
+Review: a model from the other family than the author reads the branch's diff against main on the amadan.net remote (`origin` or `amadan`, whichever points at amadan.net) and gives a verdict for every unit and every re-pinned envelope above. For a unit, compare the change with its recorded disposition and basis below; for an envelope, read every changed function in the package and what it reaches. Reject if the change lets root open, run, query or follow anything it did not before from a path or input a tenant, an app or a box agent can create, write or name; if it weakens a check, refusal, validation, argument or environment the basis relies on; or if the diff cannot settle either. Otherwise approve. Record each verdict on #280 with the tip. A rejected unit goes back to the author to correct; nothing escalates to the census owner.
+
+Seal: `846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332` → `846d1f22e6eb6b2cd8b3086fa554f15deba70418c6542b46b2e2a6a138b6c332`.
+
+Overlay: `internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv`, appended to `internal/provision/testdata/plan14-root-reads-chain.tsv`.
diff --git a/internal/provision/testdata/plan14-root-reads-chain.tsv b/internal/provision/testdata/plan14-root-reads-chain.tsv
index fb8a47b1c..5da2adc86 100644
--- a/internal/provision/testdata/plan14-root-reads-chain.tsv
+++ b/internal/provision/testdata/plan14-root-reads-chain.tsv
@@ -206,3 +206,4 @@ plan14-root-reads-spread-every-schedule-ticks.tsv 07b748a749084fdaf61c5087a6edfc
plan14-root-reads-member-backups-2b.tsv 07b748a749084fdaf61c5087a6edfca8a79273962822ce551dd4d42b0d20c063
plan14-root-reads-instance-gomemlimit-991.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
plan14-root-reads-ppv2-operator-copy.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
+plan14-root-reads-fleet-tunnel-tls-state.tsv 19c9f395547d998f4b5e87e89c0dfa3b5f012d177a87eb5010a8c4defac305dc
diff --git a/internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv b/internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv
new file mode 100644
index 000000000..fadfa1955
--- /dev/null
+++ b/internal/provision/testdata/plan14-root-reads-fleet-tunnel-tls-state.tsv
@@ -0,0 +1,3 @@
+# Census overlay fleet-tunnel-tls-state, written by census-propose (#369). census-ruling-fleet-tunnel-tls-state, approved on #280 before the merge; the approval card is docs/superpowers/notes/census-proposal-fleet-tunnel-tls-state.md.
+# 0 body, 0 sites, 1 envelope: each changed unit re-frozen at its existing disposition with its claim appended.
+@coverage internal/tunnelclient 68935c92a74f148c57ff72311be08d79851691aef6791c1b8b8bde34085457b3
diff --git a/internal/tunnelclient/tlsstate_test.go b/internal/tunnelclient/tlsstate_test.go
new file mode 100644
index 000000000..0f4963f30
--- /dev/null
+++ b/internal/tunnelclient/tlsstate_test.go
@@ -0,0 +1,145 @@
+package tunnelclient
+
+import (
+ "context"
+ "crypto/tls"
+ "fmt"
+ "io"
+ "net"
+ "net/http"
+ "net/http/httptest"
+ "net/http/httputil"
+ "net/url"
+ "testing"
+ "time"
+
+ "golang.org/x/net/http2"
+)
+
+// TestFleetTunnelKeepsHTTPS (v0.35.0 regression): a request that reaches a
+// box over its TLS tunnel is an https request on the box, on a fleet
+// tunnel (Drain set, served through refusingConn) exactly as on a static
+// one. The box's edge derives X-Forwarded-Proto from r.TLS
+// (httputil.ProxyRequest.SetXForwarded), and x/net's server sets r.TLS only
+// when the conn it serves exposes ConnectionState. v0.35.0's refusingConn
+// hid it, so every fleet app saw X-Forwarded-Proto: http, and a Rails app
+// with force_ssl answered every request with a 301 to its own URL.
+//
+// The app here is that app: it redirects unless X-Forwarded-Proto is
+// https, behind a ReverseProxy whose Rewrite calls SetXForwarded, as the
+// box's edge does (setForwarded, internal/edge/homemap.go).
+func TestFleetTunnelKeepsHTTPS(t *testing.T) {
+ for _, tc := range []struct {
+ name string
+ drain bool
+ }{{"static tunnel", false}, {"fleet tunnel", true}} {
+ t.Run(tc.name, func(t *testing.T) {
+ app := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ if r.Header.Get("X-Forwarded-Proto") != "https" {
+ http.Redirect(w, r, "https://"+r.Host+r.URL.RequestURI(), http.StatusMovedPermanently)
+ return
+ }
+ io.WriteString(w, "secure")
+ }))
+ defer app.Close()
+ appURL, _ := url.Parse(app.URL)
+ edge := &httputil.ReverseProxy{Rewrite: func(pr *httputil.ProxyRequest) {
+ pr.SetURL(appURL)
+ pr.Out.Host = pr.In.Host
+ pr.SetXForwarded()
+ }}
+ sawTLS := make(chan bool, 1)
+ handler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ select {
+ case sawTLS <- r.TLS != nil:
+ default:
+ }
+ edge.ServeHTTP(w, r)
+ })
+
+ conns := make(chan *http2.ClientConn, 1)
+ hub := httptest.NewTLSServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
+ conn, bufrw, err := w.(http.Hijacker).Hijack()
+ if err != nil {
+ t.Errorf("hijack: %v", err)
+ return
+ }
+ fmt.Fprintf(bufrw, "HTTP/1.1 101 Switching Protocols\r\nUpgrade: carlos-tunnel/1\r\nConnection: Upgrade\r\n\r\n")
+ bufrw.Flush()
+ cc, err := (&http2.Transport{}).NewClientConn(conn)
+ if err != nil {
+ t.Errorf("h2 client: %v", err)
+ return
+ }
+ conns <- cc
+ }))
+ defer hub.Close()
+ roots := hub.Client().Transport.(*http.Transport).TLSClientConfig.RootCAs
+ old := dialRootCAs
+ dialRootCAs = roots
+ t.Cleanup(func() { dialRootCAs = old })
+
+ var drain chan struct{}
+ if tc.drain {
+ drain = make(chan struct{})
+ }
+ ctx, cancel := context.WithCancel(context.Background())
+ done := make(chan struct{})
+ go func() {
+ defer close(done)
+ Loop(ctx, Config{URL: hub.URL, Name: "pi/box-1", Token: "t", Handler: handler, Drain: drain, Logf: t.Logf})
+ }()
+ defer func() { cancel(); <-done }()
+ var cc *http2.ClientConn
+ select {
+ case cc = <-conns:
+ case <-time.After(5 * time.Second):
+ t.Fatal("the box never connected")
+ }
+ defer cc.Close()
+
+ req, _ := http.NewRequest("GET", "https://shop.example.com/sign_in", nil)
+ resp, err := cc.RoundTrip(req)
+ if err != nil {
+ t.Fatal(err)
+ }
+ body, _ := io.ReadAll(resp.Body)
+ resp.Body.Close()
+ if !<-sawTLS {
+ t.Error("the box saw the tunnelled request without TLS")
+ }
+ if resp.StatusCode != http.StatusOK || string(body) != "secure" {
+ t.Fatalf("got %d %q (location %q), want 200 \"secure\": the app saw the request as http", resp.StatusCode, body, resp.Header.Get("Location"))
+ }
+ })
+ }
+}
+
+// TestWrappedConnsKeepTLSState: each conn the tunnel wraps around its TLS
+// conn (the handshake's over-read replay, the fleet refusal) still exposes
+// that conn's state, and a plain conn's wrapper does not claim one (x/net
+// would reject a zero state as TLS below 1.2).
+func TestWrappedConnsKeepTLSState(t *testing.T) {
+ type stater interface{ ConnectionState() tls.ConnectionState }
+ a, b := net.Pipe()
+ defer a.Close()
+ defer b.Close()
+ tc := tls.Client(a, &tls.Config{InsecureSkipVerify: true})
+ for name, c := range map[string]net.Conn{
+ "buffered": withTLSState(bufferedConn{r: tc, Conn: tc}, tc),
+ "refusing": servedConn(newRefusingConn(tc)),
+ "refusing+buffered": servedConn(newRefusingConn(withTLSState(bufferedConn{r: tc, Conn: tc}, tc))),
+ } {
+ if _, ok := c.(stater); !ok {
+ t.Errorf("%s: TLS state hidden", name)
+ }
+ }
+ for name, c := range map[string]net.Conn{
+ "buffered": withTLSState(bufferedConn{r: a, Conn: a}, a),
+ "refusing": servedConn(newRefusingConn(a)),
+ } {
+ if _, ok := c.(stater); ok {
+ t.Errorf("%s: a plain conn claims TLS state", name)
+ }
+ }
+}
diff --git a/internal/tunnelclient/tunnelclient.go b/internal/tunnelclient/tunnelclient.go
index ce331bfe6..44fb974a6 100644
--- a/internal/tunnelclient/tunnelclient.go
+++ b/internal/tunnelclient/tunnelclient.go
@@ -18,6 +18,7 @@ import (
"bufio"
"context"
"crypto/tls"
+ "crypto/x509"
"fmt"
"io"
"log"
@@ -210,6 +211,44 @@ type bufferedConn struct {
func (b bufferedConn) Read(p []byte) (int, error) { return b.r.Read(p) }
+// dialRootCAs verifies the edge's certificate; nil is the system roots.
+// Only tests set it.
+var dialRootCAs *x509.CertPool
+
+// connectionStater is the method x/net's h2 server looks for on the conn
+// it serves (server.go, ServeConn): only when the conn has it does a
+// request with scheme https get r.TLS. The box's edge derives
+// X-Forwarded-Proto from r.TLS, so a tunnel conn that loses it turns every
+// tunnelled request into plain http at the app (the v0.35.0 fleet tunnel
+// regression: Rails force_ssl answered every request with a 301 to its own
+// URL).
+type connectionStater interface {
+ ConnectionState() tls.ConnectionState
+}
+
+// tlsStateConn is a wrapper conn that still exposes the TLS state of the
+// conn it wraps.
+type tlsStateConn struct {
+ net.Conn
+ st connectionStater
+}
+
+func (c tlsStateConn) ConnectionState() tls.ConnectionState { return c.st.ConnectionState() }
+
+// withTLSState returns outer, a conn wrapping inner, with inner's TLS state
+// when inner has one. A plain inner stays plain: x/net rejects a zero state
+// as TLS below 1.2.
+func withTLSState(outer, inner net.Conn) net.Conn {
+ if st, ok := inner.(connectionStater); ok {
+ return tlsStateConn{Conn: outer, st: st}
+ }
+ return outer
+}
+
+// servedConn is the conn a fleet tunnel's h2 server serves: rc, with the
+// TLS state of the conn rc wraps.
+func servedConn(rc *refusingConn) net.Conn { return withTLSState(rc, rc.Conn) }
+
// Dial performs the registration handshake and returns the raw conn, ready to
// serve h2 on. https URLs use real TLS (the edge's public cert — server auth
// by PKI, client auth by bearer token); http is for tests.
@@ -238,6 +277,7 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
// fails the dial instead of hanging it — and ctx on top of that.
td := &tls.Dialer{NetDialer: dialer, Config: &tls.Config{
ServerName: u.Hostname(),
+ RootCAs: dialRootCAs,
NextProtos: []string{"http/1.1"}, // the handshake is 1.1; h2 starts after the 101
}}
conn, err = td.DialContext(ctx, "tcp", addr)
@@ -290,7 +330,7 @@ func Dial(ctx context.Context, rawURL, name, token string) (net.Conn, error) {
return nil, fmt.Errorf("tunnel: clear handshake deadline: %w", err)
}
if br.Buffered() > 0 {
- return bufferedConn{r: io.MultiReader(br, conn), Conn: conn}, nil
+ return withTLSState(bufferedConn{r: io.MultiReader(br, conn), Conn: conn}, conn), nil
}
return conn, nil
}
diff --git a/internal/tunnelclient/upgrade.go b/internal/tunnelclient/upgrade.go
index 4abf9ed5a..c071ec79c 100644
--- a/internal/tunnelclient/upgrade.go
+++ b/internal/tunnelclient/upgrade.go
@@ -152,7 +152,7 @@ func serveConn(conn net.Conn, handler http.Handler, l Limits, drain <-chan struc
_ = base.Shutdown(context.Background())
}()
rc := newRefusingConn(conn)
- srv.ServeConn(rc, &http2.ServeConnOpts{Handler: streamGate{h: handler, drain: drain, conn: rc}, BaseConfig: base})
+ srv.ServeConn(servedConn(rc), &http2.ServeConnOpts{Handler: streamGate{h: handler, drain: drain, conn: rc}, BaseConfig: base})
}
// upgradeShim is the box half of an upgrade, applied by Mark. A request