Files
tailscale/ipn/ipnlocal/serve_test.go
Claus Lensbøl c687660ac5 ipn/ipnlocal{,/netmapcache}: extract file store in prep for new stores (#22266)
The filestore was the only implemented store but we want to be able to
add other stores depending on the platform.

Make space for compiling on more stores, though keep the file store as
the default option.

Updates #22265

Signed-off-by: Claus Lensbøl <[email protected]>
2026-11-13 09:51:10 -05:00

2746 lines
78 KiB
Go

// Copyright (c) Tailscale Inc & contributors
// SPDX-License-Identifier: BSD-3-Clause
//go:build !ts_omit_serve
package ipnlocal
import (
"bytes"
"cmp"
"context"
"crypto/tls"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net"
"net/http"
"net/http/httptest"
"net/netip"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
"tailscale.com/control/controlclient"
"tailscale.com/envknob"
"tailscale.com/health"
"tailscale.com/ipn"
"tailscale.com/ipn/store/mem"
"tailscale.com/net/netmon"
"tailscale.com/net/tsdial"
"tailscale.com/tailcfg"
"tailscale.com/tailcfg/nodecap"
"tailscale.com/tailcfg/peercap"
"tailscale.com/tsd"
"tailscale.com/tstest"
"tailscale.com/tstest/tlstest"
"tailscale.com/types/logger"
"tailscale.com/types/logid"
"tailscale.com/types/netmap"
"tailscale.com/util/eventbus/eventbustest"
"tailscale.com/util/httpm"
"tailscale.com/util/mak"
"tailscale.com/util/must"
"tailscale.com/util/syspolicy/policyclient"
"tailscale.com/wgengine"
"tailscale.com/wgengine/filter"
)
func TestExpandProxyArg(t *testing.T) {
type res struct {
target string
insecure bool
}
tests := []struct {
in string
want res
}{
{"", res{}},
{"3030", res{"http://127.0.0.1:3030", false}},
{"localhost:3030", res{"http://localhost:3030", false}},
{"10.2.3.5:3030", res{"http://10.2.3.5:3030", false}},
{"http://foo.com", res{"http://foo.com", false}},
{"https://foo.com", res{"https://foo.com", false}},
{"https+insecure://10.2.3.4", res{"https://10.2.3.4", true}},
}
for _, tt := range tests {
target, insecure := expandProxyArg(tt.in)
got := res{target, insecure}
if got != tt.want {
t.Errorf("expandProxyArg(%q) = %v, want %v", tt.in, got, tt.want)
}
}
}
func TestParseRedirectWithRedirectCode(t *testing.T) {
tests := []struct {
in string
wantCode int
wantURL string
}{
{"301:https://example.com", 301, "https://example.com"},
{"302:https://example.com", 302, "https://example.com"},
{"303:/path", 303, "/path"},
{"307:https://example.com/path?query=1", 307, "https://example.com/path?query=1"},
{"308:https://example.com", 308, "https://example.com"},
{"https://example.com", 302, "https://example.com"},
{"/path", 302, "/path"},
{"http://example.com", 302, "http://example.com"},
{"git://example.com", 302, "git://example.com"},
{"200:https://example.com", 302, "200:https://example.com"},
{"404:https://example.com", 302, "404:https://example.com"},
{"500:https://example.com", 302, "500:https://example.com"},
{"30:https://example.com", 302, "30:https://example.com"},
{"3:https://example.com", 302, "3:https://example.com"},
{"3012:https://example.com", 302, "3012:https://example.com"},
{"abc:https://example.com", 302, "abc:https://example.com"},
{"301", 302, "301"},
}
for _, tt := range tests {
gotCode, gotURL := parseRedirectWithCode(tt.in)
if gotCode != tt.wantCode || gotURL != tt.wantURL {
t.Errorf("parseRedirectWithCode(%q) = (%d, %q), want (%d, %q)",
tt.in, gotCode, gotURL, tt.wantCode, tt.wantURL)
}
}
}
func TestGetServeHandler(t *testing.T) {
const serverName = "example.ts.net"
conf1 := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
serverName + ":443": {
Handlers: map[string]*ipn.HTTPHandler{
"/": {},
"/bar": {},
"/foo/": {},
"/foo/bar": {},
"/foo/bar/": {},
},
},
},
}
tests := []struct {
name string
port uint16 // or 443 is zero
path string // http.Request.URL.Path
conf *ipn.ServeConfig
want string // mountPoint
}{
{
name: "nothing",
path: "/",
conf: nil,
want: "",
},
{
name: "root",
conf: conf1,
path: "/",
want: "/",
},
{
name: "root-other",
conf: conf1,
path: "/other",
want: "/",
},
{
name: "bar",
conf: conf1,
path: "/bar",
want: "/bar",
},
{
name: "foo-bar",
conf: conf1,
path: "/foo/bar",
want: "/foo/bar",
},
{
name: "foo-bar-slash",
conf: conf1,
path: "/foo/bar/",
want: "/foo/bar/",
},
{
name: "foo-bar-other",
conf: conf1,
path: "/foo/bar/other",
want: "/foo/bar/",
},
{
name: "foo-other",
conf: conf1,
path: "/foo/other",
want: "/foo/",
},
{
name: "foo-no-trailing-slash",
conf: conf1,
path: "/foo",
want: "/foo/",
},
{
name: "dot-dots",
conf: conf1,
path: "/foo/../../../../../../../../etc/passwd",
want: "/",
},
// Malformed request targets that net/http hands the handler verbatim.
// These clean to a path.Dir fixed point ("*" or ".") that never reaches
// "/", and once spun the getServeHandler loop below forever (a remote
// serve/funnel DoS). They must resolve to not-found, not hang.
{
name: "asterisk", // "GET *"
conf: conf1,
path: "*",
want: "",
},
{
name: "empty", // "CONNECT" authority-form sets URL.Path to ""
conf: conf1,
path: "",
want: "",
},
{
name: "dot",
conf: conf1,
path: ".",
want: "",
},
{
name: "asterisk-subpath",
conf: conf1,
path: "*/foo",
want: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
b := &LocalBackend{
serveConfig: tt.conf.View(),
logf: t.Logf,
health: health.NewTracker(eventbustest.NewBus(t)),
}
req := &http.Request{
URL: &url.URL{
Path: tt.path,
},
TLS: &tls.ConnectionState{ServerName: serverName},
}
port := cmp.Or(tt.port, 443)
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(), &serveHTTPContext{
DestPort: port,
}))
// A malformed target like "*" or "" once spun getServeHandler's
// path-walk loop forever; a regression would hang here until the
// package test timeout fires.
h, got, ok := b.getServeHandler(req)
if (got != "") != ok {
t.Fatalf("got ok=%v, but got mountPoint=%q", ok, got)
}
if h.Valid() != ok {
t.Fatalf("got ok=%v, but valid=%v", ok, h.Valid())
}
if got != tt.want {
t.Errorf("got handler at mount %q, want %q", got, tt.want)
}
})
}
}
// TestServeConfigForeground tests the inter-dependency
// between a ServeConfig and a WatchIPNBus:
// 1. Creating a WatchIPNBus returns a sessionID, that
// 2. ServeConfig sets it as the key of the Foreground field.
// 3. ServeConfig expects the WatchIPNBus to clean up the Foreground
// config when the session is done.
// 4. WatchIPNBus expects the ServeConfig to send a signal (close the channel)
// if an incoming SetServeConfig removes previous foregrounds.
func TestServeConfigForeground(t *testing.T) {
b := newTestBackend(t)
ch1 := make(chan string, 1)
go func() {
defer close(ch1)
b.WatchNotifications(context.Background(), ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
if roNotify.SessionID != "" {
ch1 <- roNotify.SessionID
}
return true
})
}()
ch2 := make(chan string, 1)
go func() {
b.WatchNotifications(context.Background(), ipn.NotifyInitialState, nil, func(roNotify *ipn.Notify) (keepGoing bool) {
if roNotify.SessionID != "" {
ch2 <- roNotify.SessionID
return true
}
ch2 <- "again" // let channel know fn was called again
return true
})
}()
var session1 string
select {
case session1 = <-ch1:
case <-time.After(time.Second):
t.Fatal("timed out waiting on watch notifications session id")
}
var session2 string
select {
case session2 = <-ch2:
case <-time.After(time.Second):
t.Fatal("timed out waiting on watch notifications session id")
}
err := b.SetServeConfig(&ipn.ServeConfig{
Foreground: map[string]*ipn.ServeConfig{
session1: {
TCP: map[uint16]*ipn.TCPPortHandler{
443: {TCPForward: "http://localhost:3000"},
},
},
session2: {
TCP: map[uint16]*ipn.TCPPortHandler{
999: {TCPForward: "http://localhost:4000"},
},
},
},
}, "")
if err != nil {
t.Fatal(err)
}
// Introduce a race between [LocalBackend] sending notifications
// and [LocalBackend.WatchNotifications] shutting down due to
// setting the serve config below.
const N = 1000
for range N {
go b.send(ipn.Notify{})
}
// Setting a new serve config should shut down WatchNotifications
// whose session IDs are no longer found: session1 goes, session2 stays.
err = b.SetServeConfig(&ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
5000: {TCPForward: "http://localhost:5000"},
},
Foreground: map[string]*ipn.ServeConfig{
session2: {
TCP: map[uint16]*ipn.TCPPortHandler{
999: {TCPForward: "http://localhost:4000"},
},
},
},
}, "")
if err != nil {
t.Fatal(err)
}
select {
case _, ok := <-ch1:
if ok {
t.Fatal("expected channel to be closed")
}
case <-time.After(time.Second):
t.Fatal("timed out waiting on watch notifications closing")
}
// check that the second session is still running
b.send(ipn.Notify{})
select {
case _, ok := <-ch2:
if !ok {
t.Fatal("expected second session to remain open")
}
case <-time.After(time.Second):
t.Fatal("timed out waiting on second session")
}
}
// TestServeConfigServices tests the side effects of setting the
// Services field in a ServeConfig. The Services field is a map
// of all services the current service host is serving. Unlike what we
// serve for node itself, there is no foreground and no local handlers
// for the services. So the only things we need to test are if the
// services configured are valid and if they correctly set intercept
// functions for netStack.
func TestServeConfigServices(t *testing.T) {
b := newTestBackend(t)
svcIPMap := tailcfg.ServiceIPMappings{
"svc:foo": []netip.Addr{
netip.MustParseAddr("100.101.101.101"),
netip.MustParseAddr("fd7a:115c:a1e0:ab12:4843:cd96:6565:6565"),
},
"svc:bar": []netip.Addr{
netip.MustParseAddr("100.99.99.99"),
netip.MustParseAddr("fd7a:115c:a1e0:ab12:4843:cd96:626b:628b"),
},
}
svcIPMapJSON, err := json.Marshal(svcIPMap)
if err != nil {
t.Fatal(err)
}
b.currentNode().SetNetMap(&netmap.NetworkMap{
SelfNode: (&tailcfg.Node{
Name: "example.ts.net",
CapMap: tailcfg.NodeCapMap{
nodecap.ServiceHost: []tailcfg.RawMessage{tailcfg.RawMessage(svcIPMapJSON)},
},
}).View(),
UserProfiles: map[tailcfg.UserID]tailcfg.UserProfileView{
tailcfg.UserID(1): (&tailcfg.UserProfile{
LoginName: "[email protected]",
DisplayName: "Some One",
ProfilePicURL: "https://example.com/photo.jpg",
}).View(),
},
})
tests := []struct {
name string
conf *ipn.ServeConfig
errExpected bool
packetDstAddrPort []netip.AddrPort
intercepted bool
}{
{
name: "no-services",
conf: &ipn.ServeConfig{},
packetDstAddrPort: []netip.AddrPort{
netip.MustParseAddrPort("100.101.101.101:443"),
},
intercepted: false,
},
{
name: "one-incorrectly-configured-service",
conf: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
},
Tun: true,
},
},
},
errExpected: true,
},
{
// one correctly configured service with packet should be intercepted
name: "one-service-intercept-packet",
conf: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
81: {HTTPS: true},
},
},
},
},
packetDstAddrPort: []netip.AddrPort{
netip.MustParseAddrPort("100.101.101.101:80"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:6565:6565]:80"),
},
intercepted: true,
},
{
// one correctly configured service with packet should not be intercepted
name: "one-service-not-intercept-packet",
conf: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
81: {HTTPS: true},
},
},
},
},
packetDstAddrPort: []netip.AddrPort{
netip.MustParseAddrPort("100.99.99.99:80"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80"),
netip.MustParseAddrPort("100.101.101.101:82"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:6565:6565]:82"),
},
intercepted: false,
},
{
// multiple correctly configured service with packet should be intercepted
name: "multiple-service-intercept-packet",
conf: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
81: {HTTPS: true},
},
},
"svc:bar": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
81: {HTTPS: true},
82: {HTTPS: true},
},
},
},
},
packetDstAddrPort: []netip.AddrPort{
netip.MustParseAddrPort("100.99.99.99:80"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80"),
netip.MustParseAddrPort("100.101.101.101:81"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:6565:6565]:81"),
},
intercepted: true,
},
{
// multiple correctly configured service with packet should not be intercepted
name: "multiple-service-not-intercept-packet",
conf: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
81: {HTTPS: true},
},
},
"svc:bar": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {HTTP: true},
81: {HTTPS: true},
82: {HTTPS: true},
},
},
},
},
packetDstAddrPort: []netip.AddrPort{
// ips in capmap but port is not hosting service
netip.MustParseAddrPort("100.99.99.99:77"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:77"),
netip.MustParseAddrPort("100.101.101.101:85"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:6565:6565]:85"),
// ips not in capmap
netip.MustParseAddrPort("100.102.102.102:80"),
netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:6666:6666]:80"),
},
intercepted: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := b.SetServeConfig(tt.conf, "")
if err == nil && tt.errExpected {
t.Fatal("expected error")
}
if err != nil {
if tt.errExpected {
return
}
t.Fatal(err)
}
for _, addrPort := range tt.packetDstAddrPort {
if tt.intercepted != b.ShouldInterceptVIPServiceTCPPort(addrPort) {
if tt.intercepted {
t.Fatalf("expected packet to be intercepted")
} else {
t.Fatalf("expected packet not to be intercepted")
}
}
}
})
}
}
func TestServeConfigETag(t *testing.T) {
b := newTestBackend(t)
// the etag should be valid even when there is no config
_, emptyStateETag, err := b.ServeConfigETag()
if err != nil {
t.Fatal(err)
}
// a nil config with the empty-state etag should succeed
err = b.SetServeConfig(nil, emptyStateETag)
if err != nil {
t.Fatal(err)
}
// a nil config with an invalid etag should fail
err = b.SetServeConfig(nil, "abc")
if !errors.Is(err, ErrETagMismatch) {
t.Fatal("expected an error but got nil")
}
// a new config with the empty-state etag should succeed
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"example.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
"/": {Proxy: "http://127.0.0.1:3000"},
}},
},
}
err = b.SetServeConfig(conf, emptyStateETag)
if err != nil {
t.Fatal(err)
}
confView, etag, err := b.ServeConfigETag()
if err != nil {
t.Fatal(err)
}
conf = confView.AsStruct()
mak.Set(&conf.AllowFunnel, "example.ts.net:443", true)
// replacing an existing config with an invalid etag should fail
err = b.SetServeConfig(conf, "invalid etag")
if !errors.Is(err, ErrETagMismatch) {
t.Fatalf("expected an etag mismatch error but got %v", err)
}
// replacing an existing config with a valid etag should succeed
err = b.SetServeConfig(conf, etag)
if err != nil {
t.Fatal(err)
}
// replacing an existing config with a previous etag should fail
err = b.SetServeConfig(nil, etag)
if !errors.Is(err, ErrETagMismatch) {
t.Fatalf("expected an etag mismatch error but got %v", err)
}
// replacing an existing config with the new etag should succeed
_, etag, err = b.ServeConfigETag()
if err != nil {
t.Fatal(err)
}
err = b.SetServeConfig(nil, etag)
if err != nil {
t.Fatal(err)
}
}
func TestServeHTTPProxyPath(t *testing.T) {
b := newTestBackend(t)
// Start test serve endpoint.
testServ := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// Set the request URL path to a response header, so the
// requested URL path can be checked in tests.
t.Logf("adding path %s", r.URL.Path)
w.Header().Add("Path", r.URL.Path)
},
))
defer testServ.Close()
tests := []struct {
name string
mountPoint string
proxyPath string
requestPath string
wantRequestPath string
}{
{
name: "foo-to-foo-mount-foo",
mountPoint: "/foo",
proxyPath: "/foo",
requestPath: "/foo",
wantRequestPath: "/foo",
},
{
name: "foo-slash-to-foo-slash-mount-foo",
mountPoint: "/foo",
proxyPath: "/foo",
requestPath: "/foo/",
wantRequestPath: "/foo/",
},
{
name: "foo-to-foo-slash-mount-foo-slash",
mountPoint: "/foo/",
proxyPath: "/foo/",
requestPath: "/foo",
wantRequestPath: "/foo/",
},
{
name: "root-to-root-mount-root",
mountPoint: "/",
proxyPath: "/",
requestPath: "/",
wantRequestPath: "/",
},
{
name: "foo-to-foo-mount-root",
mountPoint: "/",
proxyPath: "/",
requestPath: "/foo",
wantRequestPath: "/foo",
},
{
name: "foo-bar-to-foo-bar-mount-foo",
mountPoint: "/foo",
proxyPath: "/foo",
requestPath: "/foo/bar",
wantRequestPath: "/foo/bar",
},
{
name: "foo-bar-baz-to-foo-bar-baz-mount-foo",
mountPoint: "/foo",
proxyPath: "/foo",
requestPath: "/foo/bar/baz",
wantRequestPath: "/foo/bar/baz",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"example.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
tt.mountPoint: {Proxy: testServ.URL + tt.proxyPath},
}},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
req := &http.Request{
URL: &url.URL{Path: tt.requestPath},
TLS: &tls.ConnectionState{ServerName: "example.ts.net"},
}
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(),
&serveHTTPContext{
DestPort: 443,
SrcAddr: netip.MustParseAddrPort("1.2.3.4:1234"), // random src
}))
w := httptest.NewRecorder()
b.serveWebHandler(w, req)
// Verify what path was requested
p := w.Result().Header.Get("Path")
if p != tt.wantRequestPath {
t.Errorf("wanted request path %s got %s", tt.wantRequestPath, p)
}
})
}
}
func TestServeHTTPProxyHeaders(t *testing.T) {
b := newTestBackend(t)
// Start test serve endpoint.
testServ := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// Piping all the headers through the response writer
// so we can check their values in tests below.
for key, val := range r.Header {
w.Header().Add(key, strings.Join(val, ","))
}
},
))
defer testServ.Close()
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"example.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
"/": {Proxy: testServ.URL},
}},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
type headerCheck struct {
header string
want string
}
tests := []struct {
name string
srcIP string
wantHeaders []headerCheck
}{
{
name: "request-from-user-within-tailnet",
srcIP: "100.150.151.152",
wantHeaders: []headerCheck{
{"X-Forwarded-Proto", "https"},
{"X-Forwarded-For", "100.150.151.152"},
{"Tailscale-User-Login", "[email protected]"},
{"Tailscale-User-Name", "Some One"},
{"Tailscale-User-Profile-Pic", "https://example.com/photo.jpg"},
{"Tailscale-Headers-Info", "https://tailscale.com/s/serve-headers"},
},
},
{
name: "request-from-tagged-node-within-tailnet",
srcIP: "100.150.151.153",
wantHeaders: []headerCheck{
{"X-Forwarded-Proto", "https"},
{"X-Forwarded-For", "100.150.151.153"},
{"Tailscale-User-Login", ""},
{"Tailscale-User-Name", ""},
{"Tailscale-User-Profile-Pic", ""},
{"Tailscale-Headers-Info", ""},
},
},
{
name: "request-from-outside-tailnet",
srcIP: "100.160.161.162",
wantHeaders: []headerCheck{
{"X-Forwarded-Proto", "https"},
{"X-Forwarded-For", "100.160.161.162"},
{"Tailscale-User-Login", ""},
{"Tailscale-User-Name", ""},
{"Tailscale-User-Profile-Pic", ""},
{"Tailscale-Headers-Info", ""},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := &http.Request{
URL: &url.URL{Path: "/"},
TLS: &tls.ConnectionState{ServerName: "example.ts.net"},
Header: spoofedTailscaleHeaders(),
}
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(), &serveHTTPContext{
DestPort: 443,
SrcAddr: netip.MustParseAddrPort(tt.srcIP + ":1234"), // random src port for tests
}))
w := httptest.NewRecorder()
b.serveWebHandler(w, req)
// Verify the headers.
h := w.Result().Header
for _, c := range tt.wantHeaders {
if got := h.Get(c.header); got != c.want {
t.Errorf("invalid %q header; want=%q, got=%q", c.header, c.want, got)
}
}
checkNoSpoofedTailscaleHeaders(t, h)
})
}
}
func TestServeHTTPProxyGrantHeader(t *testing.T) {
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": "🐿"}`,
},
},
}},
},
{
SrcIPs: []string{"100.150.151.153"},
CapGrant: []tailcfg.CapGrant{{
Dsts: []netip.Prefix{
netip.MustParsePrefix("100.150.151.151/32"),
},
CapMap: tailcfg.PeerCapMap{
"example.com/cap/boring": []tailcfg.RawMessage{
`{"role": "Viewer"}`,
},
"example.com/cap/irrelevant": []tailcfg.RawMessage{
`{"role": "Editor"}`,
},
},
}},
},
})
if err != nil {
t.Fatal(err)
}
nm.PacketFilter = matches
b.SetControlClientStatus(nil, controlclient.Status{NetMap: nm})
// Start test serve endpoint.
testServ := httptest.NewServer(http.HandlerFunc(
func(w http.ResponseWriter, r *http.Request) {
// Piping all the headers through the response writer
// so we can check their values in tests below.
for key, val := range r.Header {
w.Header().Add(key, strings.Join(val, ","))
}
},
))
defer testServ.Close()
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", "example.com/cap/boring"},
},
}},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
type headerCheck struct {
header string
want string
}
tests := []struct {
name string
srcIP string
wantHeaders []headerCheck
}{
{
name: "request-from-user-within-tailnet",
srcIP: "100.150.151.152",
wantHeaders: []headerCheck{
{"X-Forwarded-Proto", "https"},
{"X-Forwarded-For", "100.150.151.152"},
{"Tailscale-User-Login", "[email protected]"},
{"Tailscale-User-Name", "Some One"},
{"Tailscale-User-Profile-Pic", "https://example.com/photo.jpg"},
{"Tailscale-Headers-Info", "https://tailscale.com/s/serve-headers"},
{"Tailscale-App-Capabilities", `{"example.com/cap/interesting":[{"role":"🐿"}]}`},
},
},
{
name: "request-from-tagged-node-within-tailnet",
srcIP: "100.150.151.153",
wantHeaders: []headerCheck{
{"X-Forwarded-Proto", "https"},
{"X-Forwarded-For", "100.150.151.153"},
{"Tailscale-User-Login", ""},
{"Tailscale-User-Name", ""},
{"Tailscale-User-Profile-Pic", ""},
{"Tailscale-Headers-Info", ""},
{"Tailscale-App-Capabilities", `{"example.com/cap/boring":[{"role":"Viewer"}]}`},
},
},
{
name: "request-from-outside-tailnet",
srcIP: "100.160.161.162",
wantHeaders: []headerCheck{
{"X-Forwarded-Proto", "https"},
{"X-Forwarded-For", "100.160.161.162"},
{"Tailscale-User-Login", ""},
{"Tailscale-User-Name", ""},
{"Tailscale-User-Profile-Pic", ""},
{"Tailscale-Headers-Info", ""},
{"Tailscale-App-Capabilities", ""},
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
req := &http.Request{
URL: &url.URL{Path: "/"},
TLS: &tls.ConnectionState{ServerName: "example.ts.net"},
Header: spoofedTailscaleHeaders(),
}
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(), &serveHTTPContext{
DestPort: 443,
SrcAddr: netip.MustParseAddrPort(tt.srcIP + ":1234"), // random src port for tests
}))
w := httptest.NewRecorder()
b.serveWebHandler(w, req)
// Verify the headers. The contract with users is that identity and grant headers containing non-ASCII
// UTF-8 characters will be Q-encoded.
h := w.Result().Header
dec := new(mime.WordDecoder)
for _, c := range tt.wantHeaders {
maybeEncoded := h.Get(c.header)
got, err := dec.DecodeHeader(maybeEncoded)
if err != nil {
t.Fatalf("invalid %q header; failed to decode: %v", maybeEncoded, err)
}
if got != c.want {
t.Errorf("invalid %q header; want=%q, got=%q", c.header, c.want, got)
}
}
checkNoSpoofedTailscaleHeaders(t, h)
})
}
}
// spoofedTailscaleHeaders returns client-supplied request headers that try to
// impersonate the headers set by `tailscale serve`. This includes variants
// using '_' in place of '-' that CGI-style backends treat as equivalent.
func spoofedTailscaleHeaders() http.Header {
h := http.Header{}
for _, name := range []string{
"Tailscale-User-Login",
"Tailscale-User-Name",
"Tailscale-User-Profile-Pic",
"Tailscale-Funnel-Request",
"Tailscale-Headers-Info",
"Tailscale-App-Capabilities",
} {
h[name] = []string{"spoofed"}
h[strings.ReplaceAll(name, "-", "_")] = []string{"spoofed"}
h[http.CanonicalHeaderKey(strings.ReplaceAll(strings.ToLower(name), "-", "_"))] = []string{"spoofed"}
}
return h
}
// checkNoSpoofedTailscaleHeaders reports an error if any value from
// spoofedTailscaleHeaders made it to the backend.
func checkNoSpoofedTailscaleHeaders(t *testing.T, h http.Header) {
t.Helper()
for k, vv := range h {
for _, v := range vv {
if strings.Contains(v, "spoofed") {
t.Errorf("spoofed header %q reached backend: %q", k, v)
}
}
}
}
// 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 {
backend string
path string
// set to false to test that a proxy has been removed
shouldExist bool
wantsInsecure bool
wantsURL url.URL
}
runner := func(name string, tests []test) {
t.Logf("running tests for %s", name)
host := ipn.HostPort("http://example.ts.net:80")
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
host: {Handlers: map[string]*ipn.HTTPHandler{}},
},
}
for _, tt := range tests {
if tt.shouldExist {
conf.Web[host].Handlers[tt.path] = &ipn.HTTPHandler{Proxy: tt.backend}
}
}
if err := b.setServeConfigLocked(conf, ""); err != nil {
t.Fatal(err)
}
// test that reverseproxies have been set up as expected
for _, tt := range tests {
rp, ok := b.serveProxyHandlers.Load(tt.backend)
if !tt.shouldExist && ok {
t.Errorf("proxy for backend %s should not exist, but it does", tt.backend)
}
if !tt.shouldExist {
continue
}
parsedRp, ok := rp.(*reverseProxy)
if !ok {
t.Errorf("proxy for backend %q is not a reverseproxy", tt.backend)
}
if parsedRp.insecure != tt.wantsInsecure {
t.Errorf("proxy for backend %q should be insecure: %v got insecure: %v", tt.backend, tt.wantsInsecure, parsedRp.insecure)
}
if !reflect.DeepEqual(*parsedRp.url, tt.wantsURL) {
t.Errorf("proxy for backend %q should have URL %#+v, got URL %+#v", tt.backend, &tt.wantsURL, parsedRp.url)
}
if tt.backend != parsedRp.backend {
t.Errorf("proxy for backend %q should have backend %q got %q", tt.backend, tt.backend, parsedRp.backend)
}
}
}
// configure local backend with some proxy backends
runner("initial proxy configs", []test{
{
backend: "http://example.com/docs",
path: "/example",
shouldExist: true,
wantsInsecure: false,
wantsURL: mustCreateURL(t, "http://example.com/docs"),
},
{
backend: "https://example1.com",
path: "/example1",
shouldExist: true,
wantsInsecure: false,
wantsURL: mustCreateURL(t, "https://example1.com"),
},
{
backend: "https+insecure://example2.com",
path: "/example2",
shouldExist: true,
wantsInsecure: true,
wantsURL: mustCreateURL(t, "https://example2.com"),
},
})
// reconfigure the local backend with different proxies
runner("reloaded proxy configs", []test{
{
backend: "http://example.com/docs",
path: "/example",
shouldExist: true,
wantsInsecure: false,
wantsURL: mustCreateURL(t, "http://example.com/docs"),
},
{
backend: "https://example1.com",
shouldExist: false,
},
{
backend: "https+insecure://example2.com",
shouldExist: false,
},
{
backend: "https+insecure://example3.com",
path: "/example3",
shouldExist: true,
wantsInsecure: true,
wantsURL: mustCreateURL(t, "https://example3.com"),
},
})
}
func TestServeMaxIdleConnsPerHost(t *testing.T) {
for _, tt := range []struct {
name string
env string
want int
}{
{name: "default", want: 0},
{name: "configured", env: "100", want: 100},
} {
t.Run(tt.name, func(t *testing.T) {
envknob.SetenvForTest(t, "TS_DEBUG_SERVE_MAX_IDLE_CONNS_PER_HOST", tt.env)
rp := &reverseProxy{lb: &LocalBackend{dialer: tsdial.NewDialer(netmon.NewStatic())}}
if got := rp.getTransport().MaxIdleConnsPerHost; got != tt.want {
t.Errorf("MaxIdleConnsPerHost = %d, want %d", got, tt.want)
}
})
}
}
func mustCreateURL(t *testing.T, u string) url.URL {
t.Helper()
uParsed, err := url.Parse(u)
if err != nil {
t.Fatalf("failed parsing url: %v", err)
}
return *uParsed
}
func newTestBackend(t *testing.T, opts ...any) *LocalBackend {
var logf logger.Logf = logger.Discard
const debug = false
if debug {
logf = logger.WithPrefix(tstest.WhileTestRunningLogger(t), "... ")
}
bus := eventbustest.NewBus(t)
sys := tsd.NewSystemWithBus(bus)
for _, o := range opts {
switch v := o.(type) {
case policyclient.Client:
sys.PolicyClient.Set(v)
default:
panic(fmt.Sprintf("unsupported option type %T", v))
}
}
e, err := wgengine.NewUserspaceEngine(logf, wgengine.Config{
SetSubsystem: sys.Set,
HealthTracker: sys.HealthTracker.Get(),
Metrics: sys.UserMetricsRegistry(),
EventBus: sys.Bus.Get(),
})
if err != nil {
t.Fatal(err)
}
sys.Set(e)
sys.Set(new(mem.Store))
// Create temp dir before setting up the backend and the shutdown to ensure
// cleanup can happen nicely with the full file system.
dir := t.TempDir()
b, err := NewLocalBackend(logf, logid.PublicID{}, sys, 0)
if err != nil {
t.Fatal(err)
}
t.Cleanup(b.Shutdown)
b.SetVarRoot(dir)
pm := must.Get(newProfileManager(new(mem.Store), logf, health.NewTracker(bus)))
pm.currentProfile = (&ipn.LoginProfile{ID: "id0"}).View()
b.pm = pm
b.currentNode().SetNetMap(&netmap.NetworkMap{
SelfNode: (&tailcfg.Node{
Name: "example.ts.net",
Addresses: []netip.Prefix{
netip.MustParsePrefix("100.150.151.151/32"),
},
}).View(),
UserProfiles: map[tailcfg.UserID]tailcfg.UserProfileView{
tailcfg.UserID(1): (&tailcfg.UserProfile{
LoginName: "[email protected]",
DisplayName: "Some One",
ProfilePicURL: "https://example.com/photo.jpg",
}).View(),
},
Peers: []tailcfg.NodeView{
(&tailcfg.Node{
ID: 152,
ComputedName: "some-peer",
User: tailcfg.UserID(1),
Key: makeNodeKeyFromID(152),
Addresses: []netip.Prefix{
netip.MustParsePrefix("100.150.151.152/32"),
},
}).View(),
(&tailcfg.Node{
ID: 153,
ComputedName: "some-tagged-peer",
Tags: []string{"tag:server", "tag:test"},
User: tailcfg.UserID(1),
Key: makeNodeKeyFromID(153),
Addresses: []netip.Prefix{
netip.MustParsePrefix("100.150.151.153/32"),
},
}).View(),
},
})
return b
}
func TestServeFileOrDirectory(t *testing.T) {
td := t.TempDir()
writeFile := func(suffix, contents string) {
if err := os.WriteFile(filepath.Join(td, suffix), []byte(contents), 0o600); err != nil {
t.Fatal(err)
}
}
writeFile("foo", "this is foo")
writeFile("bar", "this is bar")
os.MkdirAll(filepath.Join(td, "subdir"), 0o700)
os.MkdirAll(filepath.Join(td, "subdir", "nested"), 0o700)
writeFile("subdir/file-a", "this is A")
writeFile("subdir/file-b", "this is B")
writeFile("subdir/file-c", "this is C")
writeFile("subdir/nested/index.html", "this is nested index")
contains := func(subs ...string) func([]byte, *http.Response) error {
return func(resBody []byte, res *http.Response) error {
for _, sub := range subs {
if !bytes.Contains(resBody, []byte(sub)) {
return fmt.Errorf("response body does not contain %q: %s", sub, resBody)
}
}
return nil
}
}
isStatus := func(wantCode int) func([]byte, *http.Response) error {
return func(resBody []byte, res *http.Response) error {
if res.StatusCode != wantCode {
return fmt.Errorf("response status = %d; want %d", res.StatusCode, wantCode)
}
return nil
}
}
isRedirect := func(wantLocation string) func([]byte, *http.Response) error {
return func(resBody []byte, res *http.Response) error {
switch res.StatusCode {
case 301, 302, 303, 307, 308:
if got := res.Header.Get("Location"); got != wantLocation {
return fmt.Errorf("got Location = %q; want %q", got, wantLocation)
}
default:
return fmt.Errorf("response status = %d; want redirect. body: %s", res.StatusCode, resBody)
}
return nil
}
}
b := &LocalBackend{
health: health.NewTracker(eventbustest.NewBus(t)),
}
tests := []struct {
req string
mount string
want func(resBody []byte, res *http.Response) error
}{
// Mounted at /
{"/", "/", contains("foo", "bar", "subdir")},
{"/../../.../../../../../../../etc/passwd", "/", isStatus(404)},
{"/foo", "/", contains("this is foo")},
{"/bar", "/", contains("this is bar")},
{"/bar/inside-file", "/", isStatus(404)},
{"/subdir", "/", isRedirect("/subdir/")},
{"/subdir/", "/", contains("file-a", "file-b", "file-c")},
{"/subdir/nested", "/", isRedirect("/subdir/nested/")},
{"//subdir/nested", "/", isRedirect("/subdir/nested/")},
{"/subdir/nested/index.html", "/", isRedirect("/subdir/nested/")},
{"/subdir/nested?x=1", "/", isRedirect("/subdir/nested/?x=1")},
{"/subdir/file-a", "/", contains("this is A")},
{"/subdir/file-a/", "/", isRedirect("/subdir/file-a")},
{"/subdir/file-z", "/", isStatus(404)},
{"/doc", "/doc/", isRedirect("/doc/")},
{"/doc/", "/doc/", contains("foo", "bar", "subdir")},
{"/doc/../../.../../../../../../../etc/passwd", "/doc/", isStatus(404)},
{"/doc/foo", "/doc/", contains("this is foo")},
{"/doc/bar", "/doc/", contains("this is bar")},
{"/doc/bar/inside-file", "/doc/", isStatus(404)},
{"/doc/subdir", "/doc/", isRedirect("/doc/subdir/")},
{"/doc/subdir/", "/doc/", contains("file-a", "file-b", "file-c")},
{"/doc/subdir/nested", "/doc/", isRedirect("/doc/subdir/nested/")},
{"/doc/subdir/nested/index.html", "/doc/", isRedirect("/doc/subdir/nested/")},
{"/doc/subdir/nested?x=1", "/doc/", isRedirect("/doc/subdir/nested/?x=1")},
{"/doc/subdir/file-a", "/doc/", contains("this is A")},
{"/doc/subdir/file-a/", "/doc/", isRedirect("/doc/subdir/file-a")},
{"/doc/subdir/file-z", "/doc/", isStatus(404)},
}
for _, tt := range tests {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", tt.req, nil)
b.serveFileOrDirectory(rec, req, td, tt.mount)
if tt.want == nil {
t.Errorf("no want for path %q", tt.req)
return
}
if err := tt.want(rec.Body.Bytes(), rec.Result()); err != nil {
t.Errorf("error for req %q (mount %v): %v", tt.req, tt.mount, err)
}
}
}
// newSymlinkServeTree creates a directory to serve, webroot, next to a
// directory, outside, whose file secret.txt must never be served, and
// returns the path to webroot. Besides a file and a subdirectory, webroot
// holds symlinks that lead out of it and symlinks that stay inside it.
func newSymlinkServeTree(t *testing.T) (root string) {
t.Helper()
base := t.TempDir()
root = filepath.Join(base, "webroot")
outside := filepath.Join(base, "outside")
for _, d := range []string{root, outside, filepath.Join(root, "sub")} {
if err := os.MkdirAll(d, 0o755); err != nil {
t.Fatal(err)
}
}
mustWrite := func(p, s string) {
t.Helper()
if err := os.WriteFile(p, []byte(s), 0o600); err != nil {
t.Fatal(err)
}
}
mustWrite(filepath.Join(root, "inside.txt"), "INSIDE-OK")
mustWrite(filepath.Join(root, "sub", "nested.txt"), "NESTED-OK")
mustWrite(filepath.Join(outside, "secret.txt"), "TOP-SECRET")
mustSymlink := func(target, linkName string) {
t.Helper()
if err := os.Symlink(target, filepath.Join(root, linkName)); err != nil {
if runtime.GOOS == "windows" {
t.Skipf("can't create symlinks: %v", err)
}
t.Fatal(err)
}
}
// os.Root refuses symlinks whose target leaves the root, and absolute
// symlinks even when they point inside the root, but follows relative
// symlinks that stay inside it.
mustSymlink("../outside", "escape-rel-dir")
mustSymlink("../outside/secret.txt", "escape-rel-file")
mustSymlink(filepath.Join(outside, "secret.txt"), "escape-abs")
mustSymlink(filepath.Join(root, "sub", "nested.txt"), "inroot-abs")
mustSymlink("sub/nested.txt", "inroot-rel")
mustSymlink("sub", "inroot-rel-dir")
return root
}
// TestServeFileOrDirectoryConfinesSymlinks verifies that a served directory
// doesn't follow symlinks that lead out of it, while files, subdirectories
// and relative symlinks that stay inside it are still served.
func TestServeFileOrDirectoryConfinesSymlinks(t *testing.T) {
root := newSymlinkServeTree(t)
b := &LocalBackend{
logf: t.Logf,
health: health.NewTracker(eventbustest.NewBus(t)),
}
mounts := []struct {
name string
mount string
}{
{"root-mount", "/"},
{"sub-mount", "/files/"},
}
tests := []struct {
name string
path string // request path, relative to the mount point
wantStatus int
wantBody string
}{
{"file", "inside.txt", 200, "INSIDE-OK"},
{"nested-file", "sub/nested.txt", 200, "NESTED-OK"},
{"relative-in-root-symlink", "inroot-rel", 200, "NESTED-OK"},
{"relative-in-root-dir-symlink", "inroot-rel-dir/nested.txt", 200, "NESTED-OK"},
{"escaping-dir-symlink", "escape-rel-dir/secret.txt", 404, ""},
{"escaping-file-symlink", "escape-rel-file", 404, ""},
{"absolute-symlink", "escape-abs", 404, ""},
{"absolute-in-root-symlink", "inroot-abs", 404, ""},
}
for _, m := range mounts {
t.Run(m.name, func(t *testing.T) {
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", m.mount+tt.path, nil)
b.serveFileOrDirectory(rec, req, root, m.mount)
checkServeResponse(t, rec, req, tt.wantStatus, tt.wantBody)
})
}
})
}
}
// TestServeFileOrDirectoryConfinesTarget verifies that the configured path
// itself, a single file or a directory, is resolved inside the directory
// that contains it: a symlink there that leads out of that directory, or an
// absolute one, is refused, while a relative symlink that stays inside it
// is still served.
func TestServeFileOrDirectoryConfinesTarget(t *testing.T) {
root := newSymlinkServeTree(t)
b := &LocalBackend{
logf: t.Logf,
health: health.NewTracker(eventbustest.NewBus(t)),
}
tests := []struct {
name string
target string // configured path, relative to root
mount string
req string
wantStatus int
wantBody string
}{
{"file", "inside.txt", "/f", "/f", 200, "INSIDE-OK"},
{"relative-in-parent-file-symlink", "inroot-rel", "/f", "/f", 200, "NESTED-OK"},
{"escaping-file-symlink", "escape-rel-file", "/f", "/f", 500, ""},
{"absolute-file-symlink", "escape-abs", "/f", "/f", 500, ""},
{"absolute-in-parent-file-symlink", "inroot-abs", "/f", "/f", 500, ""},
{"dir", "sub", "/files/", "/files/nested.txt", 200, "NESTED-OK"},
{"relative-in-parent-dir-symlink", "inroot-rel-dir", "/files/", "/files/nested.txt", 200, "NESTED-OK"},
{"escaping-dir-symlink", "escape-rel-dir", "/files/", "/files/secret.txt", 500, ""},
// A single file swapped for a symlink to a directory must not turn
// its mount point into a listing of that directory.
{"file-mount-escaping-dir-symlink", "escape-rel-dir", "/f", "/f/secret.txt", 500, ""},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", tt.req, nil)
b.serveFileOrDirectory(rec, req, filepath.Join(root, tt.target), tt.mount)
checkServeResponse(t, rec, req, tt.wantStatus, tt.wantBody)
})
}
// A filesystem root has no parent directory to resolve it in, so it is
// opened as is.
t.Run("filesystem-root", func(t *testing.T) {
rec := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/", nil)
b.serveFileOrDirectory(rec, req, string(filepath.Separator), "/")
if rec.Code != 200 {
t.Errorf("GET %s: status = %d; want 200 (body: %q)", req.URL.Path, rec.Code, rec.Body.String())
}
})
}
// checkServeResponse reports an error if rec, the response to req, doesn't
// have the status wantStatus and a body containing wantBody, or if it served
// the secret file from outside the tree made by newSymlinkServeTree.
func checkServeResponse(t *testing.T, rec *httptest.ResponseRecorder, req *http.Request, wantStatus int, wantBody string) {
t.Helper()
body := rec.Body.String()
if rec.Code != wantStatus {
t.Errorf("GET %s: status = %d; want %d (body: %q)", req.URL.Path, rec.Code, wantStatus, body)
}
if !strings.Contains(body, wantBody) {
t.Errorf("GET %s: body = %q; want it to contain %q", req.URL.Path, body, wantBody)
}
if strings.Contains(body, "TOP-SECRET") {
t.Errorf("GET %s: served a file from outside the root", req.URL.Path)
}
}
func Test_isGRPCContentType(t *testing.T) {
tests := []struct {
contentType string
want bool
}{
{contentType: "application/grpc", want: true},
{contentType: "application/grpc;", want: true},
{contentType: "application/grpc+", want: true},
{contentType: "application/grpcfoobar"},
{contentType: "application/text"},
{contentType: "foobar"},
{contentType: ""},
}
for _, tt := range tests {
if got := isGRPCContentType(tt.contentType); got != tt.want {
t.Errorf("isGRPCContentType(%q) = %v, want %v", tt.contentType, got, tt.want)
}
}
}
func TestEncTailscaleHeaderValue(t *testing.T) {
tests := []struct {
in string
want string
}{
{"", ""},
{"Alice Smith", "Alice Smith"},
{"Bad\xffUTF-8", ""},
{"Krūmiņa", "=?utf-8?q?Kr=C5=ABmi=C5=86a?="},
}
for _, tt := range tests {
got := encTailscaleHeaderValue(tt.in)
if got != tt.want {
t.Errorf("encTailscaleHeaderValue(%q) = %q, want %q", tt.in, got, tt.want)
}
}
}
func TestServeGRPCProxy(t *testing.T) {
const msg = "some-response\n"
backend := httptest.NewUnstartedServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Path-Was", r.RequestURI)
w.Header().Set("Proto-Was", r.Proto)
io.WriteString(w, msg)
}))
backend.EnableHTTP2 = true
backend.Config.Protocols = new(http.Protocols)
backend.Config.Protocols.SetHTTP1(true)
backend.Config.Protocols.SetUnencryptedHTTP2(true)
backend.Start()
defer backend.Close()
backendURL := must.Get(url.Parse(backend.URL))
lb := newTestBackend(t)
rp := &reverseProxy{
logf: t.Logf,
url: backendURL,
backend: backend.URL,
lb: lb,
}
req := func(method, urlStr string, opt ...any) *http.Request {
req := httptest.NewRequest(method, urlStr, nil)
for _, o := range opt {
switch v := o.(type) {
case int:
req.ProtoMajor = v
case string:
req.Header.Set("Content-Type", v)
default:
panic(fmt.Sprintf("unsupported option type %T", v))
}
}
return req
}
tests := []struct {
name string
req *http.Request
wantPath string
wantProto string
wantBody string
}{
{
name: "non-gRPC",
req: req("GET", "http://foo/bar"),
wantPath: "/bar",
wantProto: "HTTP/1.1",
},
{
name: "gRPC-but-not-http2",
req: req("GET", "http://foo/bar", "application/grpc"),
wantPath: "/bar",
wantProto: "HTTP/1.1",
},
{
name: "gRPC--http2",
req: req("GET", "http://foo/bar", 2, "application/grpc"),
wantPath: "/bar",
wantProto: "HTTP/2.0",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
rec := httptest.NewRecorder()
rp.ServeHTTP(rec, tt.req)
res := rec.Result()
got := must.Get(io.ReadAll(res.Body))
if got, want := res.Header.Get("Path-Was"), tt.wantPath; want != got {
t.Errorf("Path-Was %q, want %q", got, want)
}
if got, want := res.Header.Get("Proto-Was"), tt.wantProto; want != got {
t.Errorf("Proto-Was %q, want %q", got, want)
}
if string(got) != msg {
t.Errorf("got body %q, want %q", got, msg)
}
})
}
}
// TestServeProxyHTTP2PreservesContentType is a repro for tailscale/tailscale#19866.
// A client POSTs over HTTP/2 to a serve listener configured to reverse-proxy to a
// plaintext HTTP/1.1 backend; the test asserts the backend sees the Content-Type
// header that the client sent.
func TestServeProxyHTTP2PreservesContentType(t *testing.T) {
var (
gotHeader http.Header
gotMethod string
gotProto string
gotBody string
)
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotHeader = r.Header.Clone()
gotMethod = r.Method
gotProto = r.Proto
b, _ := io.ReadAll(r.Body)
gotBody = string(b)
w.WriteHeader(http.StatusOK)
}))
defer backend.Close()
backendURL := must.Get(url.Parse(backend.URL))
lb := newTestBackend(t)
rp := &reverseProxy{
logf: t.Logf,
url: backendURL,
backend: backend.URL,
lb: lb,
}
// Mirror serveWebHandler's behavior for a mount of "/" with a non-"/" path:
// it wraps the proxy in http.StripPrefix("", rp). That's a no-op for "/mcp"
// but worth exercising in case StripPrefix interacts weirdly with HTTP/2.
frontHandler := http.StripPrefix("", http.HandlerFunc(rp.ServeHTTP))
front := httptest.NewUnstartedServer(frontHandler)
front.EnableHTTP2 = true
front.StartTLS()
defer front.Close()
const reqBody = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`
type variant struct {
name string
http1Only bool
contentType string
setAccept bool
setContentLen bool // if false, body is a Reader with unknown length (chunked)
dropContentLen bool
emptyBody bool
}
variants := []variant{
{name: "baseline_http2", contentType: "application/json", setAccept: true, setContentLen: true},
{name: "http1_baseline", http1Only: true, contentType: "application/json", setAccept: true, setContentLen: true},
{name: "no_accept", contentType: "application/json", setContentLen: true},
{name: "charset_param", contentType: "application/json; charset=utf-8", setAccept: true, setContentLen: true},
{name: "chunked", contentType: "application/json", setAccept: true, setContentLen: false},
{name: "drop_content_length", contentType: "application/json", setAccept: true, dropContentLen: true},
{name: "empty_body", contentType: "application/json", setAccept: true, emptyBody: true},
}
for _, v := range variants {
t.Run(v.name, func(t *testing.T) {
gotHeader = nil
gotMethod = ""
gotProto = ""
gotBody = ""
var body io.Reader
switch {
case v.emptyBody:
body = http.NoBody
case v.setContentLen:
body = strings.NewReader(reqBody)
default:
// io.Reader that isn't a *bytes.Reader / *strings.Reader / *bytes.Buffer
// so net/http does not auto-set Content-Length.
body = struct{ io.Reader }{strings.NewReader(reqBody)}
}
url := front.URL + "/mcp"
req, err := http.NewRequest("POST", url, body)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", v.contentType)
if v.setAccept {
req.Header.Set("Accept", "application/json, text/event-stream")
}
if v.dropContentLen {
req.ContentLength = -1
}
client := front.Client()
if v.http1Only {
// Force the client onto HTTP/1.1 by removing h2 from ALPN.
tr := client.Transport.(*http.Transport).Clone()
if tr.TLSClientConfig != nil {
tr.TLSClientConfig = tr.TLSClientConfig.Clone()
tr.TLSClientConfig.NextProtos = []string{"http/1.1"}
}
tr.ForceAttemptHTTP2 = false
client = &http.Client{Transport: tr}
}
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
io.Copy(io.Discard, res.Body)
wantProtoMajor := 2
if v.http1Only {
wantProtoMajor = 1
}
if res.ProtoMajor != wantProtoMajor {
t.Fatalf("front-end proto = %s, want HTTP/%d.x", res.Proto, wantProtoMajor)
}
if res.StatusCode != http.StatusOK {
t.Fatalf("backend returned status %d, want 200", res.StatusCode)
}
if gotMethod != "POST" {
t.Errorf("backend method = %q, want POST", gotMethod)
}
t.Logf("backend saw proto=%q content-length=%q transfer-encoding=%v body=%q",
gotProto, gotHeader.Get("Content-Length"), gotHeader.Values("Transfer-Encoding"), gotBody)
if got, want := gotHeader.Get("Content-Type"), v.contentType; got != want {
t.Errorf("Content-Type at backend = %q, want %q (full headers: %v)", got, want, gotHeader)
}
})
}
}
// TestServeWebHandlerHTTP2PreservesContentType drives the full
// b.serveWebHandler entry point (the actual production code path) via a real
// HTTP/2 TLS frontend, with serveHTTPContext.Funnel set to mimic a funnel
// request. Repro probe for tailscale/tailscale#19866.
// stallAfterEOF delays the Read that follows the one that returned io.EOF.
// For a request body with a Content-Length, that is the Transport's extra
// read that checks for EOF after it copied the declared bytes upstream
// (net/http transfer.go, transferWriter.writeBody). The delay stands in
// for a descheduled goroutine and gives the backend time to answer first.
type stallAfterEOF struct {
io.ReadCloser
stall time.Duration
sawEOF bool
}
func (s *stallAfterEOF) Read(p []byte) (int, error) {
if s.sawEOF {
time.Sleep(s.stall)
}
n, err := s.ReadCloser.Read(p)
if err == io.EOF {
s.sawEOF = true
}
return n, err
}
// TestServeProxyStreamedResponseWithRequestBody reproduces
// tailscale/tailscale#21894: an HTTP/1.1 client POSTs to a backend that
// flushes the start of its response as soon as it has read the request.
// When the response reaches the proxy's HTTP/1 server before the proxy's
// Transport has done its final EOF read of the request body, the server
// closes that body (golang/go#15527 behavior), the Transport's read fails,
// the Transport closes the upstream connection, and the client gets a
// truncated response.
func TestServeProxyStreamedResponseWithRequestBody(t *testing.T) {
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if _, err := io.Copy(io.Discard, r.Body); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.Header().Set("Content-Type", "text/event-stream")
io.WriteString(w, "data: first\n\n")
w.(http.Flusher).Flush()
time.Sleep(50 * time.Millisecond)
io.WriteString(w, "data: final\n\n")
}))
defer backend.Close()
rp := &reverseProxy{
logf: t.Logf,
url: must.Get(url.Parse(backend.URL)),
backend: backend.URL,
lb: newTestBackend(t),
}
front := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
r.Body = &stallAfterEOF{ReadCloser: r.Body, stall: 20 * time.Millisecond}
rp.ServeHTTP(w, r)
}))
defer front.Close()
// Plain HTTP: the client speaks HTTP/1.1.
client := front.Client()
body := []byte(`{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`)
const attempts = 5
var truncated int
for i := range attempts {
req := must.Get(http.NewRequest(httpm.POST, front.URL, bytes.NewReader(body)))
req.Header.Set("Content-Type", "application/json")
resp, err := client.Do(req)
if err != nil {
t.Fatalf("attempt %d: %v", i, err)
}
got, err := io.ReadAll(resp.Body)
resp.Body.Close()
if err != nil || !strings.Contains(string(got), "data: final") {
t.Logf("attempt %d: truncated response %q, read error %v", i, got, err)
truncated++
}
}
if truncated > 0 {
t.Errorf("%d of %d responses were truncated", truncated, attempts)
}
}
func TestServeWebHandlerHTTP2PreservesContentType(t *testing.T) {
var gotHeader http.Header
backend := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
gotHeader = r.Header.Clone()
w.WriteHeader(http.StatusOK)
}))
defer backend.Close()
b := newTestBackend(t)
front := httptest.NewUnstartedServer(http.HandlerFunc(b.serveWebHandler))
front.EnableHTTP2 = true
realFrontAddr := front.Listener.Addr().String()
_, portStr, _ := net.SplitHostPort(realFrontAddr)
p, _ := strconv.ParseUint(portStr, 10, 16)
frontPort := uint16(p)
front.Config.BaseContext = func(_ net.Listener) context.Context {
return serveHTTPContextKey.WithValue(context.Background(), &serveHTTPContext{
Funnel: &funnelFlow{Host: "example.ts.net"},
SrcAddr: netip.MustParseAddrPort("1.2.3.4:1234"),
DestPort: frontPort,
})
}
front.StartTLS()
defer front.Close()
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
ipn.HostPort(net.JoinHostPort("example.ts.net", portStr)): {Handlers: map[string]*ipn.HTTPHandler{
"/": {Proxy: backend.URL},
}},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
// Custom client: dial example.ts.net:PORT to the real httptest address,
// skip cert verification, and send SNI "example.ts.net" so the serveConfig
// host lookup works.
tr := front.Client().Transport.(*http.Transport).Clone()
tr.DialContext = func(ctx context.Context, network, addr string) (net.Conn, error) {
var d net.Dialer
return d.DialContext(ctx, "tcp", realFrontAddr)
}
tr.TLSClientConfig = &tls.Config{
InsecureSkipVerify: true,
ServerName: "example.ts.net",
NextProtos: []string{"h2", "http/1.1"},
}
tr.ForceAttemptHTTP2 = true
client := &http.Client{Transport: tr}
const reqBody = `{"jsonrpc":"2.0","id":1,"method":"initialize","params":{}}`
url := "https://example.ts.net:" + portStr + "/mcp"
req, err := http.NewRequest("POST", url, strings.NewReader(reqBody))
if err != nil {
t.Fatal(err)
}
req.Header.Set("Content-Type", "application/json")
req.Header.Set("Accept", "application/json, text/event-stream")
res, err := client.Do(req)
if err != nil {
t.Fatal(err)
}
defer res.Body.Close()
body, _ := io.ReadAll(res.Body)
if res.ProtoMajor != 2 {
t.Fatalf("front-end proto = %s, want HTTP/2", res.Proto)
}
if res.StatusCode != http.StatusOK {
t.Fatalf("status %d, want 200; body=%q", res.StatusCode, body)
}
t.Logf("backend headers (full): %v", gotHeader)
if got, want := gotHeader.Get("Content-Type"), "application/json"; got != want {
t.Errorf("Content-Type at backend = %q, want %q", got, want)
}
if got := gotHeader.Get("Tailscale-Funnel-Request"); got != "?1" {
t.Errorf("Tailscale-Funnel-Request = %q, want %q (sanity check)", got, "?1")
}
}
func TestServeHTTPRedirect(t *testing.T) {
b := newTestBackend(t)
tests := []struct {
host string
path string
redirect string
reqURI string
wantCode int
wantLoc string
}{
{
host: "hardcoded-root",
path: "/",
redirect: "https://example.com/",
reqURI: "/old",
wantCode: http.StatusFound, // 302 is the default
wantLoc: "https://example.com/",
},
{
host: "template-host-and-uri",
path: "/",
redirect: "https://${HOST}${REQUEST_URI}",
reqURI: "/path?foo=bar",
wantCode: http.StatusFound, // 302 is the default
wantLoc: "https://template-host-and-uri/path?foo=bar",
},
{
host: "custom-301",
path: "/",
redirect: "301:https://example.com/",
reqURI: "/old",
wantCode: http.StatusMovedPermanently, // 301
wantLoc: "https://example.com/",
},
{
host: "custom-307",
path: "/",
redirect: "307:https://example.com/new",
reqURI: "/old",
wantCode: http.StatusTemporaryRedirect, // 307
wantLoc: "https://example.com/new",
},
{
host: "custom-308",
path: "/",
redirect: "308:https://example.com/permanent",
reqURI: "/old",
wantCode: http.StatusPermanentRedirect, // 308
wantLoc: "https://example.com/permanent",
},
}
for _, tt := range tests {
t.Run(tt.host, func(t *testing.T) {
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
ipn.HostPort(tt.host + ":80"): {
Handlers: map[string]*ipn.HTTPHandler{
tt.path: {Redirect: tt.redirect},
},
},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
req := &http.Request{
Host: tt.host,
URL: &url.URL{Path: tt.path},
RequestURI: tt.reqURI,
TLS: &tls.ConnectionState{ServerName: tt.host},
}
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(), &serveHTTPContext{
DestPort: 80,
SrcAddr: netip.MustParseAddrPort("1.2.3.4:1234"),
}))
w := httptest.NewRecorder()
b.serveWebHandler(w, req)
if w.Code != tt.wantCode {
t.Errorf("got status %d, want %d", w.Code, tt.wantCode)
}
if got := w.Header().Get("Location"); got != tt.wantLoc {
t.Errorf("got Location %q, want %q", got, tt.wantLoc)
}
})
}
}
func TestValidateServeConfigUpdate(t *testing.T) {
tests := []struct {
name, description string
existing, incoming *ipn.ServeConfig
wantError bool
}{
{
name: "empty-existing-config",
description: "should be able to update with empty existing config",
existing: &ipn.ServeConfig{},
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
8080: {},
},
},
wantError: false,
},
{
name: "no-existing-config",
description: "should be able to update with no existing config",
existing: nil,
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
8080: {},
},
},
wantError: false,
},
{
name: "empty-incoming-config",
description: "wiping config should work",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
incoming: &ipn.ServeConfig{},
wantError: false,
},
{
name: "no-incoming-config",
description: "missing incoming config should not result in an error",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
incoming: nil,
wantError: false,
},
{
name: "non-overlapping-update",
description: "non-overlapping update should work",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
8080: {},
},
},
wantError: false,
},
{
name: "overwriting-background-port",
description: "should be able to overwrite a background port",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {
TCPForward: "localhost:8080",
},
},
},
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {
TCPForward: "localhost:9999",
},
},
},
wantError: false,
},
{
name: "broken-existing-config",
description: "broken existing config should not prevent new config updates",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
// Broken because HTTPS and TCPForward are mutually exclusive.
9000: {
HTTPS: true,
TCPForward: "127.0.0.1:9000",
},
// Broken because foreground and background handlers cannot coexist.
443: {},
},
Foreground: map[string]*ipn.ServeConfig{
"12345": {
TCP: map[uint16]*ipn.TCPPortHandler{
// Broken because foreground and background handlers cannot coexist.
443: {},
},
},
},
// Broken because Services cannot specify TUN mode and a TCP handler.
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
6060: {},
},
Tun: true,
},
},
},
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
wantError: false,
},
{
name: "services-same-port-as-background",
description: "services should be able to use the same port as background listeners",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
incoming: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
},
},
wantError: false,
},
{
name: "services-tun-mode",
description: "TUN mode should be mutually exclusive with TCP or web handlers for new Services",
existing: &ipn.ServeConfig{},
incoming: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
6060: {},
},
Tun: true,
},
},
},
wantError: true,
},
{
name: "new-foreground-listener",
description: "new foreground listeners must be on open ports",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
incoming: &ipn.ServeConfig{
Foreground: map[string]*ipn.ServeConfig{
"12345": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
},
},
wantError: true,
},
{
name: "new-background-listener",
description: "new background listers cannot overwrite foreground listeners",
existing: &ipn.ServeConfig{
Foreground: map[string]*ipn.ServeConfig{
"12345": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
},
},
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {},
},
},
wantError: true,
},
{
name: "serve-type-overwrite",
description: "incoming configuration cannot change the serve type in use by a port",
existing: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {
HTTP: true,
},
},
},
incoming: &ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{
80: {
TCPForward: "localhost:8080",
},
},
},
wantError: true,
},
{
name: "serve-type-overwrite-services",
description: "incoming Services configuration cannot change the serve type in use by a port",
existing: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {
HTTP: true,
},
},
},
},
},
incoming: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
80: {
TCPForward: "localhost:8080",
},
},
},
},
},
wantError: true,
},
{
name: "tun-mode-with-handlers",
description: "Services cannot enable TUN mode if L4 or L7 handlers already exist",
existing: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
443: {
HTTPS: true,
},
},
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"127.0.0.1:443": {
Handlers: map[string]*ipn.HTTPHandler{},
},
},
},
},
},
incoming: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
Tun: true,
},
},
},
wantError: true,
},
{
name: "handlers-with-tun-mode",
description: "Services cannot add L4 or L7 handlers if TUN mode is already enabled",
existing: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
Tun: true,
},
},
},
incoming: &ipn.ServeConfig{
Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {
TCP: map[uint16]*ipn.TCPPortHandler{
443: {
HTTPS: true,
},
},
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"127.0.0.1:443": {
Handlers: map[string]*ipn.HTTPHandler{},
},
},
},
},
},
wantError: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
err := validateServeConfigUpdate(tt.existing.View(), tt.incoming.View())
if err != nil && !tt.wantError {
t.Error("unexpected error:", err)
}
if err == nil && tt.wantError {
t.Error("expected error, got nil;", tt.description)
}
})
}
}
// mkTempSocket creates an empty file to stand in for a unix socket and returns
// its path. isTailscaledSocket matches by os.SameFile, so a regular file is
// enough and its name does not matter.
func mkTempSocket(t *testing.T) string {
t.Helper()
f, err := os.CreateTemp(t.TempDir(), "sock")
if err != nil {
t.Fatal(err)
}
f.Close()
return f.Name()
}
// TestServeTargetsTailscaledSocket checks the guard that refuses a serve config
// proxying to tailscaled's own socket, across every place a handler can live and
// through a symlink alias.
func TestServeTargetsTailscaledSocket(t *testing.T) {
b := newTestBackend(t)
sock := mkTempSocket(t)
b.sys.SocketPath = sock
other := mkTempSocket(t)
alias := sock + ".symlink"
if err := os.Symlink(sock, alias); err != nil {
t.Fatal(err)
}
tcpTo := func(target string) *ipn.ServeConfig {
return &ipn.ServeConfig{TCP: map[uint16]*ipn.TCPPortHandler{443: {TCPForward: target}}}
}
tests := []struct {
name string
conf *ipn.ServeConfig
want bool
}{
{"nil", nil, false},
{"no-unix-tcp", tcpTo("127.0.0.1:8080"), false},
{"other-socket", tcpTo("unix:" + other), false},
{"tcp-forward", tcpTo("unix:" + sock), true},
{"tcp-forward-via-symlink", tcpTo("unix:" + alias), true},
{
"web-proxy",
&ipn.ServeConfig{Web: map[ipn.HostPort]*ipn.WebServerConfig{
"example.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{"/": {Proxy: "unix:" + sock}}},
}},
true,
},
{
"foreground-tcp",
&ipn.ServeConfig{Foreground: map[string]*ipn.ServeConfig{
"sess": tcpTo("unix:" + sock),
}},
true,
},
{
"service-tcp",
&ipn.ServeConfig{Services: map[tailcfg.ServiceName]*ipn.ServiceConfig{
"svc:foo": {TCP: map[uint16]*ipn.TCPPortHandler{443: {TCPForward: "unix:" + sock}}},
}},
true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if got := b.serveTargetsTailscaledSocket(tt.conf.View()); got != tt.want {
t.Errorf("serveTargetsTailscaledSocket = %v, want %v", got, tt.want)
}
})
}
}
// TestSetServeConfigRejectsTailscaledSocket confirms the guard is wired into
// the config-set path, so "tailscale serve" is refused with a surfaced error
// rather than silently accepted.
func TestSetServeConfigRejectsTailscaledSocket(t *testing.T) {
b := newTestBackend(t)
sock := mkTempSocket(t)
b.sys.SocketPath = sock
err := b.setServeConfigLocked(&ipn.ServeConfig{
TCP: map[uint16]*ipn.TCPPortHandler{443: {TCPForward: "unix:" + sock}},
}, "")
if err == nil {
t.Fatal("setServeConfigLocked accepted a forward to the tailscaled socket; want it refused")
}
}
// TestReverseProxyRechecksTailscaledSocketPerDial verifies that a unix
// backend that becomes a symlink to the tailscaled socket after the
// handler was built is refused at dial time.
func TestReverseProxyRechecksTailscaledSocketPerDial(t *testing.T) {
b := newTestBackend(t)
sock := mkTempSocket(t)
b.sys.SocketPath = sock
benign := mkTempSocket(t)
// Benign at config time, so the handler is built.
h, err := b.proxyHandlerForBackend("unix:" + benign)
if err != nil {
t.Fatalf("proxyHandlerForBackend(benign) = %v; want handler", err)
}
rp, ok := h.(*reverseProxy)
if !ok {
t.Fatalf("handler is %T; want *reverseProxy", h)
}
if _, err := rp.lb.dialServeUnixSocket(t.Context(), rp.socketPath); errors.Is(err, ErrProxyToTailscaledSocket) {
t.Fatalf("dial to the benign path was refused as the tailscaled socket")
}
// The path is swapped for a symlink to the tailscaled socket after the
// handler exists; the next dial must catch it.
if err := os.Remove(benign); err != nil {
t.Fatal(err)
}
if err := os.Symlink(sock, benign); err != nil {
t.Fatal(err)
}
if _, err := rp.lb.dialServeUnixSocket(t.Context(), rp.socketPath); !errors.Is(err, ErrProxyToTailscaledSocket) {
t.Fatalf("dial after the symlink swap = %v; want ErrProxyToTailscaledSocket", err)
}
}
// TestServeWebHandlerHostNormalization checks that a request is matched
// to its serve config regardless of how the client spells the name. DNS
// names are case-insensitive and may carry a trailing dot, while serve
// config keys are always lowercase with no trailing dot. For plain HTTP
// the name comes from the Host header. For HTTPS it comes from SNI, which
// cannot carry a trailing dot but is not lowercased by TLS. (#21538, #21986)
func TestServeWebHandlerHostNormalization(t *testing.T) {
b := newTestBackend(t)
b.pm.currentProfile = (&ipn.LoginProfile{
ID: "id0",
NetworkProfile: ipn.NetworkProfile{MagicDNSName: "example.ts.net"},
}).View()
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"svelte.example.ts.net:12075": {
Handlers: map[string]*ipn.HTTPHandler{"/": {Text: "hello"}},
},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
tests := []struct {
host string // Host header for plain HTTP; SNI for HTTPS
tls bool
wantCode int
}{
{host: "svelte.example.ts.net:12075", wantCode: http.StatusOK},
{host: "svelte:12075", wantCode: http.StatusOK},
{host: "svelte.example.ts.net.:12075", wantCode: http.StatusOK},
{host: "svelte.example.ts.net.", wantCode: http.StatusOK},
{host: "svelte.:12075", wantCode: http.StatusOK},
{host: "Svelte.Example.TS.net:12075", wantCode: http.StatusOK},
{host: "SVELTE:12075", wantCode: http.StatusOK},
{host: "other.example.ts.net:12075", wantCode: http.StatusNotFound},
{host: "svelte.example.ts.net..:12075", wantCode: http.StatusNotFound},
{host: "svelte.example.ts.net", tls: true, wantCode: http.StatusOK},
{host: "Svelte.Example.TS.net", tls: true, wantCode: http.StatusOK},
{host: "other.example.ts.net", tls: true, wantCode: http.StatusNotFound},
}
for _, tt := range tests {
name := tt.host
if tt.tls {
name = "tls/" + name
}
t.Run(name, func(t *testing.T) {
req := &http.Request{Host: tt.host, URL: &url.URL{Path: "/"}, RequestURI: "/"}
if tt.tls {
req.TLS = &tls.ConnectionState{ServerName: tt.host}
}
req = req.WithContext(serveHTTPContextKey.WithValue(req.Context(), &serveHTTPContext{
DestPort: 12075,
SrcAddr: netip.MustParseAddrPort("100.64.0.2:1234"),
}))
w := httptest.NewRecorder()
b.serveWebHandler(w, req)
if w.Code != tt.wantCode {
t.Errorf("%s: got %d, want %d", name, w.Code, tt.wantCode)
}
})
}
}
// TestGetTLSServeCertForPortLowercasesSNI checks that the serve TLS cert
// callback lowercases the SNI before both the serve config lookup and the
// cert lookup. Cert domains are lowercase and matched exactly, so passing
// the SNI through as sent made a mixed-case ClientHello fail the handshake.
func TestGetTLSServeCertForPortLowercasesSNI(t *testing.T) {
b := newTestBackend(t)
conf := &ipn.ServeConfig{
Web: map[ipn.HostPort]*ipn.WebServerConfig{
"svelte.example.ts.net:443": {
Handlers: map[string]*ipn.HTTPHandler{"/": {Text: "hello"}},
},
},
}
if err := b.SetServeConfig(conf, ""); err != nil {
t.Fatal(err)
}
var gotDomain string
restore := HookGetCertPEM.SetForTest(func(_ context.Context, _ *LocalBackend, domain string, _ time.Duration) (*TLSCertKeyPair, error) {
gotDomain = domain
if domain != "svelte.example.ts.net" {
return nil, fmt.Errorf("invalid domain %q", domain)
}
d := tlstest.Domain(domain)
return &TLSCertKeyPair{CertPEM: d.CertPEM(), KeyPEM: d.KeyPEM()}, nil
})
defer restore()
getCert := b.getTLSServeCertForPort(443, "")
for _, sni := range []string{"svelte.example.ts.net", "Svelte.Example.TS.net"} {
gotDomain = ""
cert, err := getCert(&tls.ClientHelloInfo{ServerName: sni})
if err != nil {
t.Errorf("SNI %q: %v", sni, err)
continue
}
if gotDomain != "svelte.example.ts.net" {
t.Errorf("SNI %q: cert looked up for %q", sni, gotDomain)
}
if cert == nil || cert.Leaf == nil || !slices.Contains(cert.Leaf.DNSNames, "svelte.example.ts.net") {
t.Errorf("SNI %q: unexpected cert %+v", sni, cert)
}
}
if _, err := getCert(&tls.ClientHelloInfo{ServerName: "Other.Example.TS.net"}); err == nil {
t.Error("unconfigured name: got cert, want error")
}
}