Debian Codegraph @

user/idtools_unix_test.go

raw symbols SCIP
1 //go:build !windows
2
3 package user
4
5 import (
6 "errors"
7 "fmt"
8 "os"
9 "path/filepath"
10 "testing"
11
12 "golang.org/x/sys/unix"
13 )
14
15 type node struct {
16 uid int
17 gid int
18 }
19
20 func TestMkdirAllAndChown(t *testing.T) {
21 requiresRoot(t)
22 dirName := t.TempDir()
23
24 testTree := map[string]node{
25 "usr": {0, 0},
26 "usr/bin": {0, 0},
27 "lib": {33, 33},
28 "lib/x86_64": {45, 45},
29 "lib/x86_64/share": {1, 1},
30 }
31
32 if err := buildTree(dirName, testTree); err != nil {
33 t.Fatal(err)
34 }
35
36 // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid
37 if err := MkdirAllAndChown(filepath.Join(dirName, "usr", "share"), 0o755, 99, 99); err != nil {
38 t.Fatal(err)
39 }
40 testTree["usr/share"] = node{99, 99}
41 verifyTree, err := readTree(dirName, "")
42 if err != nil {
43 t.Fatal(err)
44 }
45 compareTrees(t, testTree, verifyTree)
46
47 // test 2-deep new directories--both should be owned by the uid/gid pair
48 if err := MkdirAllAndChown(filepath.Join(dirName, "lib", "some", "other"), 0o755, 101, 101); err != nil {
49 t.Fatal(err)
50 }
51 testTree["lib/some"] = node{101, 101}
52 testTree["lib/some/other"] = node{101, 101}
53 verifyTree, err = readTree(dirName, "")
54 if err != nil {
55 t.Fatal(err)
56 }
57 compareTrees(t, testTree, verifyTree)
58
59 // test a directory that already exists; should be chowned, but nothing else
60 if err := MkdirAllAndChown(filepath.Join(dirName, "usr"), 0o755, 102, 102); err != nil {
61 t.Fatal(err)
62 }
63 testTree["usr"] = node{102, 102}
64 verifyTree, err = readTree(dirName, "")
65 if err != nil {
66 t.Fatal(err)
67 }
68 compareTrees(t, testTree, verifyTree)
69 }
70
71 func TestMkdirAllAndChownNew(t *testing.T) {
72 requiresRoot(t)
73 dirName := t.TempDir()
74
75 testTree := map[string]node{
76 "usr": {0, 0},
77 "usr/bin": {0, 0},
78 "lib": {33, 33},
79 "lib/x86_64": {45, 45},
80 "lib/x86_64/share": {1, 1},
81 }
82 if err := buildTree(dirName, testTree); err != nil {
83 t.Fatal(err)
84 }
85
86 // test adding a directory to a pre-existing dir; only the new dir is owned by the uid/gid
87 if err := MkdirAllAndChown(filepath.Join(dirName, "usr", "share"), 0o755, 99, 99, WithOnlyNew); err != nil {
88 t.Fatal(err)
89 }
90
91 testTree["usr/share"] = node{99, 99}
92 verifyTree, err := readTree(dirName, "")
93 if err != nil {
94 t.Fatal(err)
95 }
96 compareTrees(t, testTree, verifyTree)
97
98 // test 2-deep new directories--both should be owned by the uid/gid pair
99 if err = MkdirAllAndChown(filepath.Join(dirName, "lib", "some", "other"), 0o755, 101, 101, WithOnlyNew); err != nil {
100 t.Fatal(err)
101 }
102 testTree["lib/some"] = node{101, 101}
103 testTree["lib/some/other"] = node{101, 101}
104 if verifyTree, err = readTree(dirName, ""); err != nil {
105 t.Fatal(err)
106 }
107 compareTrees(t, testTree, verifyTree)
108
109 // test a directory that already exists; should NOT be chowned
110 if err = MkdirAllAndChown(filepath.Join(dirName, "usr"), 0o755, 102, 102, WithOnlyNew); err != nil {
111 t.Fatal(err)
112 }
113 if verifyTree, err = readTree(dirName, ""); err != nil {
114 t.Fatal(err)
115 }
116 compareTrees(t, testTree, verifyTree)
117 }
118
119 func TestMkdirAllAndChownNewRelative(t *testing.T) {
120 requiresRoot(t)
121
122 tests := []struct {
123 in string
124 out []string
125 }{
126 {
127 in: "dir1",
128 out: []string{"dir1"},
129 },
130 {
131 in: "dir2/subdir2",
132 out: []string{"dir2", "dir2/subdir2"},
133 },
134 {
135 in: "dir3/subdir3/",
136 out: []string{"dir3", "dir3/subdir3"},
137 },
138 {
139 in: "dir4/subdir4/.",
140 out: []string{"dir4", "dir4/subdir4"},
141 },
142 {
143 in: "dir5/././subdir5/",
144 out: []string{"dir5", "dir5/subdir5"},
145 },
146 {
147 in: "./dir6",
148 out: []string{"dir6"},
149 },
150 {
151 in: "./dir7/subdir7",
152 out: []string{"dir7", "dir7/subdir7"},
153 },
154 {
155 in: "./dir8/subdir8/",
156 out: []string{"dir8", "dir8/subdir8"},
157 },
158 {
159 in: "./dir9/subdir9/.",
160 out: []string{"dir9", "dir9/subdir9"},
161 },
162 {
163 in: "./dir10/././subdir10/",
164 out: []string{"dir10", "dir10/subdir10"},
165 },
166 }
167
168 // Set the current working directory to the temp-dir, as we're
169 // testing relative paths.
170 tmpDir := t.TempDir()
171 setWorkingDirectory(t, tmpDir)
172
173 const expectedUIDGID = 101
174
175 for _, tc := range tests {
176 t.Run(tc.in, func(t *testing.T) {
177 for _, p := range tc.out {
178 _, err := os.Stat(p)
179 if !errors.Is(err, os.ErrNotExist) {
180 t.Fatalf("expected file not exists for %v, got %v", p, err)
181 }
182 }
183
184 if err := MkdirAllAndChown(tc.in, 0o755, expectedUIDGID, expectedUIDGID, WithOnlyNew); err != nil {
185 t.Fatal(err)
186 }
187
188 for _, p := range tc.out {
189 s := &unix.Stat_t{}
190 if err := unix.Stat(p, s); err != nil {
191 t.Errorf("stat %v: %v", p, err)
192 continue
193 }
194 if s.Uid != expectedUIDGID {
195 t.Errorf("expected UID: %d, got: %d", expectedUIDGID, s.Uid)
196 }
197 if s.Gid != expectedUIDGID {
198 t.Errorf("expected GID: %d, got: %d", expectedUIDGID, s.Gid)
199 }
200 }
201 })
202 }
203 }
204
205 // Change the current working directory for the duration of the test. This may
206 // break if tests are run in parallel.
207 func setWorkingDirectory(t *testing.T, dir string) {
208 t.Helper()
209 cwd, err := os.Getwd()
210 if err != nil {
211 t.Fatal(err)
212 }
213 t.Cleanup(func() {
214 if err := os.Chdir(cwd); err != nil {
215 t.Error(err)
216 }
217 })
218 if err = os.Chdir(dir); err != nil {
219 t.Fatal(err)
220 }
221 }
222
223 func TestMkdirAndChown(t *testing.T) {
224 requiresRoot(t)
225 dirName := t.TempDir()
226
227 testTree := map[string]node{
228 "usr": {0, 0},
229 }
230 if err := buildTree(dirName, testTree); err != nil {
231 t.Fatal(err)
232 }
233
234 // test a directory that already exists; should just chown to the requested uid/gid
235 if err := MkdirAndChown(filepath.Join(dirName, "usr"), 0o755, 99, 99); err != nil {
236 t.Fatal(err)
237 }
238 testTree["usr"] = node{99, 99}
239 verifyTree, err := readTree(dirName, "")
240 if err != nil {
241 t.Fatal(err)
242 }
243 compareTrees(t, testTree, verifyTree)
244
245 // create a subdir under a dir which doesn't exist--should fail
246 if err := MkdirAndChown(filepath.Join(dirName, "usr", "bin", "subdir"), 0o755, 102, 102); err == nil {
247 t.Fatal("Trying to create a directory with Mkdir where the parent doesn't exist should have failed")
248 }
249
250 // create a subdir under an existing dir; should only change the ownership of the new subdir
251 if err := MkdirAndChown(filepath.Join(dirName, "usr", "bin"), 0o755, 102, 102); err != nil {
252 t.Fatal(err)
253 }
254 testTree["usr/bin"] = node{102, 102}
255 verifyTree, err = readTree(dirName, "")
256 if err != nil {
257 t.Fatal(err)
258 }
259 compareTrees(t, testTree, verifyTree)
260 }
261
262 func buildTree(base string, tree map[string]node) error {
263 for path, node := range tree {
264 fullPath := filepath.Join(base, path)
265 if err := os.MkdirAll(fullPath, 0o755); err != nil {
266 return err
267 }
268 if err := os.Chown(fullPath, node.uid, node.gid); err != nil {
269 return err
270 }
271 }
272 return nil
273 }
274
275 func readTree(base, root string) (map[string]node, error) {
276 tree := make(map[string]node)
277
278 dirInfos, err := os.ReadDir(base)
279 if err != nil {
280 return nil, err
281 }
282
283 for _, info := range dirInfos {
284 s := &unix.Stat_t{}
285 if err := unix.Stat(filepath.Join(base, info.Name()), s); err != nil {
286 return nil, fmt.Errorf("can't stat file %q: %w", filepath.Join(base, info.Name()), err)
287 }
288 tree[filepath.Join(root, info.Name())] = node{int(s.Uid), int(s.Gid)}
289 if info.IsDir() {
290 // read the subdirectory
291 subtree, err := readTree(filepath.Join(base, info.Name()), filepath.Join(root, info.Name()))
292 if err != nil {
293 return nil, err
294 }
295 for path, nodeinfo := range subtree {
296 tree[path] = nodeinfo
297 }
298 }
299 }
300 return tree, nil
301 }
302
303 func compareTrees(t testing.TB, left, right map[string]node) {
304 t.Helper()
305 if len(left) != len(right) {
306 t.Fatal("trees aren't the same size")
307 }
308 for path, nodeLeft := range left {
309 if nodeRight, ok := right[path]; ok {
310 if nodeRight.uid != nodeLeft.uid || nodeRight.gid != nodeLeft.gid {
311 // mismatch
312 t.Fatalf("mismatched ownership for %q: expected: %d:%d, got: %d:%d", path,
313 nodeLeft.uid, nodeLeft.gid, nodeRight.uid, nodeRight.gid)
314 }
315 continue
316 }
317 t.Fatalf("right tree didn't contain path %q", path)
318 }
319 }
320
321 func TestGetRootUIDGID(t *testing.T) {
322 uidMap := []IDMap{
323 {
324 ID: 0,
325 ParentID: int64(os.Getuid()),
326 Count: 1,
327 },
328 }
329 gidMap := []IDMap{
330 {
331 ID: 0,
332 ParentID: int64(os.Getgid()),
333 Count: 1,
334 },
335 }
336
337 uid, gid, err := getRootUIDGID(uidMap, gidMap)
338 if err != nil {
339 t.Fatal(err)
340 }
341 if uid != os.Getuid() {
342 t.Fatalf("expected %d, got %d", os.Getuid(), uid)
343 }
344 if gid != os.Getgid() {
345 t.Fatalf("expected %d, got %d", os.Getgid(), gid)
346 }
347
348 uidMapError := []IDMap{
349 {
350 ID: 1,
351 ParentID: int64(os.Getuid()),
352 Count: 1,
353 },
354 }
355 _, _, err = getRootUIDGID(uidMapError, gidMap)
356 if expected := "container ID 0 cannot be mapped to a host ID"; err.Error() != expected {
357 t.Fatalf("expected error: %v, got: %v", expected, err)
358 }
359 }
360
361 func TestToContainer(t *testing.T) {
362 uidMap := []IDMap{
363 {
364 ID: 2,
365 ParentID: 2,
366 Count: 1,
367 },
368 }
369
370 containerID, err := toContainer(2, uidMap)
371 if err != nil {
372 t.Fatal(err)
373 }
374 if uidMap[0].ID != int64(containerID) {
375 t.Fatalf("expected %d, got %d", uidMap[0].ID, containerID)
376 }
377 }
378
379 // TestMkdirIsNotDir checks that mkdirAs() function (used by MkdirAll...)
380 // returns a correct error in case a directory which it is about to create
381 // already exists but is a file (rather than a directory).
382 func TestMkdirIsNotDir(t *testing.T) {
383 file, err := os.CreateTemp(t.TempDir(), t.Name())
384 if err != nil {
385 t.Fatalf("Couldn't create temp dir: %v", err)
386 }
387
388 err = mkdirAs(file.Name(), 0o755, 0, 0, false, false)
389 if expected := "mkdir " + file.Name() + ": not a directory"; err.Error() != expected {
390 t.Fatalf("expected error: %v, got: %v", expected, err)
391 }
392 }
393
394 func requiresRoot(t *testing.T) {
395 if os.Getuid() != 0 {
396 t.Skip("skipping test that requires root")
397 }
398 }