localapi_test.go 11 KB

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