Debian Codegraph @

testsuite/rrsync-pull-arg-shapes_test.py

raw symbols SCIP
1 #!/usr/bin/env python3
2 """Every pull argument shape through rrsync must deliver what it names.
3
4 rrsync inode-pins each validated argument so the exec'd rsync cannot be
5 race-flipped between realpath() and resolution. Which pin is usable depends on
6 what rsync does with the argument, and getting that wrong is silent: the
7 transfer "succeeds" while delivering nothing, or delivers the file under the
8 wrong name.
9
10 That is exactly what happened when the pin was first added -- of the shapes
11 below only "dir-slash" survived, because it is the one rsync opens rather than
12 lstat()s. Nothing covered --relative at all, so its breakage went unnoticed
13 too.
14
15 Each case asserts the delivered tree, which is the user-visible contract and is
16 independent of which pin the implementation chooses.
17 """
18
19 import os
20 import shlex
21 import stat
22 import subprocess
23
24 from rsyncfns import (
25 RSYNC, SCRATCHDIR, forced_protocol, makepath, patched_rrsync, rmtree,
26 rsync_argv, test_fail, rsync_path_arg,
27 )
28
29 base = SCRATCHDIR / 'rrsync-arg-shapes'
30 rmtree(base)
31 restricted = base / 'restricted'
32 dest = base / 'dest'
33 makepath(restricted / 'sub' / 'deep', dest)
34
35 (restricted / 'f1').write_text('TOP\n')
36 (restricted / 'sub' / 'deep' / 'f2').write_text('DEEP\n')
37 # An in-tree directory symlink, the ordinary way to publish a path under
38 # another name. Reaching through it must keep working.
39 os.symlink('sub/deep', restricted / 'alias')
40 # A file reachable only by name: search permission on the parent, no read.
41 # rrsync must not need to list a directory just to pin it.
42 # A FIFO and a dangling symlink: rsync only needs to describe these, never to
43 # open them. Opening a FIFO blocks for a writer, and resolving a dangling link
44 # reaches nothing -- both wedged or failed the pull until the pin learned to
45 # leave them alone.
46 os.mkfifo(restricted / 'afifo')
47 os.symlink('missing-sibling', restricted / 'dangling')
48 os.symlink('f1', restricted / 'goodlink')
49
50 xonly = restricted / 'xonly'
51 xonly.mkdir()
52 (xonly / 'f3').write_text('XONLY\n')
53 xonly.chmod(0o111)
54
55 shim = base / 'rsync-shim'
56 shim.write_text('#!/bin/sh\nexec ' + rsync_path_arg(RSYNC) + ' "$@"\n')
57 shim.chmod(0o755)
58
59 rrsync = patched_rrsync(base, rsync_path=str(shim))
60
61 rsh = base / 'fake-rsh'
62 rsh.write_text(
63 '#!/bin/sh\n'
64 'shift\n'
65 'SSH_ORIGINAL_COMMAND="$*"\n'
66 'export SSH_ORIGINAL_COMMAND\n'
67 'exec %s %s\n' % (shlex.quote(str(rrsync)), shlex.quote(str(restricted))))
68 rsh.chmod(0o755)
69
70
71 def pull(*args):
72 rmtree(dest)
73 dest.mkdir()
74 proc = subprocess.run(rsync_argv('-a', '-e', str(rsh), *args,
75 str(dest) + '/'),
76 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
77 text=True)
78 got = sorted(str(p.relative_to(dest)) for p in dest.rglob('*'))
79 return proc, got
80
81
82 # What every deliverable name must BE. Comparing names alone is not enough:
83 # an empty directory called "f1", or a correctly-named symlink carrying no
84 # data, satisfies a name-only expectation -- and a symlink with no data is
85 # exactly what handing the sender a procfs magic link produced.
86 KINDS = {
87 'f1': ('reg', 'TOP\n'),
88 'f2': ('reg', 'DEEP\n'),
89 'f3': ('reg', 'XONLY\n'),
90 'deep': ('dir', None),
91 'deep/f2': ('reg', 'DEEP\n'),
92 'sub': ('dir', None),
93 'sub/deep': ('dir', None),
94 'sub/deep/f2': ('reg', 'DEEP\n'),
95 'dangling': ('sym', 'missing-sibling'),
96 'goodlink': ('sym', 'f1'),
97 }
98
99
100 def describe(path):
101 if path.is_symlink():
102 return 'a symlink to %r' % os.readlink(path)
103 if path.is_dir():
104 return 'a directory'
105 if path.is_file():
106 return 'a regular file'
107 return 'neither a file, a directory nor a symlink'
108
109
110 def check_kinds(label, names, ctx):
111 for name in names:
112 want = KINDS.get(name)
113 if want is None:
114 test_fail(f'{label}: delivered {name!r}, which has no entry in '
115 'KINDS, so nothing checked what it is -- add one')
116 kind, detail = want
117 path = dest / name
118 if kind == 'sym':
119 if not path.is_symlink():
120 test_fail(f'{label}: {name} should be a symlink, got '
121 f'{describe(path)} ({ctx})')
122 if os.readlink(path) != detail:
123 test_fail(f'{label}: {name} points at {os.readlink(path)!r}, '
124 f'expected {detail!r} ({ctx})')
125 elif kind == 'dir':
126 if path.is_symlink() or not path.is_dir():
127 test_fail(f'{label}: {name} should be a directory, got '
128 f'{describe(path)} ({ctx})')
129 elif kind != 'reg':
130 # Closed schema: a mistyped token must not fall through to the
131 # regular-file arm and quietly assert the wrong thing.
132 test_fail(f'{label}: {name} has unknown kind {kind!r} in KINDS')
133 else:
134 if path.is_symlink() or not path.is_file():
135 test_fail(f'{label}: {name} should be a regular file, got '
136 f'{describe(path)} ({ctx})')
137 if path.read_text() != detail:
138 test_fail(f'{label}: {name} holds {path.read_text()!r}, '
139 f'expected {detail!r} ({ctx})')
140
141
142 # Expectations are what a pristine 3.4.4 rrsync delivers for the same command.
143 CASES = [
144 ('file', ['dummy:f1'], ['f1']),
145 ('deep file', ['dummy:sub/deep/f2'], ['f2']),
146 ('dir', ['dummy:sub'], ['sub', 'sub/deep', 'sub/deep/f2']),
147 ('dir + slash', ['dummy:sub/'], ['deep', 'deep/f2']),
148 ('dir + /.', ['dummy:sub/.'], ['deep', 'deep/f2']),
149 ('-R deep file', ['-R', 'dummy:sub/deep/f2'], ['sub', 'sub/deep', 'sub/deep/f2']),
150 ('-R dir + slash',['-R', 'dummy:sub/'], ['sub', 'sub/deep', 'sub/deep/f2']),
151 ('-R client /./', ['-R', 'dummy:sub/./deep/f2'], ['deep', 'deep/f2']),
152 # A marker with nothing after it means "start the transmitted name here",
153 # so the argument's own directory name must NOT appear in the result.
154 ('-R terminal /./', ['-R', 'dummy:sub/./'], ['deep', 'deep/f2']),
155 ('-R terminal /./.', ['-R', 'dummy:sub/./.'], ['deep', 'deep/f2']),
156 # An in-tree directory symlink as the argument's parent is ordinary and
157 # must keep working; pinning it must not refuse to follow it.
158 ('symlinked parent', ['dummy:alias/f2'], ['f2']),
159 ('-R symlinked parent', ['-R', 'dummy:alias/./f2'], ['f2']),
160 ]
161
162 # At protocol 29 the receiver rejects "-R --no-implied-dirs" with "invalid path
163 # from sender" and transfers nothing. That is rsync's own behaviour, not the
164 # wrapper's -- a pristine 3.4.4 rrsync fails identically -- so only assert the
165 # case where it means something.
166 if forced_protocol() is None or forced_protocol() >= 30:
167 CASES.append(
168 ('-R no-implied', ['-R', '--no-implied-dirs', 'dummy:sub/deep/f2'],
169 ['sub', 'sub/deep', 'sub/deep/f2']))
170
171 CASES += [
172 ('search-only parent', ['dummy:xonly/f3'], ['f3']),
173 # These three are what a pristine 3.4.4 rrsync delivers for the same args.
174 ('dangling symlink', ['dummy:dangling'], ['dangling']),
175 ('symlink to a file', ['dummy:goodlink'], ['goodlink']),
176 ('two args', ['dummy:f1', 'dummy:sub/deep/f2'], ['f1', 'f2']),
177 ]
178
179 for label, argv, expect in CASES:
180 proc, got = pull(*argv)
181 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:200]!r}'
182 if got != expect:
183 test_fail(f'{label}: delivered {got}, expected {expect} ({ctx})')
184 check_kinds(label, got, ctx)
185 if proc.returncode != 0:
186 test_fail(f'{label}: delivered the right tree but failed ({ctx})')
187
188 # A FIFO must not WEDGE the wrapper. The pin used to open every validated path
189 # O_RDONLY, and opening a FIFO blocks until a writer appears, so naming one hung
190 # rrsync before exec and an authorised user could pile up stuck processes.
191 #
192 # It must also arrive. rrsync denies device/special CREATION on the receiving
193 # side only, so a pull carries the client's own -D and delivers the FIFO, which
194 # is what a pristine 3.4.4 rrsync does. While --no-D was forced here too, the
195 # file list desynchronised -- the sender omitted the rdev fields the client's
196 # receiver still read -- and this could assert nothing beyond "did not hang":
197 # it overflowed at protocol 29/30 and, as root, deadlocked instead.
198 rmtree(dest)
199 dest.mkdir()
200 try:
201 proc = subprocess.run(rsync_argv('-a', '-e', str(rsh), 'dummy:afifo',
202 str(dest) + '/'),
203 stdout=subprocess.PIPE, stderr=subprocess.STDOUT,
204 text=True, timeout=60)
205 except subprocess.TimeoutExpired:
206 test_fail('pulling a FIFO hung: either the wrapper opened it and blocked '
207 'for a writer, or the file list desynchronised and both ends '
208 'stalled')
209 ctx = f'rc={proc.returncode}, output={proc.stdout.strip()[:200]!r}'
210 if proc.returncode != 0:
211 test_fail(f'pulling a FIFO failed ({ctx})')
212 if not stat.S_ISFIFO(os.lstat(dest / 'afifo').st_mode):
213 test_fail(f'pulling a FIFO delivered {describe(dest / "afifo")} ({ctx})')
214
215 # The kinds, the symlink targets and the file contents are asserted by
216 # check_kinds() on every case above, rather than spot-checked on a few here.
217
218 xonly.chmod(0o755)
219
220 print(f'rrsync delivers all {len(CASES)} pull argument shapes')