Debian Codegraph @

pathrs-lite/mkdir_linux_test.go

raw ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 // SPDX-License-Identifier: MPL-2.0
2
3 //go:build linux
4
5 // Copyright (C) 2024-2025 Aleksa Sarai <[email protected]>
6 // Copyright (C) 2024-2025 SUSE LLC
7 //
8 // This Source Code Form is subject to the terms of the Mozilla Public
9 // License, v. 2.0. If a copy of the MPL was not distributed with this
10 // file, You can obtain one at https://mozilla.org/MPL/2.0/.
11
12 package pathrs
13
14 import (
15 "errors"
16 "fmt"
17 "os"
18 "path/filepath"
19 "runtime"
20 "sync"
21 "testing"
22
23 "github.com/stretchr/testify/assert"
24 "github.com/stretchr/testify/require"
25 "golang.org/x/sys/unix"
26
27 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal"
28 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/fd"
29 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/procfs"
30 "github.com/cyphar/filepath-securejoin/pathrs-lite/internal/testutils"
31 )
32
33 type mkdirAllFunc func(t *testing.T, root, unsafePath string, mode os.FileMode) error
34
35 var mkdirAll_MkdirAll mkdirAllFunc = func(_ *testing.T, root, unsafePath string, mode os.FileMode) error { //nolint:revive // underscores are more readable for test helpers
36 // We can't check expectedPath here.
37 return MkdirAll(root, unsafePath, mode)
38 }
39
40 var mkdirAll_MkdirAllHandle mkdirAllFunc = func(t *testing.T, root, unsafePath string, mode os.FileMode) error { //nolint:revive // underscores are more readable for test helpers
41 // Same logic as MkdirAll.
42 rootDir, err := os.OpenFile(root, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
43 if err != nil {
44 return err
45 }
46 defer rootDir.Close() //nolint:errcheck // test code
47 handle, err := MkdirAllHandle(rootDir, unsafePath, mode)
48 if err != nil {
49 return err
50 }
51 defer handle.Close() //nolint:errcheck // test code
52
53 // We can lookup the expected path again to get the full path. This will
54 // give a reasonable result because we aren't being attacked in this
55 // particular test.
56 handle2, err := OpenatInRoot(rootDir, unsafePath)
57 require.NoError(t, err)
58 expectedPath, err := procfs.ProcSelfFdReadlink(handle2)
59 require.NoError(t, err)
60
61 // Now double-check that the handle is correct.
62 gotPath, err := procfs.ProcSelfFdReadlink(handle)
63 require.NoError(t, err, "get real path of returned handle")
64 assert.Equal(t, expectedPath, gotPath, "wrong final path from MkdirAllHandle")
65 // Also check that the f.Name() is correct while we're at it (this is
66 // not always guaranteed but it's better to try at least).
67 assert.Equal(t, expectedPath, handle.Name(), "handle from MkdirAllHandle has the wrong .Name()")
68 return nil
69 }
70
71 func checkMkdirAll(t *testing.T, mkdirAll mkdirAllFunc, root, unsafePath string, mode os.FileMode, expectedMode int, expectedErr error) {
72 rootDir, err := os.OpenFile(root, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
73 require.NoError(t, err)
74 defer rootDir.Close() //nolint:errcheck // test code
75
76 // Before trying to make the tree, figure out what components don't exist
77 // yet so we can check them later.
78 handle, remainingPath, err := partialLookupInRoot(rootDir, unsafePath)
79 handleName := "<nil>"
80 if handle != nil {
81 handleName = handle.Name()
82 defer handle.Close() //nolint:errcheck // test code
83 }
84 defer func() {
85 if t.Failed() {
86 t.Logf("partialLookupInRoot(%s, %s) -> (<%s>, %s, %v)", root, unsafePath, handleName, remainingPath, err)
87 }
88 }()
89
90 // Actually make the tree.
91 err = mkdirAll(t, root, unsafePath, mode)
92 require.ErrorIsf(t, err, expectedErr, "MkdirAll(%q, %q)", root, unsafePath)
93
94 remainingPath = filepath.Join("/", remainingPath)
95 for remainingPath != filepath.Dir(remainingPath) {
96 stat, err := fd.Fstatat(handle, "./"+remainingPath, unix.AT_SYMLINK_NOFOLLOW)
97 if expectedErr == nil {
98 // Check that the new components have the right mode.
99 if assert.NoErrorf(t, err, "unexpected error when checking new directory %q", remainingPath) {
100 assert.Equalf(t, uint32(unix.S_IFDIR|expectedMode), stat.Mode, "new directory %q has the wrong mode", remainingPath)
101 }
102 } else {
103 // Check that none of the components are directories (i.e. make
104 // sure that the MkdirAll was a no-op).
105 if err == nil {
106 assert.NotEqualf(t, uint32(unix.S_IFDIR), stat.Mode&unix.S_IFMT, "failed MkdirAll created a new directory at %q", remainingPath)
107 }
108 }
109 // Jump up a level.
110 remainingPath = filepath.Dir(remainingPath)
111 }
112 }
113
114 func testMkdirAll_Basic(t *testing.T, mkdirAll mkdirAllFunc) { //nolint:revive // underscores are more readable for test helpers
115 // We create a new tree for each test, but the template is the same.
116 tree := []string{
117 "dir a",
118 "dir b/c/d/e/f",
119 "file b/c/file",
120 "symlink e /b/c/d/e",
121 "symlink b-file b/c/file",
122 // Dangling symlinks.
123 "symlink a-fake1 a/fake",
124 "symlink a-fake2 a/fake/foo/bar/..",
125 "symlink a-fake3 a/fake/../../b",
126 // Test non-lexical symlinks.
127 "dir target",
128 "dir link1",
129 "symlink link1/target_abs /target",
130 "symlink link1/target_rel ../target",
131 "dir link2",
132 "symlink link2/link1_abs /link1",
133 "symlink link2/link1_rel ../link1",
134 "dir link3",
135 "symlink link3/target_abs /link2/link1_rel/target_rel",
136 "symlink link3/target_rel ../link2/link1_rel/target_rel",
137 "symlink link3/deep_dangling1 ../link2/link1_rel/target_rel/nonexist",
138 "symlink link3/deep_dangling2 ../link2/link1_rel/target_rel/nonexist",
139 // Symlink loop.
140 "dir loop",
141 "symlink loop/link ../loop/link",
142 // S_ISGID directory.
143 "dir sgid-self ::2755",
144 "dir sgid-sticky-self ::3755",
145 }
146
147 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
148 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
149 for name, test := range map[string]struct {
150 unsafePath string
151 expectedErr error
152 expectedModeBits int
153 }{
154 "existing": {unsafePath: "a"},
155 "basic": {unsafePath: "a/b/c/d/e/f/g/h/i/j"},
156 "dotdot-in-nonexisting": {unsafePath: "a/b/c/d/e/f/g/h/i/j/k/../lmnop", expectedErr: unix.ENOENT},
157 "dotdot-in-existing": {unsafePath: "b/c/../c/./d/e/f/g/h"},
158 "dotdot-after-symlink": {unsafePath: "e/../dd/ee/ff"},
159 // Check that trying to create under a file fails.
160 "nondir-trailing": {unsafePath: "b/c/file", expectedErr: unix.ENOTDIR},
161 "nondir-dotdot": {unsafePath: "b/c/file/../d", expectedErr: unix.ENOTDIR},
162 "nondir-subdir": {unsafePath: "b/c/file/subdir", expectedErr: unix.ENOTDIR},
163 "nondir-symlink-trailing": {unsafePath: "b-file", expectedErr: unix.ENOTDIR},
164 "nondir-symlink-dotdot": {unsafePath: "b-file/../d", expectedErr: unix.ENOTDIR},
165 "nondir-symlink-subdir": {unsafePath: "b-file/subdir", expectedErr: unix.ENOTDIR},
166 // Dangling symlinks are not followed.
167 "dangling1-trailing": {unsafePath: "a-fake1", expectedErr: unix.ENOTDIR},
168 "dangling1-basic": {unsafePath: "a-fake1/foo", expectedErr: unix.ENOTDIR},
169 "dangling1-dotdot": {unsafePath: "a-fake1/../bar/baz", expectedErr: unix.ENOENT},
170 "dangling2-trailing": {unsafePath: "a-fake2", expectedErr: unix.ENOTDIR},
171 "dangling2-basic": {unsafePath: "a-fake2/foo", expectedErr: unix.ENOTDIR},
172 "dangling2-dotdot": {unsafePath: "a-fake2/../bar/baz", expectedErr: unix.ENOENT},
173 "dangling3-trailing": {unsafePath: "a-fake3", expectedErr: unix.ENOTDIR},
174 "dangling3-basic": {unsafePath: "a-fake3/foo", expectedErr: unix.ENOTDIR},
175 "dangling3-dotdot": {unsafePath: "a-fake3/../bar/baz", expectedErr: unix.ENOENT},
176 // Non-lexical symlinks should work.
177 "nonlexical-basic": {unsafePath: "target/foo"},
178 "nonlexical-level1-abs": {unsafePath: "link1/target_abs/foo"},
179 "nonlexical-level1-rel": {unsafePath: "link1/target_rel/foo"},
180 "nonlexical-level2-abs-abs": {unsafePath: "link2/link1_abs/target_abs/foo"},
181 "nonlexical-level2-abs-rel": {unsafePath: "link2/link1_abs/target_rel/foo"},
182 "nonlexical-level2-abs-open": {unsafePath: "link2/link1_abs/../target/foo"},
183 "nonlexical-level2-rel-abs": {unsafePath: "link2/link1_rel/target_abs/foo"},
184 "nonlexical-level2-rel-rel": {unsafePath: "link2/link1_rel/target_rel/foo"},
185 "nonlexical-level2-rel-open": {unsafePath: "link2/link1_rel/../target/foo"},
186 "nonlexical-level3-abs": {unsafePath: "link3/target_abs/foo"},
187 "nonlexical-level3-rel": {unsafePath: "link3/target_rel/foo"},
188 // But really tricky dangling symlinks should fail.
189 "dangling-tricky1-trailing": {unsafePath: "link3/deep_dangling1", expectedErr: unix.ENOTDIR},
190 "dangling-tricky1-basic": {unsafePath: "link3/deep_dangling1/foo", expectedErr: unix.ENOTDIR},
191 "dangling-tricky1-dotdot": {unsafePath: "link3/deep_dangling1/../bar", expectedErr: unix.ENOENT},
192 "dangling-tricky2-trailing": {unsafePath: "link3/deep_dangling2", expectedErr: unix.ENOTDIR},
193 "dangling-tricky2-basic": {unsafePath: "link3/deep_dangling2/foo", expectedErr: unix.ENOTDIR},
194 "dangling-tricky2-dotdot": {unsafePath: "link3/deep_dangling2/../bar", expectedErr: unix.ENOENT},
195 // And trying to mkdir inside a loop should fail.
196 "loop-trailing": {unsafePath: "loop/link", expectedErr: unix.ELOOP},
197 "loop-basic": {unsafePath: "loop/link/foo", expectedErr: unix.ELOOP},
198 "loop-dotdot": {unsafePath: "loop/link/../foo", expectedErr: unix.ELOOP},
199 // Make sure the S_ISGID handling is correct.
200 "sgid-dir-ownedbyus": {unsafePath: "sgid-self/foo/bar/baz", expectedModeBits: unix.S_ISGID},
201 "sgid-sticky-dir-ownedbyus": {unsafePath: "sgid-sticky-self/foo/bar/baz", expectedModeBits: unix.S_ISGID},
202 } {
203 test := test // copy iterator
204 t.Run(name, func(t *testing.T) {
205 root := testutils.CreateTree(t, tree...)
206 const mode = 0o711
207 checkMkdirAll(t, mkdirAll, root, test.unsafePath, mode, test.expectedModeBits|mode, test.expectedErr)
208 })
209 }
210 })
211 }
212
213 func TestMkdirAll_Basic(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
214 testMkdirAll_Basic(t, mkdirAll_MkdirAll)
215 }
216
217 func TestMkdirAllHandle_Basic(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
218 testMkdirAll_Basic(t, mkdirAll_MkdirAllHandle)
219 }
220
221 func testMkdirAll_AsRoot(t *testing.T, mkdirAll mkdirAllFunc) { //nolint:revive // underscores are more readable for test helpers
222 testutils.RequireRoot(t) // chown
223
224 // We create a new tree for each test, but the template is the same.
225 tree := []string{
226 // S_ISGID directories.
227 "dir sgid-self ::2755",
228 "dir sgid-other 1000:1000:2755",
229 "dir sgid-sticky-self ::3755",
230 "dir sgid-sticky-other 1000:1000:3755",
231 }
232
233 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
234 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
235 for name, test := range map[string]struct {
236 unsafePath string
237 expectedErr error
238 expectedModeBits int
239 }{
240 // Make sure the S_ISGID handling is correct.
241 "sgid-dir-ownedbyus": {unsafePath: "sgid-self/foo/bar/baz", expectedModeBits: unix.S_ISGID},
242 "sgid-dir-ownedbyother": {unsafePath: "sgid-other/foo/bar/baz", expectedModeBits: unix.S_ISGID},
243 "sgid-sticky-dir-ownedbyus": {unsafePath: "sgid-sticky-self/foo/bar/baz", expectedModeBits: unix.S_ISGID},
244 "sgid-sticky-dir-ownedbyother": {unsafePath: "sgid-sticky-other/foo/bar/baz", expectedModeBits: unix.S_ISGID},
245 } {
246 test := test // copy iterator
247 t.Run(name, func(t *testing.T) {
248 root := testutils.CreateTree(t, tree...)
249 const mode = 0o711
250 checkMkdirAll(t, mkdirAll, root, test.unsafePath, mode, test.expectedModeBits|mode, test.expectedErr)
251 })
252 }
253 })
254 }
255
256 func TestMkdirAll_AsRoot(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
257 testMkdirAll_AsRoot(t, mkdirAll_MkdirAll)
258 }
259
260 func TestMkdirAllHandle_AsRoot(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
261 testMkdirAll_AsRoot(t, mkdirAll_MkdirAllHandle)
262 }
263
264 func testMkdirAll_InvalidMode(t *testing.T, mkdirAll mkdirAllFunc) { //nolint:revive // underscores are more readable for test helpers
265 for _, test := range []struct {
266 mode os.FileMode
267 expectedErr error
268 }{
269 // unix.S_IS* bits are invalid.
270 {unix.S_ISUID | 0o777, errInvalidMode},
271 {unix.S_ISGID | 0o777, errInvalidMode},
272 {unix.S_ISVTX | 0o777, errInvalidMode},
273 {unix.S_ISUID | unix.S_ISGID | unix.S_ISVTX | 0o777, errInvalidMode},
274 // unix.S_IFMT bits are also invalid.
275 {unix.S_IFDIR | 0o777, errInvalidMode},
276 {unix.S_IFREG | 0o777, errInvalidMode},
277 {unix.S_IFIFO | 0o777, errInvalidMode},
278 // os.FileType bits are also invalid.
279 {os.ModeDir | 0o777, errInvalidMode},
280 {os.ModeNamedPipe | 0o777, errInvalidMode},
281 {os.ModeIrregular | 0o777, errInvalidMode},
282 // suid/sgid bits are silently ignored by mkdirat and so we return an
283 // error explicitly.
284 {os.ModeSetuid | 0o777, errInvalidMode},
285 {os.ModeSetgid | 0o777, errInvalidMode},
286 {os.ModeSetuid | os.ModeSetgid | os.ModeSticky | 0o777, errInvalidMode},
287 // Proper sticky bit should work.
288 {os.ModeSticky | 0o777, nil},
289 // Regular mode bits.
290 {0o777, nil},
291 {0o711, nil},
292 } {
293 root := t.TempDir()
294 err := mkdirAll(t, root, "a/b/c", test.mode)
295 assert.ErrorIsf(t, err, test.expectedErr, "mkdirall %+.3o (%s)", test.mode, test.mode)
296 }
297 }
298
299 func TestMkdirAll_InvalidMode(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
300 testMkdirAll_InvalidMode(t, mkdirAll_MkdirAll)
301 }
302
303 func TestMkdirAllHandle_InvalidMode(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
304 testMkdirAll_InvalidMode(t, mkdirAll_MkdirAllHandle)
305 }
306
307 type racingMkdirMeta struct {
308 passOkCount, passErrCount, failCount int
309 passErrCounts map[error]int
310 }
311
312 func newRacingMkdirMeta() *racingMkdirMeta {
313 return &racingMkdirMeta{
314 passErrCounts: map[error]int{},
315 }
316 }
317
318 func (m *racingMkdirMeta) checkMkdirAllHandle_Racing(t *testing.T, root, unsafePath string, mode os.FileMode, allowedErrs []error) { //nolint:revive // underscores are more readable for test helpers
319 rootDir, err := os.OpenFile(root, unix.O_PATH|unix.O_DIRECTORY|unix.O_CLOEXEC, 0)
320 if !assert.NoError(t, err, "open root") { //nolint:testifylint // cannot use require.* in goroutines
321 m.failCount++
322 return
323 }
324 defer rootDir.Close() //nolint:errcheck // test code
325
326 handle, err := MkdirAllHandle(rootDir, unsafePath, mode)
327 if err != nil {
328 for _, allowedErr := range allowedErrs {
329 if errors.Is(err, allowedErr) {
330 m.passErrCounts[allowedErr]++
331 m.passErrCount++
332 return
333 }
334 }
335 assert.NoError(t, err)
336 m.failCount++
337 return
338 }
339 defer handle.Close() //nolint:errcheck // test code
340
341 // It's possible for an attacker to have swapped the final directory, but
342 // this is okay because MkdirAll will use pre-existing directories anyway.
343 // So there's no need to check the returned handle.
344 // TODO: Does it make sense to even try to check the handle path?
345 m.passOkCount++
346 }
347
348 func TestMkdirAllHandle_RacingRename(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
349 if testing.Short() {
350 t.Skip("skipping race tests in short mode")
351 }
352 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
353 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
354 treeSpec := []string{
355 "dir target/a/b/c",
356 "dir swapdir-empty-ok ::0711",
357 "dir swapdir-empty-badmode ::0777",
358 "dir swapdir-nonempty1 ::0711",
359 "file swapdir-nonempty1/aaa",
360 "dir swapdir-nonempty2 ::0711",
361 "dir swapdir-nonempty2/f ::0711",
362 "file swapfile foobar ::0711",
363 }
364
365 type test struct {
366 name string
367 pathA, pathB string
368 unsafePath string
369 allowedErrs []error
370 }
371
372 tests := []test{
373 {"good", "target/a/b/c/d/e", "swapdir-empty-ok", "target/a/b/c/d/e/f/g/h/i/j/k", nil},
374 {"trailing", "target/a/b/c/d/e", "swapdir-empty-badmode", "target/a/b/c/d/e", nil},
375 {"partial", "target/a/b/c/d/e", "swapdir-empty-badmode", "target/a/b/c/d/e/f/g/h/i/j/k", nil},
376 {"trailing", "target/a/b/c/d/e", "swapdir-nonempty1", "target/a/b/c/d/e", nil},
377 {"partial", "target/a/b/c/d/e", "swapdir-nonempty1", "target/a/b/c/d/e/f/g/h/i/j/k", nil},
378 {"trailing", "target/a/b/c/d/e", "swapdir-nonempty2", "target/a/b/c/d/e", nil},
379 {"partial", "target/a/b/c/d/e", "swapdir-nonempty2", "target/a/b/c/d/e/f/g/h/i/j/k", []error{unix.ENOTDIR}},
380 {"trailing", "target/a/b/c/d/e", "swapfile", "target/a/b/c/d/e", []error{unix.ENOTDIR}},
381 {"partial", "target/a/b/c/d/e", "swapfile", "target/a/b/c/d/e/f/g/h/i/j/k", []error{unix.ENOTDIR}},
382 }
383
384 if unix.Geteuid() == 0 {
385 // Add some wrong-uid cases if we are root.
386 treeSpec = append(treeSpec,
387 "dir swapdir-empty-badowner1 123:0:0711",
388 "dir swapdir-empty-badowner2 0:456:0711",
389 "dir swapdir-empty-badowner3 111:222:0711",
390 )
391 tests = append(tests, []test{
392 {"trailing", "target/a/b/c/d/e", "swapdir-empty-badowner1", "target/a/b/c/d/e", nil},
393 {"partial", "target/a/b/c/d/e", "swapdir-empty-badowner1", "target/a/b/c/d/e/f/g/h/i/j/k", nil},
394 {"trailing", "target/a/b/c/d/e", "swapdir-empty-badowner2", "target/a/b/c/d/e", nil},
395 {"partial", "target/a/b/c/d/e", "swapdir-empty-badowner2", "target/a/b/c/d/e/f/g/h/i/j/k", nil},
396 {"trailing", "target/a/b/c/d/e", "swapdir-empty-badowner3", "target/a/b/c/d/e", nil},
397 {"partial", "target/a/b/c/d/e", "swapdir-empty-badowner3", "target/a/b/c/d/e/f/g/h/i/j/k", nil},
398 }...)
399 }
400
401 for _, test := range tests {
402 test := test // copy iterator
403 t.Run(fmt.Sprintf("%s-%s", test.pathB, test.name), func(t *testing.T) {
404 rootCh := make(chan string)
405 defer close(rootCh)
406 go func(rootCh <-chan string) {
407 var root string
408 for {
409 select {
410 case newRoot, ok := <-rootCh:
411 if !ok {
412 return
413 }
414 root = newRoot
415 default:
416 if root != "" {
417 pathA := filepath.Join(root, test.pathA)
418 pathB := filepath.Join(root, test.pathB)
419 _ = unix.Renameat2(unix.AT_FDCWD, pathA, unix.AT_FDCWD, pathB, unix.RENAME_EXCHANGE)
420 }
421 }
422 }
423 }(rootCh)
424
425 // Do several runs to try to catch bugs.
426 const (
427 testRuns = 800
428 minPassCount = 10
429 )
430 m := newRacingMkdirMeta()
431 doneRuns := 0
432 for ; doneRuns < testRuns || m.passOkCount < minPassCount; doneRuns++ {
433 root := testutils.CreateTree(t, treeSpec...)
434
435 rootCh <- root
436 runtime.Gosched() // give the thread some time to do a rename
437 m.checkMkdirAllHandle_Racing(t, root, test.unsafePath, 0o711, test.allowedErrs)
438 rootCh <- ""
439
440 // Clean up the root after each run so we don't exhaust all
441 // space in the tmpfs.
442 _ = os.RemoveAll(root)
443
444 // Make sure we don't infinite loop here.
445 if doneRuns >= 50*testRuns {
446 break
447 }
448 }
449
450 pct := func(count int) string {
451 return fmt.Sprintf("%d(%.3f%%)", count, 100.0*float64(count)/float64(doneRuns))
452 }
453
454 // No passing runs is a bit unfortunate, but some of our tests
455 // can do that and failing here would just lead to flaky tests.
456 if m.passOkCount == 0 {
457 t.Logf("WARNING: NO PASSING RUNS!")
458 }
459
460 // Output some stats.
461 t.Logf("after %d runs: passOk=%s passErr=%s fail=%s",
462 doneRuns, pct(m.passOkCount), pct(m.passErrCount), pct(m.failCount))
463 if len(m.passErrCounts) > 0 {
464 t.Logf(" passErr breakdown:")
465 for err, count := range m.passErrCounts {
466 t.Logf(" %3.d: %v", count, err)
467 }
468 }
469 })
470 }
471 })
472 }
473
474 func TestMkdirAllHandle_RacingDelete(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
475 if testing.Short() {
476 t.Skip("skipping race tests in short mode")
477 }
478 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
479 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
480 treeSpec := []string{
481 "dir target/a/b/c",
482 }
483
484 for _, test := range []struct {
485 name string
486 rmPath string
487 unsafePath string
488 allowedErrs []error
489 }{
490 {"rm-top", "target", "target/a/b/c/d/e/f/g/h/i/j/k", []error{internal.ErrInvalidDirectory, unix.ENOENT}},
491 {"rm-existing", "target/a/b/c", "target/a/b/c/d/e/f/g/h/i/j/k", []error{internal.ErrInvalidDirectory, unix.ENOENT}},
492 {"rm-nonexisting", "target/a/b/c/d/e", "target/a/b/c/d/e/f/g/h/i/j/k", []error{internal.ErrInvalidDirectory, unix.ENOENT}},
493 } {
494 test := test // copy iterator
495 t.Run(test.rmPath, func(t *testing.T) {
496 rootCh := make(chan string)
497 defer close(rootCh)
498 go func(rootCh <-chan string) {
499 var root string
500 for {
501 select {
502 case newRoot, ok := <-rootCh:
503 if !ok {
504 return
505 }
506 root = newRoot
507 default:
508 if root != "" {
509 _ = os.RemoveAll(filepath.Join(root, test.rmPath))
510 }
511 }
512 }
513 }(rootCh)
514
515 // Do several runs to try to catch bugs.
516 const (
517 testRuns = 800
518 minPassCount = 10
519 )
520 m := newRacingMkdirMeta()
521 doneRuns := 0
522 for ; doneRuns < testRuns; doneRuns++ {
523 root := testutils.CreateTree(t, treeSpec...)
524
525 rootCh <- root
526 m.checkMkdirAllHandle_Racing(t, root, test.unsafePath, 0o711, test.allowedErrs)
527 rootCh <- ""
528
529 // Clean up the root after each run so we don't exhaust all
530 // space in the tmpfs.
531 _ = os.RemoveAll(root + "/..")
532
533 // Make sure we don't infinite loop here.
534 if doneRuns >= 50*testRuns {
535 break
536 }
537 }
538
539 pct := func(count int) string {
540 return fmt.Sprintf("%d(%.3f%%)", count, 100.0*float64(count)/float64(doneRuns))
541 }
542
543 // No passing runs is a bit unfortunate, but some of our tests
544 // can do that and failing here would just lead to flaky tests.
545 if m.passOkCount == 0 {
546 t.Logf("WARNING: NO PASSING RUNS!")
547 }
548
549 // Output some stats.
550 t.Logf("after %d runs: passOk=%s passErr=%s fail=%s",
551 doneRuns, pct(m.passOkCount), pct(m.passErrCount), pct(m.failCount))
552 if len(m.passErrCounts) > 0 {
553 t.Logf(" passErr breakdown:")
554 for err, count := range m.passErrCounts {
555 t.Logf(" %3.d: %v", count, err)
556 }
557 }
558 })
559 }
560 })
561 }
562
563 // Regression test for <https://github.com/opencontainers/runc/issues/4543>.
564 func TestMkdirAllHandle_RacingCreate(t *testing.T) { //nolint:revive // underscores are more readable for test helpers
565 if testing.Short() {
566 t.Skip("skipping race tests in short mode")
567 }
568 testutils.WithWithoutOpenat2(true, tRunWrapper(t), func(ti testutils.TestingT) {
569 t := ti.(*testing.T) //nolint:forcetypeassert // guaranteed to be true and in test code
570 threadRanges := []int{2, 4, 8, 16, 32, 64, 128, 512, 1024}
571 for _, numThreads := range threadRanges {
572 numThreads := numThreads
573 t.Run(fmt.Sprintf("threads=%d", numThreads), func(t *testing.T) {
574 // Do several runs to try to catch bugs.
575 const testRuns = 500
576 m := newRacingMkdirMeta()
577 for i := 0; i < testRuns; i++ {
578 root := t.TempDir()
579 unsafePath := "a/b/c/d/e/f/g/h/i/j/k/l/m/n/o/p/q/r/s/t/u/v/x/y/z"
580
581 // Spawn many threads that will race against each other to
582 // create the same directory.
583 startCh := make(chan struct{})
584 var finishedWg sync.WaitGroup
585 for i := 0; i < numThreads; i++ {
586 finishedWg.Add(1)
587 go func() {
588 <-startCh
589 m.checkMkdirAllHandle_Racing(t, root, unsafePath, 0o711, nil)
590 finishedWg.Done()
591 }()
592 }
593
594 // Start all of the threads at the same time.
595 close(startCh)
596
597 // Wait for all of the racing threads to finish.
598 finishedWg.Wait()
599
600 // Clean up the root after each run so we don't exhaust all
601 // space in the tmpfs.
602 _ = os.RemoveAll(root)
603 }
604 })
605 }
606 })
607 }