trust_server_test.go 9.1 KB

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