mounts_linux_test.go 16 KB

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