global_test.go 7.5 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250
  1. // Copyright (C) 2015 The Syncthing Authors.
  2. //
  3. // This Source Code Form is subject to the terms of the Mozilla Public
  4. // License, v. 2.0. If a copy of the MPL was not distributed with this file,
  5. // You can obtain one at https://mozilla.org/MPL/2.0/.
  6. package discover
  7. import (
  8. "context"
  9. "crypto/tls"
  10. "io"
  11. "net"
  12. "net/http"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/syncthing/syncthing/lib/connections/registry"
  17. "github.com/syncthing/syncthing/lib/events"
  18. "github.com/syncthing/syncthing/lib/protocol"
  19. "github.com/syncthing/syncthing/lib/tlsutil"
  20. )
  21. func TestParseOptions(t *testing.T) {
  22. testcases := []struct {
  23. in string
  24. out string
  25. opts serverOptions
  26. }{
  27. {"https://example.com/", "https://example.com/", serverOptions{}},
  28. {"https://example.com/?insecure", "https://example.com/", serverOptions{insecure: true}},
  29. {"https://example.com/?insecure=true", "https://example.com/", serverOptions{insecure: true}},
  30. {"https://example.com/?insecure=yes", "https://example.com/", serverOptions{insecure: true}},
  31. {"https://example.com/?insecure=false&noannounce", "https://example.com/", serverOptions{noAnnounce: true}},
  32. {"https://example.com/?id=abc", "https://example.com/", serverOptions{id: "abc", insecure: true}},
  33. }
  34. for _, tc := range testcases {
  35. res, opts, err := parseOptions(tc.in)
  36. if err != nil {
  37. t.Errorf("Unexpected err %v for %v", err, tc.in)
  38. continue
  39. }
  40. if res != tc.out {
  41. t.Errorf("Incorrect server, %v!= %v for %v", res, tc.out, tc.in)
  42. }
  43. if opts != tc.opts {
  44. t.Errorf("Incorrect options, %v!= %v for %v", opts, tc.opts, tc.in)
  45. }
  46. }
  47. }
  48. func TestGlobalOverHTTP(t *testing.T) {
  49. // HTTP works for queries, but is obviously insecure and we can't do
  50. // announces over it (as we don't present a certificate). As such, http://
  51. // is only allowed in combination with the "insecure" and "noannounce"
  52. // parameters.
  53. registry := registry.New()
  54. if _, err := NewGlobal("http://192.0.2.42/", tls.Certificate{}, nil, events.NoopLogger, registry); err == nil {
  55. t.Fatal("http is not allowed without insecure and noannounce")
  56. }
  57. if _, err := NewGlobal("http://192.0.2.42/?insecure", tls.Certificate{}, nil, events.NoopLogger, registry); err == nil {
  58. t.Fatal("http is not allowed without noannounce")
  59. }
  60. if _, err := NewGlobal("http://192.0.2.42/?noannounce", tls.Certificate{}, nil, events.NoopLogger, registry); err == nil {
  61. t.Fatal("http is not allowed without insecure")
  62. }
  63. // Now lets check that lookups work over HTTP, given the correct options.
  64. list, err := net.Listen("tcp4", "127.0.0.1:0")
  65. if err != nil {
  66. t.Fatal(err)
  67. }
  68. defer list.Close()
  69. s := new(fakeDiscoveryServer)
  70. mux := http.NewServeMux()
  71. mux.HandleFunc("/", s.handler)
  72. go func() { _ = http.Serve(list, mux) }()
  73. // This should succeed
  74. addresses, err := testLookup("http://" + list.Addr().String() + "?insecure&noannounce")
  75. if err != nil {
  76. t.Fatalf("unexpected error: %v", err)
  77. }
  78. if !testing.Short() {
  79. // This should time out
  80. _, err = testLookup("http://" + list.Addr().String() + "/block?insecure&noannounce")
  81. if err == nil {
  82. t.Fatalf("unexpected nil error, should have been a timeout")
  83. }
  84. }
  85. // This should work again
  86. _, err = testLookup("http://" + list.Addr().String() + "?insecure&noannounce")
  87. if err != nil {
  88. t.Fatalf("unexpected error: %v", err)
  89. }
  90. if len(addresses) != 1 || addresses[0] != "tcp://192.0.2.42::22000" {
  91. t.Errorf("incorrect addresses list: %+v", addresses)
  92. }
  93. }
  94. func TestGlobalOverHTTPS(t *testing.T) {
  95. // Generate a server certificate.
  96. cert, err := tlsutil.NewCertificateInMemory("syncthing", 30)
  97. if err != nil {
  98. t.Fatal(err)
  99. }
  100. list, err := tls.Listen("tcp4", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}})
  101. if err != nil {
  102. t.Fatal(err)
  103. }
  104. defer list.Close()
  105. s := new(fakeDiscoveryServer)
  106. mux := http.NewServeMux()
  107. mux.HandleFunc("/", s.handler)
  108. go func() { _ = http.Serve(list, mux) }()
  109. // With default options the lookup code expects the server certificate to
  110. // check out according to the usual CA chains etc. That won't be the case
  111. // here so we expect the lookup to fail.
  112. url := "https://" + list.Addr().String()
  113. if _, err := testLookup(url); err == nil {
  114. t.Fatalf("unexpected nil error when we should have got a certificate error")
  115. }
  116. // With "insecure" set, whatever certificate is on the other side should
  117. // be accepted.
  118. url = "https://" + list.Addr().String() + "?insecure"
  119. if addresses, err := testLookup(url); err != nil {
  120. t.Fatalf("unexpected error: %v", err)
  121. } else if len(addresses) != 1 || addresses[0] != "tcp://192.0.2.42::22000" {
  122. t.Errorf("incorrect addresses list: %+v", addresses)
  123. }
  124. // With "id" set to something incorrect, the checks should fail again.
  125. url = "https://" + list.Addr().String() + "?id=" + protocol.LocalDeviceID.String()
  126. if _, err := testLookup(url); err == nil {
  127. t.Fatalf("unexpected nil error for incorrect discovery server ID")
  128. }
  129. // With the correct device ID, the check should pass and we should get a
  130. // lookup response.
  131. id := protocol.NewDeviceID(cert.Certificate[0])
  132. url = "https://" + list.Addr().String() + "?id=" + id.String()
  133. if addresses, err := testLookup(url); err != nil {
  134. t.Fatalf("unexpected error: %v", err)
  135. } else if len(addresses) != 1 || addresses[0] != "tcp://192.0.2.42::22000" {
  136. t.Errorf("incorrect addresses list: %+v", addresses)
  137. }
  138. }
  139. func TestGlobalAnnounce(t *testing.T) {
  140. // Generate a server certificate.
  141. cert, err := tlsutil.NewCertificateInMemory("syncthing", 30)
  142. if err != nil {
  143. t.Fatal(err)
  144. }
  145. list, err := tls.Listen("tcp4", "127.0.0.1:0", &tls.Config{Certificates: []tls.Certificate{cert}})
  146. if err != nil {
  147. t.Fatal(err)
  148. }
  149. defer list.Close()
  150. s := new(fakeDiscoveryServer)
  151. mux := http.NewServeMux()
  152. mux.HandleFunc("/", s.handler)
  153. go func() { _ = http.Serve(list, mux) }()
  154. url := "https://" + list.Addr().String() + "?insecure"
  155. disco, err := NewGlobal(url, cert, new(fakeAddressLister), events.NoopLogger, registry.New())
  156. if err != nil {
  157. t.Fatal(err)
  158. }
  159. ctx, cancel := context.WithCancel(context.Background())
  160. go disco.Serve(ctx)
  161. defer cancel()
  162. // The discovery thing should attempt an announcement immediately. We wait
  163. // for it to succeed, a while.
  164. t0 := time.Now()
  165. for err := disco.Error(); err != nil; err = disco.Error() {
  166. if time.Since(t0) > 10*time.Second {
  167. t.Fatal("announce failed:", err)
  168. }
  169. time.Sleep(100 * time.Millisecond)
  170. }
  171. if !strings.Contains(string(s.announce), "tcp://0.0.0.0:22000") {
  172. t.Errorf("announce missing address: %q", s.announce)
  173. }
  174. }
  175. func testLookup(url string) ([]string, error) {
  176. disco, err := NewGlobal(url, tls.Certificate{}, nil, events.NoopLogger, registry.New())
  177. if err != nil {
  178. return nil, err
  179. }
  180. ctx, cancel := context.WithCancel(context.Background())
  181. go disco.Serve(ctx)
  182. defer cancel()
  183. return disco.Lookup(context.Background(), protocol.LocalDeviceID)
  184. }
  185. type fakeDiscoveryServer struct {
  186. announce []byte
  187. }
  188. func (s *fakeDiscoveryServer) handler(w http.ResponseWriter, r *http.Request) {
  189. if r.URL.Path == "/block" {
  190. // Never return for requests here
  191. select {}
  192. }
  193. if r.Method == "POST" {
  194. s.announce, _ = io.ReadAll(r.Body)
  195. w.WriteHeader(204)
  196. } else {
  197. w.Header().Set("Content-Type", "application/json")
  198. w.Write([]byte(`{"addresses":["tcp://192.0.2.42::22000"], "relays":[{"url": "relay://192.0.2.43:443", "latency": 42}]}`))
  199. }
  200. }
  201. type fakeAddressLister struct{}
  202. func (*fakeAddressLister) ExternalAddresses() []string {
  203. return []string{"tcp://0.0.0.0:22000"}
  204. }
  205. func (*fakeAddressLister) AllAddresses() []string {
  206. return []string{"tcp://0.0.0.0:22000", "tcp://192.168.0.1:22000"}
  207. }