localapi_test.go 1.7 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879
  1. // Copyright (c) Tailscale Inc & AUTHORS
  2. // SPDX-License-Identifier: BSD-3-Clause
  3. package localapi
  4. import (
  5. "bytes"
  6. "encoding/json"
  7. "io"
  8. "net/http"
  9. "net/http/httptest"
  10. "testing"
  11. "tailscale.com/client/tailscale/apitype"
  12. "tailscale.com/hostinfo"
  13. "tailscale.com/ipn/ipnlocal"
  14. "tailscale.com/tstest"
  15. )
  16. func TestValidHost(t *testing.T) {
  17. tests := []struct {
  18. host string
  19. valid bool
  20. }{
  21. {"", true},
  22. {apitype.LocalAPIHost, true},
  23. {"localhost:9109", false},
  24. {"127.0.0.1:9110", false},
  25. {"[::1]:9111", false},
  26. {"100.100.100.100:41112", false},
  27. {"10.0.0.1:41112", false},
  28. {"37.16.9.210:41112", false},
  29. }
  30. for _, test := range tests {
  31. t.Run(test.host, func(t *testing.T) {
  32. h := &Handler{}
  33. if got := h.validHost(test.host); got != test.valid {
  34. t.Errorf("validHost(%q)=%v, want %v", test.host, got, test.valid)
  35. }
  36. })
  37. }
  38. }
  39. func TestSetPushDeviceToken(t *testing.T) {
  40. tstest.Replace(t, &validLocalHostForTesting, true)
  41. h := &Handler{
  42. PermitWrite: true,
  43. b: &ipnlocal.LocalBackend{},
  44. }
  45. s := httptest.NewServer(h)
  46. defer s.Close()
  47. c := s.Client()
  48. want := "my-test-device-token"
  49. body, err := json.Marshal(apitype.SetPushDeviceTokenRequest{PushDeviceToken: want})
  50. if err != nil {
  51. t.Fatal(err)
  52. }
  53. req, err := http.NewRequest("POST", s.URL+"/localapi/v0/set-push-device-token", bytes.NewReader(body))
  54. if err != nil {
  55. t.Fatal(err)
  56. }
  57. res, err := c.Do(req)
  58. if err != nil {
  59. t.Fatal(err)
  60. }
  61. body, err = io.ReadAll(res.Body)
  62. if err != nil {
  63. t.Fatal(err)
  64. }
  65. if res.StatusCode != 200 {
  66. t.Errorf("res.StatusCode=%d, want 200. body: %s", res.StatusCode, body)
  67. }
  68. if got := hostinfo.New().PushDeviceToken; got != want {
  69. t.Errorf("hostinfo.PushDeviceToken=%q, want %q", got, want)
  70. }
  71. }