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