localapi_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package localapi
  4. import (
  5. "bytes"
  6. "context"
  7. "encoding/json"
  8. "errors"
  9. "fmt"
  10. "go/ast"
  11. "go/parser"
  12. "go/token"
  13. "io"
  14. "log"
  15. "net/http"
  16. "net/http/httptest"
  17. "net/netip"
  18. "net/url"
  19. "os"
  20. "slices"
  21. "strconv"
  22. "strings"
  23. "testing"
  24. "tailscale.com/client/tailscale/apitype"
  25. "tailscale.com/ipn"
  26. "tailscale.com/ipn/ipnauth"
  27. "tailscale.com/ipn/ipnlocal"
  28. "tailscale.com/ipn/store/mem"
  29. "tailscale.com/tailcfg"
  30. "tailscale.com/tsd"
  31. "tailscale.com/tstest"
  32. "tailscale.com/types/key"
  33. "tailscale.com/types/logger"
  34. "tailscale.com/types/logid"
  35. "tailscale.com/util/slicesx"
  36. "tailscale.com/wgengine"
  37. )
  38. func TestValidHost(t *testing.T) {
  39. tests := []struct {
  40. host string
  41. valid bool
  42. }{
  43. {"", true},
  44. {apitype.LocalAPIHost, true},
  45. {"localhost:9109", false},
  46. {"127.0.0.1:9110", false},
  47. {"[::1]:9111", false},
  48. {"100.100.100.100:41112", false},
  49. {"10.0.0.1:41112", false},
  50. {"37.16.9.210:41112", false},
  51. }
  52. for _, test := range tests {
  53. t.Run(test.host, func(t *testing.T) {
  54. h := &Handler{}
  55. if got := h.validHost(test.host); got != test.valid {
  56. t.Errorf("validHost(%q)=%v, want %v", test.host, got, test.valid)
  57. }
  58. })
  59. }
  60. }
  61. func TestSetPushDeviceToken(t *testing.T) {
  62. tstest.Replace(t, &validLocalHostForTesting, true)
  63. h := &Handler{
  64. PermitWrite: true,
  65. b: &ipnlocal.LocalBackend{},
  66. }
  67. s := httptest.NewServer(h)
  68. defer s.Close()
  69. c := s.Client()
  70. want := "my-test-device-token"
  71. body, err := json.Marshal(apitype.SetPushDeviceTokenRequest{PushDeviceToken: want})
  72. if err != nil {
  73. t.Fatal(err)
  74. }
  75. req, err := http.NewRequest("POST", s.URL+"/localapi/v0/set-push-device-token", bytes.NewReader(body))
  76. if err != nil {
  77. t.Fatal(err)
  78. }
  79. res, err := c.Do(req)
  80. if err != nil {
  81. t.Fatal(err)
  82. }
  83. body, err = io.ReadAll(res.Body)
  84. if err != nil {
  85. t.Fatal(err)
  86. }
  87. if res.StatusCode != 200 {
  88. t.Errorf("res.StatusCode=%d, want 200. body: %s", res.StatusCode, body)
  89. }
  90. if got := h.b.GetPushDeviceToken(); got != want {
  91. t.Errorf("hostinfo.PushDeviceToken=%q, want %q", got, want)
  92. }
  93. }
  94. type whoIsBackend struct {
  95. whoIs func(proto string, ipp netip.AddrPort) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool)
  96. whoIsNodeKey func(key.NodePublic) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool)
  97. peerCaps map[netip.Addr]tailcfg.PeerCapMap
  98. }
  99. func (b whoIsBackend) WhoIs(proto string, ipp netip.AddrPort) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
  100. return b.whoIs(proto, ipp)
  101. }
  102. func (b whoIsBackend) WhoIsNodeKey(k key.NodePublic) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
  103. return b.whoIsNodeKey(k)
  104. }
  105. func (b whoIsBackend) PeerCaps(ip netip.Addr) tailcfg.PeerCapMap {
  106. return b.peerCaps[ip]
  107. }
  108. // Tests that the WhoIs handler accepts IPs, IP:ports, or nodekeys.
  109. //
  110. // From https://github.com/tailscale/tailscale/pull/9714 (a PR that is effectively a bug report)
  111. //
  112. // And https://github.com/tailscale/tailscale/issues/12465
  113. func TestWhoIsArgTypes(t *testing.T) {
  114. h := &Handler{
  115. PermitRead: true,
  116. }
  117. match := func() (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
  118. return (&tailcfg.Node{
  119. ID: 123,
  120. Addresses: []netip.Prefix{
  121. netip.MustParsePrefix("100.101.102.103/32"),
  122. },
  123. }).View(),
  124. tailcfg.UserProfile{ID: 456, DisplayName: "foo"},
  125. true
  126. }
  127. const keyStr = "nodekey:5c8f86d5fc70d924e55f02446165a5dae8f822994ad26bcf4b08fd841f9bf261"
  128. for _, input := range []string{"100.101.102.103", "127.0.0.1:123", keyStr} {
  129. rec := httptest.NewRecorder()
  130. t.Run(input, func(t *testing.T) {
  131. b := whoIsBackend{
  132. whoIs: func(proto string, ipp netip.AddrPort) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
  133. if !strings.Contains(input, ":") {
  134. want := netip.MustParseAddrPort("100.101.102.103:0")
  135. if ipp != want {
  136. t.Fatalf("backend called with %v; want %v", ipp, want)
  137. }
  138. }
  139. return match()
  140. },
  141. whoIsNodeKey: func(k key.NodePublic) (n tailcfg.NodeView, u tailcfg.UserProfile, ok bool) {
  142. if k.String() != keyStr {
  143. t.Fatalf("backend called with %v; want %v", k, keyStr)
  144. }
  145. return match()
  146. },
  147. peerCaps: map[netip.Addr]tailcfg.PeerCapMap{
  148. netip.MustParseAddr("100.101.102.103"): map[tailcfg.PeerCapability][]tailcfg.RawMessage{
  149. "foo": {`"bar"`},
  150. },
  151. },
  152. }
  153. h.serveWhoIsWithBackend(rec, httptest.NewRequest("GET", "/v0/whois?addr="+url.QueryEscape(input), nil), b)
  154. if rec.Code != 200 {
  155. t.Fatalf("response code %d", rec.Code)
  156. }
  157. var res apitype.WhoIsResponse
  158. if err := json.Unmarshal(rec.Body.Bytes(), &res); err != nil {
  159. t.Fatalf("parsing response %#q: %v", rec.Body.Bytes(), err)
  160. }
  161. if got, want := res.Node.ID, tailcfg.NodeID(123); got != want {
  162. t.Errorf("res.Node.ID=%v, want %v", got, want)
  163. }
  164. if got, want := res.UserProfile.DisplayName, "foo"; got != want {
  165. t.Errorf("res.UserProfile.DisplayName=%q, want %q", got, want)
  166. }
  167. if got, want := len(res.CapMap), 1; got != want {
  168. t.Errorf("capmap size=%v, want %v", got, want)
  169. }
  170. })
  171. }
  172. }
  173. func TestShouldDenyServeConfigForGOOSAndUserContext(t *testing.T) {
  174. newHandler := func(connIsLocalAdmin bool) *Handler {
  175. return &Handler{Actor: &ipnauth.TestActor{LocalAdmin: connIsLocalAdmin}, b: newTestLocalBackend(t)}
  176. }
  177. tests := []struct {
  178. name string
  179. configIn *ipn.ServeConfig
  180. h *Handler
  181. wantErr bool
  182. }{
  183. {
  184. name: "not-path-handler",
  185. configIn: &ipn.ServeConfig{
  186. Web: map[ipn.HostPort]*ipn.WebServerConfig{
  187. "foo.test.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
  188. "/": {Proxy: "http://127.0.0.1:3000"},
  189. }},
  190. },
  191. },
  192. h: newHandler(false),
  193. wantErr: false,
  194. },
  195. {
  196. name: "path-handler-admin",
  197. configIn: &ipn.ServeConfig{
  198. Web: map[ipn.HostPort]*ipn.WebServerConfig{
  199. "foo.test.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
  200. "/": {Path: "/tmp"},
  201. }},
  202. },
  203. },
  204. h: newHandler(true),
  205. wantErr: false,
  206. },
  207. {
  208. name: "path-handler-not-admin",
  209. configIn: &ipn.ServeConfig{
  210. Web: map[ipn.HostPort]*ipn.WebServerConfig{
  211. "foo.test.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
  212. "/": {Path: "/tmp"},
  213. }},
  214. },
  215. },
  216. h: newHandler(false),
  217. wantErr: true,
  218. },
  219. }
  220. for _, tt := range tests {
  221. for _, goos := range []string{"linux", "windows", "darwin", "illumos", "solaris"} {
  222. t.Run(goos+"-"+tt.name, func(t *testing.T) {
  223. err := authorizeServeConfigForGOOSAndUserContext(goos, tt.configIn, tt.h)
  224. gotErr := err != nil
  225. if gotErr != tt.wantErr {
  226. t.Errorf("authorizeServeConfigForGOOSAndUserContext() got error = %v, want error %v", err, tt.wantErr)
  227. }
  228. })
  229. }
  230. }
  231. t.Run("other-goos", func(t *testing.T) {
  232. configIn := &ipn.ServeConfig{
  233. Web: map[ipn.HostPort]*ipn.WebServerConfig{
  234. "foo.test.ts.net:443": {Handlers: map[string]*ipn.HTTPHandler{
  235. "/": {Path: "/tmp"},
  236. }},
  237. },
  238. }
  239. h := newHandler(false)
  240. err := authorizeServeConfigForGOOSAndUserContext("dos", configIn, h)
  241. if err != nil {
  242. t.Errorf("authorizeServeConfigForGOOSAndUserContext() got error = %v, want nil", err)
  243. }
  244. })
  245. }
  246. func TestServeWatchIPNBus(t *testing.T) {
  247. tstest.Replace(t, &validLocalHostForTesting, true)
  248. tests := []struct {
  249. desc string
  250. permitRead, permitWrite bool
  251. mask ipn.NotifyWatchOpt // extra bits in addition to ipn.NotifyInitialState
  252. wantStatus int
  253. }{
  254. {
  255. desc: "no-permission",
  256. permitRead: false,
  257. permitWrite: false,
  258. wantStatus: http.StatusForbidden,
  259. },
  260. {
  261. desc: "read-initial-state",
  262. permitRead: true,
  263. permitWrite: false,
  264. wantStatus: http.StatusForbidden,
  265. },
  266. {
  267. desc: "read-initial-state-no-private-keys",
  268. permitRead: true,
  269. permitWrite: false,
  270. mask: ipn.NotifyNoPrivateKeys,
  271. wantStatus: http.StatusOK,
  272. },
  273. {
  274. desc: "read-initial-state-with-private-keys",
  275. permitRead: true,
  276. permitWrite: true,
  277. wantStatus: http.StatusOK,
  278. },
  279. }
  280. for _, tt := range tests {
  281. t.Run(tt.desc, func(t *testing.T) {
  282. h := &Handler{
  283. PermitRead: tt.permitRead,
  284. PermitWrite: tt.permitWrite,
  285. b: newTestLocalBackend(t),
  286. }
  287. s := httptest.NewServer(h)
  288. defer s.Close()
  289. c := s.Client()
  290. ctx, cancel := context.WithCancel(context.Background())
  291. req, err := http.NewRequestWithContext(ctx, "GET", fmt.Sprintf("%s/localapi/v0/watch-ipn-bus?mask=%d", s.URL, ipn.NotifyInitialState|tt.mask), nil)
  292. if err != nil {
  293. t.Fatal(err)
  294. }
  295. res, err := c.Do(req)
  296. if err != nil {
  297. t.Fatal(err)
  298. }
  299. defer res.Body.Close()
  300. // Cancel the context so that localapi stops streaming IPN bus
  301. // updates.
  302. cancel()
  303. body, err := io.ReadAll(res.Body)
  304. if err != nil && !errors.Is(err, context.Canceled) {
  305. t.Fatal(err)
  306. }
  307. if res.StatusCode != tt.wantStatus {
  308. t.Errorf("res.StatusCode=%d, want %d. body: %s", res.StatusCode, tt.wantStatus, body)
  309. }
  310. })
  311. }
  312. }
  313. func newTestLocalBackend(t testing.TB) *ipnlocal.LocalBackend {
  314. var logf logger.Logf = logger.Discard
  315. sys := tsd.NewSystem()
  316. store := new(mem.Store)
  317. sys.Set(store)
  318. eng, err := wgengine.NewFakeUserspaceEngine(logf, sys.Set, sys.HealthTracker(), sys.UserMetricsRegistry(), sys.Bus.Get())
  319. if err != nil {
  320. t.Fatalf("NewFakeUserspaceEngine: %v", err)
  321. }
  322. t.Cleanup(eng.Close)
  323. sys.Set(eng)
  324. lb, err := ipnlocal.NewLocalBackend(logf, logid.PublicID{}, sys, 0)
  325. if err != nil {
  326. t.Fatalf("NewLocalBackend: %v", err)
  327. }
  328. t.Cleanup(lb.Shutdown)
  329. return lb
  330. }
  331. func TestKeepItSorted(t *testing.T) {
  332. // Parse the localapi.go file into an AST.
  333. fset := token.NewFileSet() // positions are relative to fset
  334. src, err := os.ReadFile("localapi.go")
  335. if err != nil {
  336. log.Fatal(err)
  337. }
  338. f, err := parser.ParseFile(fset, "localapi.go", src, 0)
  339. if err != nil {
  340. log.Fatal(err)
  341. }
  342. getHandler := func() *ast.ValueSpec {
  343. for _, d := range f.Decls {
  344. if g, ok := d.(*ast.GenDecl); ok && g.Tok == token.VAR {
  345. for _, s := range g.Specs {
  346. if vs, ok := s.(*ast.ValueSpec); ok {
  347. if len(vs.Names) == 1 && vs.Names[0].Name == "handler" {
  348. return vs
  349. }
  350. }
  351. }
  352. }
  353. }
  354. return nil
  355. }
  356. keys := func() (ret []string) {
  357. h := getHandler()
  358. if h == nil {
  359. t.Fatal("no handler var found")
  360. }
  361. cl, ok := h.Values[0].(*ast.CompositeLit)
  362. if !ok {
  363. t.Fatalf("handler[0] is %T, want *ast.CompositeLit", h.Values[0])
  364. }
  365. for _, e := range cl.Elts {
  366. kv := e.(*ast.KeyValueExpr)
  367. strLt := kv.Key.(*ast.BasicLit)
  368. if strLt.Kind != token.STRING {
  369. t.Fatalf("got: %T, %q", kv.Key, kv.Key)
  370. }
  371. k, err := strconv.Unquote(strLt.Value)
  372. if err != nil {
  373. t.Fatalf("unquote: %v", err)
  374. }
  375. ret = append(ret, k)
  376. }
  377. return
  378. }
  379. gotKeys := keys()
  380. endSlash, noSlash := slicesx.Partition(keys(), func(s string) bool { return strings.HasSuffix(s, "/") })
  381. if !slices.IsSorted(endSlash) {
  382. t.Errorf("the items ending in a slash aren't sorted")
  383. }
  384. if !slices.IsSorted(noSlash) {
  385. t.Errorf("the items ending in a slash aren't sorted")
  386. }
  387. if !t.Failed() {
  388. want := append(endSlash, noSlash...)
  389. if !slices.Equal(gotKeys, want) {
  390. t.Errorf("items with trailing slashes should precede those without")
  391. }
  392. }
  393. }