mounts_linux_test.go 15 KB

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