Debian Codegraph @

testsuite/protected-regular_test.py

raw symbols ◀ ▶
Source reconstructed at patch state 0 of 1 — not the installed (fully patched) source.
1 Debian patch touch this file
1 #!/usr/bin/env python3
2 # Python rewrite of testsuite/protected-regular.test.
3 #
4 # Modern Linux kernels can set fs.protected_regular = {1,2}, which
5 # blocks O_CREAT|O_WRONLY opens of files in world-writable sticky
6 # directories that the opener doesn't own. rsync --inplace must still
7 # be able to write into these files; this test guards that path.
8
9 import os
10 import shutil
11 import subprocess
12 import sys
13 from pathlib import Path
14
15 from rsyncfns import TMPDIR, run_rsync, test_fail, test_skipped
16
17
18 pr_path = Path('/proc/sys/fs/protected_regular')
19 if not pr_path.is_file():
20 test_skipped("Can't find protected_regular setting (only available on Linux)")
21
22 try:
23 pr_lvl = pr_path.read_text().strip()
24 except OSError:
25 test_skipped("Can't check if fs.protected_regular is enabled")
26 if pr_lvl == '0':
27 test_skipped("fs.protected_regular is not enabled")
28
29 workdir = TMPDIR / 'files'
30 workdir.mkdir(parents=True, exist_ok=True)
31 os.chmod(workdir, 0o1777)
32
33 (workdir / 'src').write_text("Source\n")
34 (workdir / 'dst').write_text("")
35
36
37 def _chown_5001(path: Path) -> bool:
38 """Try to chown(2) `path` to uid 5001. Returns True on success."""
39 try:
40 os.chown(path, 5001, -1)
41 return True
42 except PermissionError:
43 return False
44
45
46 if not _chown_5001(workdir / 'dst'):
47 # Not root: fall back to re-running ourselves under unshare with a
48 # uid mapping (Linux user-namespace trick). Only attempt once.
49 if not os.environ.get('RSYNC_UNSHARED'):
50 unshare = shutil.which('unshare')
51 if unshare is not None:
52 probe = subprocess.run(
53 [unshare, '--user', '--map-root-user',
54 '--map-users', '5001:100000:1', 'true'],
55 capture_output=True,
56 )
57 if probe.returncode == 0:
58 print("Re-running under unshare with UID mapping...")
59 env = os.environ.copy()
60 env['RSYNC_UNSHARED'] = '1'
61 os.execvpe(
62 unshare,
63 [unshare, '--user', '--map-root-user',
64 '--map-users', '5001:100000:1',
65 sys.executable, __file__],
66 env,
67 )
68 test_skipped("Can't chown (need root or unshare with uidmap)")
69
70 print(f"Contents of {workdir}:")
71 subprocess.run(['ls', '-al', str(workdir)])
72
73 run_rsync('--inplace', str(workdir / 'src'), str(workdir / 'dst'))
74
75 # A zero exit isn't enough: confirm --inplace actually wrote the source bytes
76 # into the protected destination (a no-op/short write would also exit 0).
77 dst_content = (workdir / 'dst').read_text()
78 if dst_content != "Source\n":
79 test_fail(f"--inplace did not write the source content into the protected "
80 f"dst: got {dst_content!r}")