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