// Copyright (c) Tailscale Inc & contributors // SPDX-License-Identifier: BSD-3-Clause //go:build !plan9 package apiproxy import ( "bufio" "context" "encoding/json" "net" "net/http" "net/http/httptest" "net/http/httputil" "net/netip" "net/url" "reflect" "sync" "testing" "time" "github.com/google/go-cmp/cmp" "go.uber.org/zap" "tailscale.com/client/local" "tailscale.com/client/tailscale/apitype" "tailscale.com/net/memnet" "tailscale.com/tailcfg" "tailscale.com/tailcfg/peercap" "tailscale.com/util/must" ) func TestImpersonationHeaders(t *testing.T) { zl, err := zap.NewDevelopment() if err != nil { t.Fatal(err) } tests := []struct { name string emailish string tags []string capMap tailcfg.PeerCapMap wantHeaders http.Header }{ { name: "user", emailish: "foo@example.com", wantHeaders: http.Header{ "Impersonate-User": {"foo@example.com"}, }, }, { name: "tagged", emailish: "tagged-device", tags: []string{"tag:foo", "tag:bar"}, wantHeaders: http.Header{ "Impersonate-User": {"node.ts.net"}, "Impersonate-Group": {"tag:foo", "tag:bar"}, }, }, { name: "user-with-cap", emailish: "foo@example.com", capMap: tailcfg.PeerCapMap{ peercap.Kubernetes: { tailcfg.RawMessage(`{"impersonate":{"groups":["group1","group2"]}}`), tailcfg.RawMessage(`{"impersonate":{"groups":["group1","group3"]}}`), // One group is duplicated. tailcfg.RawMessage(`{"impersonate":{"groups":["group4"]}}`), tailcfg.RawMessage(`{"impersonate":{"groups":["group2"]}}`), // duplicate // These should be ignored, but should parse correctly. tailcfg.RawMessage(`{}`), tailcfg.RawMessage(`{"impersonate":{}}`), tailcfg.RawMessage(`{"impersonate":{"groups":[]}}`), }, }, wantHeaders: http.Header{ "Impersonate-Group": {"group1", "group2", "group3", "group4"}, "Impersonate-User": {"foo@example.com"}, }, }, { name: "tagged-with-cap", emailish: "tagged-device", tags: []string{"tag:foo", "tag:bar"}, capMap: tailcfg.PeerCapMap{ peercap.Kubernetes: { tailcfg.RawMessage(`{"impersonate":{"groups":["group1"]}}`), }, }, wantHeaders: http.Header{ "Impersonate-Group": {"group1"}, "Impersonate-User": {"node.ts.net"}, }, }, { name: "mix-of-caps", emailish: "tagged-device", tags: []string{"tag:foo", "tag:bar"}, capMap: tailcfg.PeerCapMap{ peercap.Kubernetes: { tailcfg.RawMessage(`{"impersonate":{"groups":["group1"]},"recorder":["tag:foo"],"enforceRecorder":true}`), }, }, wantHeaders: http.Header{ "Impersonate-Group": {"group1"}, "Impersonate-User": {"node.ts.net"}, }, }, { name: "bad-cap", emailish: "tagged-device", tags: []string{"tag:foo", "tag:bar"}, capMap: tailcfg.PeerCapMap{ peercap.Kubernetes: { tailcfg.RawMessage(`[]`), }, }, wantHeaders: http.Header{}, }, } for _, tc := range tests { r := must.Get(http.NewRequest("GET", "https://op.ts.net/api/foo", nil)) r = r.WithContext(whoIsKey.WithValue(r.Context(), &apitype.WhoIsResponse{ Node: &tailcfg.Node{ Name: "node.ts.net", Tags: tc.tags, }, UserProfile: &tailcfg.UserProfile{ LoginName: tc.emailish, }, CapMap: tc.capMap, })) addImpersonationHeaders(r, zl.Sugar()) if d := cmp.Diff(tc.wantHeaders, r.Header); d != "" { t.Errorf("unexpected header (-want +got):\n%s", d) } } } func Test_determineRecorderConfig(t *testing.T) { addr1, addr2 := netip.MustParseAddrPort("[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80"), netip.MustParseAddrPort("100.99.99.99:80") tests := []struct { name string wantFailOpen bool wantRecorderAddresses []netip.AddrPort who *apitype.WhoIsResponse }{ { name: "two_ips_fail_closed", who: whoResp(map[string][]string{string(peercap.Kubernetes): {`{"recorderAddrs":["[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80","100.99.99.99:80"],"enforceRecorder":true}`}}), wantRecorderAddresses: []netip.AddrPort{addr1, addr2}, }, { name: "two_ips_fail_open", who: whoResp(map[string][]string{string(peercap.Kubernetes): {`{"recorderAddrs":["[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80","100.99.99.99:80"]}`}}), wantRecorderAddresses: []netip.AddrPort{addr1, addr2}, wantFailOpen: true, }, { name: "odd_rule_combination_fail_closed", who: whoResp(map[string][]string{string(peercap.Kubernetes): {`{"recorderAddrs":["100.99.99.99:80"],"enforceRecorder":false}`, `{"recorderAddrs":["[fd7a:115c:a1e0:ab12:4843:cd96:626b:628b]:80"]}`, `{"enforceRecorder":true,"impersonate":{"groups":["system:masters"]}}`}}), wantRecorderAddresses: []netip.AddrPort{addr2, addr1}, }, { name: "no_caps", who: whoResp(map[string][]string{}), wantFailOpen: true, }, { name: "no_recorder_caps", who: whoResp(map[string][]string{"foo": {`{"x":"y"}`}, string(peercap.Kubernetes): {`{"impersonate":{"groups":["system:masters"]}}`}}), wantFailOpen: true, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { c, err := determineRecorderConfig(tt.who) if err != nil { t.Fatalf("unexpected error: %v", err) } if c.failOpen != tt.wantFailOpen { t.Errorf("determineRecorderConfig() gotFailOpen = %v, want %v", c.failOpen, tt.wantFailOpen) } if !reflect.DeepEqual(c.recorderAddresses, tt.wantRecorderAddresses) { t.Errorf("determineRecorderConfig() gotRecorderAddresses = %v, want %v", c.recorderAddresses, tt.wantRecorderAddresses) } }) } } // TestWhoIs checks that whoIs resolves the caller from the request's remote // address and ignores the X-Forwarded-For header. func TestWhoIs(t *testing.T) { zl, err := zap.NewDevelopment() if err != nil { t.Fatal(err) } nodes := map[string]*apitype.WhoIsResponse{ "100.64.0.1:1234": { Node: &tailcfg.Node{Name: "user-node.ts.net."}, UserProfile: &tailcfg.UserProfile{LoginName: "user@example.com"}, }, "100.64.0.2": { Node: &tailcfg.Node{Name: "admin-node.ts.net."}, UserProfile: &tailcfg.UserProfile{LoginName: "admin@example.com"}, }, } lal := memnet.Listen("local-tailscaled.sock:80") defer lal.Close() localAPI := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { who, ok := nodes[r.URL.Query().Get("addr")] if !ok { http.Error(w, "no match for IP:port", http.StatusNotFound) return } json.NewEncoder(w).Encode(who) })} defer localAPI.Close() go localAPI.Serve(lal) ap := &APIServerProxy{ log: zl.Sugar(), lc: &local.Client{Dial: lal.Dial}, } tests := []struct { name string remoteAddr string xForwardedFor string wantLogin string // empty if whoIs should fail }{ { name: "tailnet_node", remoteAddr: "100.64.0.1:1234", wantLogin: "user@example.com", }, { name: "not_a_tailnet_node", remoteAddr: "10.0.0.5:1234", }, { name: "x_forwarded_for_ignored", remoteAddr: "10.0.0.5:1234", xForwardedFor: "100.64.0.2", }, { name: "x_forwarded_for_ignored_for_tailnet_node", remoteAddr: "100.64.0.1:1234", xForwardedFor: "100.64.0.2", wantLogin: "user@example.com", }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { r := httptest.NewRequest("GET", "/api/v1/namespaces/kube-system/secrets", nil) r.RemoteAddr = tt.remoteAddr if tt.xForwardedFor != "" { r.Header.Set("X-Forwarded-For", tt.xForwardedFor) } who, err := ap.whoIs(r) if tt.wantLogin == "" { if err == nil { t.Fatalf("whoIs() = %q, want error", who.UserProfile.LoginName) } return } if err != nil { t.Fatalf("whoIs() unexpected error: %v", err) } if got := who.UserProfile.LoginName; got != tt.wantLogin { t.Errorf("whoIs() = %q, want %q", got, tt.wantLogin) } }) } } // TestCrossOriginRequests checks that in auth mode the proxy rejects browser // requests from other origins, including exec WebSocket upgrades, and still // forwards requests with no Origin (kubectl), with an Origin that matches // Host (the Python client) or marked same-origin by the browser (a web UI's // own proxy). func TestCrossOriginRequests(t *testing.T) { lal := memnet.Listen("local-tailscaled.sock:80") defer lal.Close() localAPI := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { json.NewEncoder(w).Encode(&apitype.WhoIsResponse{ Node: &tailcfg.Node{Name: "user-node.ts.net."}, UserProfile: &tailcfg.UserProfile{LoginName: "user@example.com"}, }) })} defer localAPI.Close() go localAPI.Serve(lal) tests := []struct { name string method string // empty means a GET WebSocket upgrade path string origin string fetchSite string // Sec-Fetch-Site sameOrigin bool otherPort bool noAuth bool wantStatus int }{ { name: "exec_ws_no_origin", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", wantStatus: http.StatusSwitchingProtocols, }, { name: "exec_ws_origin_matches_host", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", sameOrigin: true, wantStatus: http.StatusSwitchingProtocols, }, { name: "exec_ws_origin_other_port", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", otherPort: true, wantStatus: http.StatusForbidden, }, { name: "exec_ws_cross_origin", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", origin: "https://evil.example", wantStatus: http.StatusForbidden, }, { name: "exec_ws_null_origin", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", origin: "null", wantStatus: http.StatusForbidden, }, { name: "exec_ws_via_ui_proxy", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", origin: "http://127.0.0.1:4466", fetchSite: "same-origin", wantStatus: http.StatusSwitchingProtocols, }, { name: "exec_ws_cross_site", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", origin: "https://evil.example", fetchSite: "cross-site", wantStatus: http.StatusForbidden, }, { name: "attach_ws_cross_origin", path: "/api/v1/namespaces/default/pods/foo/attach", origin: "https://evil.example", wantStatus: http.StatusForbidden, }, { name: "watch_ws_cross_origin", path: "/api/v1/secrets?watch=true", origin: "https://evil.example", wantStatus: http.StatusForbidden, }, { name: "nodes_proxy_post_cross_origin", method: "POST", path: "/api/v1/nodes/foo/proxy/run/default/bar/baz?cmd=id", origin: "https://evil.example", wantStatus: http.StatusForbidden, }, { name: "noauth_exec_ws_cross_origin", path: "/api/v1/namespaces/default/pods/foo/exec?command=sh", origin: "https://evil.example", noAuth: true, wantStatus: http.StatusSwitchingProtocols, }, } for _, tt := range tests { t.Run(tt.name, func(t *testing.T) { gotUser := make(chan string, 1) upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { gotUser <- r.Header.Get("Impersonate-User") if r.Header.Get("Upgrade") == "" { return } w.Header().Set("Connection", "Upgrade") w.Header().Set("Upgrade", "websocket") w.WriteHeader(http.StatusSwitchingProtocols) })) defer upstream.Close() ap := &APIServerProxy{ log: zap.NewNop().Sugar(), lc: &local.Client{Dial: lal.Dial}, authMode: !tt.noAuth, upstreamURL: must.Get(url.Parse(upstream.URL)), } ap.rp = &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { ap.addImpersonationHeadersAsRequired(pr.Out) }, } mux := http.NewServeMux() mux.HandleFunc("/", ap.serveDefault) mux.HandleFunc("GET /api/v1/namespaces/{namespace}/pods/{pod}/exec", ap.serveExecWS) mux.HandleFunc("GET /api/v1/namespaces/{namespace}/pods/{pod}/attach", ap.serveAttachWS) srv := httptest.NewServer(mux) defer srv.Close() method := tt.method if method == "" { method = "GET" } req := must.Get(http.NewRequestWithContext(t.Context(), method, srv.URL+tt.path, nil)) if method == "GET" { req.Header.Set("Connection", "Upgrade") req.Header.Set("Upgrade", "websocket") req.Header.Set("Sec-WebSocket-Version", "13") req.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==") req.Header.Set("Sec-WebSocket-Protocol", "v5.channel.k8s.io") } switch { case tt.sameOrigin: req.Header.Set("Origin", srv.URL) case tt.otherPort: host, _, _ := net.SplitHostPort(srv.Listener.Addr().String()) req.Header.Set("Origin", "http://"+net.JoinHostPort(host, "1")) case tt.origin != "": req.Header.Set("Origin", tt.origin) } if tt.fetchSite != "" { req.Header.Set("Sec-Fetch-Site", tt.fetchSite) } resp, err := srv.Client().Do(req) if err != nil { t.Fatal(err) } resp.Body.Close() if resp.StatusCode != tt.wantStatus { t.Fatalf("status = %d, want %d", resp.StatusCode, tt.wantStatus) } select { case user := <-gotUser: if tt.wantStatus == http.StatusForbidden { t.Fatalf("rejected request reached the API server as %q", user) } if want := "user@example.com"; !tt.noAuth && user != want { t.Errorf("Impersonate-User = %q, want %q", user, want) } default: if tt.wantStatus != http.StatusForbidden { t.Fatal("request was not forwarded to the API server") } } }) } } func whoResp(capMap map[string][]string) *apitype.WhoIsResponse { resp := &apitype.WhoIsResponse{ CapMap: tailcfg.PeerCapMap{}, } for cap, rules := range capMap { resp.CapMap[peercap.Cap(cap)] = raw(rules...) } return resp } func raw(in ...string) []tailcfg.RawMessage { var out []tailcfg.RawMessage for _, i := range in { out = append(out, tailcfg.RawMessage(i)) } return out } func TestRunForgedProxyHeader(t *testing.T) { zl, err := zap.NewDevelopment() if err != nil { t.Fatal(err) } // Only the forged source resolves, as a netmap address does in LocalBackend.WhoIs. forgedIP := netip.MustParseAddr("100.64.0.9") var mu sync.Mutex var whoIsAddrs []string lal := memnet.Listen("local-tailscaled.sock:80") defer lal.Close() localAPI := &http.Server{Handler: http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { addr := r.URL.Query().Get("addr") mu.Lock() whoIsAddrs = append(whoIsAddrs, addr) mu.Unlock() if ap, err := netip.ParseAddrPort(addr); err != nil || ap.Addr() != forgedIP { http.Error(w, "no match for IP:port", http.StatusNotFound) return } json.NewEncoder(w).Encode(&apitype.WhoIsResponse{ Node: &tailcfg.Node{Name: "admin-node.ts.net."}, UserProfile: &tailcfg.UserProfile{LoginName: "admin@example.com"}, }) })} defer localAPI.Close() go localAPI.Serve(lal) var upstreamReqs int upstream := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { mu.Lock() upstreamReqs++ mu.Unlock() })) defer upstream.Close() ln, err := net.Listen("tcp", "127.0.0.1:0") if err != nil { t.Fatal(err) } ap := &APIServerProxy{ log: zl.Sugar(), lc: &local.Client{Dial: lal.Dial}, authMode: true, upstreamURL: must.Get(url.Parse(upstream.URL)), listenFunc: func(network, address string) (net.Listener, error) { return ln, nil }, } ap.rp = &httputil.ReverseProxy{ Rewrite: func(pr *httputil.ProxyRequest) { ap.addImpersonationHeadersAsRequired(pr.Out) }, } ctx, cancel := context.WithCancel(t.Context()) runErr := make(chan error, 1) go func() { runErr <- ap.Run(ctx) }() defer func() { cancel() <-runErr }() c, err := net.Dial("tcp", ln.Addr().String()) if err != nil { t.Fatal(err) } defer c.Close() c.SetDeadline(time.Now().Add(10 * time.Second)) if _, err := c.Write([]byte("PROXY TCP4 " + forgedIP.String() + " 100.100.100.100 12345 443\r\n" + "GET /api/v1/namespaces/kube-system/secrets HTTP/1.1\r\n" + "Host: localhost\r\n" + "Connection: close\r\n\r\n")); err != nil { t.Fatalf("writing request: %v", err) } resp, err := http.ReadResponse(bufio.NewReader(c), nil) if err != nil { t.Fatalf("reading response: %v", err) } resp.Body.Close() if resp.StatusCode == http.StatusOK { t.Errorf("forged request got %s, want an error", resp.Status) } mu.Lock() defer mu.Unlock() for _, addr := range whoIsAddrs { if ap, err := netip.ParseAddrPort(addr); err == nil && ap.Addr() == forgedIP { t.Errorf("whoIs was asked about %q from the PROXY header", addr) } } if upstreamReqs > 0 { t.Errorf("upstream got %d requests, want 0", upstreamReqs) } }