acn_test.go 14 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498
  1. package acn
  2. import (
  3. "context"
  4. "net/http"
  5. "net/http/httptest"
  6. "path/filepath"
  7. "strings"
  8. "sync"
  9. "testing"
  10. "time"
  11. )
  12. /*
  13. Test helpers
  14. */
  15. type staticResolver struct {
  16. mu sync.RWMutex
  17. peers map[string]*Peer
  18. }
  19. func newStaticResolver() *staticResolver {
  20. return &staticResolver{peers: map[string]*Peer{}}
  21. }
  22. func (s *staticResolver) add(p *Peer) {
  23. s.mu.Lock()
  24. defer s.mu.Unlock()
  25. s.peers[p.ID] = p
  26. }
  27. func (s *staticResolver) ResolvePeer(id string) (*Peer, bool) {
  28. s.mu.RLock()
  29. defer s.mu.RUnlock()
  30. p, ok := s.peers[id]
  31. return p, ok
  32. }
  33. type testNode struct {
  34. id string
  35. key *NodeKey
  36. signer *Signer
  37. verifier *Verifier
  38. hub *TunnelHub
  39. server *Server
  40. resolver *staticResolver
  41. http *httptest.Server
  42. tr *Transport
  43. }
  44. func newTestNode(t *testing.T, id string, cluster string, resolver *staticResolver) *testNode {
  45. t.Helper()
  46. key, err := GenerateNodeKey()
  47. if err != nil {
  48. t.Fatalf("GenerateNodeKey: %v", err)
  49. }
  50. n := &testNode{id: id, key: key, resolver: resolver}
  51. n.signer = &Signer{NodeID: id, ClusterID: cluster, Key: key}
  52. n.verifier = NewVerifier(func() string { return cluster }, resolver)
  53. n.hub = NewTunnelHub(n.verifier)
  54. n.server = NewServer(n.verifier, n.hub, "test")
  55. n.http = httptest.NewServer(n.server)
  56. n.tr = NewTransport(n.signer, resolver, n.hub, false)
  57. t.Cleanup(func() {
  58. n.hub.Close()
  59. n.http.Close()
  60. })
  61. return n
  62. }
  63. func (n *testNode) peer(advertise bool, tunnelVia string) *Peer {
  64. p := &Peer{ID: n.id, Name: n.id, PublicKey: n.key.Public, TunnelVia: tunnelVia}
  65. if advertise {
  66. p.AdvertiseURL = n.http.URL
  67. }
  68. return p
  69. }
  70. /*
  71. Keys
  72. */
  73. func TestNodeKeyRoundTrip(t *testing.T) {
  74. key, err := GenerateNodeKey()
  75. if err != nil {
  76. t.Fatalf("GenerateNodeKey: %v", err)
  77. }
  78. parsed, err := ParseNodeKey(key.Encode())
  79. if err != nil {
  80. t.Fatalf("ParseNodeKey: %v", err)
  81. }
  82. if parsed.PublicKeyString() != key.PublicKeyString() {
  83. t.Errorf("public key mismatch after round trip")
  84. }
  85. pub, err := DecodePublicKey(key.PublicKeyString())
  86. if err != nil {
  87. t.Fatalf("DecodePublicKey: %v", err)
  88. }
  89. if string(pub) != string(key.Public) {
  90. t.Errorf("decoded public key differs")
  91. }
  92. }
  93. func TestLoadOrCreateNodeKeyPersists(t *testing.T) {
  94. dir := t.TempDir()
  95. keyfile := filepath.Join(dir, "sub", "node.key")
  96. first, err := LoadOrCreateNodeKey(keyfile)
  97. if err != nil {
  98. t.Fatalf("first load: %v", err)
  99. }
  100. second, err := LoadOrCreateNodeKey(keyfile)
  101. if err != nil {
  102. t.Fatalf("second load: %v", err)
  103. }
  104. if first.PublicKeyString() != second.PublicKeyString() {
  105. t.Errorf("key not persisted: %s != %s", first.PublicKeyString(), second.PublicKeyString())
  106. }
  107. }
  108. func TestParseNodeKeyInvalid(t *testing.T) {
  109. cases := []string{"", "zz", "abcd"}
  110. for _, c := range cases {
  111. if _, err := ParseNodeKey(c); err == nil {
  112. t.Errorf("ParseNodeKey(%q) expected error", c)
  113. }
  114. }
  115. if _, err := DecodePublicKey("not-base64!"); err == nil {
  116. t.Errorf("DecodePublicKey expected error")
  117. }
  118. }
  119. /*
  120. Signing
  121. */
  122. func TestSignVerifyRoundTrip(t *testing.T) {
  123. resolver := newStaticResolver()
  124. a := newTestNode(t, "node-a", "cluster-1", resolver)
  125. resolver.add(a.peer(true, ""))
  126. body := []byte(`{"hello":"world"}`)
  127. req := httptest.NewRequest(http.MethodPost, "/cluster/acn/ping?x=1", strings.NewReader(string(body)))
  128. a.signer.Sign(req, SignedTarget("/cluster/acn/ping", "x=1"), body)
  129. id, got, err := a.verifier.VerifyRequest(req)
  130. if err != nil {
  131. t.Fatalf("VerifyRequest: %v", err)
  132. }
  133. if id.NodeID != "node-a" {
  134. t.Errorf("expected sender node-a, got %s", id.NodeID)
  135. }
  136. if string(got) != string(body) {
  137. t.Errorf("body not preserved")
  138. }
  139. }
  140. func TestVerifyRejects(t *testing.T) {
  141. resolver := newStaticResolver()
  142. a := newTestNode(t, "node-a", "cluster-1", resolver)
  143. resolver.add(a.peer(true, ""))
  144. stranger := newTestNode(t, "node-x", "cluster-1", resolver) //never added to resolver
  145. other := newTestNode(t, "node-b", "cluster-2", resolver)
  146. resolver.add(other.peer(true, ""))
  147. body := []byte("payload")
  148. mk := func() *http.Request {
  149. return httptest.NewRequest(http.MethodPost, "/cluster/acn/ping", strings.NewReader(string(body)))
  150. }
  151. tests := []struct {
  152. name string
  153. req func() *http.Request
  154. want error
  155. }{
  156. {"unsigned", func() *http.Request { return mk() }, ErrNotSigned},
  157. {"unknown node", func() *http.Request {
  158. r := mk()
  159. stranger.signer.Sign(r, "/cluster/acn/ping", body)
  160. return r
  161. }, ErrUnknownNode},
  162. {"wrong cluster", func() *http.Request {
  163. r := mk()
  164. other.signer.Sign(r, "/cluster/acn/ping", body)
  165. return r
  166. }, ErrWrongCluster},
  167. {"clock skew", func() *http.Request {
  168. r := mk()
  169. a.signer.SignAt(r, "/cluster/acn/ping", body, time.Now().Add(-MaxClockSkew-time.Minute))
  170. return r
  171. }, ErrClockSkew},
  172. {"tampered body", func() *http.Request {
  173. r := mk()
  174. a.signer.Sign(r, "/cluster/acn/ping", []byte("different"))
  175. return r
  176. }, ErrBadSignature},
  177. {"wrong path", func() *http.Request {
  178. r := mk()
  179. a.signer.Sign(r, "/cluster/acn/other", body)
  180. return r
  181. }, ErrBadSignature},
  182. }
  183. for _, tc := range tests {
  184. t.Run(tc.name, func(t *testing.T) {
  185. _, _, err := a.verifier.VerifyRequest(tc.req())
  186. if err != tc.want {
  187. t.Errorf("expected %v, got %v", tc.want, err)
  188. }
  189. })
  190. }
  191. }
  192. func TestVerifyRejectsReplay(t *testing.T) {
  193. resolver := newStaticResolver()
  194. a := newTestNode(t, "node-a", "cluster-1", resolver)
  195. resolver.add(a.peer(true, ""))
  196. body := []byte("once")
  197. req := httptest.NewRequest(http.MethodPost, "/cluster/acn/ping", strings.NewReader(string(body)))
  198. a.signer.Sign(req, "/cluster/acn/ping", body)
  199. headers := req.Header.Clone()
  200. if _, _, err := a.verifier.VerifyRequest(req); err != nil {
  201. t.Fatalf("first verify: %v", err)
  202. }
  203. replay := httptest.NewRequest(http.MethodPost, "/cluster/acn/ping", strings.NewReader(string(body)))
  204. replay.Header = headers
  205. if _, _, err := a.verifier.VerifyRequest(replay); err != ErrReplay {
  206. t.Errorf("expected ErrReplay, got %v", err)
  207. }
  208. }
  209. func TestStripRelayPrefix(t *testing.T) {
  210. tests := []struct {
  211. path string
  212. node string
  213. original string
  214. ok bool
  215. }{
  216. {"/cluster/acn/relay/node-b/cluster/acn/ping", "node-b", "/cluster/acn/ping", true},
  217. {"/cluster/acn/relay/node-b/cluster/acn/a/b", "node-b", "/cluster/acn/a/b", true},
  218. {"/cluster/acn/ping", "", "/cluster/acn/ping", false},
  219. {"/cluster/acn/relay/", "", "/cluster/acn/relay/", false},
  220. {"/cluster/acn/relay/node-b", "", "/cluster/acn/relay/node-b", false},
  221. }
  222. for _, tc := range tests {
  223. node, original, ok := StripRelayPrefix(tc.path)
  224. if node != tc.node || original != tc.original || ok != tc.ok {
  225. t.Errorf("StripRelayPrefix(%q) = (%q,%q,%v) want (%q,%q,%v)", tc.path, node, original, ok, tc.node, tc.original, tc.ok)
  226. }
  227. }
  228. }
  229. /*
  230. Frames
  231. */
  232. func TestFrameRoundTrip(t *testing.T) {
  233. hdr := frameHeader{ID: "1", Method: "POST", Target: "/cluster/acn/ping?q=1", Headers: map[string][]string{"X-Test": {"a", "b"}}}
  234. body := []byte("body-bytes")
  235. data, err := encodeFrame(frameKindRequest, hdr, body)
  236. if err != nil {
  237. t.Fatalf("encodeFrame: %v", err)
  238. }
  239. kind, got, gotBody, err := decodeFrame(data)
  240. if err != nil {
  241. t.Fatalf("decodeFrame: %v", err)
  242. }
  243. if kind != frameKindRequest || got.ID != "1" || got.Target != hdr.Target || string(gotBody) != "body-bytes" {
  244. t.Errorf("frame mismatch: %v %+v %q", kind, got, gotBody)
  245. }
  246. if len(got.Headers["X-Test"]) != 2 {
  247. t.Errorf("headers not preserved")
  248. }
  249. if _, _, _, err := decodeFrame([]byte{1, 0}); err == nil {
  250. t.Errorf("short frame should fail")
  251. }
  252. if _, err := encodeFrame(frameKindRequest, hdr, make([]byte, TunnelMaxFrame)); err != ErrFrameTooLarge {
  253. t.Errorf("oversized frame should fail, got %v", err)
  254. }
  255. }
  256. func TestWebSocketURL(t *testing.T) {
  257. tests := []struct {
  258. in string
  259. want string
  260. err bool
  261. }{
  262. {"https://node.example.com", "wss://node.example.com/cluster/acn/tunnel", false},
  263. {"http://10.0.0.2:8080/", "ws://10.0.0.2:8080/cluster/acn/tunnel", false},
  264. {"ftp://x", "", true},
  265. }
  266. for _, tc := range tests {
  267. got, err := WebSocketURL(tc.in, TunnelPath)
  268. if (err != nil) != tc.err {
  269. t.Errorf("WebSocketURL(%q) err=%v", tc.in, err)
  270. continue
  271. }
  272. if got != tc.want {
  273. t.Errorf("WebSocketURL(%q)=%q want %q", tc.in, got, tc.want)
  274. }
  275. }
  276. }
  277. /*
  278. Transport routes
  279. */
  280. func TestTransportDirect(t *testing.T) {
  281. resolver := newStaticResolver()
  282. a := newTestNode(t, "node-a", "cluster-1", resolver)
  283. b := newTestNode(t, "node-b", "cluster-1", resolver)
  284. resolver.add(a.peer(true, ""))
  285. resolver.add(b.peer(true, ""))
  286. var out map[string]interface{}
  287. err := a.tr.DoJSON(context.Background(), "node-b", http.MethodPost, BasePath+"/ping", map[string]string{"k": "v"}, &out)
  288. if err != nil {
  289. t.Fatalf("DoJSON: %v", err)
  290. }
  291. if out["node"] != "node-a" {
  292. t.Errorf("ping should echo sender, got %v", out)
  293. }
  294. //Anonymous hello
  295. resp, err := a.tr.DoURL(context.Background(), b.http.URL, http.MethodGet, BasePath+"/hello", nil, false)
  296. if err != nil || resp.Status != 200 {
  297. t.Fatalf("hello: %v %v", err, resp)
  298. }
  299. if !strings.Contains(string(resp.Body), `"acn":true`) {
  300. t.Errorf("hello body unexpected: %s", resp.Body)
  301. }
  302. }
  303. func TestTransportUnknownPeer(t *testing.T) {
  304. resolver := newStaticResolver()
  305. a := newTestNode(t, "node-a", "cluster-1", resolver)
  306. if _, err := a.tr.Do(context.Background(), "ghost", http.MethodPost, BasePath+"/ping", nil); err != ErrUnknownNode {
  307. t.Errorf("expected ErrUnknownNode, got %v", err)
  308. }
  309. resolver.add(&Peer{ID: "nat-only", PublicKey: a.key.Public})
  310. if _, err := a.tr.Do(context.Background(), "nat-only", http.MethodPost, BasePath+"/ping", nil); err != ErrPeerNoEndpoint {
  311. t.Errorf("expected ErrPeerNoEndpoint, got %v", err)
  312. }
  313. }
  314. // connectTunnel attaches nat (no URL) to host and waits for the hub to see it.
  315. func connectTunnel(t *testing.T, nat *testNode, host *testNode) *TunnelClient {
  316. t.Helper()
  317. client := &TunnelClient{
  318. Signer: nat.signer,
  319. Handler: nat.server,
  320. PickHost: func() (TunnelHost, bool) {
  321. return TunnelHost{NodeID: host.id, URL: host.http.URL}, true
  322. },
  323. }
  324. client.Start()
  325. t.Cleanup(client.Stop)
  326. deadline := time.Now().Add(5 * time.Second)
  327. for !host.hub.Connected(nat.id) {
  328. if time.Now().After(deadline) {
  329. t.Fatalf("tunnel from %s to %s never connected", nat.id, host.id)
  330. }
  331. time.Sleep(20 * time.Millisecond)
  332. }
  333. return client
  334. }
  335. func TestTransportTunnelAndRelay(t *testing.T) {
  336. resolver := newStaticResolver()
  337. host := newTestNode(t, "node-host", "cluster-1", resolver)
  338. nat := newTestNode(t, "node-nat", "cluster-1", resolver)
  339. other := newTestNode(t, "node-other", "cluster-1", resolver)
  340. resolver.add(host.peer(true, ""))
  341. resolver.add(other.peer(true, ""))
  342. resolver.add(nat.peer(false, host.id))
  343. client := connectTunnel(t, nat, host)
  344. if ok, h := client.Status(); !ok || h.NodeID != host.id {
  345. t.Fatalf("client status wrong: %v %+v", ok, h)
  346. }
  347. //Host reaches nat over its own tunnel
  348. var out map[string]interface{}
  349. if err := host.tr.DoJSON(context.Background(), nat.id, http.MethodPost, BasePath+"/ping", map[string]int{"n": 1}, &out); err != nil {
  350. t.Fatalf("host->nat via tunnel: %v", err)
  351. }
  352. if out["node"] != host.id {
  353. t.Errorf("nat should see host as sender, got %v", out)
  354. }
  355. //Other reaches nat by relaying through host
  356. out = nil
  357. if err := other.tr.DoJSON(context.Background(), nat.id, http.MethodPost, BasePath+"/ping?via=relay", map[string]int{"n": 2}, &out); err != nil {
  358. t.Fatalf("other->nat via relay: %v", err)
  359. }
  360. if out["node"] != other.id {
  361. t.Errorf("nat should see other as original sender, got %v", out)
  362. }
  363. //Nat reaches other directly (other has a URL)
  364. out = nil
  365. if err := nat.tr.DoJSON(context.Background(), other.id, http.MethodPost, BasePath+"/ping", nil, &out); err != nil {
  366. t.Fatalf("nat->other direct: %v", err)
  367. }
  368. //Relay refuses non-ACN paths
  369. req, _ := http.NewRequest(http.MethodGet, host.http.URL+RelayPrefix+"/"+nat.id+"/system/secret", nil)
  370. other.signer.Sign(req, "/system/secret", []byte{})
  371. resp, err := http.DefaultClient.Do(req)
  372. if err != nil {
  373. t.Fatalf("relay request: %v", err)
  374. }
  375. resp.Body.Close()
  376. if resp.StatusCode != http.StatusBadRequest {
  377. t.Errorf("relay of non-ACN path should be rejected, got %d", resp.StatusCode)
  378. }
  379. //Drop the tunnel: host can no longer reach nat, relay returns bad gateway
  380. client.Stop()
  381. deadline := time.Now().Add(5 * time.Second)
  382. for host.hub.Connected(nat.id) {
  383. if time.Now().After(deadline) {
  384. t.Fatalf("tunnel did not close")
  385. }
  386. time.Sleep(20 * time.Millisecond)
  387. }
  388. if _, err := host.tr.Do(context.Background(), nat.id, http.MethodPost, BasePath+"/ping", nil); err != ErrTunnelNotConnected {
  389. t.Errorf("expected ErrTunnelNotConnected, got %v", err)
  390. }
  391. r, err := other.tr.Do(context.Background(), nat.id, http.MethodPost, BasePath+"/ping", nil)
  392. if err != nil {
  393. t.Fatalf("relay after close: %v", err)
  394. }
  395. if r.Status != http.StatusBadGateway {
  396. t.Errorf("relay after close expected 502, got %d", r.Status)
  397. }
  398. }
  399. func TestTunnelRejectsUnsignedUpgrade(t *testing.T) {
  400. resolver := newStaticResolver()
  401. host := newTestNode(t, "node-host", "cluster-1", resolver)
  402. resp, err := http.Get(host.http.URL + TunnelPath)
  403. if err != nil {
  404. t.Fatalf("GET tunnel: %v", err)
  405. }
  406. resp.Body.Close()
  407. if resp.StatusCode != http.StatusUnauthorized {
  408. t.Errorf("unsigned tunnel upgrade expected 401, got %d", resp.StatusCode)
  409. }
  410. }
  411. func TestTunnelClientReconnects(t *testing.T) {
  412. resolver := newStaticResolver()
  413. host := newTestNode(t, "node-host", "cluster-1", resolver)
  414. nat := newTestNode(t, "node-nat", "cluster-1", resolver)
  415. resolver.add(host.peer(true, ""))
  416. resolver.add(nat.peer(false, host.id))
  417. client := connectTunnel(t, nat, host)
  418. client.Reconnect() //drops the socket, loop must dial again
  419. deadline := time.Now().Add(10 * time.Second)
  420. for {
  421. //First wait for the drop to be observed on both ends
  422. if ok, _ := client.Status(); !ok && !host.hub.Connected(nat.id) {
  423. break
  424. }
  425. if time.Now().After(deadline) {
  426. t.Fatalf("tunnel did not drop after Reconnect")
  427. }
  428. time.Sleep(20 * time.Millisecond)
  429. }
  430. for {
  431. if ok, _ := client.Status(); ok && host.hub.Connected(nat.id) {
  432. break
  433. }
  434. if time.Now().After(deadline) {
  435. t.Fatalf("tunnel did not reconnect")
  436. }
  437. time.Sleep(50 * time.Millisecond)
  438. }
  439. if _, err := host.tr.Do(context.Background(), nat.id, http.MethodPost, BasePath+"/ping", nil); err != nil {
  440. t.Errorf("ping after reconnect: %v", err)
  441. }
  442. }
  443. func TestResponseError(t *testing.T) {
  444. if (&Response{Status: 200}).Error() != nil {
  445. t.Errorf("200 should not be an error")
  446. }
  447. if (&Response{Status: 500, Body: []byte("boom")}).Error() == nil {
  448. t.Errorf("500 should be an error")
  449. }
  450. var nilResp *Response
  451. if nilResp.Error() == nil {
  452. t.Errorf("nil response should be an error")
  453. }
  454. }