Debian Codegraph @

tests/by-util/test_chgrp.rs

raw
1 // This file is part of the uutils coreutils package.
2 //
3 // For the full copyright and license information, please view the LICENSE
4 // file that was distributed with this source code.
5
6 // spell-checker:ignore (words) nosuchgroup groupname
7
8 use rustix::process::getegid;
9 #[cfg(not(target_vendor = "apple"))]
10 use rustix::process::getgroups;
11 #[cfg(target_os = "linux")]
12 use std::os::unix::ffi::OsStringExt;
13 use uutests::{at_and_ucmd, new_ucmd};
14 #[cfg(not(target_vendor = "apple"))]
15 use uutests::{util::TestScenario, util_name};
16
17 #[test]
18 fn test_invalid_option() {
19 new_ucmd!().arg("-w").arg("/").fails();
20 }
21
22 #[test]
23 fn test_invalid_arg() {
24 new_ucmd!().arg("--definitely-invalid").fails_with_code(1);
25 }
26
27 static DIR: &str = "/dev";
28
29 // we should always get both arguments, regardless of whether --reference was used
30 #[test]
31 fn test_help() {
32 new_ucmd!()
33 .arg("--help")
34 .succeeds()
35 .stdout_contains("Arguments:");
36 }
37
38 #[test]
39 fn test_help_ref() {
40 new_ucmd!()
41 .arg("--help")
42 .arg("--reference=ref_file")
43 .succeeds()
44 .stdout_contains("Arguments:");
45 }
46
47 #[test]
48 fn test_ref_help() {
49 new_ucmd!()
50 .arg("--reference=ref_file")
51 .arg("--help")
52 .succeeds()
53 .stdout_contains("Arguments:");
54 }
55
56 #[test]
57 fn test_invalid_group() {
58 new_ucmd!()
59 .arg("__nosuchgroup__")
60 .arg("/")
61 .fails()
62 .stderr_is("chgrp: invalid group: '__nosuchgroup__'\n");
63 }
64
65 #[test]
66 fn test_error_1() {
67 if !getegid().is_root() {
68 new_ucmd!().arg("bin").arg(DIR).fails().stderr_contains(
69 // linux fails with "Operation not permitted (os error 1)"
70 // because of insufficient permissions,
71 // android fails with "Permission denied (os error 13)"
72 // because it can't resolve /proc (even though it can resolve /proc/self/)
73 "chgrp: changing group of '/dev': ",
74 );
75 }
76 }
77
78 #[test]
79 fn test_fail_silently() {
80 if !getegid().is_root() {
81 for opt in ["-f", "--silent", "--quiet", "--sil", "--qui"] {
82 new_ucmd!()
83 .arg(opt)
84 .arg("bin")
85 .arg(DIR)
86 .run()
87 .fails_silently();
88 }
89 }
90 }
91
92 #[test]
93 fn test_preserve_root() {
94 // It's weird that on OS X, `realpath /etc/..` returns '/private'
95 new_ucmd!()
96 .arg("--preserve-root")
97 .arg("-R")
98 .arg("bin")
99 .arg("/")
100 .fails()
101 .stderr_is("chgrp: it is dangerous to operate recursively on '/'\nchgrp: use --no-preserve-root to override this failsafe\n");
102 for d in [
103 "/////dev///../../../../",
104 "../../../../../../../../../../../../../../",
105 "./../../../../../../../../../../../../../../",
106 ] {
107 let expected_error = format!(
108 "chgrp: it is dangerous to operate recursively on '{d}' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n",
109 );
110 new_ucmd!()
111 .arg("--preserve-root")
112 .arg("-R")
113 .arg("bin")
114 .arg(d)
115 .fails()
116 .stderr_is(expected_error);
117 }
118 }
119
120 #[test]
121 fn test_preserve_root_symlink() {
122 let file = "test_chgrp_symlink2root";
123 for d in [
124 "/",
125 "//",
126 "///",
127 "////dev//../../../../",
128 "..//../../..//../..//../../../../../../../../",
129 ".//../../../../../../..//../../../../../../../",
130 ] {
131 let (at, mut ucmd) = at_and_ucmd!();
132 at.symlink_file(d, file);
133 let expected_error = "chgrp: it is dangerous to operate recursively on 'test_chgrp_symlink2root' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n";
134 ucmd.arg("--preserve-root")
135 .arg("-HR")
136 .arg("bin")
137 .arg(file)
138 .fails()
139 .stderr_is(expected_error);
140 }
141
142 let (at, mut ucmd) = at_and_ucmd!();
143 at.symlink_file("///dev", file);
144 ucmd.arg("--preserve-root")
145 .arg("-HR")
146 .arg("bin").arg(format!(".//{file}/..//..//../../"))
147 .fails()
148 .stderr_is("chgrp: it is dangerous to operate recursively on './/test_chgrp_symlink2root/..//..//../../' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n");
149
150 let (at, mut ucmd) = at_and_ucmd!();
151 at.symlink_file("/", "__root__");
152 ucmd.arg("--preserve-root")
153 .arg("-R")
154 .arg("bin").arg("__root__/.")
155 .fails()
156 .stderr_is("chgrp: it is dangerous to operate recursively on '__root__/.' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n");
157 }
158
159 #[test]
160 fn test_preserve_root_symlink_cwd_root() {
161 new_ucmd!()
162 .current_dir("/")
163 .arg("--preserve-root")
164 .arg("-R")
165 .arg("bin").arg(".")
166 .fails()
167 .stderr_is("chgrp: it is dangerous to operate recursively on '.' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n");
168 new_ucmd!()
169 .current_dir("/")
170 .arg("--preserve-root")
171 .arg("-R")
172 .arg("bin").arg("/.")
173 .fails()
174 .stderr_is("chgrp: it is dangerous to operate recursively on '/.' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n");
175 new_ucmd!()
176 .current_dir("/")
177 .arg("--preserve-root")
178 .arg("-R")
179 .arg("bin").arg("..")
180 .fails()
181 .stderr_is("chgrp: it is dangerous to operate recursively on '..' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n");
182 new_ucmd!()
183 .current_dir("/")
184 .arg("--preserve-root")
185 .arg("-R")
186 .arg("bin").arg("/..")
187 .fails()
188 .stderr_is("chgrp: it is dangerous to operate recursively on '/..' (same as '/')\nchgrp: use --no-preserve-root to override this failsafe\n");
189 new_ucmd!()
190 .current_dir("/")
191 .arg("--preserve-root")
192 .arg("-R")
193 .arg("bin")
194 .arg("...")
195 .fails()
196 .stderr_is("chgrp: cannot access '...': No such file or directory\n");
197 }
198
199 #[test]
200 #[cfg(target_os = "linux")]
201 fn test_reference() {
202 // skip for root or MS-WSL
203 // * MS-WSL is bugged (as of 2019-12-25), allowing non-root accounts su-level privileges for `chgrp`
204 // * for MS-WSL, succeeds and stdout == 'group of /etc retained as root'
205 if !(getegid().is_root() || uucore::os::is_wsl_1()) {
206 new_ucmd!()
207 .arg("-v")
208 .arg("--reference=/etc/passwd")
209 .arg("/etc")
210 .fails()
211 // group name can differ, so just check the first part of the message
212 .stderr_contains("chgrp: changing group of '/etc': Operation not permitted\nfailed to change group of '/etc' from ");
213 }
214 }
215
216 #[test]
217 #[cfg(target_vendor = "apple")]
218 fn test_reference() {
219 new_ucmd!()
220 .arg("-v")
221 .arg("--reference=ref_file")
222 .arg("/etc")
223 .fails()
224 // group name can differ, so just check the first part of the message
225 .stderr_contains("chgrp: changing group of '/etc': Operation not permitted\nfailed to change group of '/etc' from ");
226 }
227
228 #[test]
229 #[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))]
230 fn test_reference_multi_no_equal() {
231 new_ucmd!()
232 .arg("-v")
233 .arg("--reference")
234 .arg("ref_file")
235 .arg("file1")
236 .arg("file2")
237 .succeeds()
238 .stdout_contains("group of 'file1' retained as ")
239 .stdout_contains("\ngroup of 'file2' retained as ")
240 .no_stderr();
241 }
242
243 #[test]
244 #[cfg(any(target_vendor = "apple", target_os = "linux", target_os = "android"))]
245 fn test_reference_last() {
246 new_ucmd!()
247 .arg("-v")
248 .arg("file1")
249 .arg("file2")
250 .arg("file3")
251 .arg("--reference")
252 .arg("ref_file")
253 .succeeds()
254 .stdout_contains("group of 'file1' retained as ")
255 .stdout_contains("\ngroup of 'file2' retained as ")
256 .stdout_contains("\ngroup of 'file3' retained as ")
257 .no_stderr();
258 }
259
260 #[test]
261 fn test_missing_files() {
262 new_ucmd!()
263 .arg("-v")
264 .arg("groupname")
265 .fails()
266 .stderr_contains(
267 "error: the following required arguments were not provided:\n <FILE>...\n",
268 );
269 }
270
271 #[test]
272 #[cfg(target_os = "linux")]
273 fn test_big_p() {
274 if !getegid().is_root() {
275 new_ucmd!()
276 .arg("-RP")
277 .arg("bin")
278 .arg("/proc/self/cwd")
279 .fails()
280 .stderr_contains(
281 "chgrp: changing group of '/proc/self/cwd': Operation not permitted\n",
282 );
283 }
284 }
285
286 #[test]
287 #[cfg(any(target_os = "linux", target_os = "android"))]
288 fn test_big_h() {
289 if !getegid().is_root() {
290 assert!(
291 new_ucmd!()
292 .arg("-RH")
293 .arg("bin")
294 .arg("/proc/self/fd")
295 .fails()
296 .stderr_str()
297 .lines()
298 .fold(0, |acc, _| acc + 1)
299 > 1
300 );
301 }
302 }
303
304 #[test]
305 #[cfg(not(target_vendor = "apple"))]
306 fn basic_succeeds() {
307 let (at, mut ucmd) = at_and_ucmd!();
308 // if there are no groups we can't run this test.
309 if let Some(group) = getgroups().unwrap().first() {
310 at.touch("f1");
311 ucmd.arg(group.as_raw().to_string())
312 .arg("f1")
313 .succeeds()
314 .no_output();
315 }
316 }
317
318 #[test]
319 fn test_no_change() {
320 let (at, mut ucmd) = at_and_ucmd!();
321 at.touch("file");
322 ucmd.arg("").arg(at.plus("file")).succeeds();
323 }
324
325 #[test]
326 #[cfg(not(target_vendor = "apple"))]
327 fn test_permission_denied() {
328 use std::os::unix::prelude::PermissionsExt;
329
330 if let Some(group) = getgroups().unwrap().first() {
331 let (at, mut ucmd) = at_and_ucmd!();
332 at.mkdir("dir");
333 at.touch("dir/file");
334 std::fs::set_permissions(at.plus("dir"), PermissionsExt::from_mode(0o0000)).unwrap();
335 ucmd.arg("-R")
336 .arg(group.as_raw().to_string())
337 .arg("dir")
338 .fails()
339 .stderr_only("chgrp: cannot access 'dir': Permission denied\n");
340 }
341 }
342
343 #[test]
344 #[cfg(not(target_vendor = "apple"))]
345 fn test_subdir_permission_denied() {
346 use std::os::unix::prelude::PermissionsExt;
347
348 if let Some(group) = getgroups().unwrap().first() {
349 let (at, mut ucmd) = at_and_ucmd!();
350 at.mkdir("dir");
351 at.mkdir("dir/subdir");
352 at.touch("dir/subdir/file");
353 std::fs::set_permissions(at.plus("dir/subdir"), PermissionsExt::from_mode(0o0000)).unwrap();
354 ucmd.arg("-R")
355 .arg(group.as_raw().to_string())
356 .arg("dir")
357 .fails()
358 .stderr_only("chgrp: cannot access 'dir/subdir': Permission denied\n");
359 }
360 }
361
362 #[test]
363 #[cfg(not(target_vendor = "apple"))]
364 fn test_traverse_symlinks() {
365 use std::os::unix::prelude::MetadataExt;
366 let groups = getgroups().unwrap();
367 if groups.len() < 2 {
368 return;
369 }
370 let (first_group, second_group) = (groups[0], groups[1]);
371
372 for (args, traverse_first, traverse_second) in [
373 (&[][..] as &[&str], false, false),
374 (&["-H"][..], true, false),
375 (&["-P"][..], false, false),
376 (&["-L"][..], true, true),
377 ] {
378 let scenario = TestScenario::new(util_name!());
379
380 let (at, mut ucmd) = (scenario.fixtures.clone(), scenario.ucmd());
381
382 at.mkdir("dir");
383 at.mkdir("dir2");
384 at.touch("dir2/file");
385 at.mkdir("dir3");
386 at.touch("dir3/file");
387 at.symlink_dir("dir2", "dir/dir2_ln");
388 at.symlink_dir("dir3", "dir3_ln");
389
390 scenario
391 .ccmd("chgrp")
392 .arg(first_group.to_string())
393 .arg("dir2/file")
394 .arg("dir3/file")
395 .succeeds();
396
397 assert_eq!(
398 at.plus("dir2/file").metadata().unwrap().gid(),
399 first_group.as_raw()
400 );
401 assert_eq!(
402 at.plus("dir3/file").metadata().unwrap().gid(),
403 first_group.as_raw()
404 );
405
406 ucmd.arg("-R")
407 .args(args)
408 .arg(second_group.to_string())
409 .arg("dir")
410 .arg("dir3_ln")
411 .succeeds()
412 .no_stderr();
413
414 assert_eq!(
415 at.plus("dir2/file").metadata().unwrap().gid(),
416 if traverse_second {
417 second_group.as_raw()
418 } else {
419 first_group.as_raw()
420 }
421 );
422 assert_eq!(
423 at.plus("dir3/file").metadata().unwrap().gid(),
424 if traverse_first {
425 second_group.as_raw()
426 } else {
427 first_group.as_raw()
428 }
429 );
430 }
431 }
432
433 #[test]
434 #[cfg(not(target_vendor = "apple"))]
435 fn test_from_option() {
436 use std::os::unix::fs::MetadataExt;
437 let scene = TestScenario::new(util_name!());
438 let at = &scene.fixtures;
439 let groups = getgroups().unwrap();
440 // Skip test if we don't have at least two different groups to work with
441 if groups.len() < 2 {
442 return;
443 }
444 let (first_group, second_group) = (groups[0], groups[1]);
445
446 at.touch("test_file");
447 scene
448 .ucmd()
449 .arg(first_group.to_string())
450 .arg("test_file")
451 .succeeds();
452
453 // Test successful group change with --from
454 scene
455 .ucmd()
456 .arg("--from")
457 .arg(first_group.to_string())
458 .arg(second_group.to_string())
459 .arg("test_file")
460 .succeeds()
461 .no_stderr();
462
463 // Verify the group was changed
464 let new_gid = at.plus("test_file").metadata().unwrap().gid();
465 assert_eq!(new_gid, second_group.as_raw());
466
467 scene
468 .ucmd()
469 .arg("--from")
470 .arg(first_group.to_string())
471 .arg(first_group.to_string())
472 .arg("test_file")
473 .succeeds()
474 .no_stderr();
475
476 let unchanged_gid = at.plus("test_file").metadata().unwrap().gid();
477 assert_eq!(unchanged_gid, second_group.as_raw());
478 }
479
480 #[test]
481 #[cfg(not(any(target_vendor = "apple", target_os = "android")))]
482 fn test_from_with_invalid_group() {
483 let scene = TestScenario::new(util_name!());
484 let at = &scene.fixtures;
485 at.touch("test_file");
486
487 let err_msg = "chgrp: invalid user: 'nonexistent_group'\n";
488
489 scene
490 .ucmd()
491 .arg("--from")
492 .arg("nonexistent_group")
493 .arg("nobody") // assumption: group exists
494 .arg("test_file")
495 .fails()
496 .stderr_is(err_msg);
497
498 scene
499 .ucmd()
500 .arg("--from")
501 .arg("nonexistent_group")
502 .arg("another_nonexistent_group")
503 .arg("test_file")
504 .fails()
505 .stderr_is(err_msg);
506 }
507
508 #[test]
509 #[cfg(not(target_vendor = "apple"))]
510 fn test_verbosity_messages() {
511 let scene = TestScenario::new(util_name!());
512 let at = &scene.fixtures;
513 let groups = getgroups().unwrap();
514 // Skip test if we don't have at least one group to work with
515 if groups.is_empty() {
516 return;
517 }
518
519 at.touch("ref_file");
520 at.touch("target_file");
521
522 scene
523 .ucmd()
524 .arg("-v")
525 .arg("--reference=ref_file")
526 .arg("target_file")
527 .succeeds()
528 .stdout_contains("group of 'target_file' retained as ")
529 .no_stderr();
530 }
531
532 #[test]
533 #[cfg(not(target_vendor = "apple"))]
534 fn test_from_with_reference() {
535 use std::os::unix::fs::MetadataExt;
536 let scene = TestScenario::new(util_name!());
537 let at = &scene.fixtures;
538 let groups = getgroups().unwrap();
539 if groups.len() < 2 {
540 return;
541 }
542 let (first_group, second_group) = (groups[0], groups[1]);
543
544 at.touch("ref_file");
545 at.touch("test_file");
546
547 scene
548 .ucmd()
549 .arg(first_group.to_string())
550 .arg("test_file")
551 .succeeds();
552
553 scene
554 .ucmd()
555 .arg(second_group.to_string())
556 .arg("ref_file")
557 .succeeds();
558
559 // Test --from with --reference
560 scene
561 .ucmd()
562 .arg("--from")
563 .arg(first_group.to_string())
564 .arg("--reference=ref_file")
565 .arg("test_file")
566 .succeeds()
567 .no_stderr();
568
569 let new_gid = at.plus("test_file").metadata().unwrap().gid();
570 let ref_gid = at.plus("ref_file").metadata().unwrap().gid();
571 assert_eq!(new_gid, ref_gid);
572 }
573
574 #[test]
575 #[cfg(not(target_vendor = "apple"))]
576 fn test_numeric_group_formats() {
577 use std::os::unix::fs::MetadataExt;
578 let scene = TestScenario::new(util_name!());
579 let at = &scene.fixtures;
580
581 let groups = getgroups().unwrap();
582 if groups.len() < 2 {
583 return;
584 }
585 let (first_group, second_group) = (groups[0], groups[1]);
586
587 at.touch("test_file");
588
589 scene
590 .ucmd()
591 .arg(first_group.to_string())
592 .arg("test_file")
593 .succeeds();
594
595 // Test :gid format in --from
596 scene
597 .ucmd()
598 .arg(format!("--from=:{}", first_group.as_raw()))
599 .arg(second_group.to_string())
600 .arg("test_file")
601 .succeeds()
602 .no_stderr();
603
604 let new_gid = at.plus("test_file").metadata().unwrap().gid();
605 assert_eq!(new_gid, second_group.as_raw());
606
607 // Test :gid format in target group
608 scene
609 .ucmd()
610 .arg(format!("--from={}", second_group.as_raw()))
611 .arg(format!(":{}", first_group.as_raw()))
612 .arg("test_file")
613 .succeeds()
614 .no_stderr();
615
616 let final_gid = at.plus("test_file").metadata().unwrap().gid();
617 assert_eq!(final_gid, first_group.as_raw());
618 }
619
620 #[test]
621 #[cfg(target_os = "linux")]
622 fn test_chgrp_non_utf8_paths() {
623 let (at, mut ucmd) = at_and_ucmd!();
624
625 let filename = std::ffi::OsString::from_vec(vec![0xFF, 0xFE]);
626 std::fs::write(at.plus(&filename), b"test content").unwrap();
627
628 // Get current user's primary group
629 let current_gid = getegid().as_raw();
630
631 ucmd.arg(current_gid.to_string()).arg(&filename).succeeds();
632 }
633
634 #[test]
635 fn test_chgrp_recursive_on_file() {
636 // Test for regression where `chgrp -R` on a regular file would fail
637 // with "Not a directory" error. This should succeed since there's nothing
638 // to recurse into, similar to GNU chgrp behavior.
639 // equivalent of tests/chgrp/recurse in GNU coreutils
640 use std::os::unix::fs::MetadataExt;
641 let (at, mut ucmd) = at_and_ucmd!();
642
643 at.touch("regular_file");
644
645 let current_gid = getegid().as_raw();
646
647 ucmd.arg("-R")
648 .arg(current_gid.to_string())
649 .arg("regular_file")
650 .succeeds()
651 .no_stderr();
652
653 assert_eq!(
654 at.plus("regular_file").metadata().unwrap().gid(),
655 current_gid
656 );
657 }
658
659 #[test]
660 fn test_chgrp_exit_code_not_being_overwritten_by_last_file() {
661 use std::os::unix::prelude::PermissionsExt;
662
663 let current_gid = getegid().as_raw();
664 let (at, mut ucmd) = at_and_ucmd!();
665 at.mkdir("dir");
666 at.mkdir("dir/a");
667 at.mkdir("dir/b");
668 at.touch("dir/b/file");
669 at.touch("dir/a/file");
670 std::fs::set_permissions(at.plus("dir/a"), PermissionsExt::from_mode(0o0000)).unwrap();
671
672 // chgrp walks the dir alphabetically. Dir a does not have permissions so it fails, dir b does have
673 // permissions so it succeeds. We check that the overall command does fail although the
674 // last step succeeded.
675
676 ucmd.arg("-R")
677 .arg(current_gid.to_string())
678 .arg("dir")
679 .fails();
680 }
681
682 #[cfg(target_os = "linux")]
683 #[test]
684 fn verbose_missing_file_write_error_is_reported_not_panic() {
685 use std::fs::OpenOptions;
686
687 let dev_full = OpenOptions::new().write(true).open("/dev/full").unwrap();
688 new_ucmd!()
689 .arg("--verbose")
690 .arg(getegid().to_string())
691 .arg("does-not-exist")
692 .set_stdout(dev_full)
693 .fails_with_code(1)
694 .stderr_contains("chgrp: write error: No space left on device");
695 }