mounts_linux_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508
  1. package container // import "github.com/docker/docker/integration/container"
  2. import (
  3. "fmt"
  4. "os"
  5. "path/filepath"
  6. "syscall"
  7. "testing"
  8. "time"
  9. "github.com/docker/docker/api/types"
  10. containertypes "github.com/docker/docker/api/types/container"
  11. mounttypes "github.com/docker/docker/api/types/mount"
  12. "github.com/docker/docker/api/types/network"
  13. "github.com/docker/docker/api/types/versions"
  14. "github.com/docker/docker/client"
  15. "github.com/docker/docker/integration/internal/container"
  16. "github.com/docker/docker/pkg/parsers/kernel"
  17. "github.com/docker/docker/testutil"
  18. "github.com/moby/sys/mount"
  19. "github.com/moby/sys/mountinfo"
  20. "gotest.tools/v3/assert"
  21. is "gotest.tools/v3/assert/cmp"
  22. "gotest.tools/v3/fs"
  23. "gotest.tools/v3/poll"
  24. "gotest.tools/v3/skip"
  25. )
  26. func TestContainerNetworkMountsNoChown(t *testing.T) {
  27. // chown only applies to Linux bind mounted volumes; must be same host to verify
  28. skip.If(t, testEnv.IsRemoteDaemon)
  29. ctx := setupTest(t)
  30. tmpDir := fs.NewDir(t, "network-file-mounts", fs.WithMode(0o755), fs.WithFile("nwfile", "network file bind mount", fs.WithMode(0o644)))
  31. defer tmpDir.Remove()
  32. tmpNWFileMount := tmpDir.Join("nwfile")
  33. config := containertypes.Config{
  34. Image: "busybox",
  35. }
  36. hostConfig := containertypes.HostConfig{
  37. Mounts: []mounttypes.Mount{
  38. {
  39. Type: "bind",
  40. Source: tmpNWFileMount,
  41. Target: "/etc/resolv.conf",
  42. },
  43. {
  44. Type: "bind",
  45. Source: tmpNWFileMount,
  46. Target: "/etc/hostname",
  47. },
  48. {
  49. Type: "bind",
  50. Source: tmpNWFileMount,
  51. Target: "/etc/hosts",
  52. },
  53. },
  54. }
  55. cli, err := client.NewClientWithOpts(client.FromEnv)
  56. assert.NilError(t, err)
  57. defer cli.Close()
  58. ctrCreate, err := cli.ContainerCreate(ctx, &config, &hostConfig, &network.NetworkingConfig{}, nil, "")
  59. assert.NilError(t, err)
  60. // container will exit immediately because of no tty, but we only need the start sequence to test the condition
  61. err = cli.ContainerStart(ctx, ctrCreate.ID, types.ContainerStartOptions{})
  62. assert.NilError(t, err)
  63. // Check that host-located bind mount network file did not change ownership when the container was started
  64. // Note: If the user specifies a mountpath from the host, we should not be
  65. // attempting to chown files outside the daemon's metadata directory
  66. // (represented by `daemon.repository` at init time).
  67. // This forces users who want to use user namespaces to handle the
  68. // ownership needs of any external files mounted as network files
  69. // (/etc/resolv.conf, /etc/hosts, /etc/hostname) separately from the
  70. // daemon. In all other volume/bind mount situations we have taken this
  71. // same line--we don't chown host file content.
  72. // See GitHub PR 34224 for details.
  73. info, err := os.Stat(tmpNWFileMount)
  74. assert.NilError(t, err)
  75. fi := info.Sys().(*syscall.Stat_t)
  76. assert.Check(t, is.Equal(fi.Uid, uint32(0)), "bind mounted network file should not change ownership from root")
  77. }
  78. func TestMountDaemonRoot(t *testing.T) {
  79. skip.If(t, testEnv.IsRemoteDaemon)
  80. ctx := setupTest(t)
  81. apiClient := testEnv.APIClient()
  82. info, err := apiClient.Info(ctx)
  83. if err != nil {
  84. t.Fatal(err)
  85. }
  86. for _, test := range []struct {
  87. desc string
  88. propagation mounttypes.Propagation
  89. expected mounttypes.Propagation
  90. }{
  91. {
  92. desc: "default",
  93. propagation: "",
  94. expected: mounttypes.PropagationRSlave,
  95. },
  96. {
  97. desc: "private",
  98. propagation: mounttypes.PropagationPrivate,
  99. },
  100. {
  101. desc: "rprivate",
  102. propagation: mounttypes.PropagationRPrivate,
  103. },
  104. {
  105. desc: "slave",
  106. propagation: mounttypes.PropagationSlave,
  107. },
  108. {
  109. desc: "rslave",
  110. propagation: mounttypes.PropagationRSlave,
  111. expected: mounttypes.PropagationRSlave,
  112. },
  113. {
  114. desc: "shared",
  115. propagation: mounttypes.PropagationShared,
  116. },
  117. {
  118. desc: "rshared",
  119. propagation: mounttypes.PropagationRShared,
  120. expected: mounttypes.PropagationRShared,
  121. },
  122. } {
  123. t.Run(test.desc, func(t *testing.T) {
  124. test := test
  125. t.Parallel()
  126. ctx := testutil.StartSpan(ctx, t)
  127. propagationSpec := fmt.Sprintf(":%s", test.propagation)
  128. if test.propagation == "" {
  129. propagationSpec = ""
  130. }
  131. bindSpecRoot := info.DockerRootDir + ":" + "/foo" + propagationSpec
  132. bindSpecSub := filepath.Join(info.DockerRootDir, "containers") + ":/foo" + propagationSpec
  133. for name, hc := range map[string]*containertypes.HostConfig{
  134. "bind root": {Binds: []string{bindSpecRoot}},
  135. "bind subpath": {Binds: []string{bindSpecSub}},
  136. "mount root": {
  137. Mounts: []mounttypes.Mount{
  138. {
  139. Type: mounttypes.TypeBind,
  140. Source: info.DockerRootDir,
  141. Target: "/foo",
  142. BindOptions: &mounttypes.BindOptions{Propagation: test.propagation},
  143. },
  144. },
  145. },
  146. "mount subpath": {
  147. Mounts: []mounttypes.Mount{
  148. {
  149. Type: mounttypes.TypeBind,
  150. Source: filepath.Join(info.DockerRootDir, "containers"),
  151. Target: "/foo",
  152. BindOptions: &mounttypes.BindOptions{Propagation: test.propagation},
  153. },
  154. },
  155. },
  156. } {
  157. t.Run(name, func(t *testing.T) {
  158. hc := hc
  159. t.Parallel()
  160. ctx := testutil.StartSpan(ctx, t)
  161. c, err := apiClient.ContainerCreate(ctx, &containertypes.Config{
  162. Image: "busybox",
  163. Cmd: []string{"true"},
  164. }, hc, nil, nil, "")
  165. if err != nil {
  166. if test.expected != "" {
  167. t.Fatal(err)
  168. }
  169. // expected an error, so this is ok and should not continue
  170. return
  171. }
  172. if test.expected == "" {
  173. t.Fatal("expected create to fail")
  174. }
  175. defer func() {
  176. if err := apiClient.ContainerRemove(ctx, c.ID, containertypes.RemoveOptions{Force: true}); err != nil {
  177. panic(err)
  178. }
  179. }()
  180. inspect, err := apiClient.ContainerInspect(ctx, c.ID)
  181. if err != nil {
  182. t.Fatal(err)
  183. }
  184. if len(inspect.Mounts) != 1 {
  185. t.Fatalf("unexpected number of mounts: %+v", inspect.Mounts)
  186. }
  187. m := inspect.Mounts[0]
  188. if m.Propagation != test.expected {
  189. t.Fatalf("got unexpected propagation mode, expected %q, got: %v", test.expected, m.Propagation)
  190. }
  191. })
  192. }
  193. })
  194. }
  195. }
  196. func TestContainerBindMountNonRecursive(t *testing.T) {
  197. skip.If(t, testEnv.IsRemoteDaemon)
  198. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.40"), "BindOptions.NonRecursive requires API v1.40")
  199. skip.If(t, testEnv.IsRootless, "cannot be tested because RootlessKit executes the daemon in private mount namespace (https://github.com/rootless-containers/rootlesskit/issues/97)")
  200. ctx := setupTest(t)
  201. tmpDir1 := fs.NewDir(t, "tmpdir1", fs.WithMode(0o755),
  202. fs.WithDir("mnt", fs.WithMode(0o755)))
  203. defer tmpDir1.Remove()
  204. tmpDir1Mnt := filepath.Join(tmpDir1.Path(), "mnt")
  205. tmpDir2 := fs.NewDir(t, "tmpdir2", fs.WithMode(0o755),
  206. fs.WithFile("file", "should not be visible when NonRecursive", fs.WithMode(0o644)))
  207. defer tmpDir2.Remove()
  208. err := mount.Mount(tmpDir2.Path(), tmpDir1Mnt, "none", "bind,ro")
  209. if err != nil {
  210. t.Fatal(err)
  211. }
  212. defer func() {
  213. if err := mount.Unmount(tmpDir1Mnt); err != nil {
  214. t.Fatal(err)
  215. }
  216. }()
  217. // implicit is recursive (NonRecursive: false)
  218. implicit := mounttypes.Mount{
  219. Type: "bind",
  220. Source: tmpDir1.Path(),
  221. Target: "/foo",
  222. ReadOnly: true,
  223. }
  224. recursive := implicit
  225. recursive.BindOptions = &mounttypes.BindOptions{
  226. NonRecursive: false,
  227. }
  228. recursiveVerifier := []string{"test", "-f", "/foo/mnt/file"}
  229. nonRecursive := implicit
  230. nonRecursive.BindOptions = &mounttypes.BindOptions{
  231. NonRecursive: true,
  232. }
  233. nonRecursiveVerifier := []string{"test", "!", "-f", "/foo/mnt/file"}
  234. apiClient := testEnv.APIClient()
  235. containers := []string{
  236. container.Run(ctx, t, apiClient, container.WithMount(implicit), container.WithCmd(recursiveVerifier...)),
  237. container.Run(ctx, t, apiClient, container.WithMount(recursive), container.WithCmd(recursiveVerifier...)),
  238. container.Run(ctx, t, apiClient, container.WithMount(nonRecursive), container.WithCmd(nonRecursiveVerifier...)),
  239. }
  240. for _, c := range containers {
  241. poll.WaitOn(t, container.IsSuccessful(ctx, apiClient, c), poll.WithDelay(100*time.Millisecond))
  242. }
  243. }
  244. func TestContainerVolumesMountedAsShared(t *testing.T) {
  245. // Volume propagation is linux only. Also it creates directories for
  246. // bind mounting, so needs to be same host.
  247. skip.If(t, testEnv.IsRemoteDaemon)
  248. skip.If(t, testEnv.IsUserNamespace)
  249. skip.If(t, testEnv.IsRootless, "cannot be tested because RootlessKit executes the daemon in private mount namespace (https://github.com/rootless-containers/rootlesskit/issues/97)")
  250. ctx := setupTest(t)
  251. // Prepare a source directory to bind mount
  252. tmpDir1 := fs.NewDir(t, "volume-source", fs.WithMode(0o755),
  253. fs.WithDir("mnt1", fs.WithMode(0o755)))
  254. defer tmpDir1.Remove()
  255. tmpDir1Mnt := filepath.Join(tmpDir1.Path(), "mnt1")
  256. // Convert this directory into a shared mount point so that we do
  257. // not rely on propagation properties of parent mount.
  258. if err := mount.MakePrivate(tmpDir1.Path()); err != nil {
  259. t.Fatal(err)
  260. }
  261. defer func() {
  262. if err := mount.Unmount(tmpDir1.Path()); err != nil {
  263. t.Fatal(err)
  264. }
  265. }()
  266. if err := mount.MakeShared(tmpDir1.Path()); err != nil {
  267. t.Fatal(err)
  268. }
  269. sharedMount := mounttypes.Mount{
  270. Type: mounttypes.TypeBind,
  271. Source: tmpDir1.Path(),
  272. Target: "/volume-dest",
  273. BindOptions: &mounttypes.BindOptions{
  274. Propagation: mounttypes.PropagationShared,
  275. },
  276. }
  277. bindMountCmd := []string{"mount", "--bind", "/volume-dest/mnt1", "/volume-dest/mnt1"}
  278. apiClient := testEnv.APIClient()
  279. containerID := container.Run(ctx, t, apiClient, container.WithPrivileged(true), container.WithMount(sharedMount), container.WithCmd(bindMountCmd...))
  280. poll.WaitOn(t, container.IsSuccessful(ctx, apiClient, containerID), poll.WithDelay(100*time.Millisecond))
  281. // Make sure a bind mount under a shared volume propagated to host.
  282. if mounted, _ := mountinfo.Mounted(tmpDir1Mnt); !mounted {
  283. t.Fatalf("Bind mount under shared volume did not propagate to host")
  284. }
  285. mount.Unmount(tmpDir1Mnt)
  286. }
  287. func TestContainerVolumesMountedAsSlave(t *testing.T) {
  288. // Volume propagation is linux only. Also it creates directories for
  289. // bind mounting, so needs to be same host.
  290. skip.If(t, testEnv.IsRemoteDaemon)
  291. skip.If(t, testEnv.IsUserNamespace)
  292. skip.If(t, testEnv.IsRootless, "cannot be tested because RootlessKit executes the daemon in private mount namespace (https://github.com/rootless-containers/rootlesskit/issues/97)")
  293. ctx := testutil.StartSpan(baseContext, t)
  294. // Prepare a source directory to bind mount
  295. tmpDir1 := fs.NewDir(t, "volume-source", fs.WithMode(0o755),
  296. fs.WithDir("mnt1", fs.WithMode(0o755)))
  297. defer tmpDir1.Remove()
  298. tmpDir1Mnt := filepath.Join(tmpDir1.Path(), "mnt1")
  299. // Prepare a source directory with file in it. We will bind mount this
  300. // directory and see if file shows up.
  301. tmpDir2 := fs.NewDir(t, "volume-source2", fs.WithMode(0o755),
  302. fs.WithFile("slave-testfile", "Test", fs.WithMode(0o644)))
  303. defer tmpDir2.Remove()
  304. // Convert this directory into a shared mount point so that we do
  305. // not rely on propagation properties of parent mount.
  306. if err := mount.MakePrivate(tmpDir1.Path()); err != nil {
  307. t.Fatal(err)
  308. }
  309. defer func() {
  310. if err := mount.Unmount(tmpDir1.Path()); err != nil {
  311. t.Fatal(err)
  312. }
  313. }()
  314. if err := mount.MakeShared(tmpDir1.Path()); err != nil {
  315. t.Fatal(err)
  316. }
  317. slaveMount := mounttypes.Mount{
  318. Type: mounttypes.TypeBind,
  319. Source: tmpDir1.Path(),
  320. Target: "/volume-dest",
  321. BindOptions: &mounttypes.BindOptions{
  322. Propagation: mounttypes.PropagationSlave,
  323. },
  324. }
  325. topCmd := []string{"top"}
  326. apiClient := testEnv.APIClient()
  327. containerID := container.Run(ctx, t, apiClient, container.WithTty(true), container.WithMount(slaveMount), container.WithCmd(topCmd...))
  328. // Bind mount tmpDir2/ onto tmpDir1/mnt1. If mount propagates inside
  329. // container then contents of tmpDir2/slave-testfile should become
  330. // visible at "/volume-dest/mnt1/slave-testfile"
  331. if err := mount.Mount(tmpDir2.Path(), tmpDir1Mnt, "none", "bind"); err != nil {
  332. t.Fatal(err)
  333. }
  334. defer func() {
  335. if err := mount.Unmount(tmpDir1Mnt); err != nil {
  336. t.Fatal(err)
  337. }
  338. }()
  339. mountCmd := []string{"cat", "/volume-dest/mnt1/slave-testfile"}
  340. if result, err := container.Exec(ctx, apiClient, containerID, mountCmd); err == nil {
  341. if result.Stdout() != "Test" {
  342. t.Fatalf("Bind mount under slave volume did not propagate to container")
  343. }
  344. } else {
  345. t.Fatal(err)
  346. }
  347. }
  348. // Regression test for #38995 and #43390.
  349. func TestContainerCopyLeaksMounts(t *testing.T) {
  350. ctx := setupTest(t)
  351. bindMount := mounttypes.Mount{
  352. Type: mounttypes.TypeBind,
  353. Source: "/var",
  354. Target: "/hostvar",
  355. BindOptions: &mounttypes.BindOptions{
  356. Propagation: mounttypes.PropagationRSlave,
  357. },
  358. }
  359. apiClient := testEnv.APIClient()
  360. cid := container.Run(ctx, t, apiClient, container.WithMount(bindMount), container.WithCmd("sleep", "120s"))
  361. getMounts := func() string {
  362. t.Helper()
  363. res, err := container.Exec(ctx, apiClient, cid, []string{"cat", "/proc/self/mountinfo"})
  364. assert.NilError(t, err)
  365. assert.Equal(t, res.ExitCode, 0)
  366. return res.Stdout()
  367. }
  368. mountsBefore := getMounts()
  369. _, _, err := apiClient.CopyFromContainer(ctx, cid, "/etc/passwd")
  370. assert.NilError(t, err)
  371. mountsAfter := getMounts()
  372. assert.Equal(t, mountsBefore, mountsAfter)
  373. }
  374. func TestContainerBindMountRecursivelyReadOnly(t *testing.T) {
  375. skip.If(t, testEnv.IsRemoteDaemon)
  376. skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.44"), "requires API v1.44")
  377. ctx := setupTest(t)
  378. // 0o777 for allowing rootless containers to write to this directory
  379. tmpDir1 := fs.NewDir(t, "tmpdir1", fs.WithMode(0o777),
  380. fs.WithDir("mnt", fs.WithMode(0o777)))
  381. defer tmpDir1.Remove()
  382. tmpDir1Mnt := filepath.Join(tmpDir1.Path(), "mnt")
  383. tmpDir2 := fs.NewDir(t, "tmpdir2", fs.WithMode(0o777),
  384. fs.WithFile("file", "should not be writable when recursively read only", fs.WithMode(0o666)))
  385. defer tmpDir2.Remove()
  386. if err := mount.Mount(tmpDir2.Path(), tmpDir1Mnt, "none", "bind"); err != nil {
  387. t.Fatal(err)
  388. }
  389. defer func() {
  390. if err := mount.Unmount(tmpDir1Mnt); err != nil {
  391. t.Fatal(err)
  392. }
  393. }()
  394. rroSupported := kernel.CheckKernelVersion(5, 12, 0)
  395. nonRecursiveVerifier := []string{`/bin/sh`, `-xc`, `touch /foo/mnt/file; [ $? = 0 ]`}
  396. forceRecursiveVerifier := []string{`/bin/sh`, `-xc`, `touch /foo/mnt/file; [ $? != 0 ]`}
  397. // ro (recursive if kernel >= 5.12)
  398. ro := mounttypes.Mount{
  399. Type: mounttypes.TypeBind,
  400. Source: tmpDir1.Path(),
  401. Target: "/foo",
  402. ReadOnly: true,
  403. BindOptions: &mounttypes.BindOptions{
  404. Propagation: mounttypes.PropagationRPrivate,
  405. },
  406. }
  407. roAsStr := ro.Source + ":" + ro.Target + ":ro,rprivate"
  408. roVerifier := nonRecursiveVerifier
  409. if rroSupported {
  410. roVerifier = forceRecursiveVerifier
  411. }
  412. // Non-recursive
  413. nonRecursive := ro
  414. nonRecursive.BindOptions = &mounttypes.BindOptions{
  415. ReadOnlyNonRecursive: true,
  416. Propagation: mounttypes.PropagationRPrivate,
  417. }
  418. // Force recursive
  419. forceRecursive := ro
  420. forceRecursive.BindOptions = &mounttypes.BindOptions{
  421. ReadOnlyForceRecursive: true,
  422. Propagation: mounttypes.PropagationRPrivate,
  423. }
  424. apiClient := testEnv.APIClient()
  425. containers := []string{
  426. container.Run(ctx, t, apiClient, container.WithMount(ro), container.WithCmd(roVerifier...)),
  427. container.Run(ctx, t, apiClient, container.WithBindRaw(roAsStr), container.WithCmd(roVerifier...)),
  428. container.Run(ctx, t, apiClient, container.WithMount(nonRecursive), container.WithCmd(nonRecursiveVerifier...)),
  429. }
  430. if rroSupported {
  431. containers = append(containers,
  432. container.Run(ctx, t, apiClient, container.WithMount(forceRecursive), container.WithCmd(forceRecursiveVerifier...)),
  433. )
  434. }
  435. for _, c := range containers {
  436. poll.WaitOn(t, container.IsSuccessful(ctx, apiClient, c), poll.WithDelay(100*time.Millisecond))
  437. }
  438. }