github.com/adityamillind98/moby@v23.0.0-rc.4+incompatible/integration-cli/docker_cli_run_unix_test.go (about)

     1  //go:build !windows
     2  // +build !windows
     3  
     4  package main
     5  
     6  import (
     7  	"bufio"
     8  	"context"
     9  	"encoding/json"
    10  	"fmt"
    11  	"os"
    12  	"os/exec"
    13  	"path/filepath"
    14  	"regexp"
    15  	"strconv"
    16  	"strings"
    17  	"syscall"
    18  	"testing"
    19  	"time"
    20  
    21  	"github.com/creack/pty"
    22  	"github.com/docker/docker/client"
    23  	"github.com/docker/docker/integration-cli/cli"
    24  	"github.com/docker/docker/integration-cli/cli/build"
    25  	"github.com/docker/docker/pkg/homedir"
    26  	"github.com/docker/docker/pkg/parsers"
    27  	"github.com/docker/docker/pkg/sysinfo"
    28  	"github.com/moby/sys/mount"
    29  	"gotest.tools/v3/assert"
    30  	"gotest.tools/v3/icmd"
    31  )
    32  
    33  // #6509
    34  func (s *DockerCLIRunSuite) TestRunRedirectStdout(c *testing.T) {
    35  	checkRedirect := func(command string) {
    36  		_, tty, err := pty.Open()
    37  		assert.Assert(c, err == nil, "Could not open pty")
    38  		cmd := exec.Command("sh", "-c", command)
    39  		cmd.Stdin = tty
    40  		cmd.Stdout = tty
    41  		cmd.Stderr = tty
    42  		assert.NilError(c, cmd.Start())
    43  		ch := make(chan error, 1)
    44  		go func() {
    45  			ch <- cmd.Wait()
    46  			close(ch)
    47  		}()
    48  
    49  		select {
    50  		case <-time.After(10 * time.Second):
    51  			c.Fatal("command timeout")
    52  		case err := <-ch:
    53  			assert.Assert(c, err == nil, "wait err")
    54  		}
    55  	}
    56  
    57  	checkRedirect(dockerBinary + " run -i busybox cat /etc/passwd | grep -q root")
    58  	checkRedirect(dockerBinary + " run busybox cat /etc/passwd | grep -q root")
    59  }
    60  
    61  // Test recursive bind mount works by default
    62  func (s *DockerCLIRunSuite) TestRunWithVolumesIsRecursive(c *testing.T) {
    63  	// /tmp gets permission denied
    64  	testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon)
    65  	tmpDir, err := os.MkdirTemp("", "docker_recursive_mount_test")
    66  	assert.NilError(c, err)
    67  
    68  	defer os.RemoveAll(tmpDir)
    69  
    70  	// Create a temporary tmpfs mount.
    71  	tmpfsDir := filepath.Join(tmpDir, "tmpfs")
    72  	assert.Assert(c, os.MkdirAll(tmpfsDir, 0777) == nil, "failed to mkdir at %s", tmpfsDir)
    73  	assert.Assert(c, mount.Mount("tmpfs", tmpfsDir, "tmpfs", "") == nil, "failed to create a tmpfs mount at %s", tmpfsDir)
    74  
    75  	f, err := os.CreateTemp(tmpfsDir, "touch-me")
    76  	assert.NilError(c, err)
    77  	defer f.Close()
    78  
    79  	out, _ := dockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs")
    80  	assert.Assert(c, strings.Contains(out, filepath.Base(f.Name())), "Recursive bind mount test failed. Expected file not found")
    81  }
    82  
    83  func (s *DockerCLIRunSuite) TestRunDeviceDirectory(c *testing.T) {
    84  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm)
    85  	if _, err := os.Stat("/dev/snd"); err != nil {
    86  		c.Skip("Host does not have /dev/snd")
    87  	}
    88  
    89  	out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/")
    90  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "timer"), "expected output /dev/snd/timer")
    91  	out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/")
    92  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "seq"), "expected output /dev/othersnd/seq")
    93  }
    94  
    95  // TestRunAttachDetach checks attaching and detaching with the default escape sequence.
    96  func (s *DockerCLIRunSuite) TestRunAttachDetach(c *testing.T) {
    97  	name := "attach-detach"
    98  
    99  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   100  
   101  	cmd := exec.Command(dockerBinary, "attach", name)
   102  	stdout, err := cmd.StdoutPipe()
   103  	assert.NilError(c, err)
   104  	cpty, tty, err := pty.Open()
   105  	assert.NilError(c, err)
   106  	defer cpty.Close()
   107  	cmd.Stdin = tty
   108  	assert.NilError(c, cmd.Start())
   109  	assert.Assert(c, waitRun(name) == nil)
   110  
   111  	_, err = cpty.Write([]byte("hello\n"))
   112  	assert.NilError(c, err)
   113  
   114  	out, err := bufio.NewReader(stdout).ReadString('\n')
   115  	assert.NilError(c, err)
   116  	assert.Equal(c, strings.TrimSpace(out), "hello")
   117  
   118  	// escape sequence
   119  	_, err = cpty.Write([]byte{16})
   120  	assert.NilError(c, err)
   121  	time.Sleep(100 * time.Millisecond)
   122  	_, err = cpty.Write([]byte{17})
   123  	assert.NilError(c, err)
   124  
   125  	ch := make(chan struct{}, 1)
   126  	go func() {
   127  		cmd.Wait()
   128  		ch <- struct{}{}
   129  	}()
   130  
   131  	select {
   132  	case <-ch:
   133  	case <-time.After(10 * time.Second):
   134  		c.Fatal("timed out waiting for container to exit")
   135  	}
   136  
   137  	running := inspectField(c, name, "State.Running")
   138  	assert.Equal(c, running, "true", "expected container to still be running")
   139  
   140  	out, _ = dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name)
   141  	// attach and detach event should be monitored
   142  	assert.Assert(c, strings.Contains(out, "attach"))
   143  	assert.Assert(c, strings.Contains(out, "detach"))
   144  }
   145  
   146  // TestRunAttachDetachFromFlag checks attaching and detaching with the escape sequence specified via flags.
   147  func (s *DockerCLIRunSuite) TestRunAttachDetachFromFlag(c *testing.T) {
   148  	name := "attach-detach"
   149  	keyCtrlA := []byte{1}
   150  	keyA := []byte{97}
   151  
   152  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   153  
   154  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
   155  	stdout, err := cmd.StdoutPipe()
   156  	if err != nil {
   157  		c.Fatal(err)
   158  	}
   159  	cpty, tty, err := pty.Open()
   160  	if err != nil {
   161  		c.Fatal(err)
   162  	}
   163  	defer cpty.Close()
   164  	cmd.Stdin = tty
   165  	if err := cmd.Start(); err != nil {
   166  		c.Fatal(err)
   167  	}
   168  	assert.Assert(c, waitRun(name) == nil)
   169  
   170  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   171  		c.Fatal(err)
   172  	}
   173  
   174  	out, err := bufio.NewReader(stdout).ReadString('\n')
   175  	if err != nil {
   176  		c.Fatal(err)
   177  	}
   178  	if strings.TrimSpace(out) != "hello" {
   179  		c.Fatalf("expected 'hello', got %q", out)
   180  	}
   181  
   182  	// escape sequence
   183  	if _, err := cpty.Write(keyCtrlA); err != nil {
   184  		c.Fatal(err)
   185  	}
   186  	time.Sleep(100 * time.Millisecond)
   187  	if _, err := cpty.Write(keyA); err != nil {
   188  		c.Fatal(err)
   189  	}
   190  
   191  	ch := make(chan struct{}, 1)
   192  	go func() {
   193  		cmd.Wait()
   194  		ch <- struct{}{}
   195  	}()
   196  
   197  	select {
   198  	case <-ch:
   199  	case <-time.After(10 * time.Second):
   200  		c.Fatal("timed out waiting for container to exit")
   201  	}
   202  
   203  	running := inspectField(c, name, "State.Running")
   204  	assert.Equal(c, running, "true", "expected container to still be running")
   205  }
   206  
   207  // TestRunAttachDetachFromInvalidFlag checks attaching and detaching with the escape sequence specified via flags.
   208  func (s *DockerCLIRunSuite) TestRunAttachDetachFromInvalidFlag(c *testing.T) {
   209  	name := "attach-detach"
   210  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "top")
   211  	assert.Assert(c, waitRun(name) == nil)
   212  
   213  	// specify an invalid detach key, container will ignore it and use default
   214  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-A,a", name)
   215  	stdout, err := cmd.StdoutPipe()
   216  	if err != nil {
   217  		c.Fatal(err)
   218  	}
   219  	cpty, tty, err := pty.Open()
   220  	if err != nil {
   221  		c.Fatal(err)
   222  	}
   223  	defer cpty.Close()
   224  	cmd.Stdin = tty
   225  	if err := cmd.Start(); err != nil {
   226  		c.Fatal(err)
   227  	}
   228  	go cmd.Wait()
   229  
   230  	bufReader := bufio.NewReader(stdout)
   231  	out, err := bufReader.ReadString('\n')
   232  	if err != nil {
   233  		c.Fatal(err)
   234  	}
   235  	// it should print a warning to indicate the detach key flag is invalid
   236  	errStr := "Invalid detach keys (ctrl-A,a) provided"
   237  	assert.Equal(c, strings.TrimSpace(out), errStr)
   238  }
   239  
   240  // TestRunAttachDetachFromConfig checks attaching and detaching with the escape sequence specified via config file.
   241  func (s *DockerCLIRunSuite) TestRunAttachDetachFromConfig(c *testing.T) {
   242  	keyCtrlA := []byte{1}
   243  	keyA := []byte{97}
   244  
   245  	// Setup config
   246  	tmpDir, err := os.MkdirTemp("", "fake-home")
   247  	assert.NilError(c, err)
   248  	defer os.RemoveAll(tmpDir)
   249  
   250  	dotDocker := filepath.Join(tmpDir, ".docker")
   251  	os.Mkdir(dotDocker, 0600)
   252  	tmpCfg := filepath.Join(dotDocker, "config.json")
   253  
   254  	c.Setenv(homedir.Key(), tmpDir)
   255  
   256  	data := `{
   257  		"detachKeys": "ctrl-a,a"
   258  	}`
   259  
   260  	err = os.WriteFile(tmpCfg, []byte(data), 0600)
   261  	assert.NilError(c, err)
   262  
   263  	// Then do the work
   264  	name := "attach-detach"
   265  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   266  
   267  	cmd := exec.Command(dockerBinary, "attach", name)
   268  	stdout, err := cmd.StdoutPipe()
   269  	if err != nil {
   270  		c.Fatal(err)
   271  	}
   272  	cpty, tty, err := pty.Open()
   273  	if err != nil {
   274  		c.Fatal(err)
   275  	}
   276  	defer cpty.Close()
   277  	cmd.Stdin = tty
   278  	if err := cmd.Start(); err != nil {
   279  		c.Fatal(err)
   280  	}
   281  	assert.Assert(c, waitRun(name) == nil)
   282  
   283  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   284  		c.Fatal(err)
   285  	}
   286  
   287  	out, err := bufio.NewReader(stdout).ReadString('\n')
   288  	if err != nil {
   289  		c.Fatal(err)
   290  	}
   291  	if strings.TrimSpace(out) != "hello" {
   292  		c.Fatalf("expected 'hello', got %q", out)
   293  	}
   294  
   295  	// escape sequence
   296  	if _, err := cpty.Write(keyCtrlA); err != nil {
   297  		c.Fatal(err)
   298  	}
   299  	time.Sleep(100 * time.Millisecond)
   300  	if _, err := cpty.Write(keyA); err != nil {
   301  		c.Fatal(err)
   302  	}
   303  
   304  	ch := make(chan struct{}, 1)
   305  	go func() {
   306  		cmd.Wait()
   307  		ch <- struct{}{}
   308  	}()
   309  
   310  	select {
   311  	case <-ch:
   312  	case <-time.After(10 * time.Second):
   313  		c.Fatal("timed out waiting for container to exit")
   314  	}
   315  
   316  	running := inspectField(c, name, "State.Running")
   317  	assert.Equal(c, running, "true", "expected container to still be running")
   318  }
   319  
   320  // TestRunAttachDetachKeysOverrideConfig checks attaching and detaching with the detach flags, making sure it overrides config file
   321  func (s *DockerCLIRunSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) {
   322  	keyCtrlA := []byte{1}
   323  	keyA := []byte{97}
   324  
   325  	// Setup config
   326  	tmpDir, err := os.MkdirTemp("", "fake-home")
   327  	assert.NilError(c, err)
   328  	defer os.RemoveAll(tmpDir)
   329  
   330  	dotDocker := filepath.Join(tmpDir, ".docker")
   331  	os.Mkdir(dotDocker, 0600)
   332  	tmpCfg := filepath.Join(dotDocker, "config.json")
   333  
   334  	c.Setenv(homedir.Key(), tmpDir)
   335  
   336  	data := `{
   337  		"detachKeys": "ctrl-e,e"
   338  	}`
   339  
   340  	err = os.WriteFile(tmpCfg, []byte(data), 0600)
   341  	assert.NilError(c, err)
   342  
   343  	// Then do the work
   344  	name := "attach-detach"
   345  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   346  
   347  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name)
   348  	stdout, err := cmd.StdoutPipe()
   349  	if err != nil {
   350  		c.Fatal(err)
   351  	}
   352  	cpty, tty, err := pty.Open()
   353  	if err != nil {
   354  		c.Fatal(err)
   355  	}
   356  	defer cpty.Close()
   357  	cmd.Stdin = tty
   358  	if err := cmd.Start(); err != nil {
   359  		c.Fatal(err)
   360  	}
   361  	assert.Assert(c, waitRun(name) == nil)
   362  
   363  	if _, err := cpty.Write([]byte("hello\n")); err != nil {
   364  		c.Fatal(err)
   365  	}
   366  
   367  	out, err := bufio.NewReader(stdout).ReadString('\n')
   368  	if err != nil {
   369  		c.Fatal(err)
   370  	}
   371  	if strings.TrimSpace(out) != "hello" {
   372  		c.Fatalf("expected 'hello', got %q", out)
   373  	}
   374  
   375  	// escape sequence
   376  	if _, err := cpty.Write(keyCtrlA); err != nil {
   377  		c.Fatal(err)
   378  	}
   379  	time.Sleep(100 * time.Millisecond)
   380  	if _, err := cpty.Write(keyA); err != nil {
   381  		c.Fatal(err)
   382  	}
   383  
   384  	ch := make(chan struct{}, 1)
   385  	go func() {
   386  		cmd.Wait()
   387  		ch <- struct{}{}
   388  	}()
   389  
   390  	select {
   391  	case <-ch:
   392  	case <-time.After(10 * time.Second):
   393  		c.Fatal("timed out waiting for container to exit")
   394  	}
   395  
   396  	running := inspectField(c, name, "State.Running")
   397  	assert.Equal(c, running, "true", "expected container to still be running")
   398  }
   399  
   400  func (s *DockerCLIRunSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *testing.T) {
   401  	name := "attach-detach"
   402  	keyA := []byte{97}
   403  	keyB := []byte{98}
   404  
   405  	dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat")
   406  
   407  	cmd := exec.Command(dockerBinary, "attach", "--detach-keys=a,b,c", name)
   408  	stdout, err := cmd.StdoutPipe()
   409  	if err != nil {
   410  		c.Fatal(err)
   411  	}
   412  	cpty, tty, err := pty.Open()
   413  	if err != nil {
   414  		c.Fatal(err)
   415  	}
   416  	defer cpty.Close()
   417  	cmd.Stdin = tty
   418  	if err := cmd.Start(); err != nil {
   419  		c.Fatal(err)
   420  	}
   421  	go cmd.Wait()
   422  	assert.Assert(c, waitRun(name) == nil)
   423  
   424  	// Invalid escape sequence aba, should print aba in output
   425  	if _, err := cpty.Write(keyA); err != nil {
   426  		c.Fatal(err)
   427  	}
   428  	time.Sleep(100 * time.Millisecond)
   429  	if _, err := cpty.Write(keyB); err != nil {
   430  		c.Fatal(err)
   431  	}
   432  	time.Sleep(100 * time.Millisecond)
   433  	if _, err := cpty.Write(keyA); err != nil {
   434  		c.Fatal(err)
   435  	}
   436  	time.Sleep(100 * time.Millisecond)
   437  	if _, err := cpty.Write([]byte("\n")); err != nil {
   438  		c.Fatal(err)
   439  	}
   440  
   441  	out, err := bufio.NewReader(stdout).ReadString('\n')
   442  	if err != nil {
   443  		c.Fatal(err)
   444  	}
   445  	if strings.TrimSpace(out) != "aba" {
   446  		c.Fatalf("expected 'aba', got %q", out)
   447  	}
   448  }
   449  
   450  // "test" should be printed
   451  func (s *DockerCLIRunSuite) TestRunWithCPUQuota(c *testing.T) {
   452  	testRequires(c, cpuCfsQuota)
   453  
   454  	file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
   455  	out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file)
   456  	assert.Equal(c, strings.TrimSpace(out), "8000")
   457  
   458  	out = inspectField(c, "test", "HostConfig.CpuQuota")
   459  	assert.Equal(c, out, "8000", "setting the CPU CFS quota failed")
   460  }
   461  
   462  func (s *DockerCLIRunSuite) TestRunWithCpuPeriod(c *testing.T) {
   463  	testRequires(c, cpuCfsPeriod)
   464  
   465  	file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
   466  	out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file)
   467  	assert.Equal(c, strings.TrimSpace(out), "50000")
   468  
   469  	out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file)
   470  	assert.Equal(c, strings.TrimSpace(out), "100000")
   471  
   472  	out = inspectField(c, "test", "HostConfig.CpuPeriod")
   473  	assert.Equal(c, out, "50000", "setting the CPU CFS period failed")
   474  }
   475  
   476  func (s *DockerCLIRunSuite) TestRunWithInvalidCpuPeriod(c *testing.T) {
   477  	testRequires(c, cpuCfsPeriod)
   478  	out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true")
   479  	assert.ErrorContains(c, err, "")
   480  	expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)"
   481  	assert.Assert(c, strings.Contains(out, expected))
   482  
   483  	out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true")
   484  	assert.ErrorContains(c, err, "")
   485  	assert.Assert(c, strings.Contains(out, expected))
   486  
   487  	out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true")
   488  	assert.ErrorContains(c, err, "")
   489  	assert.Assert(c, strings.Contains(out, expected))
   490  }
   491  
   492  func (s *DockerCLIRunSuite) TestRunWithCPUShares(c *testing.T) {
   493  	testRequires(c, cpuShare)
   494  
   495  	file := "/sys/fs/cgroup/cpu/cpu.shares"
   496  	out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file)
   497  	assert.Equal(c, strings.TrimSpace(out), "1000")
   498  
   499  	out = inspectField(c, "test", "HostConfig.CPUShares")
   500  	assert.Equal(c, out, "1000")
   501  }
   502  
   503  // "test" should be printed
   504  func (s *DockerCLIRunSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *testing.T) {
   505  	testRequires(c, cpuShare)
   506  	testRequires(c, memoryLimitSupport)
   507  	cli.DockerCmd(c, "run", "--cpu-shares", "1000", "-m", "32m", "busybox", "echo", "test").Assert(c, icmd.Expected{
   508  		Out: "test\n",
   509  	})
   510  }
   511  
   512  func (s *DockerCLIRunSuite) TestRunWithCpusetCpus(c *testing.T) {
   513  	testRequires(c, cgroupCpuset)
   514  
   515  	file := "/sys/fs/cgroup/cpuset/cpuset.cpus"
   516  	out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file)
   517  	assert.Equal(c, strings.TrimSpace(out), "0")
   518  
   519  	out = inspectField(c, "test", "HostConfig.CpusetCpus")
   520  	assert.Equal(c, out, "0")
   521  }
   522  
   523  func (s *DockerCLIRunSuite) TestRunWithCpusetMems(c *testing.T) {
   524  	testRequires(c, cgroupCpuset)
   525  
   526  	file := "/sys/fs/cgroup/cpuset/cpuset.mems"
   527  	out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file)
   528  	assert.Equal(c, strings.TrimSpace(out), "0")
   529  
   530  	out = inspectField(c, "test", "HostConfig.CpusetMems")
   531  	assert.Equal(c, out, "0")
   532  }
   533  
   534  func (s *DockerCLIRunSuite) TestRunWithBlkioWeight(c *testing.T) {
   535  	testRequires(c, blkioWeight)
   536  
   537  	file := "/sys/fs/cgroup/blkio/blkio.weight"
   538  	out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file)
   539  	assert.Equal(c, strings.TrimSpace(out), "300")
   540  
   541  	out = inspectField(c, "test", "HostConfig.BlkioWeight")
   542  	assert.Equal(c, out, "300")
   543  }
   544  
   545  func (s *DockerCLIRunSuite) TestRunWithInvalidBlkioWeight(c *testing.T) {
   546  	testRequires(c, blkioWeight)
   547  	out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true")
   548  	assert.ErrorContains(c, err, "", out)
   549  	expected := "Range of blkio weight is from 10 to 1000"
   550  	assert.Assert(c, strings.Contains(out, expected))
   551  }
   552  
   553  func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *testing.T) {
   554  	testRequires(c, blkioWeight)
   555  	out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true")
   556  	assert.ErrorContains(c, err, "", out)
   557  }
   558  
   559  func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *testing.T) {
   560  	testRequires(c, blkioWeight)
   561  	out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true")
   562  	assert.ErrorContains(c, err, "", out)
   563  }
   564  
   565  func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *testing.T) {
   566  	testRequires(c, blkioWeight)
   567  	out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true")
   568  	assert.ErrorContains(c, err, "", out)
   569  }
   570  
   571  func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *testing.T) {
   572  	testRequires(c, blkioWeight)
   573  	out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true")
   574  	assert.ErrorContains(c, err, "", out)
   575  }
   576  
   577  func (s *DockerCLIRunSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *testing.T) {
   578  	testRequires(c, blkioWeight)
   579  	out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true")
   580  	assert.ErrorContains(c, err, "", out)
   581  }
   582  
   583  func (s *DockerCLIRunSuite) TestRunOOMExitCode(c *testing.T) {
   584  	testRequires(c, memoryLimitSupport, swapMemorySupport, NotPpc64le)
   585  	errChan := make(chan error, 1)
   586  	go func() {
   587  		defer close(errChan)
   588  		// memory limit lower than 8MB will raise an error of "device or resource busy" from docker-runc.
   589  		out, exitCode, _ := dockerCmdWithError("run", "-m", "8MB", "busybox", "sh", "-c", "x=a; while true; do x=$x$x$x$x; done")
   590  		if expected := 137; exitCode != expected {
   591  			errChan <- fmt.Errorf("wrong exit code for OOM container: expected %d, got %d (output: %q)", expected, exitCode, out)
   592  		}
   593  	}()
   594  
   595  	select {
   596  	case err := <-errChan:
   597  		assert.NilError(c, err)
   598  	case <-time.After(600 * time.Second):
   599  		c.Fatal("Timeout waiting for container to die on OOM")
   600  	}
   601  }
   602  
   603  func (s *DockerCLIRunSuite) TestRunWithMemoryLimit(c *testing.T) {
   604  	testRequires(c, memoryLimitSupport)
   605  
   606  	file := "/sys/fs/cgroup/memory/memory.limit_in_bytes"
   607  	cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{
   608  		Out: "33554432",
   609  	})
   610  	cli.InspectCmd(c, "test", cli.Format(".HostConfig.Memory")).Assert(c, icmd.Expected{
   611  		Out: "33554432",
   612  	})
   613  }
   614  
   615  // TestRunWithoutMemoryswapLimit sets memory limit and disables swap
   616  // memory limit, this means the processes in the container can use
   617  // 16M memory and as much swap memory as they need (if the host
   618  // supports swap memory).
   619  func (s *DockerCLIRunSuite) TestRunWithoutMemoryswapLimit(c *testing.T) {
   620  	testRequires(c, DaemonIsLinux)
   621  	testRequires(c, memoryLimitSupport)
   622  	testRequires(c, swapMemorySupport)
   623  	dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true")
   624  }
   625  
   626  func (s *DockerCLIRunSuite) TestRunWithSwappiness(c *testing.T) {
   627  	testRequires(c, memorySwappinessSupport)
   628  	file := "/sys/fs/cgroup/memory/memory.swappiness"
   629  	out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file)
   630  	assert.Equal(c, strings.TrimSpace(out), "0")
   631  
   632  	out = inspectField(c, "test", "HostConfig.MemorySwappiness")
   633  	assert.Equal(c, out, "0")
   634  }
   635  
   636  func (s *DockerCLIRunSuite) TestRunWithSwappinessInvalid(c *testing.T) {
   637  	testRequires(c, memorySwappinessSupport)
   638  	out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true")
   639  	assert.ErrorContains(c, err, "")
   640  	expected := "Valid memory swappiness range is 0-100"
   641  	assert.Assert(c, strings.Contains(out, expected), "Expected output to contain %q, not %q", out, expected)
   642  	out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true")
   643  	assert.ErrorContains(c, err, "")
   644  	assert.Assert(c, strings.Contains(out, expected), "Expected output to contain %q, not %q", out, expected)
   645  }
   646  
   647  func (s *DockerCLIRunSuite) TestRunWithMemoryReservation(c *testing.T) {
   648  	testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport)
   649  
   650  	file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes"
   651  	out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file)
   652  	assert.Equal(c, strings.TrimSpace(out), "209715200")
   653  
   654  	out = inspectField(c, "test", "HostConfig.MemoryReservation")
   655  	assert.Equal(c, out, "209715200")
   656  }
   657  
   658  func (s *DockerCLIRunSuite) TestRunWithMemoryReservationInvalid(c *testing.T) {
   659  	testRequires(c, memoryLimitSupport)
   660  	testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport)
   661  	out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true")
   662  	assert.ErrorContains(c, err, "")
   663  	expected := "Minimum memory limit can not be less than memory reservation limit"
   664  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), expected), "run container should fail with invalid memory reservation")
   665  	out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true")
   666  	assert.ErrorContains(c, err, "")
   667  	expected = "Minimum memory reservation allowed is 6MB"
   668  	assert.Assert(c, strings.Contains(strings.TrimSpace(out), expected), "run container should fail with invalid memory reservation")
   669  }
   670  
   671  func (s *DockerCLIRunSuite) TestStopContainerSignal(c *testing.T) {
   672  	out, _ := dockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`)
   673  	containerID := strings.TrimSpace(out)
   674  
   675  	assert.Assert(c, waitRun(containerID) == nil)
   676  
   677  	dockerCmd(c, "stop", containerID)
   678  	out, _ = dockerCmd(c, "logs", containerID)
   679  
   680  	assert.Assert(c, strings.Contains(out, "exit trapped"), "Expected `exit trapped` in the log")
   681  }
   682  
   683  func (s *DockerCLIRunSuite) TestRunSwapLessThanMemoryLimit(c *testing.T) {
   684  	testRequires(c, memoryLimitSupport)
   685  	testRequires(c, swapMemorySupport)
   686  	out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test")
   687  	expected := "Minimum memoryswap limit should be larger than memory limit"
   688  	assert.ErrorContains(c, err, "")
   689  
   690  	assert.Assert(c, strings.Contains(out, expected))
   691  }
   692  
   693  func (s *DockerCLIRunSuite) TestRunInvalidCpusetCpusFlagValue(c *testing.T) {
   694  	testRequires(c, cgroupCpuset, testEnv.IsLocalDaemon)
   695  
   696  	sysInfo := sysinfo.New()
   697  	cpus, err := parsers.ParseUintList(sysInfo.Cpus)
   698  	assert.NilError(c, err)
   699  	var invalid int
   700  	for i := 0; i <= len(cpus)+1; i++ {
   701  		if !cpus[i] {
   702  			invalid = i
   703  			break
   704  		}
   705  	}
   706  	out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true")
   707  	assert.ErrorContains(c, err, "")
   708  	expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus)
   709  	assert.Assert(c, strings.Contains(out, expected))
   710  }
   711  
   712  func (s *DockerCLIRunSuite) TestRunInvalidCpusetMemsFlagValue(c *testing.T) {
   713  	testRequires(c, cgroupCpuset)
   714  
   715  	sysInfo := sysinfo.New()
   716  	mems, err := parsers.ParseUintList(sysInfo.Mems)
   717  	assert.NilError(c, err)
   718  	var invalid int
   719  	for i := 0; i <= len(mems)+1; i++ {
   720  		if !mems[i] {
   721  			invalid = i
   722  			break
   723  		}
   724  	}
   725  	out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true")
   726  	assert.ErrorContains(c, err, "")
   727  	expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems)
   728  	assert.Assert(c, strings.Contains(out, expected))
   729  }
   730  
   731  func (s *DockerCLIRunSuite) TestRunInvalidCPUShares(c *testing.T) {
   732  	testRequires(c, cpuShare, DaemonIsLinux)
   733  	out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test")
   734  	assert.ErrorContains(c, err, "", out)
   735  	expected := "minimum allowed cpu-shares is 2"
   736  	assert.Assert(c, strings.Contains(out, expected))
   737  
   738  	out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test")
   739  	assert.ErrorContains(c, err, "", out)
   740  	expected = "shares: invalid argument"
   741  	assert.Assert(c, strings.Contains(out, expected))
   742  
   743  	out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test")
   744  	assert.ErrorContains(c, err, "", out)
   745  	expected = "maximum allowed cpu-shares is"
   746  	assert.Assert(c, strings.Contains(out, expected))
   747  }
   748  
   749  func (s *DockerCLIRunSuite) TestRunWithDefaultShmSize(c *testing.T) {
   750  	testRequires(c, DaemonIsLinux)
   751  
   752  	name := "shm-default"
   753  	out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount")
   754  	shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`)
   755  	if !shmRegex.MatchString(out) {
   756  		c.Fatalf("Expected shm of 64MB in mount command, got %v", out)
   757  	}
   758  	shmSize := inspectField(c, name, "HostConfig.ShmSize")
   759  	assert.Equal(c, shmSize, "67108864")
   760  }
   761  
   762  func (s *DockerCLIRunSuite) TestRunWithShmSize(c *testing.T) {
   763  	testRequires(c, DaemonIsLinux)
   764  
   765  	name := "shm"
   766  	out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount")
   767  	shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`)
   768  	if !shmRegex.MatchString(out) {
   769  		c.Fatalf("Expected shm of 1GB in mount command, got %v", out)
   770  	}
   771  	shmSize := inspectField(c, name, "HostConfig.ShmSize")
   772  	assert.Equal(c, shmSize, "1073741824")
   773  }
   774  
   775  func (s *DockerCLIRunSuite) TestRunTmpfsMountsEnsureOrdered(c *testing.T) {
   776  	tmpFile, err := os.CreateTemp("", "test")
   777  	assert.NilError(c, err)
   778  	defer tmpFile.Close()
   779  	out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run")
   780  	assert.Assert(c, strings.Contains(out, "test"))
   781  }
   782  
   783  func (s *DockerCLIRunSuite) TestRunTmpfsMounts(c *testing.T) {
   784  	// TODO Windows (Post TP5): This test cannot run on a Windows daemon as
   785  	// Windows does not support tmpfs mounts.
   786  	testRequires(c, DaemonIsLinux)
   787  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "busybox", "touch", "/run/somefile"); err != nil {
   788  		c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
   789  	}
   790  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec", "busybox", "touch", "/run/somefile"); err != nil {
   791  		c.Fatalf("/run directory not mounted on tmpfs %q %s", err, out)
   792  	}
   793  	if out, _, err := dockerCmdWithError("run", "--tmpfs", "/run:noexec,nosuid,rw,size=5k,mode=700", "busybox", "touch", "/run/somefile"); err != nil {
   794  		c.Fatalf("/run failed to mount on tmpfs with valid options %q %s", err, out)
   795  	}
   796  	if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run:foobar", "busybox", "touch", "/run/somefile"); err == nil {
   797  		c.Fatalf("/run mounted on tmpfs when it should have vailed within invalid mount option")
   798  	}
   799  	if _, _, err := dockerCmdWithError("run", "--tmpfs", "/run", "-v", "/run:/run", "busybox", "touch", "/run/somefile"); err == nil {
   800  		c.Fatalf("Should have generated an error saying Duplicate mount  points")
   801  	}
   802  }
   803  
   804  func (s *DockerCLIRunSuite) TestRunTmpfsMountsOverrideImageVolumes(c *testing.T) {
   805  	name := "img-with-volumes"
   806  	buildImageSuccessfully(c, name, build.WithDockerfile(`
   807      FROM busybox
   808      VOLUME /run
   809      RUN touch /run/stuff
   810      `))
   811  	out, _ := dockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run")
   812  	assert.Assert(c, !strings.Contains(out, "stuff"))
   813  }
   814  
   815  // Test case for #22420
   816  func (s *DockerCLIRunSuite) TestRunTmpfsMountsWithOptions(c *testing.T) {
   817  	testRequires(c, DaemonIsLinux)
   818  
   819  	expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
   820  	out, _ := dockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   821  	for _, option := range expectedOptions {
   822  		assert.Assert(c, strings.Contains(out, option))
   823  	}
   824  	assert.Assert(c, !strings.Contains(out, "size="))
   825  	expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"}
   826  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   827  	for _, option := range expectedOptions {
   828  		assert.Assert(c, strings.Contains(out, option))
   829  	}
   830  	assert.Assert(c, !strings.Contains(out, "size="))
   831  	expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"}
   832  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   833  	for _, option := range expectedOptions {
   834  		assert.Assert(c, strings.Contains(out, option))
   835  	}
   836  
   837  	expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"}
   838  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'")
   839  	for _, option := range expectedOptions {
   840  		assert.Assert(c, strings.Contains(out, option))
   841  	}
   842  
   843  	// We use debian:bullseye-slim as there is no findmnt in busybox. Also the output will be in the format of
   844  	// TARGET PROPAGATION
   845  	// /tmp   shared
   846  	// so we only capture `shared` here.
   847  	expectedOptions = []string{"shared"}
   848  	out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:bullseye-slim", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp")
   849  	for _, option := range expectedOptions {
   850  		assert.Assert(c, strings.Contains(out, option))
   851  	}
   852  }
   853  
   854  func (s *DockerCLIRunSuite) TestRunSysctls(c *testing.T) {
   855  	testRequires(c, DaemonIsLinux)
   856  	var err error
   857  
   858  	out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
   859  	assert.Equal(c, strings.TrimSpace(out), "1")
   860  
   861  	out = inspectFieldJSON(c, "test", "HostConfig.Sysctls")
   862  
   863  	sysctls := make(map[string]string)
   864  	err = json.Unmarshal([]byte(out), &sysctls)
   865  	assert.NilError(c, err)
   866  	assert.Equal(c, sysctls["net.ipv4.ip_forward"], "1")
   867  
   868  	out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward")
   869  	assert.Equal(c, strings.TrimSpace(out), "0")
   870  
   871  	out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls")
   872  
   873  	err = json.Unmarshal([]byte(out), &sysctls)
   874  	assert.NilError(c, err)
   875  	assert.Equal(c, sysctls["net.ipv4.ip_forward"], "0")
   876  
   877  	icmd.RunCommand(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2",
   878  		"busybox", "cat", "/proc/sys/kernel/foobar").Assert(c, icmd.Expected{
   879  		ExitCode: 125,
   880  		Err:      "invalid argument",
   881  	})
   882  }
   883  
   884  // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:bullseye-slim unshare' exits with operation not permitted.
   885  func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyUnshare(c *testing.T) {
   886  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotArm, Apparmor)
   887  	jsonData := `{
   888  	"defaultAction": "SCMP_ACT_ALLOW",
   889  	"syscalls": [
   890  		{
   891  			"name": "unshare",
   892  			"action": "SCMP_ACT_ERRNO"
   893  		}
   894  	]
   895  }`
   896  	tmpFile, err := os.CreateTemp("", "profile.json")
   897  	if err != nil {
   898  		c.Fatal(err)
   899  	}
   900  	defer tmpFile.Close()
   901  
   902  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   903  		c.Fatal(err)
   904  	}
   905  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "apparmor=unconfined",
   906  		"--security-opt", "seccomp="+tmpFile.Name(),
   907  		"debian:bullseye-slim", "unshare", "-p", "-m", "-f", "-r", "mount", "-t", "proc", "none", "/proc").Assert(c, icmd.Expected{
   908  		ExitCode: 1,
   909  		Err:      "Operation not permitted",
   910  	})
   911  }
   912  
   913  // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted.
   914  func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyChmod(c *testing.T) {
   915  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
   916  	jsonData := `{
   917  	"defaultAction": "SCMP_ACT_ALLOW",
   918  	"syscalls": [
   919  		{
   920  			"name": "chmod",
   921  			"action": "SCMP_ACT_ERRNO"
   922  		},
   923  		{
   924  			"name":"fchmod",
   925  			"action": "SCMP_ACT_ERRNO"
   926  		},
   927  		{
   928  			"name": "fchmodat",
   929  			"action":"SCMP_ACT_ERRNO"
   930  		}
   931  	]
   932  }`
   933  	tmpFile, err := os.CreateTemp("", "profile.json")
   934  	assert.NilError(c, err)
   935  	defer tmpFile.Close()
   936  
   937  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   938  		c.Fatal(err)
   939  	}
   940  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp="+tmpFile.Name(),
   941  		"busybox", "chmod", "400", "/etc/hostname").Assert(c, icmd.Expected{
   942  		ExitCode: 1,
   943  		Err:      "Operation not permitted",
   944  	})
   945  }
   946  
   947  // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:bullseye-slim unshare --map-root-user --user sh -c whoami' with a specific profile to
   948  // deny unshare of a userns exits with operation not permitted.
   949  func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyUnshareUserns(c *testing.T) {
   950  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotArm, Apparmor)
   951  	// from sched.h
   952  	jsonData := fmt.Sprintf(`{
   953  	"defaultAction": "SCMP_ACT_ALLOW",
   954  	"syscalls": [
   955  		{
   956  			"name": "unshare",
   957  			"action": "SCMP_ACT_ERRNO",
   958  			"args": [
   959  				{
   960  					"index": 0,
   961  					"value": %d,
   962  					"op": "SCMP_CMP_EQ"
   963  				}
   964  			]
   965  		}
   966  	]
   967  }`, uint64(0x10000000))
   968  	tmpFile, err := os.CreateTemp("", "profile.json")
   969  	if err != nil {
   970  		c.Fatal(err)
   971  	}
   972  	defer tmpFile.Close()
   973  
   974  	if _, err := tmpFile.Write([]byte(jsonData)); err != nil {
   975  		c.Fatal(err)
   976  	}
   977  	icmd.RunCommand(dockerBinary, "run",
   978  		"--security-opt", "apparmor=unconfined", "--security-opt", "seccomp="+tmpFile.Name(),
   979  		"debian:bullseye-slim", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami").Assert(c, icmd.Expected{
   980  		ExitCode: 1,
   981  		Err:      "Operation not permitted",
   982  	})
   983  }
   984  
   985  // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test'
   986  // with a the default seccomp profile exits with operation not permitted.
   987  func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyCloneUserns(c *testing.T) {
   988  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
   989  	ensureSyscallTest(c)
   990  
   991  	icmd.RunCommand(dockerBinary, "run", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
   992  		ExitCode: 1,
   993  		Err:      "clone failed: Operation not permitted",
   994  	})
   995  }
   996  
   997  // TestRunSeccompUnconfinedCloneUserns checks that
   998  // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns.
   999  func (s *DockerCLIRunSuite) TestRunSeccompUnconfinedCloneUserns(c *testing.T) {
  1000  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone)
  1001  	ensureSyscallTest(c)
  1002  
  1003  	// make sure running w privileged is ok
  1004  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined",
  1005  		"syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1006  		Out: "nobody",
  1007  	})
  1008  }
  1009  
  1010  // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test'
  1011  // allows creating a userns.
  1012  func (s *DockerCLIRunSuite) TestRunSeccompAllowPrivCloneUserns(c *testing.T) {
  1013  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace)
  1014  	ensureSyscallTest(c)
  1015  
  1016  	// make sure running w privileged is ok
  1017  	icmd.RunCommand(dockerBinary, "run", "--privileged", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{
  1018  		Out: "nobody",
  1019  	})
  1020  }
  1021  
  1022  // TestRunSeccompProfileAllow32Bit checks that 32 bit code can run on x86_64
  1023  // with the default seccomp profile.
  1024  func (s *DockerCLIRunSuite) TestRunSeccompProfileAllow32Bit(c *testing.T) {
  1025  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, IsAmd64)
  1026  	ensureSyscallTest(c)
  1027  
  1028  	icmd.RunCommand(dockerBinary, "run", "syscall-test", "exit32-test").Assert(c, icmd.Success)
  1029  }
  1030  
  1031  // TestRunSeccompAllowSetrlimit checks that 'docker run debian:bullseye-slim ulimit -v 1048510' succeeds.
  1032  func (s *DockerCLIRunSuite) TestRunSeccompAllowSetrlimit(c *testing.T) {
  1033  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
  1034  
  1035  	// ulimit uses setrlimit, so we want to make sure we don't break it
  1036  	icmd.RunCommand(dockerBinary, "run", "debian:bullseye-slim", "bash", "-c", "ulimit -v 1048510").Assert(c, icmd.Success)
  1037  }
  1038  
  1039  func (s *DockerCLIRunSuite) TestRunSeccompDefaultProfileAcct(c *testing.T) {
  1040  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace)
  1041  	ensureSyscallTest(c)
  1042  
  1043  	out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test")
  1044  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1045  		c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  1046  	}
  1047  
  1048  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "acct-test")
  1049  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1050  		c.Fatalf("test 1: expected Operation not permitted, got: %s", out)
  1051  	}
  1052  
  1053  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  1054  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1055  		c.Fatalf("test 2: expected No such file or directory, got: %s", out)
  1056  	}
  1057  
  1058  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "acct-test")
  1059  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1060  		c.Fatalf("test 3: expected No such file or directory, got: %s", out)
  1061  	}
  1062  
  1063  	out, _, err = dockerCmdWithError("run", "--cap-drop", "ALL", "--cap-add", "sys_pacct", "syscall-test", "acct-test")
  1064  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1065  		c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  1066  	}
  1067  }
  1068  
  1069  func (s *DockerCLIRunSuite) TestRunSeccompDefaultProfileNS(c *testing.T) {
  1070  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace)
  1071  	ensureSyscallTest(c)
  1072  
  1073  	out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0")
  1074  	if err == nil || !strings.Contains(out, "Operation not permitted") {
  1075  		c.Fatalf("test 0: expected Operation not permitted, got: %s", out)
  1076  	}
  1077  
  1078  	out, _, err = dockerCmdWithError("run", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello1")
  1079  	if err != nil || !strings.Contains(out, "hello1") {
  1080  		c.Fatalf("test 1: expected hello1, got: %s, %v", out, err)
  1081  	}
  1082  
  1083  	out, _, err = dockerCmdWithError("run", "--cap-drop", "all", "--cap-add", "sys_admin", "syscall-test", "ns-test", "echo", "hello2")
  1084  	if err != nil || !strings.Contains(out, "hello2") {
  1085  		c.Fatalf("test 2: expected hello2, got: %s, %v", out, err)
  1086  	}
  1087  
  1088  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "syscall-test", "ns-test", "echo", "hello3")
  1089  	if err != nil || !strings.Contains(out, "hello3") {
  1090  		c.Fatalf("test 3: expected hello3, got: %s, %v", out, err)
  1091  	}
  1092  
  1093  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "acct-test")
  1094  	if err == nil || !strings.Contains(out, "No such file or directory") {
  1095  		c.Fatalf("test 4: expected No such file or directory, got: %s", out)
  1096  	}
  1097  
  1098  	out, _, err = dockerCmdWithError("run", "--cap-add", "ALL", "--security-opt", "seccomp=unconfined", "syscall-test", "ns-test", "echo", "hello4")
  1099  	if err != nil || !strings.Contains(out, "hello4") {
  1100  		c.Fatalf("test 5: expected hello4, got: %s, %v", out, err)
  1101  	}
  1102  }
  1103  
  1104  // TestRunNoNewPrivSetuid checks that --security-opt='no-new-privileges=true' prevents
  1105  // effective uid transitions on executing setuid binaries.
  1106  func (s *DockerCLIRunSuite) TestRunNoNewPrivSetuid(c *testing.T) {
  1107  	testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  1108  	ensureNNPTest(c)
  1109  
  1110  	// test that running a setuid binary results in no effective uid transition
  1111  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges=true", "--user", "1000",
  1112  		"nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  1113  		Out: "EUID=1000",
  1114  	})
  1115  }
  1116  
  1117  // TestLegacyRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents
  1118  // effective uid transitions on executing setuid binaries.
  1119  func (s *DockerCLIRunSuite) TestLegacyRunNoNewPrivSetuid(c *testing.T) {
  1120  	testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  1121  	ensureNNPTest(c)
  1122  
  1123  	// test that running a setuid binary results in no effective uid transition
  1124  	icmd.RunCommand(dockerBinary, "run", "--security-opt", "no-new-privileges", "--user", "1000",
  1125  		"nnp-test", "/usr/bin/nnp-test").Assert(c, icmd.Expected{
  1126  		Out: "EUID=1000",
  1127  	})
  1128  }
  1129  
  1130  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesChown(c *testing.T) {
  1131  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1132  	ensureSyscallTest(c)
  1133  
  1134  	// test that a root user has default capability CAP_CHOWN
  1135  	dockerCmd(c, "run", "busybox", "chown", "100", "/tmp")
  1136  	// test that non root user does not have default capability CAP_CHOWN
  1137  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  1138  		ExitCode: 1,
  1139  		Err:      "Operation not permitted",
  1140  	})
  1141  	// test that root user can drop default capability CAP_CHOWN
  1142  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "chown", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{
  1143  		ExitCode: 1,
  1144  		Err:      "Operation not permitted",
  1145  	})
  1146  }
  1147  
  1148  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *testing.T) {
  1149  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1150  	ensureSyscallTest(c)
  1151  
  1152  	// test that a root user has default capability CAP_DAC_OVERRIDE
  1153  	dockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd")
  1154  	// test that non root user does not have default capability CAP_DAC_OVERRIDE
  1155  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "sh", "-c", "echo test > /etc/passwd").Assert(c, icmd.Expected{
  1156  		ExitCode: 1,
  1157  		Err:      "Permission denied",
  1158  	})
  1159  }
  1160  
  1161  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesFowner(c *testing.T) {
  1162  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1163  	ensureSyscallTest(c)
  1164  
  1165  	// test that a root user has default capability CAP_FOWNER
  1166  	dockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd")
  1167  	// test that non root user does not have default capability CAP_FOWNER
  1168  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chmod", "777", "/etc/passwd").Assert(c, icmd.Expected{
  1169  		ExitCode: 1,
  1170  		Err:      "Operation not permitted",
  1171  	})
  1172  	// TODO test that root user can drop default capability CAP_FOWNER
  1173  }
  1174  
  1175  // TODO CAP_KILL
  1176  
  1177  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesSetuid(c *testing.T) {
  1178  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1179  	ensureSyscallTest(c)
  1180  
  1181  	// test that a root user has default capability CAP_SETUID
  1182  	dockerCmd(c, "run", "syscall-test", "setuid-test")
  1183  	// test that non root user does not have default capability CAP_SETUID
  1184  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1185  		ExitCode: 1,
  1186  		Err:      "Operation not permitted",
  1187  	})
  1188  	// test that root user can drop default capability CAP_SETUID
  1189  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setuid", "syscall-test", "setuid-test").Assert(c, icmd.Expected{
  1190  		ExitCode: 1,
  1191  		Err:      "Operation not permitted",
  1192  	})
  1193  }
  1194  
  1195  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) {
  1196  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1197  	ensureSyscallTest(c)
  1198  
  1199  	// test that a root user has default capability CAP_SETGID
  1200  	dockerCmd(c, "run", "syscall-test", "setgid-test")
  1201  	// test that non root user does not have default capability CAP_SETGID
  1202  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1203  		ExitCode: 1,
  1204  		Err:      "Operation not permitted",
  1205  	})
  1206  	// test that root user can drop default capability CAP_SETGID
  1207  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "setgid", "syscall-test", "setgid-test").Assert(c, icmd.Expected{
  1208  		ExitCode: 1,
  1209  		Err:      "Operation not permitted",
  1210  	})
  1211  }
  1212  
  1213  // TODO CAP_SETPCAP
  1214  
  1215  // sysctlExists checks if a sysctl exists; runc will error if we add any that do not actually
  1216  // exist, so do not add the default ones if running on an old kernel.
  1217  func sysctlExists(s string) bool {
  1218  	f := filepath.Join("/proc", "sys", strings.ReplaceAll(s, ".", "/"))
  1219  	_, err := os.Stat(f)
  1220  	return err == nil
  1221  }
  1222  
  1223  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *testing.T) {
  1224  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1225  	ensureSyscallTest(c)
  1226  
  1227  	// test that a root user has default capability CAP_NET_BIND_SERVICE
  1228  	dockerCmd(c, "run", "syscall-test", "socket-test")
  1229  	// test that non root user does not have default capability CAP_NET_BIND_SERVICE
  1230  	// as we allow this via sysctl, also tweak the sysctl back to default
  1231  	args := []string{"run", "--user", "1000:1000"}
  1232  	if sysctlExists("net.ipv4.ip_unprivileged_port_start") {
  1233  		args = append(args, "--sysctl", "net.ipv4.ip_unprivileged_port_start=1024")
  1234  	}
  1235  	args = append(args, "syscall-test", "socket-test")
  1236  	icmd.RunCommand(dockerBinary, args...).Assert(c, icmd.Expected{
  1237  		ExitCode: 1,
  1238  		Err:      "Permission denied",
  1239  	})
  1240  	// test that root user can drop default capability CAP_NET_BIND_SERVICE
  1241  	args = []string{"run", "--cap-drop", "net_bind_service"}
  1242  	if sysctlExists("net.ipv4.ip_unprivileged_port_start") {
  1243  		args = append(args, "--sysctl", "net.ipv4.ip_unprivileged_port_start=1024")
  1244  	}
  1245  	args = append(args, "syscall-test", "socket-test")
  1246  	icmd.RunCommand(dockerBinary, args...).Assert(c, icmd.Expected{
  1247  		ExitCode: 1,
  1248  		Err:      "Permission denied",
  1249  	})
  1250  }
  1251  
  1252  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *testing.T) {
  1253  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1254  	ensureSyscallTest(c)
  1255  
  1256  	// test that a root user has default capability CAP_NET_RAW
  1257  	dockerCmd(c, "run", "syscall-test", "raw-test")
  1258  	// test that non root user does not have default capability CAP_NET_RAW
  1259  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1260  		ExitCode: 1,
  1261  		Err:      "Operation not permitted",
  1262  	})
  1263  	// test that root user can drop default capability CAP_NET_RAW
  1264  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "net_raw", "syscall-test", "raw-test").Assert(c, icmd.Expected{
  1265  		ExitCode: 1,
  1266  		Err:      "Operation not permitted",
  1267  	})
  1268  }
  1269  
  1270  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesChroot(c *testing.T) {
  1271  	testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon)
  1272  	ensureSyscallTest(c)
  1273  
  1274  	// test that a root user has default capability CAP_SYS_CHROOT
  1275  	dockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true")
  1276  	// test that non root user does not have default capability CAP_SYS_CHROOT
  1277  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1278  		ExitCode: 1,
  1279  		Err:      "Operation not permitted",
  1280  	})
  1281  	// test that root user can drop default capability CAP_SYS_CHROOT
  1282  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "sys_chroot", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{
  1283  		ExitCode: 1,
  1284  		Err:      "Operation not permitted",
  1285  	})
  1286  }
  1287  
  1288  func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesMknod(c *testing.T) {
  1289  	testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon)
  1290  	ensureSyscallTest(c)
  1291  
  1292  	// test that a root user has default capability CAP_MKNOD
  1293  	dockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2")
  1294  	// test that non root user does not have default capability CAP_MKNOD
  1295  	// test that root user can drop default capability CAP_SYS_CHROOT
  1296  	icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1297  		ExitCode: 1,
  1298  		Err:      "Operation not permitted",
  1299  	})
  1300  	// test that root user can drop default capability CAP_MKNOD
  1301  	icmd.RunCommand(dockerBinary, "run", "--cap-drop", "mknod", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{
  1302  		ExitCode: 1,
  1303  		Err:      "Operation not permitted",
  1304  	})
  1305  }
  1306  
  1307  // TODO CAP_AUDIT_WRITE
  1308  // TODO CAP_SETFCAP
  1309  
  1310  func (s *DockerCLIRunSuite) TestRunApparmorProcDirectory(c *testing.T) {
  1311  	testRequires(c, testEnv.IsLocalDaemon, Apparmor)
  1312  
  1313  	// running w seccomp unconfined tests the apparmor profile
  1314  	result := icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup")
  1315  	result.Assert(c, icmd.Expected{ExitCode: 1})
  1316  	if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1317  		c.Fatalf("expected chmod 777 /proc/1/cgroup to fail, got %s: %v", result.Combined(), result.Error)
  1318  	}
  1319  
  1320  	result = icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/attr/current")
  1321  	result.Assert(c, icmd.Expected{ExitCode: 1})
  1322  	if !(strings.Contains(result.Combined(), "Permission denied") || strings.Contains(result.Combined(), "Operation not permitted")) {
  1323  		c.Fatalf("expected chmod 777 /proc/1/attr/current to fail, got %s: %v", result.Combined(), result.Error)
  1324  	}
  1325  }
  1326  
  1327  // make sure the default profile can be successfully parsed (using unshare as it is
  1328  // something which we know is blocked in the default profile)
  1329  func (s *DockerCLIRunSuite) TestRunSeccompWithDefaultProfile(c *testing.T) {
  1330  	testRequires(c, testEnv.IsLocalDaemon, seccompEnabled)
  1331  
  1332  	out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:bullseye-slim", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami")
  1333  	assert.ErrorContains(c, err, "", out)
  1334  	assert.Equal(c, strings.TrimSpace(out), "unshare: unshare failed: Operation not permitted")
  1335  }
  1336  
  1337  // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271)
  1338  func (s *DockerCLIRunSuite) TestRunDeviceSymlink(c *testing.T) {
  1339  	testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, testEnv.IsLocalDaemon)
  1340  	if _, err := os.Stat("/dev/zero"); err != nil {
  1341  		c.Skip("Host does not have /dev/zero")
  1342  	}
  1343  
  1344  	// Create a temporary directory to create symlink
  1345  	tmpDir, err := os.MkdirTemp("", "docker_device_follow_symlink_tests")
  1346  	assert.NilError(c, err)
  1347  
  1348  	defer os.RemoveAll(tmpDir)
  1349  
  1350  	// Create a symbolic link to /dev/zero
  1351  	symZero := filepath.Join(tmpDir, "zero")
  1352  	err = os.Symlink("/dev/zero", symZero)
  1353  	assert.NilError(c, err)
  1354  
  1355  	// Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp",
  1356  	// then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp".
  1357  	tmpFile := filepath.Join(tmpDir, "temp")
  1358  	err = os.WriteFile(tmpFile, []byte("temp"), 0666)
  1359  	assert.NilError(c, err)
  1360  	symFile := filepath.Join(tmpDir, "file")
  1361  	err = os.Symlink(tmpFile, symFile)
  1362  	assert.NilError(c, err)
  1363  
  1364  	// Create a symbolic link to /dev/zero, this time with a relative path (#22271)
  1365  	err = os.Symlink("zero", "/dev/symzero")
  1366  	if err != nil {
  1367  		c.Fatal("/dev/symzero creation failed")
  1368  	}
  1369  	// We need to remove this symbolic link here as it is created in /dev/, not temporary directory as above
  1370  	defer os.Remove("/dev/symzero")
  1371  
  1372  	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23
  1373  	out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1374  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "bb7df04e1b0a2570657527a7e108ae23"), "expected output bb7df04e1b0a2570657527a7e108ae23")
  1375  	// symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device.
  1376  	out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1377  	assert.ErrorContains(c, err, "")
  1378  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "not a device node"), "expected output 'not a device node'")
  1379  	// md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271)
  1380  	out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum")
  1381  	assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "bb7df04e1b0a2570657527a7e108ae23"), "expected output bb7df04e1b0a2570657527a7e108ae23")
  1382  }
  1383  
  1384  // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit
  1385  func (s *DockerCLIRunSuite) TestRunPIDsLimit(c *testing.T) {
  1386  	testRequires(c, testEnv.IsLocalDaemon, pidsLimit)
  1387  
  1388  	file := "/sys/fs/cgroup/pids/pids.max"
  1389  	out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file)
  1390  	assert.Equal(c, strings.TrimSpace(out), "4")
  1391  
  1392  	out = inspectField(c, "skittles", "HostConfig.PidsLimit")
  1393  	assert.Equal(c, out, "4", "setting the pids limit failed")
  1394  }
  1395  
  1396  func (s *DockerCLIRunSuite) TestRunPrivilegedAllowedDevices(c *testing.T) {
  1397  	testRequires(c, DaemonIsLinux, NotUserNamespace)
  1398  
  1399  	file := "/sys/fs/cgroup/devices/devices.list"
  1400  	out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file)
  1401  	c.Logf("out: %q", out)
  1402  	assert.Equal(c, strings.TrimSpace(out), "a *:* rwm")
  1403  }
  1404  
  1405  func (s *DockerCLIRunSuite) TestRunUserDeviceAllowed(c *testing.T) {
  1406  	testRequires(c, DaemonIsLinux)
  1407  
  1408  	fi, err := os.Stat("/dev/snd/timer")
  1409  	if err != nil {
  1410  		c.Skip("Host does not have /dev/snd/timer")
  1411  	}
  1412  	stat, ok := fi.Sys().(*syscall.Stat_t)
  1413  	if !ok {
  1414  		c.Skip("Could not stat /dev/snd/timer")
  1415  	}
  1416  
  1417  	file := "/sys/fs/cgroup/devices/devices.list"
  1418  	out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file)
  1419  	assert.Assert(c, strings.Contains(out, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256)))
  1420  }
  1421  
  1422  func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *testing.T) {
  1423  	testRequires(c, seccompEnabled)
  1424  
  1425  	s.d.StartWithBusybox(c)
  1426  
  1427  	jsonData := `{
  1428  	"defaultAction": "SCMP_ACT_ALLOW",
  1429  	"syscalls": [
  1430  		{
  1431  			"names": ["chmod", "fchmod", "fchmodat"],
  1432  			"action": "SCMP_ACT_ERRNO"
  1433  		}
  1434  	]
  1435  }`
  1436  	tmpFile, err := os.CreateTemp("", "profile.json")
  1437  	assert.NilError(c, err)
  1438  	defer tmpFile.Close()
  1439  	_, err = tmpFile.Write([]byte(jsonData))
  1440  	assert.NilError(c, err)
  1441  
  1442  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1443  	assert.ErrorContains(c, err, "")
  1444  	assert.Assert(c, strings.Contains(out, "Operation not permitted"))
  1445  }
  1446  
  1447  func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *testing.T) {
  1448  	testRequires(c, seccompEnabled)
  1449  
  1450  	s.d.StartWithBusybox(c)
  1451  
  1452  	jsonData := `{
  1453  	"defaultAction": "SCMP_ACT_ALLOW",
  1454  	"syscalls": [
  1455  		{
  1456  			"name": "chmod",
  1457  			"names": ["fchmod", "fchmodat"],
  1458  			"action": "SCMP_ACT_ERRNO"
  1459  		}
  1460  	]
  1461  }`
  1462  	tmpFile, err := os.CreateTemp("", "profile.json")
  1463  	assert.NilError(c, err)
  1464  	defer tmpFile.Close()
  1465  	_, err = tmpFile.Write([]byte(jsonData))
  1466  	assert.NilError(c, err)
  1467  
  1468  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1469  	assert.ErrorContains(c, err, "")
  1470  	assert.Assert(c, strings.Contains(out, "use either 'name' or 'names'"))
  1471  }
  1472  
  1473  func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *testing.T) {
  1474  	testRequires(c, seccompEnabled)
  1475  
  1476  	s.d.StartWithBusybox(c)
  1477  
  1478  	jsonData := `{
  1479  	"archMap": [
  1480  		{
  1481  			"architecture": "SCMP_ARCH_X86_64",
  1482  			"subArchitectures": [
  1483  				"SCMP_ARCH_X86",
  1484  				"SCMP_ARCH_X32"
  1485  			]
  1486  		}
  1487  	],
  1488  	"architectures": [
  1489  		"SCMP_ARCH_X32"
  1490  	],
  1491  	"defaultAction": "SCMP_ACT_ALLOW",
  1492  	"syscalls": [
  1493  		{
  1494  			"names": ["chmod", "fchmod", "fchmodat"],
  1495  			"action": "SCMP_ACT_ERRNO"
  1496  		}
  1497  	]
  1498  }`
  1499  	tmpFile, err := os.CreateTemp("", "profile.json")
  1500  	assert.NilError(c, err)
  1501  	defer tmpFile.Close()
  1502  	_, err = tmpFile.Write([]byte(jsonData))
  1503  	assert.NilError(c, err)
  1504  
  1505  	out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".")
  1506  	assert.ErrorContains(c, err, "")
  1507  	assert.Assert(c, strings.Contains(out, "use either 'architectures' or 'archMap'"))
  1508  }
  1509  
  1510  func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *testing.T) {
  1511  	testRequires(c, seccompEnabled)
  1512  
  1513  	s.d.StartWithBusybox(c)
  1514  
  1515  	// 1) verify I can run containers with the Docker default shipped profile which allows chmod
  1516  	_, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1517  	assert.NilError(c, err)
  1518  
  1519  	jsonData := `{
  1520  	"defaultAction": "SCMP_ACT_ALLOW",
  1521  	"syscalls": [
  1522  		{
  1523  			"name": "chmod",
  1524  			"action": "SCMP_ACT_ERRNO"
  1525  		},
  1526  		{
  1527  			"name": "fchmodat",
  1528  			"action": "SCMP_ACT_ERRNO"
  1529  		}
  1530  	]
  1531  }`
  1532  	tmpFile, err := os.CreateTemp("", "profile.json")
  1533  	assert.NilError(c, err)
  1534  	defer tmpFile.Close()
  1535  	_, err = tmpFile.Write([]byte(jsonData))
  1536  	assert.NilError(c, err)
  1537  
  1538  	// 2) restart the daemon and add a custom seccomp profile in which we deny chmod
  1539  	s.d.Restart(c, "--seccomp-profile="+tmpFile.Name())
  1540  
  1541  	out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".")
  1542  	assert.ErrorContains(c, err, "")
  1543  	assert.Assert(c, strings.Contains(out, "Operation not permitted"))
  1544  }
  1545  
  1546  func (s *DockerCLIRunSuite) TestRunWithNanoCPUs(c *testing.T) {
  1547  	testRequires(c, cpuCfsQuota, cpuCfsPeriod)
  1548  
  1549  	file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us"
  1550  	file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us"
  1551  	out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2))
  1552  	assert.Equal(c, strings.TrimSpace(out), "50000\n100000")
  1553  
  1554  	clt, err := client.NewClientWithOpts(client.FromEnv)
  1555  	assert.NilError(c, err)
  1556  	inspect, err := clt.ContainerInspect(context.Background(), "test")
  1557  	assert.NilError(c, err)
  1558  	assert.Equal(c, inspect.HostConfig.NanoCPUs, int64(500000000))
  1559  
  1560  	out = inspectField(c, "test", "HostConfig.CpuQuota")
  1561  	assert.Equal(c, out, "0", "CPU CFS quota should be 0")
  1562  	out = inspectField(c, "test", "HostConfig.CpuPeriod")
  1563  	assert.Equal(c, out, "0", "CPU CFS period should be 0")
  1564  
  1565  	out, _, err = dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh")
  1566  	assert.ErrorContains(c, err, "")
  1567  	assert.Assert(c, strings.Contains(out, "Conflicting options: Nano CPUs and CPU Period cannot both be set"))
  1568  }