trust.go 20 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605
  1. package client
  2. import (
  3. "encoding/hex"
  4. "encoding/json"
  5. "errors"
  6. "fmt"
  7. "io"
  8. "net"
  9. "net/http"
  10. "net/url"
  11. "os"
  12. "path"
  13. "path/filepath"
  14. "sort"
  15. "strconv"
  16. "time"
  17. "golang.org/x/net/context"
  18. "github.com/Sirupsen/logrus"
  19. "github.com/docker/distribution/digest"
  20. "github.com/docker/distribution/registry/client/auth"
  21. "github.com/docker/distribution/registry/client/transport"
  22. "github.com/docker/docker/cliconfig"
  23. "github.com/docker/docker/distribution"
  24. "github.com/docker/docker/pkg/jsonmessage"
  25. flag "github.com/docker/docker/pkg/mflag"
  26. "github.com/docker/docker/reference"
  27. "github.com/docker/docker/registry"
  28. "github.com/docker/engine-api/types"
  29. registrytypes "github.com/docker/engine-api/types/registry"
  30. "github.com/docker/go-connections/tlsconfig"
  31. "github.com/docker/notary/client"
  32. "github.com/docker/notary/passphrase"
  33. "github.com/docker/notary/trustmanager"
  34. "github.com/docker/notary/trustpinning"
  35. "github.com/docker/notary/tuf/data"
  36. "github.com/docker/notary/tuf/signed"
  37. "github.com/docker/notary/tuf/store"
  38. "github.com/spf13/pflag"
  39. )
  40. var (
  41. releasesRole = path.Join(data.CanonicalTargetsRole, "releases")
  42. untrusted bool
  43. )
  44. // addTrustedFlags is the mflag version of AddTrustedFlags
  45. func addTrustedFlags(fs *flag.FlagSet, verify bool) {
  46. trusted, message := setupTrustedFlag(verify)
  47. fs.BoolVar(&untrusted, []string{"-disable-content-trust"}, !trusted, message)
  48. }
  49. // AddTrustedFlags adds content trust flags to the current command flagset
  50. func AddTrustedFlags(fs *pflag.FlagSet, verify bool) {
  51. trusted, message := setupTrustedFlag(verify)
  52. fs.BoolVar(&untrusted, "disable-content-trust", !trusted, message)
  53. }
  54. func setupTrustedFlag(verify bool) (bool, string) {
  55. var trusted bool
  56. if e := os.Getenv("DOCKER_CONTENT_TRUST"); e != "" {
  57. if t, err := strconv.ParseBool(e); t || err != nil {
  58. // treat any other value as true
  59. trusted = true
  60. }
  61. }
  62. message := "Skip image signing"
  63. if verify {
  64. message = "Skip image verification"
  65. }
  66. return trusted, message
  67. }
  68. // IsTrusted returns true if content trust is enabled
  69. func IsTrusted() bool {
  70. return !untrusted
  71. }
  72. type target struct {
  73. reference registry.Reference
  74. digest digest.Digest
  75. size int64
  76. }
  77. func (cli *DockerCli) trustDirectory() string {
  78. return filepath.Join(cliconfig.ConfigDir(), "trust")
  79. }
  80. // certificateDirectory returns the directory containing
  81. // TLS certificates for the given server. An error is
  82. // returned if there was an error parsing the server string.
  83. func (cli *DockerCli) certificateDirectory(server string) (string, error) {
  84. u, err := url.Parse(server)
  85. if err != nil {
  86. return "", err
  87. }
  88. return filepath.Join(cliconfig.ConfigDir(), "tls", u.Host), nil
  89. }
  90. func trustServer(index *registrytypes.IndexInfo) (string, error) {
  91. if s := os.Getenv("DOCKER_CONTENT_TRUST_SERVER"); s != "" {
  92. urlObj, err := url.Parse(s)
  93. if err != nil || urlObj.Scheme != "https" {
  94. return "", fmt.Errorf("valid https URL required for trust server, got %s", s)
  95. }
  96. return s, nil
  97. }
  98. if index.Official {
  99. return registry.NotaryServer, nil
  100. }
  101. return "https://" + index.Name, nil
  102. }
  103. type simpleCredentialStore struct {
  104. auth types.AuthConfig
  105. }
  106. func (scs simpleCredentialStore) Basic(u *url.URL) (string, string) {
  107. return scs.auth.Username, scs.auth.Password
  108. }
  109. func (scs simpleCredentialStore) RefreshToken(u *url.URL, service string) string {
  110. return scs.auth.IdentityToken
  111. }
  112. func (scs simpleCredentialStore) SetRefreshToken(*url.URL, string, string) {
  113. }
  114. // getNotaryRepository returns a NotaryRepository which stores all the
  115. // information needed to operate on a notary repository.
  116. // It creates an HTTP transport providing authentication support.
  117. func (cli *DockerCli) getNotaryRepository(repoInfo *registry.RepositoryInfo, authConfig types.AuthConfig, actions ...string) (*client.NotaryRepository, error) {
  118. server, err := trustServer(repoInfo.Index)
  119. if err != nil {
  120. return nil, err
  121. }
  122. var cfg = tlsconfig.ClientDefault
  123. cfg.InsecureSkipVerify = !repoInfo.Index.Secure
  124. // Get certificate base directory
  125. certDir, err := cli.certificateDirectory(server)
  126. if err != nil {
  127. return nil, err
  128. }
  129. logrus.Debugf("reading certificate directory: %s", certDir)
  130. if err := registry.ReadCertsDirectory(&cfg, certDir); err != nil {
  131. return nil, err
  132. }
  133. base := &http.Transport{
  134. Proxy: http.ProxyFromEnvironment,
  135. Dial: (&net.Dialer{
  136. Timeout: 30 * time.Second,
  137. KeepAlive: 30 * time.Second,
  138. DualStack: true,
  139. }).Dial,
  140. TLSHandshakeTimeout: 10 * time.Second,
  141. TLSClientConfig: &cfg,
  142. DisableKeepAlives: true,
  143. }
  144. // Skip configuration headers since request is not going to Docker daemon
  145. modifiers := registry.DockerHeaders(clientUserAgent(), http.Header{})
  146. authTransport := transport.NewTransport(base, modifiers...)
  147. pingClient := &http.Client{
  148. Transport: authTransport,
  149. Timeout: 5 * time.Second,
  150. }
  151. endpointStr := server + "/v2/"
  152. req, err := http.NewRequest("GET", endpointStr, nil)
  153. if err != nil {
  154. return nil, err
  155. }
  156. challengeManager := auth.NewSimpleChallengeManager()
  157. resp, err := pingClient.Do(req)
  158. if err != nil {
  159. // Ignore error on ping to operate in offline mode
  160. logrus.Debugf("Error pinging notary server %q: %s", endpointStr, err)
  161. } else {
  162. defer resp.Body.Close()
  163. // Add response to the challenge manager to parse out
  164. // authentication header and register authentication method
  165. if err := challengeManager.AddResponse(resp); err != nil {
  166. return nil, err
  167. }
  168. }
  169. creds := simpleCredentialStore{auth: authConfig}
  170. tokenHandler := auth.NewTokenHandler(authTransport, creds, repoInfo.FullName(), actions...)
  171. basicHandler := auth.NewBasicHandler(creds)
  172. modifiers = append(modifiers, transport.RequestModifier(auth.NewAuthorizer(challengeManager, tokenHandler, basicHandler)))
  173. tr := transport.NewTransport(base, modifiers...)
  174. return client.NewNotaryRepository(
  175. cli.trustDirectory(), repoInfo.FullName(), server, tr, cli.getPassphraseRetriever(),
  176. trustpinning.TrustPinConfig{})
  177. }
  178. func convertTarget(t client.Target) (target, error) {
  179. h, ok := t.Hashes["sha256"]
  180. if !ok {
  181. return target{}, errors.New("no valid hash, expecting sha256")
  182. }
  183. return target{
  184. reference: registry.ParseReference(t.Name),
  185. digest: digest.NewDigestFromHex("sha256", hex.EncodeToString(h)),
  186. size: t.Length,
  187. }, nil
  188. }
  189. func (cli *DockerCli) getPassphraseRetriever() passphrase.Retriever {
  190. aliasMap := map[string]string{
  191. "root": "root",
  192. "snapshot": "repository",
  193. "targets": "repository",
  194. "default": "repository",
  195. }
  196. baseRetriever := passphrase.PromptRetrieverWithInOut(cli.in, cli.out, aliasMap)
  197. env := map[string]string{
  198. "root": os.Getenv("DOCKER_CONTENT_TRUST_ROOT_PASSPHRASE"),
  199. "snapshot": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  200. "targets": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  201. "default": os.Getenv("DOCKER_CONTENT_TRUST_REPOSITORY_PASSPHRASE"),
  202. }
  203. return func(keyName string, alias string, createNew bool, numAttempts int) (string, bool, error) {
  204. if v := env[alias]; v != "" {
  205. return v, numAttempts > 1, nil
  206. }
  207. // For non-root roles, we can also try the "default" alias if it is specified
  208. if v := env["default"]; v != "" && alias != data.CanonicalRootRole {
  209. return v, numAttempts > 1, nil
  210. }
  211. return baseRetriever(keyName, alias, createNew, numAttempts)
  212. }
  213. }
  214. // TrustedReference returns the canonical trusted reference for an image reference
  215. func (cli *DockerCli) TrustedReference(ctx context.Context, ref reference.NamedTagged) (reference.Canonical, error) {
  216. repoInfo, err := registry.ParseRepositoryInfo(ref)
  217. if err != nil {
  218. return nil, err
  219. }
  220. // Resolve the Auth config relevant for this server
  221. authConfig := cli.ResolveAuthConfig(ctx, repoInfo.Index)
  222. notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig, "pull")
  223. if err != nil {
  224. fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err)
  225. return nil, err
  226. }
  227. t, err := notaryRepo.GetTargetByName(ref.Tag(), releasesRole, data.CanonicalTargetsRole)
  228. if err != nil {
  229. return nil, err
  230. }
  231. // Only list tags in the top level targets role or the releases delegation role - ignore
  232. // all other delegation roles
  233. if t.Role != releasesRole && t.Role != data.CanonicalTargetsRole {
  234. return nil, notaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.Tag()))
  235. }
  236. r, err := convertTarget(t.Target)
  237. if err != nil {
  238. return nil, err
  239. }
  240. return reference.WithDigest(ref, r.digest)
  241. }
  242. // TagTrusted tags a trusted ref
  243. func (cli *DockerCli) TagTrusted(ctx context.Context, trustedRef reference.Canonical, ref reference.NamedTagged) error {
  244. fmt.Fprintf(cli.out, "Tagging %s as %s\n", trustedRef.String(), ref.String())
  245. return cli.client.ImageTag(ctx, trustedRef.String(), ref.String())
  246. }
  247. func notaryError(repoName string, err error) error {
  248. switch err.(type) {
  249. case *json.SyntaxError:
  250. logrus.Debugf("Notary syntax error: %s", err)
  251. return fmt.Errorf("Error: no trust data available for remote repository %s. Try running notary server and setting DOCKER_CONTENT_TRUST_SERVER to its HTTPS address?", repoName)
  252. case signed.ErrExpired:
  253. return fmt.Errorf("Error: remote repository %s out-of-date: %v", repoName, err)
  254. case trustmanager.ErrKeyNotFound:
  255. return fmt.Errorf("Error: signing keys for remote repository %s not found: %v", repoName, err)
  256. case *net.OpError:
  257. return fmt.Errorf("Error: error contacting notary server: %v", err)
  258. case store.ErrMetaNotFound:
  259. return fmt.Errorf("Error: trust data missing for remote repository %s or remote repository not found: %v", repoName, err)
  260. case signed.ErrInvalidKeyType:
  261. return fmt.Errorf("Warning: potential malicious behavior - trust data mismatch for remote repository %s: %v", repoName, err)
  262. case signed.ErrNoKeys:
  263. return fmt.Errorf("Error: could not find signing keys for remote repository %s, or could not decrypt signing key: %v", repoName, err)
  264. case signed.ErrLowVersion:
  265. return fmt.Errorf("Warning: potential malicious behavior - trust data version is lower than expected for remote repository %s: %v", repoName, err)
  266. case signed.ErrRoleThreshold:
  267. return fmt.Errorf("Warning: potential malicious behavior - trust data has insufficient signatures for remote repository %s: %v", repoName, err)
  268. case client.ErrRepositoryNotExist:
  269. return fmt.Errorf("Error: remote trust data does not exist for %s: %v", repoName, err)
  270. case signed.ErrInsufficientSignatures:
  271. return fmt.Errorf("Error: could not produce valid signature for %s. If Yubikey was used, was touch input provided?: %v", repoName, err)
  272. }
  273. return err
  274. }
  275. // TrustedPull handles content trust pulling of an image
  276. func (cli *DockerCli) TrustedPull(ctx context.Context, repoInfo *registry.RepositoryInfo, ref registry.Reference, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
  277. var refs []target
  278. notaryRepo, err := cli.getNotaryRepository(repoInfo, authConfig, "pull")
  279. if err != nil {
  280. fmt.Fprintf(cli.out, "Error establishing connection to trust repository: %s\n", err)
  281. return err
  282. }
  283. if ref.String() == "" {
  284. // List all targets
  285. targets, err := notaryRepo.ListTargets(releasesRole, data.CanonicalTargetsRole)
  286. if err != nil {
  287. return notaryError(repoInfo.FullName(), err)
  288. }
  289. for _, tgt := range targets {
  290. t, err := convertTarget(tgt.Target)
  291. if err != nil {
  292. fmt.Fprintf(cli.out, "Skipping target for %q\n", repoInfo.Name())
  293. continue
  294. }
  295. // Only list tags in the top level targets role or the releases delegation role - ignore
  296. // all other delegation roles
  297. if tgt.Role != releasesRole && tgt.Role != data.CanonicalTargetsRole {
  298. continue
  299. }
  300. refs = append(refs, t)
  301. }
  302. if len(refs) == 0 {
  303. return notaryError(repoInfo.FullName(), fmt.Errorf("No trusted tags for %s", repoInfo.FullName()))
  304. }
  305. } else {
  306. t, err := notaryRepo.GetTargetByName(ref.String(), releasesRole, data.CanonicalTargetsRole)
  307. if err != nil {
  308. return notaryError(repoInfo.FullName(), err)
  309. }
  310. // Only get the tag if it's in the top level targets role or the releases delegation role
  311. // ignore it if it's in any other delegation roles
  312. if t.Role != releasesRole && t.Role != data.CanonicalTargetsRole {
  313. return notaryError(repoInfo.FullName(), fmt.Errorf("No trust data for %s", ref.String()))
  314. }
  315. logrus.Debugf("retrieving target for %s role\n", t.Role)
  316. r, err := convertTarget(t.Target)
  317. if err != nil {
  318. return err
  319. }
  320. refs = append(refs, r)
  321. }
  322. for i, r := range refs {
  323. displayTag := r.reference.String()
  324. if displayTag != "" {
  325. displayTag = ":" + displayTag
  326. }
  327. fmt.Fprintf(cli.out, "Pull (%d of %d): %s%s@%s\n", i+1, len(refs), repoInfo.Name(), displayTag, r.digest)
  328. ref, err := reference.WithDigest(repoInfo, r.digest)
  329. if err != nil {
  330. return err
  331. }
  332. if err := cli.ImagePullPrivileged(ctx, authConfig, ref.String(), requestPrivilege, false); err != nil {
  333. return err
  334. }
  335. // If reference is not trusted, tag by trusted reference
  336. if !r.reference.HasDigest() {
  337. tagged, err := reference.WithTag(repoInfo, r.reference.String())
  338. if err != nil {
  339. return err
  340. }
  341. trustedRef, err := reference.WithDigest(repoInfo, r.digest)
  342. if err != nil {
  343. return err
  344. }
  345. if err := cli.TagTrusted(ctx, trustedRef, tagged); err != nil {
  346. return err
  347. }
  348. }
  349. }
  350. return nil
  351. }
  352. // TrustedPush handles content trust pushing of an image
  353. func (cli *DockerCli) TrustedPush(ctx context.Context, repoInfo *registry.RepositoryInfo, ref reference.Named, authConfig types.AuthConfig, requestPrivilege types.RequestPrivilegeFunc) error {
  354. responseBody, err := cli.ImagePushPrivileged(ctx, authConfig, ref.String(), requestPrivilege)
  355. if err != nil {
  356. return err
  357. }
  358. defer responseBody.Close()
  359. // If it is a trusted push we would like to find the target entry which match the
  360. // tag provided in the function and then do an AddTarget later.
  361. target := &client.Target{}
  362. // Count the times of calling for handleTarget,
  363. // if it is called more that once, that should be considered an error in a trusted push.
  364. cnt := 0
  365. handleTarget := func(aux *json.RawMessage) {
  366. cnt++
  367. if cnt > 1 {
  368. // handleTarget should only be called one. This will be treated as an error.
  369. return
  370. }
  371. var pushResult distribution.PushResult
  372. err := json.Unmarshal(*aux, &pushResult)
  373. if err == nil && pushResult.Tag != "" && pushResult.Digest.Validate() == nil {
  374. h, err := hex.DecodeString(pushResult.Digest.Hex())
  375. if err != nil {
  376. target = nil
  377. return
  378. }
  379. target.Name = registry.ParseReference(pushResult.Tag).String()
  380. target.Hashes = data.Hashes{string(pushResult.Digest.Algorithm()): h}
  381. target.Length = int64(pushResult.Size)
  382. }
  383. }
  384. var tag string
  385. switch x := ref.(type) {
  386. case reference.Canonical:
  387. return errors.New("cannot push a digest reference")
  388. case reference.NamedTagged:
  389. tag = x.Tag()
  390. }
  391. // We want trust signatures to always take an explicit tag,
  392. // otherwise it will act as an untrusted push.
  393. if tag == "" {
  394. if err = jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, nil); err != nil {
  395. return err
  396. }
  397. fmt.Fprintln(cli.out, "No tag specified, skipping trust metadata push")
  398. return nil
  399. }
  400. if err = jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, handleTarget); err != nil {
  401. return err
  402. }
  403. if cnt > 1 {
  404. return fmt.Errorf("internal error: only one call to handleTarget expected")
  405. }
  406. if target == nil {
  407. fmt.Fprintln(cli.out, "No targets found, please provide a specific tag in order to sign it")
  408. return nil
  409. }
  410. fmt.Fprintln(cli.out, "Signing and pushing trust metadata")
  411. repo, err := cli.getNotaryRepository(repoInfo, authConfig, "push", "pull")
  412. if err != nil {
  413. fmt.Fprintf(cli.out, "Error establishing connection to notary repository: %s\n", err)
  414. return err
  415. }
  416. // get the latest repository metadata so we can figure out which roles to sign
  417. err = repo.Update(false)
  418. switch err.(type) {
  419. case client.ErrRepoNotInitialized, client.ErrRepositoryNotExist:
  420. keys := repo.CryptoService.ListKeys(data.CanonicalRootRole)
  421. var rootKeyID string
  422. // always select the first root key
  423. if len(keys) > 0 {
  424. sort.Strings(keys)
  425. rootKeyID = keys[0]
  426. } else {
  427. rootPublicKey, err := repo.CryptoService.Create(data.CanonicalRootRole, "", data.ECDSAKey)
  428. if err != nil {
  429. return err
  430. }
  431. rootKeyID = rootPublicKey.ID()
  432. }
  433. // Initialize the notary repository with a remotely managed snapshot key
  434. if err := repo.Initialize(rootKeyID, data.CanonicalSnapshotRole); err != nil {
  435. return notaryError(repoInfo.FullName(), err)
  436. }
  437. fmt.Fprintf(cli.out, "Finished initializing %q\n", repoInfo.FullName())
  438. err = repo.AddTarget(target, data.CanonicalTargetsRole)
  439. case nil:
  440. // already initialized and we have successfully downloaded the latest metadata
  441. err = cli.addTargetToAllSignableRoles(repo, target)
  442. default:
  443. return notaryError(repoInfo.FullName(), err)
  444. }
  445. if err == nil {
  446. err = repo.Publish()
  447. }
  448. if err != nil {
  449. fmt.Fprintf(cli.out, "Failed to sign %q:%s - %s\n", repoInfo.FullName(), tag, err.Error())
  450. return notaryError(repoInfo.FullName(), err)
  451. }
  452. fmt.Fprintf(cli.out, "Successfully signed %q:%s\n", repoInfo.FullName(), tag)
  453. return nil
  454. }
  455. // Attempt to add the image target to all the top level delegation roles we can
  456. // (based on whether we have the signing key and whether the role's path allows
  457. // us to).
  458. // If there are no delegation roles, we add to the targets role.
  459. func (cli *DockerCli) addTargetToAllSignableRoles(repo *client.NotaryRepository, target *client.Target) error {
  460. var signableRoles []string
  461. // translate the full key names, which includes the GUN, into just the key IDs
  462. allCanonicalKeyIDs := make(map[string]struct{})
  463. for fullKeyID := range repo.CryptoService.ListAllKeys() {
  464. allCanonicalKeyIDs[path.Base(fullKeyID)] = struct{}{}
  465. }
  466. allDelegationRoles, err := repo.GetDelegationRoles()
  467. if err != nil {
  468. return err
  469. }
  470. // if there are no delegation roles, then just try to sign it into the targets role
  471. if len(allDelegationRoles) == 0 {
  472. return repo.AddTarget(target, data.CanonicalTargetsRole)
  473. }
  474. // there are delegation roles, find every delegation role we have a key for, and
  475. // attempt to sign into into all those roles.
  476. for _, delegationRole := range allDelegationRoles {
  477. // We do not support signing any delegation role that isn't a direct child of the targets role.
  478. // Also don't bother checking the keys if we can't add the target
  479. // to this role due to path restrictions
  480. if path.Dir(delegationRole.Name) != data.CanonicalTargetsRole || !delegationRole.CheckPaths(target.Name) {
  481. continue
  482. }
  483. for _, canonicalKeyID := range delegationRole.KeyIDs {
  484. if _, ok := allCanonicalKeyIDs[canonicalKeyID]; ok {
  485. signableRoles = append(signableRoles, delegationRole.Name)
  486. break
  487. }
  488. }
  489. }
  490. if len(signableRoles) == 0 {
  491. return fmt.Errorf("no valid signing keys for delegation roles")
  492. }
  493. return repo.AddTarget(target, signableRoles...)
  494. }
  495. // ImagePullPrivileged pulls the image and displays it to the output
  496. func (cli *DockerCli) ImagePullPrivileged(ctx context.Context, authConfig types.AuthConfig, ref string, requestPrivilege types.RequestPrivilegeFunc, all bool) error {
  497. encodedAuth, err := EncodeAuthToBase64(authConfig)
  498. if err != nil {
  499. return err
  500. }
  501. options := types.ImagePullOptions{
  502. RegistryAuth: encodedAuth,
  503. PrivilegeFunc: requestPrivilege,
  504. All: all,
  505. }
  506. responseBody, err := cli.client.ImagePull(ctx, ref, options)
  507. if err != nil {
  508. return err
  509. }
  510. defer responseBody.Close()
  511. return jsonmessage.DisplayJSONMessagesStream(responseBody, cli.out, cli.outFd, cli.isTerminalOut, nil)
  512. }
  513. // ImagePushPrivileged push the image
  514. func (cli *DockerCli) ImagePushPrivileged(ctx context.Context, authConfig types.AuthConfig, ref string, requestPrivilege types.RequestPrivilegeFunc) (io.ReadCloser, error) {
  515. encodedAuth, err := EncodeAuthToBase64(authConfig)
  516. if err != nil {
  517. return nil, err
  518. }
  519. options := types.ImagePushOptions{
  520. RegistryAuth: encodedAuth,
  521. PrivilegeFunc: requestPrivilege,
  522. }
  523. return cli.client.ImagePush(ctx, ref, options)
  524. }