ipn/ipnlocal: fix serve app caps leaking across mounts (#21931)

`serveWebHandler` wrote each mount's accepted app capabilities into the connection-scoped serveHTTPContext. Concurrent h2 streams of one TLS serve connection share that struct, so a request to a mount accepting no capabilities could be proxied carrying another mount's `Tailscale-App-Capabilities` header, letting backends that trust the header authorize the wrong mount.

This change fixes that issue by storing accepted capabilities per-request via a context value instead of a field on the shared struct.

Updates tailscale/corp#50380

Change-Id: I5d0a4a02266018f342ba75a1b3291176738ce05b

Signed-off-by: Mike Jensen <[email protected]>
This commit is contained in:
Mike Jensen authored and GitHub committed 2026-10-24 18:39:53 -06:00
1 parent 729cd431b3
commit 566f89e0fb
2 files changed
+183 -10

No files matched your search

+12 -10
View File
@@ -86,6 +86,14 @@ var ErrProxyToTailscaledSocket = errors.New("cannot proxy to tailscaled socket")
var serveHTTPContextKey ctxkey.Key[*serveHTTPContext]
// appCapsContextKey holds the app capabilities accepted by the mount handling
// the current request. It is per-request state: serveHTTPContext is shared by
// all streams of a connection, so mount state must not be stored on it.
var appCapsContextKey = ctxkey.New("ipnlocal.appCapsContextKey", views.Slice[peercap.Cap]{})
// serveHTTPContext is connection-scoped: one value is shared by all requests on
// the connection, including concurrent h2 streams. Do not add per-request state
// to it, use a separate context key like appCapsContextKey instead.
type serveHTTPContext struct {
SrcAddr netip.AddrPort
ForVIPService tailcfg.ServiceName // "" means local
@@ -93,8 +101,6 @@ type serveHTTPContext struct {
// provides funnel-specific context, nil if not funneled
Funnel *funnelFlow
// AppCapabilities lists all PeerCapabilities that should be forwarded by serve
AppCapabilities views.Slice[peercap.Cap]
}
// funnelFlow represents a funneled connection initiated via IngressPeer
@@ -1149,8 +1155,8 @@ func (b *LocalBackend) addAppCapabilitiesHeader(r *httputil.ProxyRequest) error
if !ok || c.Funnel != nil {
return nil
}
acceptCaps := c.AppCapabilities
if acceptCaps.IsNil() {
acceptCaps, ok := appCapsContextKey.ValueOk(r.Out.Context())
if !ok || acceptCaps.IsNil() {
return nil
}
peerCaps := b.PeerCaps(c.SrcAddr.Addr())
@@ -1218,12 +1224,8 @@ func (b *LocalBackend) serveWebHandler(w http.ResponseWriter, r *http.Request) {
http.Error(w, "unknown proxy destination", http.StatusInternalServerError)
return
}
// Inject app capabilities to forward into the request context
c, ok := serveHTTPContextKey.ValueOk(r.Context())
if !ok {
return
}
c.AppCapabilities = h.AcceptAppCaps()
// Mount-accepted capabilities are per-request state
r = r.WithContext(appCapsContextKey.WithValue(r.Context(), h.AcceptAppCaps()))
h := p.(http.Handler)
// Trim the mount point from the URL path before proxying. (#6571)
if r.URL.Path != "/" {
+171
View File
@@ -25,6 +25,7 @@ import (
"reflect"
"strconv"
"strings"
"sync"
"testing"
"time"
@@ -990,6 +991,176 @@ func TestServeHTTPProxyGrantHeader(t *testing.T) {
}
}
// newAppCapsTestBackend returns a test backend whose peer at 100.150.151.152
// holds the example.com/cap/interesting capability for the node 100.150.151.151.
func newAppCapsTestBackend(t *testing.T) *LocalBackend {
b := newTestBackend(t)
nm := b.NetMapWithPeers()
matches, err := filter.MatchesFromFilterRules([]tailcfg.FilterRule{
{
SrcIPs: []string{"100.150.151.152"},
CapGrant: []tailcfg.CapGrant{{
Dsts: []netip.Prefix{
netip.MustParsePrefix("100.150.151.151/32"),
},
CapMap: tailcfg.PeerCapMap{
"example.com/cap/interesting": []tailcfg.RawMessage{
`{"role": "engineer"}`,
},
},
}},
},
})
if err != nil {
t.Fatal(err)
}
nm.PacketFilter = matches
b.SetControlClientStatus(nil, controlclient.Status{NetMap: nm})
return b
}
// appCapsEchoServer returns a test backend that echoes the
// Tailscale-App-Capabilities request header in its response body.
func appCapsEchoServer(t *testing.T) *httptest.Server {
t.Helper()
testServ := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, r.Header.Get("Tailscale-App-Capabilities"))
},
))
t.Cleanup(testServ.Close)
return testServ
}
// TestServeAppCapsConcurrentStreams verifies that app capabilities accepted by one
// serve mount are not forwarded for requests to another mount, when the requests
// share the connection-scoped serveHTTPContext the way concurrent h2 streams do.
func TestServeAppCapsConcurrentStreams(t *testing.T) {
b := newAppCapsTestBackend(t)
testServ := appCapsEchoServer(t)
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"example.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
"/ops": {
Proxy: testServ.URL,
AcceptAppCaps: []peercap.Cap{"example.com/cap/interesting"},
},
"/admin": {
Proxy: testServ.URL, // accepts no capabilities
},
}},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
// One connection-scoped serveHTTPContext
connCtx := serveHTTPContextKey.WithValue(t.Context(), &serveHTTPContext{
DestPort: 443,
SrcAddr: netip.MustParseAddrPort("100.150.151.152:1234"),
})
newReq := func(path string) *http.Request {
req := &http.Request{
URL: &url.URL{Path: path},
TLS: &tls.ConnectionState{ServerName: "example.ts.net"},
}
return req.WithContext(connCtx)
}
const rounds = 200
var wg sync.WaitGroup
errCh := make(chan error, 2*rounds) // both mounts can fail every round
for range rounds {
wg.Add(2)
go func() {
defer wg.Done()
w := httptest.NewRecorder()
b.serveWebHandler(w, newReq("/ops"))
if got := w.Body.String(); got == "" {
errCh <- fmt.Errorf("/ops: capabilities header missing")
}
}()
go func() {
defer wg.Done()
w := httptest.NewRecorder()
b.serveWebHandler(w, newReq("/admin"))
if got := w.Body.String(); got != "" {
errCh <- fmt.Errorf("/admin: unexpected capabilities header %q", got)
}
}()
}
wg.Wait()
close(errCh)
for err := range errCh {
t.Error(err)
}
}
// TestServeAppCapsPerRequest verifies that the accepted capabilities
// forwarded to the backend match the mount that served each request.
func TestServeAppCapsPerRequest(t *testing.T) {
b := newAppCapsTestBackend(t)
testServ := appCapsEchoServer(t)
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"example.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
"/": {
Proxy: testServ.URL,
AcceptAppCaps: []peercap.Cap{"example.com/cap/interesting"},
},
"/text": {
Text: "not proxied", // no proxy, no capabilities involved
},
}},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
tests := []struct {
name string
path string
wantBody string
}{
{
name: "accepting_mount_forwards_caps",
path: "/",
wantBody: `{"example.com/cap/interesting":[{"role":"engineer"}]}`,
},
{
name: "text_mount_no_caps",
path: "/text",
wantBody: "not proxied",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := &http.Request{
URL: &url.URL{Path: tt.path},
TLS: &tls.ConnectionState{ServerName: "example.ts.net"},
}
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(), &serveHTTPContext{
DestPort: 443,
SrcAddr: netip.MustParseAddrPort("100.150.151.152:1234"),
}))
w := httptest.NewRecorder()
b.serveWebHandler(w, req)
if got := w.Body.String(); got != tt.wantBody {
t.Errorf("capabilities header; want=%q got=%q", tt.wantBody, got)
}
})
}
}
func Test_reverseProxyConfiguration(t *testing.T) {
b := newTestBackend(t)
type test struct {