etcd_tls_test.go 6.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  1. package test
  2. import (
  3. "crypto/tls"
  4. "crypto/x509"
  5. "errors"
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/url"
  10. "os"
  11. "strings"
  12. "testing"
  13. "time"
  14. )
  15. // TestTLSOff asserts that non-TLS-encrypted communication between the
  16. // etcd server and an unauthenticated client works
  17. func TestTLSOff(t *testing.T) {
  18. proc, err := startServer([]string{})
  19. if err != nil {
  20. t.Fatal(err.Error())
  21. }
  22. defer stopServer(proc)
  23. client := buildClient()
  24. err = assertServerFunctional(client, "http")
  25. if err != nil {
  26. t.Fatal(err.Error())
  27. }
  28. }
  29. // TestTLSAnonymousClient asserts that TLS-encrypted communication between the etcd
  30. // server and an anonymous client works
  31. func TestTLSAnonymousClient(t *testing.T) {
  32. proc, err := startServer([]string{
  33. "-cert-file=../../fixtures/ca/server.crt",
  34. "-key-file=../../fixtures/ca/server.key.insecure",
  35. })
  36. if err != nil {
  37. t.Fatal(err.Error())
  38. }
  39. defer stopServer(proc)
  40. cacertfile := "../../fixtures/ca/ca.crt"
  41. cp := x509.NewCertPool()
  42. bytes, err := ioutil.ReadFile(cacertfile)
  43. if err != nil {
  44. panic(err)
  45. }
  46. cp.AppendCertsFromPEM(bytes)
  47. cfg := tls.Config{}
  48. cfg.RootCAs = cp
  49. client := buildTLSClient(&cfg)
  50. err = assertServerFunctional(client, "https")
  51. if err != nil {
  52. t.Fatal(err)
  53. }
  54. }
  55. // TestTLSAuthenticatedClient asserts that TLS-encrypted communication
  56. // between the etcd server and an authenticated client works
  57. func TestTLSAuthenticatedClient(t *testing.T) {
  58. proc, err := startServer([]string{
  59. "-cert-file=../../fixtures/ca/server.crt",
  60. "-key-file=../../fixtures/ca/server.key.insecure",
  61. "-ca-file=../../fixtures/ca/ca.crt",
  62. })
  63. if err != nil {
  64. t.Fatal(err.Error())
  65. }
  66. defer stopServer(proc)
  67. cacertfile := "../../fixtures/ca/ca.crt"
  68. certfile := "../../fixtures/ca/server2.crt"
  69. keyfile := "../../fixtures/ca/server2.key.insecure"
  70. cert, err := tls.LoadX509KeyPair(certfile, keyfile)
  71. if err != nil {
  72. panic(err)
  73. }
  74. cp := x509.NewCertPool()
  75. bytes, err := ioutil.ReadFile(cacertfile)
  76. if err != nil {
  77. panic(err)
  78. }
  79. cp.AppendCertsFromPEM(bytes)
  80. cfg := tls.Config{}
  81. cfg.Certificates = []tls.Certificate{cert}
  82. cfg.RootCAs = cp
  83. time.Sleep(time.Second)
  84. client := buildTLSClient(&cfg)
  85. err = assertServerFunctional(client, "https")
  86. if err != nil {
  87. t.Fatal(err)
  88. }
  89. }
  90. // TestTLSUnathenticatedClient asserts that TLS-encrypted communication
  91. // between the etcd server and an unauthenticated client fails
  92. func TestTLSUnauthenticatedClient(t *testing.T) {
  93. proc, err := startServer([]string{
  94. "-cert-file=../../fixtures/ca/server.crt",
  95. "-key-file=../../fixtures/ca/server.key.insecure",
  96. "-ca-file=../../fixtures/ca/ca.crt",
  97. })
  98. if err != nil {
  99. t.Fatal(err.Error())
  100. }
  101. defer stopServer(proc)
  102. cacertfile := "../../fixtures/ca/ca.crt"
  103. certfile := "../../fixtures/ca/broken_server.crt"
  104. keyfile := "../../fixtures/ca/broken_server.key.insecure"
  105. cert, err := tls.LoadX509KeyPair(certfile, keyfile)
  106. if err != nil {
  107. panic(err)
  108. }
  109. cp := x509.NewCertPool()
  110. bytes, err := ioutil.ReadFile(cacertfile)
  111. if err != nil {
  112. panic(err)
  113. }
  114. cp.AppendCertsFromPEM(bytes)
  115. cfg := tls.Config{}
  116. cfg.Certificates = []tls.Certificate{cert}
  117. cfg.RootCAs = cp
  118. time.Sleep(time.Second)
  119. client := buildTLSClient(&cfg)
  120. err = assertServerNotFunctional(client, "https")
  121. if err != nil {
  122. t.Fatal(err)
  123. }
  124. }
  125. func buildClient() http.Client {
  126. return http.Client{}
  127. }
  128. func buildTLSClient(tlsConf *tls.Config) http.Client {
  129. tr := http.Transport{TLSClientConfig: tlsConf}
  130. return http.Client{Transport: &tr}
  131. }
  132. func startServer(extra []string) (*os.Process, error) {
  133. procAttr := new(os.ProcAttr)
  134. procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
  135. cmd := []string{"etcd", "-f", "-data-dir=/tmp/node1", "-name=node1"}
  136. cmd = append(cmd, extra...)
  137. println(strings.Join(cmd, " "))
  138. return os.StartProcess(EtcdBinPath, cmd, procAttr)
  139. }
  140. // TODO(yichengq): refactor these helper functions in #645
  141. func startServer2(extra []string) (*os.Process, error) {
  142. procAttr := new(os.ProcAttr)
  143. procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
  144. cmd := []string{"etcd", "-f", "-data-dir=/tmp/node2", "-name=node2"}
  145. cmd = append(cmd, extra...)
  146. fmt.Println(strings.Join(cmd, " "))
  147. return os.StartProcess(EtcdBinPath, cmd, procAttr)
  148. }
  149. func startServerWithDataDir(extra []string) (*os.Process, error) {
  150. procAttr := new(os.ProcAttr)
  151. procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
  152. cmd := []string{"etcd", "-data-dir=/tmp/node1", "-name=node1"}
  153. cmd = append(cmd, extra...)
  154. fmt.Println(strings.Join(cmd, " "))
  155. return os.StartProcess(EtcdBinPath, cmd, procAttr)
  156. }
  157. func startServer2WithDataDir(extra []string) (*os.Process, error) {
  158. procAttr := new(os.ProcAttr)
  159. procAttr.Files = []*os.File{nil, os.Stdout, os.Stderr}
  160. cmd := []string{"etcd", "-data-dir=/tmp/node2", "-name=node2"}
  161. cmd = append(cmd, extra...)
  162. println(strings.Join(cmd, " "))
  163. return os.StartProcess(EtcdBinPath, cmd, procAttr)
  164. }
  165. func stopServer(proc *os.Process) {
  166. err := proc.Kill()
  167. if err != nil {
  168. panic(err.Error())
  169. }
  170. proc.Release()
  171. }
  172. func assertServerFunctional(client http.Client, scheme string) error {
  173. path := fmt.Sprintf("%s://127.0.0.1:4001/v2/keys/foo", scheme)
  174. fields := url.Values(map[string][]string{"value": {"bar"}})
  175. for i := 0; i < 10; i++ {
  176. time.Sleep(1 * time.Second)
  177. resp, err := client.PostForm(path, fields)
  178. // If the status is Temporary Redirect, we should follow the
  179. // new location, because the request did not go to the leader yet.
  180. // TODO(yichengq): the difference between Temporary Redirect(307)
  181. // and Created(201) could distinguish between leader and followers
  182. for err == nil && resp.StatusCode == http.StatusTemporaryRedirect {
  183. loc, _ := resp.Location()
  184. newPath := loc.String()
  185. resp, err = client.PostForm(newPath, fields)
  186. }
  187. if err == nil {
  188. // Internal error may mean that servers are in leader election
  189. if resp.StatusCode != http.StatusCreated && resp.StatusCode != http.StatusInternalServerError {
  190. return errors.New(fmt.Sprintf("resp.StatusCode == %s", resp.Status))
  191. } else {
  192. return nil
  193. }
  194. }
  195. }
  196. return errors.New("etcd server was not reachable in time / had internal error")
  197. }
  198. func assertServerNotFunctional(client http.Client, scheme string) error {
  199. path := fmt.Sprintf("%s://127.0.0.1:4001/v2/keys/foo", scheme)
  200. fields := url.Values(map[string][]string{"value": {"bar"}})
  201. for i := 0; i < 10; i++ {
  202. time.Sleep(1 * time.Second)
  203. _, err := client.PostForm(path, fields)
  204. if err == nil {
  205. return errors.New("Expected error during POST, got nil")
  206. } else {
  207. errString := err.Error()
  208. if strings.Contains(errString, "connection refused") {
  209. continue
  210. } else if strings.Contains(errString, "bad certificate") {
  211. return nil
  212. } else {
  213. return err
  214. }
  215. }
  216. }
  217. return errors.New("Expected server to fail with 'bad certificate'")
  218. }