github.com/Prakhar-Agarwal-byte/moby@v0.0.0-20231027092010-a14e3e8ab87e/integration-cli/docker_cli_cp_to_container_unix_test.go (about) 1 //go:build !windows 2 3 package main 4 5 import ( 6 "fmt" 7 "os" 8 "os/exec" 9 "path/filepath" 10 "strconv" 11 "strings" 12 "syscall" 13 "testing" 14 15 "github.com/Prakhar-Agarwal-byte/moby/integration-cli/cli" 16 "gotest.tools/v3/assert" 17 ) 18 19 func (s *DockerCLICpSuite) TestCpToContainerWithPermissions(c *testing.T) { 20 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) 21 22 tmpDir := getTestDir(c, "test-cp-to-host-with-permissions") 23 defer os.RemoveAll(tmpDir) 24 25 makeTestContentInDir(c, tmpDir) 26 27 containerName := "permtest" 28 29 exc := cli.DockerCmd(c, "create", "--name", containerName, "busybox", "/bin/sh", "-c", "stat -c '%u %g %a' /permdirtest /permdirtest/permtest").ExitCode 30 assert.Equal(c, exc, 0) 31 defer cli.DockerCmd(c, "rm", "-f", containerName) 32 33 srcPath := cpPath(tmpDir, "permdirtest") 34 dstPath := containerCpPath(containerName, "/") 35 36 args := []string{"cp", "-a", srcPath, dstPath} 37 out, _, err := runCommandWithOutput(exec.Command(dockerBinary, args...)) 38 assert.NilError(c, err, "output: %v", out) 39 40 out, err = startContainerGetOutput(c, containerName) 41 assert.NilError(c, err, "output: %v", out) 42 assert.Equal(c, strings.TrimSpace(out), "2 2 700\n65534 65534 400", "output: %v", out) 43 } 44 45 // Check ownership is root, both in non-userns and userns enabled modes 46 func (s *DockerCLICpSuite) TestCpCheckDestOwnership(c *testing.T) { 47 testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) 48 tmpVolDir := getTestDir(c, "test-cp-tmpvol") 49 containerID := makeTestContainer(c, 50 testContainerOptions{volumes: []string{fmt.Sprintf("%s:/tmpvol", tmpVolDir)}}) 51 52 tmpDir := getTestDir(c, "test-cp-to-check-ownership") 53 defer os.RemoveAll(tmpDir) 54 55 makeTestContentInDir(c, tmpDir) 56 57 srcPath := cpPath(tmpDir, "file1") 58 dstPath := containerCpPath(containerID, "/tmpvol", "file1") 59 60 assert.NilError(c, runDockerCp(c, srcPath, dstPath)) 61 62 stat, err := os.Stat(filepath.Join(tmpVolDir, "file1")) 63 assert.NilError(c, err) 64 uid, gid, err := getRootUIDGID() 65 assert.NilError(c, err) 66 fi := stat.Sys().(*syscall.Stat_t) 67 assert.Equal(c, fi.Uid, uint32(uid), "Copied file not owned by container root UID") 68 assert.Equal(c, fi.Gid, uint32(gid), "Copied file not owned by container root GID") 69 } 70 71 func getRootUIDGID() (int, int, error) { 72 uidgid := strings.Split(filepath.Base(testEnv.DaemonInfo.DockerRootDir), ".") 73 if len(uidgid) == 1 { 74 // user namespace remapping is not turned on; return 0 75 return 0, 0, nil 76 } 77 uid, err := strconv.Atoi(uidgid[0]) 78 if err != nil { 79 return 0, 0, err 80 } 81 gid, err := strconv.Atoi(uidgid[1]) 82 if err != nil { 83 return 0, 0, err 84 } 85 return uid, gid, nil 86 }