docker_cli_cp_to_container_unix_test.go 2.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081
  1. // +build !windows
  2. package main
  3. import (
  4. "fmt"
  5. "os"
  6. "path/filepath"
  7. "strconv"
  8. "strings"
  9. "testing"
  10. "github.com/docker/docker/pkg/system"
  11. "gotest.tools/assert"
  12. )
  13. func (s *DockerSuite) TestCpToContainerWithPermissions(c *testing.T) {
  14. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux)
  15. tmpDir := getTestDir(c, "test-cp-to-host-with-permissions")
  16. defer os.RemoveAll(tmpDir)
  17. makeTestContentInDir(c, tmpDir)
  18. containerName := "permtest"
  19. _, exc := dockerCmd(c, "create", "--name", containerName, "debian:jessie", "/bin/bash", "-c", "stat -c '%u %g %a' /permdirtest /permdirtest/permtest")
  20. assert.Equal(c, exc, 0)
  21. defer dockerCmd(c, "rm", "-f", containerName)
  22. srcPath := cpPath(tmpDir, "permdirtest")
  23. dstPath := containerCpPath(containerName, "/")
  24. assert.NilError(c, runDockerCp(c, srcPath, dstPath, []string{"-a"}))
  25. out, err := startContainerGetOutput(c, containerName)
  26. assert.NilError(c, err, "output: %v", out)
  27. assert.Equal(c, strings.TrimSpace(out), "2 2 700\n65534 65534 400", "output: %v", out)
  28. }
  29. // Check ownership is root, both in non-userns and userns enabled modes
  30. func (s *DockerSuite) TestCpCheckDestOwnership(c *testing.T) {
  31. testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  32. tmpVolDir := getTestDir(c, "test-cp-tmpvol")
  33. containerID := makeTestContainer(c,
  34. testContainerOptions{volumes: []string{fmt.Sprintf("%s:/tmpvol", tmpVolDir)}})
  35. tmpDir := getTestDir(c, "test-cp-to-check-ownership")
  36. defer os.RemoveAll(tmpDir)
  37. makeTestContentInDir(c, tmpDir)
  38. srcPath := cpPath(tmpDir, "file1")
  39. dstPath := containerCpPath(containerID, "/tmpvol", "file1")
  40. err := runDockerCp(c, srcPath, dstPath, nil)
  41. assert.NilError(c, err)
  42. stat, err := system.Stat(filepath.Join(tmpVolDir, "file1"))
  43. assert.NilError(c, err)
  44. uid, gid, err := getRootUIDGID()
  45. assert.NilError(c, err)
  46. assert.Equal(c, stat.UID(), uint32(uid), "Copied file not owned by container root UID")
  47. assert.Equal(c, stat.GID(), uint32(gid), "Copied file not owned by container root GID")
  48. }
  49. func getRootUIDGID() (int, int, error) {
  50. uidgid := strings.Split(filepath.Base(testEnv.DaemonInfo.DockerRootDir), ".")
  51. if len(uidgid) == 1 {
  52. //user namespace remapping is not turned on; return 0
  53. return 0, 0, nil
  54. }
  55. uid, err := strconv.Atoi(uidgid[0])
  56. if err != nil {
  57. return 0, 0, err
  58. }
  59. gid, err := strconv.Atoi(uidgid[1])
  60. if err != nil {
  61. return 0, 0, err
  62. }
  63. return uid, gid, nil
  64. }