trust_server_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319
  1. package main
  2. import (
  3. "fmt"
  4. "io/ioutil"
  5. "net"
  6. "net/http"
  7. "os"
  8. "os/exec"
  9. "path/filepath"
  10. "strings"
  11. "time"
  12. cliconfig "github.com/docker/docker/cli/config"
  13. "github.com/docker/docker/integration-cli/checker"
  14. "github.com/docker/docker/integration-cli/cli"
  15. icmd "github.com/docker/docker/pkg/testutil/cmd"
  16. "github.com/docker/go-connections/tlsconfig"
  17. "github.com/go-check/check"
  18. )
  19. var notaryBinary = "notary"
  20. var notaryServerBinary = "notary-server"
  21. type keyPair struct {
  22. Public string
  23. Private string
  24. }
  25. type testNotary struct {
  26. cmd *exec.Cmd
  27. dir string
  28. keys []keyPair
  29. }
  30. const notaryHost = "localhost:4443"
  31. const notaryURL = "https://" + notaryHost
  32. var SuccessTagging = icmd.Expected{
  33. Out: "Tagging",
  34. }
  35. var SuccessSigningAndPushing = icmd.Expected{
  36. Out: "Signing and pushing trust metadata",
  37. }
  38. var SuccessDownloaded = icmd.Expected{
  39. Out: "Status: Downloaded",
  40. }
  41. var SuccessDownloadedOnStderr = icmd.Expected{
  42. Err: "Status: Downloaded",
  43. }
  44. func newTestNotary(c *check.C) (*testNotary, error) {
  45. // generate server config
  46. template := `{
  47. "server": {
  48. "http_addr": "%s",
  49. "tls_key_file": "%s",
  50. "tls_cert_file": "%s"
  51. },
  52. "trust_service": {
  53. "type": "local",
  54. "hostname": "",
  55. "port": "",
  56. "key_algorithm": "ed25519"
  57. },
  58. "logging": {
  59. "level": "debug"
  60. },
  61. "storage": {
  62. "backend": "memory"
  63. }
  64. }`
  65. tmp, err := ioutil.TempDir("", "notary-test-")
  66. if err != nil {
  67. return nil, err
  68. }
  69. confPath := filepath.Join(tmp, "config.json")
  70. config, err := os.Create(confPath)
  71. if err != nil {
  72. return nil, err
  73. }
  74. defer config.Close()
  75. workingDir, err := os.Getwd()
  76. if err != nil {
  77. return nil, err
  78. }
  79. if _, err := fmt.Fprintf(config, template, notaryHost, filepath.Join(workingDir, "fixtures/notary/localhost.key"), filepath.Join(workingDir, "fixtures/notary/localhost.cert")); err != nil {
  80. os.RemoveAll(tmp)
  81. return nil, err
  82. }
  83. // generate client config
  84. clientConfPath := filepath.Join(tmp, "client-config.json")
  85. clientConfig, err := os.Create(clientConfPath)
  86. if err != nil {
  87. return nil, err
  88. }
  89. defer clientConfig.Close()
  90. template = `{
  91. "trust_dir" : "%s",
  92. "remote_server": {
  93. "url": "%s",
  94. "skipTLSVerify": true
  95. }
  96. }`
  97. if _, err = fmt.Fprintf(clientConfig, template, filepath.Join(cliconfig.Dir(), "trust"), notaryURL); err != nil {
  98. os.RemoveAll(tmp)
  99. return nil, err
  100. }
  101. // load key fixture filenames
  102. var keys []keyPair
  103. for i := 1; i < 5; i++ {
  104. keys = append(keys, keyPair{
  105. Public: filepath.Join(workingDir, fmt.Sprintf("fixtures/notary/delgkey%v.crt", i)),
  106. Private: filepath.Join(workingDir, fmt.Sprintf("fixtures/notary/delgkey%v.key", i)),
  107. })
  108. }
  109. // run notary-server
  110. cmd := exec.Command(notaryServerBinary, "-config", confPath)
  111. if err := cmd.Start(); err != nil {
  112. os.RemoveAll(tmp)
  113. if os.IsNotExist(err) {
  114. c.Skip(err.Error())
  115. }
  116. return nil, err
  117. }
  118. testNotary := &testNotary{
  119. cmd: cmd,
  120. dir: tmp,
  121. keys: keys,
  122. }
  123. // Wait for notary to be ready to serve requests.
  124. for i := 1; i <= 20; i++ {
  125. if err = testNotary.Ping(); err == nil {
  126. break
  127. }
  128. time.Sleep(10 * time.Millisecond * time.Duration(i*i))
  129. }
  130. if err != nil {
  131. c.Fatalf("Timeout waiting for test notary to become available: %s", err)
  132. }
  133. return testNotary, nil
  134. }
  135. func (t *testNotary) Ping() error {
  136. tlsConfig := tlsconfig.ClientDefault()
  137. tlsConfig.InsecureSkipVerify = true
  138. client := http.Client{
  139. Transport: &http.Transport{
  140. Proxy: http.ProxyFromEnvironment,
  141. Dial: (&net.Dialer{
  142. Timeout: 30 * time.Second,
  143. KeepAlive: 30 * time.Second,
  144. }).Dial,
  145. TLSHandshakeTimeout: 10 * time.Second,
  146. TLSClientConfig: tlsConfig,
  147. },
  148. }
  149. resp, err := client.Get(fmt.Sprintf("%s/v2/", notaryURL))
  150. if err != nil {
  151. return err
  152. }
  153. if resp.StatusCode != http.StatusOK {
  154. return fmt.Errorf("notary ping replied with an unexpected status code %d", resp.StatusCode)
  155. }
  156. return nil
  157. }
  158. func (t *testNotary) Close() {
  159. t.cmd.Process.Kill()
  160. t.cmd.Process.Wait()
  161. os.RemoveAll(t.dir)
  162. }
  163. func trustedCmd(cmd *icmd.Cmd) func() {
  164. pwd := "12345678"
  165. cmd.Env = append(cmd.Env, trustEnv(notaryURL, pwd, pwd)...)
  166. return nil
  167. }
  168. func trustedCmdWithServer(server string) func(*icmd.Cmd) func() {
  169. return func(cmd *icmd.Cmd) func() {
  170. pwd := "12345678"
  171. cmd.Env = append(cmd.Env, trustEnv(server, pwd, pwd)...)
  172. return nil
  173. }
  174. }
  175. func trustedCmdWithPassphrases(rootPwd, repositoryPwd string) func(*icmd.Cmd) func() {
  176. return func(cmd *icmd.Cmd) func() {
  177. cmd.Env = append(cmd.Env, trustEnv(notaryURL, rootPwd, repositoryPwd)...)
  178. return nil
  179. }
  180. }
  181. func trustEnv(server, rootPwd, repositoryPwd string) []string {
  182. env := append(os.Environ(), []string{
  183. "DOCKER_CONTENT_TRUST=1",
  184. fmt.Sprintf("DOCKER_CONTENT_TRUST_SERVER=%s", server),
  185. fmt.Sprintf("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE=%s", rootPwd),
  186. fmt.Sprintf("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE=%s", repositoryPwd),
  187. }...)
  188. return env
  189. }
  190. func (s *DockerTrustSuite) setupTrustedImage(c *check.C, name string) string {
  191. repoName := fmt.Sprintf("%v/dockercli/%s:latest", privateRegistryURL, name)
  192. // tag the image and upload it to the private registry
  193. cli.DockerCmd(c, "tag", "busybox", repoName)
  194. cli.Docker(cli.Args("push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  195. cli.DockerCmd(c, "rmi", repoName)
  196. return repoName
  197. }
  198. func (s *DockerTrustSuite) setupTrustedplugin(c *check.C, source, name string) string {
  199. repoName := fmt.Sprintf("%v/dockercli/%s:latest", privateRegistryURL, name)
  200. // tag the image and upload it to the private registry
  201. cli.DockerCmd(c, "plugin", "install", "--grant-all-permissions", "--alias", repoName, source)
  202. cli.Docker(cli.Args("plugin", "push", repoName), trustedCmd).Assert(c, SuccessSigningAndPushing)
  203. cli.DockerCmd(c, "plugin", "rm", "-f", repoName)
  204. return repoName
  205. }
  206. func (s *DockerTrustSuite) notaryCmd(c *check.C, args ...string) string {
  207. pwd := "12345678"
  208. env := []string{
  209. fmt.Sprintf("NOTARY_ROOT_PASSPHRASE=%s", pwd),
  210. fmt.Sprintf("NOTARY_TARGETS_PASSPHRASE=%s", pwd),
  211. fmt.Sprintf("NOTARY_SNAPSHOT_PASSPHRASE=%s", pwd),
  212. fmt.Sprintf("NOTARY_DELEGATION_PASSPHRASE=%s", pwd),
  213. }
  214. result := icmd.RunCmd(icmd.Cmd{
  215. Command: append([]string{notaryBinary, "-c", filepath.Join(s.not.dir, "client-config.json")}, args...),
  216. Env: append(os.Environ(), env...),
  217. })
  218. result.Assert(c, icmd.Success)
  219. return result.Combined()
  220. }
  221. func (s *DockerTrustSuite) notaryInitRepo(c *check.C, repoName string) {
  222. s.notaryCmd(c, "init", repoName)
  223. }
  224. func (s *DockerTrustSuite) notaryCreateDelegation(c *check.C, repoName, role string, pubKey string, paths ...string) {
  225. pathsArg := "--all-paths"
  226. if len(paths) > 0 {
  227. pathsArg = "--paths=" + strings.Join(paths, ",")
  228. }
  229. s.notaryCmd(c, "delegation", "add", repoName, role, pubKey, pathsArg)
  230. }
  231. func (s *DockerTrustSuite) notaryPublish(c *check.C, repoName string) {
  232. s.notaryCmd(c, "publish", repoName)
  233. }
  234. func (s *DockerTrustSuite) notaryImportKey(c *check.C, repoName, role string, privKey string) {
  235. s.notaryCmd(c, "key", "import", privKey, "-g", repoName, "-r", role)
  236. }
  237. func (s *DockerTrustSuite) notaryListTargetsInRole(c *check.C, repoName, role string) map[string]string {
  238. out := s.notaryCmd(c, "list", repoName, "-r", role)
  239. // should look something like:
  240. // NAME DIGEST SIZE (BYTES) ROLE
  241. // ------------------------------------------------------------------------------------------------------
  242. // latest 24a36bbc059b1345b7e8be0df20f1b23caa3602e85d42fff7ecd9d0bd255de56 1377 targets
  243. targets := make(map[string]string)
  244. // no target
  245. lines := strings.Split(strings.TrimSpace(out), "\n")
  246. if len(lines) == 1 && strings.Contains(out, "No targets present in this repository.") {
  247. return targets
  248. }
  249. // otherwise, there is at least one target
  250. c.Assert(len(lines), checker.GreaterOrEqualThan, 3)
  251. for _, line := range lines[2:] {
  252. tokens := strings.Fields(line)
  253. c.Assert(tokens, checker.HasLen, 4)
  254. targets[tokens[0]] = tokens[3]
  255. }
  256. return targets
  257. }
  258. func (s *DockerTrustSuite) assertTargetInRoles(c *check.C, repoName, target string, roles ...string) {
  259. // check all the roles
  260. for _, role := range roles {
  261. targets := s.notaryListTargetsInRole(c, repoName, role)
  262. roleName, ok := targets[target]
  263. c.Assert(ok, checker.True)
  264. c.Assert(roleName, checker.Equals, role)
  265. }
  266. }
  267. func (s *DockerTrustSuite) assertTargetNotInRoles(c *check.C, repoName, target string, roles ...string) {
  268. targets := s.notaryListTargetsInRole(c, repoName, "targets")
  269. roleName, ok := targets[target]
  270. if ok {
  271. for _, role := range roles {
  272. c.Assert(roleName, checker.Not(checker.Equals), role)
  273. }
  274. }
  275. }