Debian Codegraph @

test/pytest/test_bridge.py

raw
1 import argparse
2 import asyncio
3 import contextlib
4 import errno
5 import getpass
6 import grp
7 import json
8 import os
9 import pwd
10 import shlex
11 import stat
12 import subprocess
13 import sys
14 import unittest.mock
15 from collections import deque
16 from pathlib import Path
17 from typing import AsyncGenerator, Dict, Generator, Iterator, Sequence, Union
18
19 import pytest
20 import pytest_asyncio
21
22 from cockpit._vendor.systemd_ctypes import bus
23 from cockpit.bridge import Bridge
24 from cockpit.channel import AsyncChannel, Channel, ChannelRoutingRule
25 from cockpit.channels import CHANNEL_TYPES
26 from cockpit.channels.filesystem import tag_from_path
27 from cockpit.jsonutil import JsonDict, JsonObject, JsonValue, get_bool, get_dict, get_int, get_str, json_merge_patch
28 from cockpit.packages import BridgeConfig
29 from cockpit.peer import ConfiguredPeer
30 from cockpit.superuser import is_valid_superuser_config
31
32 from .mocktransport import MOCK_HOSTNAME, MockTransport
33
34
35 class test_iface(bus.Object):
36 sig = bus.Interface.Signal('s')
37 prop = bus.Interface.Property('s', value='none')
38
39 @bus.Interface.Method('s')
40 def get_prop(self) -> str:
41 return self.prop
42
43
44 @pytest.fixture
45 def bridge() -> Bridge:
46 bridge = Bridge(argparse.Namespace(privileged=False, beipack=False))
47 bridge.superuser_bridges = list(bridge.superuser_rule.bridges) # type: ignore[attr-defined]
48 return bridge
49
50
51 def add_pseudo(bridge: Bridge) -> None:
52 bridge.more_superuser_bridges = [*bridge.superuser_bridges, 'pseudo'] # type: ignore[attr-defined]
53
54 assert bridge.packages is not None
55
56 # Add pseudo to the existing set of superuser rules
57 bridge.superuser_rule.set_configs([
58 *bridge.packages.get_bridge_configs(),
59 BridgeConfig({
60 'label': 'pseudo',
61 'spawn': [
62 sys.executable, os.path.abspath(f'{__file__}/../pseudo.py'),
63 sys.executable, '-m', 'cockpit.bridge', '--privileged'
64 ],
65 'environ': [
66 f'PYTHONPATH={":".join(sys.path)}'
67 ],
68 'privileged': True
69 })
70 ])
71
72
73 @pytest_asyncio.fixture
74 async def no_init_transport(bridge: Bridge) -> AsyncGenerator[MockTransport, None]:
75 transport = MockTransport(bridge)
76 try:
77 yield transport
78 finally:
79 await transport.stop()
80
81
82 @pytest.fixture
83 def transport(no_init_transport: MockTransport) -> MockTransport:
84 no_init_transport.init()
85 return no_init_transport
86
87
88 @pytest.mark.asyncio
89 async def test_echo(transport: MockTransport) -> None:
90 echo = await transport.check_open('echo')
91
92 transport.send_data(echo, b'foo')
93 await transport.assert_data(echo, b'foo')
94
95 transport.send_ping(channel=echo)
96 await transport.assert_msg('', command='pong', channel=echo)
97
98 transport.send_done(echo)
99 await transport.assert_msg('', command='done', channel=echo)
100 await transport.assert_msg('', command='close', channel=echo)
101
102
103 @pytest.mark.asyncio
104 async def test_echo_invalid_utf8(transport: MockTransport) -> None:
105 echo = await transport.check_open('echo')
106
107 # invalid UTF-8 closes the channel with protocol-error
108 transport.send_data(echo, b'\x80\xff\xfe')
109 await transport.assert_msg('', command='close', channel=echo, problem='protocol-error')
110
111
112 @pytest.mark.asyncio
113 async def test_host(transport: MockTransport) -> None:
114 # try to open a null channel, explicitly naming our host
115 await transport.check_open('null', host=MOCK_HOSTNAME)
116
117 # try to open a null channel, no host
118 await transport.check_open('null')
119
120 # try to open a null channel, a different host which is sure to fail DNS
121 await transport.check_open('null', host='¡invalid!', problem='no-host')
122
123 # make sure host check happens before superuser
124 # ie: requesting superuser=True on another host should fail because we
125 # can't contact the other host ('no-host'), rather than trying to first
126 # go to our superuser bridge ('access-denied')
127 await transport.check_open('null', host='¡invalid!', superuser=True, problem='no-host')
128
129 # but make sure superuser is indeed failing as we expect, on our host
130 await transport.check_open('null', host=MOCK_HOSTNAME, superuser=True, problem='access-denied')
131
132
133 @pytest.mark.asyncio
134 async def test_dbus_call_internal(bridge: Bridge, transport: MockTransport) -> None:
135 my_object = test_iface()
136 bridge.internal_bus.export('/foo', my_object)
137 assert my_object._dbus_bus == bridge.internal_bus.server
138 assert my_object._dbus_path == '/foo'
139
140 values, = await transport.check_bus_call('/foo', 'org.freedesktop.DBus.Properties',
141 'GetAll', ["test.iface"])
142 assert values == {'Prop': {'t': 's', 'v': 'none'}}
143
144 result, = await transport.check_bus_call('/foo', 'test.iface', 'GetProp', [])
145 assert result == 'none'
146
147
148 @pytest.mark.asyncio
149 async def test_dbus_watch(bridge: Bridge, transport: MockTransport) -> None:
150 my_object = test_iface()
151 bridge.internal_bus.export('/foo', my_object)
152 assert my_object._dbus_bus == bridge.internal_bus.server
153 assert my_object._dbus_path == '/foo'
154
155 # Add a watch
156 internal = await transport.ensure_internal_bus()
157
158 transport.send_json(internal, watch={'path': '/foo', 'interface': 'test.iface'}, id='4')
159 meta = await transport.next_msg(internal)
160 assert meta['meta']['test.iface'] == {
161 'methods': {'GetProp': {'in': [], 'out': ['s']}},
162 'properties': {'Prop': {'flags': 'r', 'type': 's'}},
163 'signals': {'Sig': {'in': ['s']}}
164 }
165 notify = await transport.next_msg(internal)
166 assert notify['notify']['/foo'] == {'test.iface': {'Prop': 'none'}}
167 reply = await transport.next_msg(internal)
168 assert reply == {'id': '4', 'reply': []}
169
170 # Change a property
171 my_object.prop = 'xyz'
172 notify = await transport.next_msg(internal)
173 assert 'notify' in notify
174 assert notify['notify']['/foo'] == {'test.iface': {'Prop': 'xyz'}}
175
176
177 async def verify_root_bridge_not_running(bridge: Bridge, transport: MockTransport) -> None:
178 assert bridge.superuser_rule.peer is None
179 await transport.assert_bus_props('/superuser', 'cockpit.Superuser',
180 {'Bridges': bridge.more_superuser_bridges, 'Current': 'none'}) # type: ignore[attr-defined]
181 null = await transport.check_open('null', superuser=True, problem='access-denied')
182 assert null not in bridge.open_channels
183
184
185 @pytest.mark.asyncio
186 async def verify_root_bridge_running(bridge: Bridge, transport: MockTransport) -> None:
187 await transport.assert_bus_props('/superuser', 'cockpit.Superuser',
188 {'Bridges': bridge.more_superuser_bridges, 'Current': 'pseudo'}) # type: ignore[attr-defined]
189 assert bridge.superuser_rule.peer is not None
190
191 # try to open dbus on the root bridge
192 root_dbus = await transport.check_open('dbus-json3', bus='internal', superuser=True)
193
194 # verify that the bridge thinks that it's the root bridge
195 await transport.assert_bus_props('/superuser', 'cockpit.Superuser',
196 {'Bridges': [], 'Current': 'root'}, bus=root_dbus)
197
198 # close up
199 await transport.check_close(channel=root_dbus)
200
201
202 @pytest.mark.asyncio
203 async def test_superuser_dbus(bridge: Bridge, transport: MockTransport) -> None:
204 add_pseudo(bridge)
205 await verify_root_bridge_not_running(bridge, transport)
206
207 # start the superuser bridge -- no password, so it should work straight away
208 () = await transport.check_bus_call('/superuser', 'cockpit.Superuser', 'Start', ['pseudo'])
209
210 await verify_root_bridge_running(bridge, transport)
211
212 # open a channel on the root bridge
213 root_null = await transport.check_open('null', superuser=True)
214
215 # stop the bridge
216 stop = transport.send_bus_call(transport.internal_bus, '/superuser',
217 'cockpit.Superuser', 'Stop', [])
218
219 # that should have implicitly closed the open channel
220 await transport.assert_msg('', command='close', channel=root_null)
221 assert root_null not in bridge.open_channels
222
223 # The Stop method call is done now
224 await transport.assert_msg(transport.internal_bus, reply=[[]], id=stop)
225
226
227 def format_methods(methods: Dict[str, str]):
228 return {name: {'t': 'a{sv}', 'v': {'label': {'t': 's', 'v': label}}} for name, label in methods.items()}
229
230
231 @pytest.mark.asyncio
232 async def test_superuser_dbus_pw(bridge: Bridge, transport: MockTransport, monkeypatch) -> None:
233 monkeypatch.setenv('PSEUDO_PASSWORD', 'p4ssw0rd')
234 add_pseudo(bridge)
235 await verify_root_bridge_not_running(bridge, transport)
236
237 # watch for signals
238 await transport.add_bus_match('/superuser', 'cockpit.Superuser')
239 await transport.watch_bus('/superuser', 'cockpit.Superuser',
240 {
241 'Bridges': bridge.more_superuser_bridges, # type: ignore[attr-defined]
242 'Current': 'none',
243 'Methods': format_methods({'pseudo': 'pseudo'}),
244 })
245
246 # start the bridge. with a password this is more complicated
247 start = transport.send_bus_call(transport.internal_bus, '/superuser',
248 'cockpit.Superuser', 'Start', ['pseudo'])
249 # first, init state
250 await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'init'})
251 # then, we'll be asked for a password
252 await transport.assert_bus_signal('/superuser', 'cockpit.Superuser', 'Prompt',
253 ['', 'can haz pw?', '', False, ''])
254 # give it
255 await transport.check_bus_call('/superuser', 'cockpit.Superuser', 'Answer', ['p4ssw0rd'])
256 # and now the bridge should be running
257 await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'pseudo'})
258
259 # Start call is now done
260 await transport.assert_bus_reply(start, [])
261
262 # double-check
263 await verify_root_bridge_running(bridge, transport)
264
265
266 @pytest.mark.asyncio
267 async def test_superuser_dbus_wrong_pw(bridge: Bridge, transport: MockTransport, monkeypatch) -> None:
268 monkeypatch.setenv('PSEUDO_PASSWORD', 'p4ssw0rd')
269 add_pseudo(bridge)
270 await verify_root_bridge_not_running(bridge, transport)
271
272 # watch for signals
273 await transport.add_bus_match('/superuser', 'cockpit.Superuser')
274 await transport.watch_bus('/superuser', 'cockpit.Superuser',
275 {
276 'Bridges': bridge.more_superuser_bridges, # type: ignore[attr-defined]
277 'Current': 'none',
278 'Methods': format_methods({'pseudo': 'pseudo'}),
279 })
280
281 # start the bridge. with a password this is more complicated
282 start = transport.send_bus_call(transport.internal_bus, '/superuser',
283 'cockpit.Superuser', 'Start', ['pseudo'])
284 # first, init state
285 await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'init'})
286 # then, we'll be asked for a password
287 await transport.assert_bus_signal('/superuser', 'cockpit.Superuser', 'Prompt',
288 ['', 'can haz pw?', '', False, ''])
289 # give it
290 await transport.check_bus_call('/superuser', 'cockpit.Superuser',
291 'Answer', ['p5ssw0rd']) # wrong password
292 # pseudo fails after the first wrong attempt
293 await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'none'})
294
295 # Start call is now done and returned failure
296 await transport.assert_bus_error(start, 'cockpit.Superuser.Error', 'pseudo says: Bad password')
297
298 # double-check
299 await verify_root_bridge_not_running(bridge, transport)
300
301
302 @pytest.mark.asyncio
303 async def test_superuser_init(bridge: Bridge, no_init_transport: MockTransport) -> None:
304 add_pseudo(bridge)
305 no_init_transport.init(superuser={"id": "pseudo"})
306 transport = no_init_transport
307
308 # this should work right away without auth
309 await transport.assert_msg('', command='superuser-init-done')
310
311 await verify_root_bridge_running(bridge, transport)
312
313
314 @pytest.mark.asyncio
315 async def test_superuser_init_pw(bridge: Bridge, no_init_transport: MockTransport, monkeypatch) -> None:
316 monkeypatch.setenv('PSEUDO_PASSWORD', 'p4ssw0rd')
317 add_pseudo(bridge)
318 no_init_transport.init(superuser={"id": "pseudo"})
319 transport = no_init_transport
320
321 msg = await transport.assert_msg('', command='authorize')
322 transport.send_json('', command='authorize', cookie=msg['cookie'], response='p4ssw0rd')
323
324 # that should have worked
325 await transport.assert_msg('', command='superuser-init-done')
326
327 await verify_root_bridge_running(bridge, transport)
328
329
330 @pytest.mark.asyncio
331 async def test_no_login_messages(transport: MockTransport) -> None:
332 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])
333 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Dismiss', [], [])
334 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])
335
336
337 @pytest.fixture
338 def login_messages_envvar(monkeypatch):
339 if sys.version_info < (3, 8):
340 pytest.skip("os.memfd_create new in 3.8")
341 fd = os.memfd_create('login messages')
342 os.write(fd, b"msg")
343 # this is questionable (since it relies on ordering of fixtures), but it works
344 monkeypatch.setenv('COCKPIT_LOGIN_MESSAGES_MEMFD', str(fd))
345 return None
346
347
348 @pytest.mark.asyncio
349 async def test_login_messages(login_messages_envvar, transport: MockTransport) -> None:
350 del login_messages_envvar
351
352 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["msg"])
353 # repeated read should get the messages again
354 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["msg"])
355 # ...but not after they were dismissed
356 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Dismiss', [], [])
357 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])
358 # idempotency
359 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Dismiss', [], [])
360 await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])
361
362
363 @pytest.mark.asyncio
364 async def test_freeze(bridge: Bridge, transport: MockTransport) -> None:
365 koelle = await transport.check_open('echo')
366 malle = await transport.check_open('echo')
367
368 # send a bunch of data to frozen koelle
369 bridge.open_channels[koelle].freeze_endpoint()
370 transport.send_data(koelle, b'x1')
371 transport.send_data(koelle, b'x2')
372 transport.send_data(koelle, b'x3')
373 transport.send_done(koelle)
374
375 # malle never freezes
376 transport.send_data(malle, b'yy')
377 transport.send_done(malle)
378
379 # unfreeze koelle
380 bridge.open_channels[koelle].thaw_endpoint()
381
382 # malle should have sent its messages first
383 await transport.assert_data(malle, b'yy')
384 await transport.assert_msg('', command='done', channel=malle)
385 await transport.assert_msg('', command='close', channel=malle)
386
387 # the data from koelle should still be in the right order, though
388 await transport.assert_data(koelle, b'x1')
389 await transport.assert_data(koelle, b'x2')
390 await transport.assert_data(koelle, b'x3')
391 await transport.assert_msg('', command='done', channel=koelle)
392 await transport.assert_msg('', command='close', channel=koelle)
393
394
395 @pytest.mark.asyncio
396 async def test_internal_metrics(transport: MockTransport) -> None:
397 metrics = [
398 {"name": "cpu.core.user", "derive": "rate"},
399 {"name": "memory.used"},
400 ]
401 interval = 100
402 source = 'internal'
403
404 await transport.check_open('metrics1', source=source, interval=interval, metrics=metrics)
405 _, data = await transport.next_frame()
406 # first message is always the meta message
407 meta = json.loads(data)
408 assert isinstance(meta['timestamp'], float)
409 assert meta['interval'] == interval
410 assert meta['source'] == source
411 assert isinstance(meta['metrics'], list)
412 instances = len(next(m['instances'] for m in meta['metrics'] if m['name'] == 'cpu.core.user'))
413
414 # actual data
415 _, data = await transport.next_frame()
416 data = json.loads(data)
417 assert isinstance(data, list)
418 # cpu.core.user instances should be the same as meta sent instances
419 assert instances == len(data[0][0])
420 # all instances should be False, as this is a rate
421 assert all(d is False for d in data[0][0])
422 # memory.used should be an integer
423 assert isinstance(data[0][1], int)
424
425 # next data for rate should not be False
426 _, data = await transport.next_frame()
427 data = json.loads(data)
428 assert all(d is not False for d in data[0][0])
429
430
431 @pytest.mark.asyncio
432 async def test_fsread1_errors(transport: MockTransport, tmp_path: Path) -> None:
433 if os.geteuid() != 0:
434 await transport.check_open('fsread1', path='/etc/shadow', problem='access-denied')
435 else:
436 print('running as root, skipping access-denied check')
437 await transport.check_open('fsread1', path='/', problem='internal-error',
438 reply_keys={'message': "[Errno 21] Is a directory: '/'"})
439 await transport.check_open('fsread1', path='/etc/passwd', max_read_size="lol",
440 problem='protocol-error',
441 reply_keys={'message': "attribute 'max_read_size': must have type int"})
442 await transport.check_open('fsread1', path='/etc/passwd', max_read_size=1,
443 problem='too-large')
444 # default read size limit
445 big_file = tmp_path / 'bigfile.img'
446 fd = os.open(big_file, os.O_RDWR | os.O_CREAT)
447 os.posix_fallocate(fd, 0, 17 * 1024 * 1024)
448 os.close(fd)
449 await transport.check_open('fsread1', path=str(big_file),
450 problem='too-large')
451
452 # -1 implies no limit
453 await transport.check_open('fsread1', path=str(big_file),
454 max_read_size=-1)
455
456
457 @pytest.mark.asyncio
458 async def test_fsread1_size_hint(transport: MockTransport) -> None:
459 data = None
460 stat = os.stat('/usr/lib/os-release')
461 with open('/usr/lib/os-release', 'rb') as fp:
462 data = fp.read()
463 ch = await transport.check_open('fsread1', path='/usr/lib/os-release', binary='raw',
464 reply_keys={'size-hint': stat.st_size})
465 await transport.assert_data(ch, data)
466
467
468 @pytest.mark.asyncio
469 async def test_fsread1_size_hint_absent(transport: MockTransport) -> None:
470 # non-binary fsread1 has no size-hint
471 await transport.check_open('fsread1', path='/etc/passwd', absent_keys=['size-hint'])
472
473
474 @pytest.mark.asyncio
475 async def test_fsread1_size_hint_absent_char_device(transport: MockTransport) -> None:
476 # character device fsread1 has no size-hint
477 await transport.check_open('fsread1', path='/dev/null', binary='raw', absent_keys=['size-hint'])
478
479
480 @pytest.mark.asyncio
481 async def test_fslist1_no_watch(transport: MockTransport, tmp_path: Path) -> None:
482 # empty
483 ch = await transport.check_open('fslist1', path=str(tmp_path), watch=False)
484 await transport.assert_msg('', command='done', channel=ch)
485 await transport.check_close(channel=ch)
486
487 # create a file and a directory in some_dir
488 (tmp_path / 'somefile').touch()
489 (tmp_path / 'somedir').mkdir()
490
491 ch = await transport.check_open('fslist1', path=str(tmp_path), watch=False)
492 # don't assume any ordering
493 msg1 = await transport.next_msg(ch)
494 msg2 = await transport.next_msg(ch)
495 if msg1['type'] == 'file':
496 msg1, msg2 = msg2, msg1
497 assert msg1 == {'event': 'present', 'path': 'somedir', 'type': 'directory'}
498 assert msg2 == {'event': 'present', 'path': 'somefile', 'type': 'file'}
499
500 await transport.assert_msg('', command='done', channel=ch)
501 await transport.check_close(channel=ch)
502
503
504 @pytest.mark.asyncio
505 async def test_fslist1_notexist(transport: MockTransport) -> None:
506 await transport.check_open(
507 'fslist1', path='/nonexisting', watch=False,
508 problem='not-found',
509 reply_keys={'message': "[Errno 2] No such file or directory: '/nonexisting'"})
510
511
512 class GrpPwMock:
513 def __init__(self, uid: 'int', gid: 'int | None' = None) -> None:
514 self.pw_uid = uid
515 self.gr_gid = gid
516
517 def __str__(self) -> str:
518 return f'uid={self.pw_uid},gid={self.gr_gid}'
519
520
521 @pytest.fixture
522 def fchown_mock() -> Generator[unittest.mock.MagicMock, unittest.mock.MagicMock, None]:
523 with unittest.mock.patch('os.fchown', return_value=True) as fchown_mock:
524 yield fchown_mock
525
526
527 @pytest.fixture
528 def user_group_mock(user_group_mock_arg: GrpPwMock) -> Generator[GrpPwMock, GrpPwMock, None]:
529 with unittest.mock.patch('pwd.getpwnam', return_value=user_group_mock_arg):
530 with unittest.mock.patch('grp.getgrnam', return_value=user_group_mock_arg):
531 yield user_group_mock_arg
532
533
534 @pytest.mark.asyncio
535 async def test_fsreplace1(transport: MockTransport, tmp_path: Path) -> None:
536 # create non-existing file
537 myfile = tmp_path / 'newfile'
538 ch = await transport.check_open('fsreplace1', path=str(myfile))
539 transport.send_data(ch, b'some stuff')
540 transport.send_done(ch)
541 await transport.assert_msg('', command='done', channel=ch)
542 await transport.check_close(channel=ch)
543 assert myfile.read_bytes() == b'some stuff'
544 # no leftover files
545 assert os.listdir(tmp_path) == ['newfile']
546 # default umask is applied
547 prev_umask = os.umask(0)
548 os.umask(prev_umask)
549 assert stat.S_IMODE(myfile.stat().st_mode) == 0o666 & ~prev_umask
550
551 # now update its contents
552 ch = await transport.check_open('fsreplace1', path=str(myfile))
553 transport.send_data(ch, b'new new new!')
554 transport.send_done(ch)
555 await transport.assert_msg('', command='done', channel=ch)
556 await transport.check_close(channel=ch)
557 assert myfile.read_bytes() == b'new new new!'
558 # no leftover files
559 assert os.listdir(tmp_path) == ['newfile']
560
561 # set funny permissions to check that they are preserved
562 perms = 0o625
563 myfile.chmod(perms)
564
565 # get the current tag
566 ch = await transport.check_open('fsread1', path=str(myfile))
567 transport.send_done(ch)
568 await transport.assert_data(ch, b'new new new!')
569 await transport.assert_msg('', command='done', channel=ch)
570 transport.send_close(ch)
571 close_msg = await transport.next_msg('')
572 assert close_msg['command'] == 'close'
573 tag = close_msg['tag']
574
575 # update contents with expected tag
576 ch = await transport.check_open('fsreplace1', path=str(myfile), tag=tag)
577 transport.send_data(ch, b'even newer')
578 transport.send_done(ch)
579 await transport.assert_msg('', command='done', channel=ch)
580 await transport.check_close(channel=ch)
581 assert myfile.read_bytes() == b'even newer'
582
583 # preserves existing permissions when giving expected tag
584 assert stat.S_IMODE(myfile.stat().st_mode) == perms
585
586 # mode supplied via attrs overrides existing permissions
587 new_perms = 0o422
588 ch = await transport.check_open('fsreplace1', path=str(myfile), attrs={'mode': new_perms})
589 transport.send_data(ch, b'in the future')
590 transport.send_done(ch)
591 await transport.assert_msg('', command='done', channel=ch)
592 await transport.check_close(channel=ch)
593 assert myfile.read_bytes() == b'in the future'
594 assert stat.S_IMODE(myfile.stat().st_mode) == new_perms
595
596 # write empty file
597 ch = await transport.check_open('fsreplace1', path=str(myfile))
598 transport.send_data(ch, b'')
599 transport.send_done(ch)
600 await transport.assert_msg('', command='done', channel=ch)
601 await transport.check_close(channel=ch)
602 assert myfile.read_bytes() == b''
603
604 # delete file
605 ch = await transport.check_open('fsreplace1', path=str(myfile))
606 transport.send_done(ch)
607 await transport.assert_msg('', command='done', channel=ch)
608 await transport.check_close(channel=ch)
609 assert not myfile.exists()
610
611 # acks
612 ch = await transport.check_open('fsreplace1', path=str(myfile), send_acks='bytes')
613 transport.send_data(ch, b'some stuff')
614 await transport.assert_msg('', command='ack', bytes=10, channel=ch)
615 transport.send_data(ch, b'some more stuff')
616 await transport.assert_msg('', command='ack', bytes=15, channel=ch)
617 transport.send_done(ch)
618 await transport.assert_msg('', command='done', channel=ch)
619 await transport.check_close(channel=ch)
620
621 # tag is "-" and file should not exist
622 newfile = tmp_path / 'new'
623 ch = await transport.check_open('fsreplace1', path=str(newfile), tag='-')
624 transport.send_data(ch, b'some stuff')
625 transport.send_done(ch)
626 await transport.assert_msg('', command='done', channel=ch)
627 await transport.check_close(channel=ch)
628 assert newfile.read_text() == 'some stuff'
629
630 # delete the now written newfile with tag='-' the file should now exist so this should fail
631 ch = await transport.check_open('fsreplace1', path=str(newfile), tag='-')
632 transport.send_done(ch)
633 await transport.assert_msg('', problem='change-conflict', channel=ch)
634 assert newfile.exists()
635
636 # create file with a custom mode
637 newfile.unlink()
638 assert not newfile.exists()
639 ch = await transport.check_open('fsreplace1', path=str(newfile), attrs={'mode': perms})
640 transport.send_data(ch, b'some stuff')
641 transport.send_done(ch)
642 await transport.assert_msg('', command='done', channel=ch)
643 await transport.check_close(channel=ch)
644 assert newfile.read_text() == 'some stuff'
645 assert stat.S_IMODE(newfile.stat().st_mode) == perms
646
647 # create file with tag='-' and custom mode
648 newfile.unlink()
649 assert not newfile.exists()
650 ch = await transport.check_open('fsreplace1', path=str(newfile), tag='-', attrs={'mode': perms})
651 transport.send_data(ch, b'some stuff')
652 transport.send_done(ch)
653 await transport.assert_msg('', command='done', channel=ch)
654 await transport.check_close(channel=ch)
655 assert newfile.read_text() == 'some stuff'
656 assert stat.S_IMODE(newfile.stat().st_mode) == perms
657
658
659 @pytest.mark.asyncio
660 async def test_fsreplace1_change_conflict(transport: MockTransport, tmp_path: Path) -> None:
661 myfile = tmp_path / 'data'
662 myfile.write_text('hello')
663
664 # get current tag from fsread1
665 ch = await transport.check_open('fsread1', path=str(myfile))
666 transport.send_done(ch)
667 await transport.assert_data(ch, b'hello')
668 await transport.assert_msg('', command='done', channel=ch)
669 transport.send_close(ch)
670 close_msg = await transport.next_msg('')
671 assert close_msg['command'] == 'close'
672 tag = close_msg['tag']
673
674 # modify the file in between read and replace operations
675 # we have to wait a bit, assuming that file systems we run tests on have at least centisecond mtime resolution
676 await asyncio.sleep(0.2)
677 myfile.write_text('goodbye')
678
679 # try to replace it, expecting the old contents (via tag)
680 ch = await transport.check_open('fsreplace1', path=str(myfile), tag=tag)
681 transport.send_data(ch, b'newcontent')
682 transport.send_done(ch)
683 await transport.assert_msg('', command='close', channel=ch, problem='change-conflict')
684 transport.send_close(ch)
685
686 # file was not touched by fsreplace1 due to conflict
687 assert myfile.read_text() == 'goodbye'
688
689
690 @pytest.mark.asyncio
691 async def test_fsreplace1_change_conflict_mode(transport: MockTransport, tmp_path: Path) -> None:
692 myfile = tmp_path / 'data'
693 myfile.write_text('hello')
694
695 # get current tag
696 ch = await transport.check_open('fsread1', path=str(myfile))
697 transport.send_done(ch)
698 await transport.assert_data(ch, b'hello')
699 await transport.assert_msg('', command='done', channel=ch)
700 transport.send_close(ch)
701 close_msg = await transport.next_msg('')
702 assert close_msg['command'] == 'close'
703 tag = close_msg['tag']
704
705 # modify the stat metadata in between read and replace operations
706 new_mode = 0o741
707 assert stat.S_IMODE(myfile.stat().st_mode) != new_mode
708 myfile.chmod(new_mode)
709
710 # try to replace it, expecting the old mode (via tag)
711 ch = await transport.check_open('fsreplace1', path=str(myfile), tag=tag)
712 transport.send_data(ch, b'newcontent')
713 transport.send_done(ch)
714 await transport.assert_msg('', command='close', channel=ch, problem='change-conflict')
715 transport.send_close(ch)
716
717 # file was not touched by fsreplace1 due to conflict
718 assert stat.S_IMODE(myfile.stat().st_mode) == new_mode
719 assert myfile.read_text() == 'hello'
720
721
722 @pytest.mark.asyncio
723 async def test_fsreplace1_error(transport: MockTransport, tmp_path: Path) -> None:
724 # trying to write a directory
725 ch = await transport.check_open('fsreplace1', path=str(tmp_path))
726 transport.send_data(ch, b'not me')
727 transport.send_done(ch)
728 await transport.assert_msg('', command='close', channel=ch, problem='access-denied')
729
730 # nonexisting directory
731 ch = await transport.check_open('fsreplace1', path='/non/existing/file')
732 transport.send_data(ch, b'not me')
733 transport.send_done(ch)
734 await transport.assert_msg('', command='close', channel=ch, problem='not-found')
735
736 # invalid send-acks option
737 await transport.check_open('fsreplace1', path=str(tmp_path), send_acks='not-valid',
738 problem='protocol-error',
739 reply_keys={
740 'message': """attribute 'send-acks': invalid value "not-valid" not in ['bytes']"""
741 })
742
743 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'),
744 attrs={'user': 'cockpit', 'group': 'cockpit', 'selinux': True},
745 problem='protocol-error',
746 reply_keys={
747 'message': '"attrs" contains unsupported key(s): selinux',
748 'unsupported_attrs': ['selinux']
749 })
750
751 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'user': 'cockpit'},
752 problem='protocol-error',
753 reply_keys={
754 'message': '"group" attribute is empty while "user" is provided'
755 })
756
757 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'group': 'cockpit'},
758 problem='protocol-error',
759 reply_keys={
760 'message': '"user" attribute is empty while "group" is provided'
761 })
762
763 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'user': 'cockpit', 'group': []},
764 problem='protocol-error',
765 reply_keys={
766 'message': "attribute 'attrs': attribute 'group': must be a string or integer"
767 })
768
769 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'user': [], 'group': 'test'},
770 problem='protocol-error',
771 reply_keys={
772 'message': "attribute 'attrs': attribute 'user': must be a string or integer"
773 })
774
775 mock_val = GrpPwMock(uid=0, gid=1000)
776 with unittest.mock.patch('pwd.getpwnam', side_effect=KeyError()):
777 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'),
778 attrs={'user': 'bazinga', 'group': 'foo'},
779 problem='not-found',
780 reply_keys={
781 'message': 'uid not found for bazinga'
782 })
783
784 with unittest.mock.patch('pwd.getpwnam', return_value=mock_val):
785 with unittest.mock.patch('grp.getgrnam', side_effect=KeyError()):
786 await transport.check_open('fsreplace1', path=str(tmp_path / 'test'),
787 attrs={'user': 'bazinga', 'group': 'test'},
788 problem='not-found',
789 reply_keys={
790 'message': 'gid not found for test'
791 })
792
793
794 ATTRS_TEST_DATA = [
795 (GrpPwMock(1111, 1110), {'user': 1111, 'group': 1110}),
796 (GrpPwMock(1111, 1110), {'user': 'monkey', 'group': 'group'}),
797 ]
798
799
800 @pytest.mark.parametrize(('user_group_mock_arg', 'attrs'), ATTRS_TEST_DATA)
801 @pytest.mark.asyncio
802 async def test_fsreplace1_attrs(transport: MockTransport, fchown_mock: unittest.mock.MagicMock,
803 tmp_path: Path, user_group_mock, attrs: Dict[str, Union[int, str]]) -> None:
804 async def existing_file_with_attrs(filename: str, tag: str) -> None:
805 test_file = tmp_path / filename
806 ch = await transport.check_open('fsreplace1', path=str(test_file), attrs=attrs, tag=tag)
807 transport.send_data(ch, b'content')
808 transport.send_done(ch)
809 await transport.assert_msg('', command='done', channel=ch)
810 await transport.check_close(ch)
811 assert test_file.read_bytes() == b'content'
812
813 async def create_file_with_attrs(filename: str) -> None:
814 test_file = tmp_path / filename
815 ch = await transport.check_open('fsreplace1', path=str(test_file), attrs=attrs)
816 transport.send_data(ch, b'content')
817 transport.send_done(ch)
818 await transport.assert_msg('', command='done', channel=ch)
819 await transport.check_close(ch)
820 assert test_file.read_bytes() == b'content'
821
822 await create_file_with_attrs('test')
823 fchown_mock.assert_called()
824 _, call_uid, call_gid = fchown_mock.call_args[0]
825 assert call_uid == user_group_mock.pw_uid
826 if user_group_mock.gr_gid is None:
827 assert call_gid == user_group_mock.pw_uid
828 else:
829 assert call_gid == user_group_mock.gr_gid
830
831 # Existing file
832 existing_file = tmp_path / 'existing'
833 existing_file.write_text('new')
834
835 tag = tag_from_path(existing_file)
836 assert tag is not None
837 await existing_file_with_attrs('existing', tag)
838 fchown_mock.assert_called()
839 _, call_uid, call_gid = fchown_mock.call_args[0]
840 assert call_uid == user_group_mock.pw_uid
841 if user_group_mock.gr_gid is None:
842 assert call_gid == user_group_mock.pw_uid
843 else:
844 assert call_gid == user_group_mock.gr_gid
845
846
847 @pytest.mark.asyncio
848 async def test_fsreplace1_size_hint(transport: MockTransport, tmp_path: Path) -> None:
849 myfile = tmp_path / 'myfile'
850
851 # create a file, no size hint
852 ch = await transport.check_open('fsreplace1', path=str(myfile))
853 assert list(tmp_path.iterdir()) == [] # no temp file should be created yet
854 transport.send_data(ch, b'content')
855 transport.send_done(ch)
856 await transport.assert_msg('', command='done', channel=ch)
857 await transport.check_close(ch)
858 assert list(tmp_path.iterdir()) == [myfile] # no temp file left
859 assert myfile.read_bytes() == b'content'
860
861 # delete it again
862 ch = await transport.check_open('fsreplace1', path=str(myfile))
863 assert list(tmp_path.iterdir()) == [myfile] # no temp file created
864 transport.send_done(ch)
865 await transport.assert_msg('', command='done', channel=ch)
866 await transport.check_close(ch)
867 assert list(tmp_path.iterdir()) == [] # empty again
868
869 # enospc in advance: 1PB ought to be enough for anybody...
870 ch = transport.send_open('fsreplace1', path=str(myfile), size=1 << 50) # 1PB
871 err = await transport.assert_msg('', command='close', channel=ch, problem='internal-error')
872 message = get_str(err, 'message')
873 assert 'No space left on device' in message or 'File too large' in message
874 assert list(tmp_path.iterdir()) == [] # still empty
875 assert not myfile.exists()
876
877 # ensure cancellation is always a no-op, even with size specified
878 ch = await transport.check_open('fsreplace1', path=str(myfile), size=1 << 20) # 1MB
879 assert len(list(tmp_path.iterdir())) == 1 # observe the temp file created immediately
880 await transport.check_close(ch)
881 assert list(tmp_path.iterdir()) == [] # no temp file left
882 assert not myfile.exists()
883
884 # ...but even size=0 will result in the file being created without payload
885 ch = await transport.check_open('fsreplace1', path=str(myfile), size=0)
886 assert len(list(tmp_path.iterdir())) == 1 # observe the temp file created immediately
887 transport.send_done(ch)
888 await transport.assert_msg('', command='done', channel=ch)
889 await transport.check_close(ch)
890 assert list(tmp_path.iterdir()) == [myfile] # no temp file left
891 assert myfile.read_bytes() == b''
892
893 # check too little data written
894 ch = await transport.check_open('fsreplace1', path=str(myfile), size=1 << 20) # 1 MB
895 assert len(list(tmp_path.iterdir())) == 2 # observe the temp file created immediately
896 transport.send_data(ch, b'too small')
897 transport.send_done(ch)
898 await transport.assert_msg('', command='done', channel=ch)
899 await transport.check_close(ch)
900 assert list(tmp_path.iterdir()) == [myfile] # no temp file left
901 assert myfile.read_bytes() == b'too small'
902
903 # check too much data written
904 ch = await transport.check_open('fsreplace1', path=str(myfile), size=5)
905 assert len(list(tmp_path.iterdir())) == 2 # observe the temp file created immediately
906 transport.send_data(ch, b'too large')
907 transport.send_done(ch)
908 await transport.assert_msg('', command='done', channel=ch)
909 await transport.check_close(ch)
910 assert list(tmp_path.iterdir()) == [myfile] # no temp file left
911 assert myfile.read_bytes() == b'too large'
912
913
914 @pytest.mark.asyncio
915 @pytest.mark.parametrize('channeltype', CHANNEL_TYPES)
916 async def test_channel(bridge: Bridge, transport: MockTransport, channeltype, tmp_path: Path) -> None:
917 payload = channeltype.payload
918 args = dict(channeltype.restrictions)
919
920 async def serve_page(reader, writer):
921 while True:
922 line = await reader.readline()
923 if line.strip():
924 print('HTTP Request line', line)
925 else:
926 break
927
928 print('Sending HTTP reply')
929 writer.write(b'HTTP/1.1 200 OK\r\n\r\nA document\r\n')
930 await writer.drain()
931 writer.close()
932
933 srv = str(tmp_path / 'sock')
934 await asyncio.start_unix_server(serve_page, srv)
935
936 if payload == 'fsinfo':
937 args = {'path': '/', 'attrs': []}
938 elif payload == 'fslist1':
939 args = {'path': '/', 'watch': False}
940 elif payload == 'fsread1':
941 args = {'path': '/etc/passwd'}
942 elif payload == 'fsreplace1':
943 args = {'path': 'tmpfile'}
944 elif payload == 'fswatch1':
945 args = {'path': '/etc'}
946 elif payload == 'http-stream1':
947 args = {'internal': 'packages', 'method': 'GET', 'path': '/manifests.js',
948 'headers': {'X-Forwarded-Proto': 'http', 'X-Forwarded-Host': 'localhost'}}
949 elif payload == 'http-stream2':
950 args = {'method': 'GET', 'path': '/bzzt', 'unix': srv}
951 elif payload == 'stream':
952 if 'spawn' in args:
953 args = {'spawn': ['cat']}
954 else:
955 args = {'unix': srv}
956 elif payload == 'metrics1' and channeltype.restrictions:
957 args['metrics'] = [{'name': 'memory.free'}]
958 elif payload == 'metrics1':
959 pytest.skip('no PCP metric data')
960 elif payload == 'dbus-json3':
961 if not os.path.exists('/run/dbus/system_bus_socket'):
962 pytest.skip('no dbus')
963 elif payload == 'session-control':
964 pytest.skip('too special')
965 else:
966 args = {}
967
968 print('sending open', payload, args)
969 ch = transport.send_open(payload, **args)
970 saw_data = False
971
972 while True:
973 channel, msg = await transport.next_frame()
974 print(channel, msg)
975 if channel == '':
976 control = json.loads(msg)
977 assert control['channel'] == ch
978 command = control['command']
979 if command == 'ready':
980 if 'spawn' in args:
981 assert isinstance(control['pid'], int)
982 with open(f"/proc/{control['pid']}/cmdline") as f:
983 assert f.read() == 'cat\0'
984 # If we get ready, it's our turn to send data first.
985 # Hopefully we didn't receive any before.
986 assert not saw_data
987 break
988 else:
989 pytest.fail(f'unexpected event: {(payload, args, control)}')
990 else:
991 saw_data = True
992
993 # If we're here, it's our turn to talk. Say nothing.
994 print('sending done')
995 transport.send_done(ch)
996
997 if payload in ['dbus-json3', 'fswatch1', 'metrics1', 'null']:
998 transport.send_close(ch)
999
1000 while True:
1001 channel, msg = await transport.next_frame()
1002 print(channel, msg)
1003 if channel == '':
1004 control = json.loads(msg)
1005 command = control['command']
1006 if command == 'done':
1007 continue
1008 elif command == 'close':
1009 assert 'problem' not in control
1010 return
1011
1012
1013 @pytest.mark.parametrize(('os_release', 'expected'), [
1014 # simple values, with comments and ignored space
1015 (
1016 '\n\n# simple\nID=mylinux\nVERSION=1.2\n\n# comment\nFOO=bar\n\n',
1017 {'ID': 'mylinux', 'VERSION': '1.2', 'FOO': 'bar'}
1018 ),
1019 # quoted values
1020 (
1021 '''SINGLE='foo:bar '\nDOUBLE=" bar//foo"\n''',
1022 {'SINGLE': 'foo:bar ', 'DOUBLE': ' bar//foo'}
1023 ),
1024 # ignore ungrammatical lines
1025 (
1026 'A=a\nNOVALUE\nDOUBLEEQ=a=b\nB=b',
1027 {'A': 'a', 'B': 'b'}
1028 ),
1029 # invalid values; anything outside [A-Za-z0-9] must be quoted; but our parser is more liberal
1030 (
1031 'X=a:b\nY=a b\nZ=a-b\nV=a_b',
1032 {'X': 'a:b', 'Z': 'a-b', 'V': 'a_b'}
1033 ),
1034 ])
1035 def test_get_os_release(os_release: str, expected: str) -> None:
1036 with unittest.mock.patch('builtins.open', unittest.mock.mock_open(read_data=os_release)):
1037 assert Bridge.get_os_release() == expected
1038
1039
1040 class AckChannel(AsyncChannel):
1041 payload = 'ack1'
1042
1043 async def run(self, options: JsonObject) -> None:
1044 self.semaphore = asyncio.Semaphore(0)
1045 self.ready()
1046 while await self.read():
1047 await self.semaphore.acquire()
1048
1049
1050 @pytest.mark.asyncio
1051 async def test_async_acks(bridge: Bridge, transport: MockTransport) -> None:
1052 # Inject our mock channel type
1053 for rule in bridge.routing_rules:
1054 if isinstance(rule, ChannelRoutingRule):
1055 rule.table['ack1'] = [AckChannel]
1056
1057 # invalid send-acks values
1058 await transport.check_open('ack1', send_acks=True, problem='protocol-error')
1059 await transport.check_open('ack1', send_acks='x', problem='protocol-error')
1060
1061 # open the channel with acks off
1062 ch = await transport.check_open('ack1')
1063 # send a bunch of data and get no acks
1064 for _ in range(20):
1065 transport.send_data(ch, b'x')
1066 # this will assert that we receive only the close message (and no acks)
1067 await transport.check_close(ch)
1068
1069 # open the channel with acks on
1070 ch = await transport.check_open('ack1', send_acks='bytes')
1071 # send a bunch of data
1072 for _ in range(20):
1073 transport.send_data(ch, b'x')
1074 # we should get exactly one ack (from the first read) before things block
1075 await transport.assert_msg('', channel=ch, command='ack', bytes=1)
1076 # this will assert that we receive only the close message (and no additional acks)
1077 await transport.check_close(ch)
1078
1079 # open the channel with acks on
1080 ch = await transport.check_open('ack1', send_acks='bytes')
1081 # fish the open channel out of the bridge
1082 ack = bridge.open_channels[ch]
1083 assert isinstance(ack, AckChannel)
1084 # let's give ourselves a bit more headroom
1085 for _ in range(5):
1086 ack.semaphore.release()
1087 # send a bunch of data and get some acks
1088 for _ in range(10):
1089 transport.send_data(ch, b'x')
1090 for _ in range(6):
1091 await transport.assert_msg('', channel=ch, command='ack', bytes=1)
1092 # make sure that as we "consume" the data we get more acks:
1093 for _ in range(4):
1094 # no ack in the queue...
1095 await transport.assert_empty()
1096 ack.semaphore.release()
1097 # ... but now there is.
1098 await transport.assert_msg('', channel=ch, command='ack', bytes=1)
1099 # make some more room (for data we didn't send)
1100 for _ in range(5):
1101 ack.semaphore.release()
1102 # but we shouldn't have gotten any acks for those
1103 await transport.check_close(ch)
1104
1105
1106 @pytest.mark.asyncio
1107 async def test_flow_control(transport: MockTransport, tmp_path: Path) -> None:
1108 bigun = tmp_path / 'bigun'
1109 total_bytes = 8 * 1024 * 1024
1110 recvd_bytes = 0
1111 bigun.write_bytes(b'0' * total_bytes)
1112 fsread1 = await transport.check_open('fsread1', path=str(bigun), flow_control=True)
1113
1114 # We should receive a number of blocks of initial data, each with a ping.
1115 # We save the pings to reply later.
1116 pings: 'deque[JsonObject]' = deque()
1117
1118 async def recv_one():
1119 nonlocal recvd_bytes
1120
1121 channel, data = await transport.next_frame()
1122 assert channel == fsread1
1123 assert data == b'0' * Channel.BLOCK_SIZE
1124 recvd_bytes += len(data)
1125
1126 ping = await transport.next_msg('')
1127 assert ping['command'] == 'ping'
1128 assert ping['channel'] == fsread1
1129 assert ping['sequence'] == recvd_bytes
1130 pings.append(ping)
1131
1132 while recvd_bytes < Channel.SEND_WINDOW:
1133 await recv_one()
1134
1135 # We should stall out here. Make sure nothing else arrives.
1136 await transport.assert_empty()
1137
1138 # Start sending pongs and make sure we receive a new block of data for each
1139 # one (as the window extends)
1140 while recvd_bytes < total_bytes:
1141 ping = pings.popleft()
1142 transport.send_json('', **dict(ping, command='pong'))
1143 await recv_one()
1144
1145 transport.send_close(fsread1)
1146
1147
1148 @pytest.mark.asyncio
1149 async def test_large_upload(transport: MockTransport, tmp_path: Path) -> None:
1150 fifo = str(tmp_path / 'pipe')
1151 os.mkfifo(fifo)
1152
1153 sender = await transport.check_open('stream', spawn=['dd', f'of={fifo}'])
1154 # cockpit.js doesn't do flow control, so neither do we...
1155 chunk = b'0' * Channel.BLOCK_SIZE
1156 loops = 100
1157 for _ in range(loops):
1158 transport.send_data(sender, chunk)
1159 transport.send_done(sender)
1160
1161 # we should be in a state now where we have a bunch of bytes queued up in
1162 # the bridge but they can't be delivered because nobody is reading from the
1163 # pipe... make sure dd is still running and we didn't get any messages.
1164 await transport.assert_empty()
1165
1166 # start draining now, and make sure we get everything we sent.
1167 with open(fifo, 'rb') as receiver:
1168 received = await asyncio.get_running_loop().run_in_executor(None, receiver.read)
1169 assert len(received) == loops * Channel.BLOCK_SIZE
1170
1171 # and now our done and close messages should come
1172 await transport.assert_msg('', command='done', channel=sender)
1173 await transport.assert_msg('', command='close', channel=sender)
1174
1175
1176 class FsInfoClient:
1177 def __init__(self, transport: MockTransport, channel: str):
1178 self.transport = transport
1179 self.channel = channel
1180 self.state: JsonObject = {}
1181
1182 @classmethod
1183 async def open(
1184 cls,
1185 transport: MockTransport,
1186 path: 'str | Path',
1187 attrs: Sequence[str] = ('type', 'target'),
1188 fnmatch: str = '*.txt',
1189 **kwargs: JsonValue
1190 ) -> 'FsInfoClient':
1191 channel = await transport.check_open('fsinfo', path=str(path), attrs=attrs,
1192 fnmatch=fnmatch, reply_keys=None,
1193 absent_keys=(), **kwargs) # type: ignore[arg-type]
1194 return cls(transport, channel)
1195
1196 async def next_state(self) -> JsonObject:
1197 while True:
1198 patch = await self.transport.next_msg(self.channel)
1199 self.state = json_merge_patch(self.state, patch)
1200 if not get_bool(self.state, 'partial', None):
1201 break
1202 return self.state
1203
1204 async def wait(self) -> JsonObject:
1205 state = await self.next_state()
1206 await self.transport.assert_msg('', command='done', channel=self.channel)
1207 await self.transport.assert_msg('', command='close', channel=self.channel)
1208 return state
1209
1210 async def close(self):
1211 await self.transport.check_close(self.channel)
1212
1213
1214 def fsinfo_err(err: int) -> JsonObject:
1215 problems = {
1216 errno.ENOENT: 'not-found',
1217 errno.EPERM: 'access-denied',
1218 errno.EACCES: 'access-denied',
1219 errno.ENOTDIR: 'not-directory'
1220 }
1221 return {
1222 'error': {
1223 'problem': problems.get(err, 'internal-error'),
1224 'message': os.strerror(err),
1225 'errno': errno.errorcode[err],
1226 }
1227 }
1228
1229
1230 @pytest.fixture
1231 def fsinfo_test_cases(tmp_path: Path) -> 'Iterator[dict[Path, JsonObject]]':
1232 # a normal directory
1233 normal_dir = tmp_path / 'dir'
1234 normal_dir.mkdir()
1235 (normal_dir / 'dir-file.txt').write_text('dir file')
1236 (normal_dir / 'dir-file.xtx').write_text('do not read this')
1237
1238 # a directory without +x (search)
1239 no_x_dir = tmp_path / 'no-x-dir'
1240 no_x_dir.mkdir()
1241 (no_x_dir / 'no-x-dir-file.txt').write_text('file')
1242 no_x_dir.chmod(0o644)
1243
1244 # a directory without +r (read)
1245 no_r_dir = tmp_path / 'no-r-dir'
1246 no_r_dir.mkdir()
1247 (no_r_dir / 'no-r-dir-file.txt').write_text('file')
1248 no_r_dir.chmod(0o311)
1249
1250 # a normal file
1251 file = tmp_path / 'file'
1252 file.write_text('normal file')
1253
1254 # a non-readable file
1255 no_r_file = tmp_path / 'no-r-file'
1256 no_r_file.write_text('inaccessible file')
1257 no_r_file.chmod(0)
1258
1259 # a device
1260 dev = tmp_path / 'dev'
1261 dev.symlink_to('/dev/null')
1262
1263 # a dangling symlink
1264 dangling = tmp_path / 'dangling'
1265 dangling.symlink_to('does-not-exist')
1266
1267 # a symlink pointing to itself
1268 loopy = tmp_path / 'loopy'
1269 loopy.symlink_to(loopy)
1270
1271 expected_state: 'dict[Path, JsonObject]' = {
1272 normal_dir: {"info": {"type": "dir", "entries": {'dir-file.txt': {"type": "reg"}}}},
1273
1274 # can't stat() the file
1275 no_x_dir: {"info": {"type": "dir", "entries": {"no-x-dir-file.txt": {}}}},
1276
1277 # can't read the directory, so no entries
1278 no_r_dir: {"info": {"type": "dir"}},
1279
1280 # normal file, can read its contents
1281 file: {"info": {"type": "reg"}},
1282
1283 # can't read file, so no contents
1284 no_r_file: {"info": {"type": "reg"}},
1285
1286 # a device
1287 dev: {"info": {"type": "chr"}},
1288
1289 # a dangling symlink
1290 dangling: fsinfo_err(errno.ENOENT),
1291
1292 # a link pointing at itself
1293 loopy: fsinfo_err(errno.ELOOP),
1294 }
1295
1296 if os.getuid() == 0:
1297 # we can't do the permissions-dependent tests as root
1298 del expected_state[no_x_dir]
1299 del expected_state[no_r_dir]
1300 del expected_state[no_r_file]
1301
1302 try:
1303 yield expected_state
1304
1305 finally:
1306 # restore writable permissions on directories. pytest has trouble cleaning
1307 # these up, otherwise...
1308 for path in expected_state:
1309 if not path.is_symlink() and path.is_dir():
1310 path.chmod(0o700)
1311
1312
1313 @pytest.mark.asyncio
1314 async def test_fsinfo_nopath(transport: MockTransport) -> None:
1315 await transport.check_open('fsinfo', attrs=['type'], problem='protocol-error')
1316
1317
1318 @pytest.mark.asyncio
1319 async def test_fsinfo_noattrs(transport: MockTransport) -> None:
1320 await transport.check_open('fsinfo', path='/', problem='protocol-error')
1321
1322
1323 @pytest.mark.asyncio
1324 async def test_fsinfo_relative(transport: MockTransport) -> None:
1325 await transport.check_open('fsinfo', path='rel', problem='protocol-error')
1326 await transport.check_open('fsinfo', path='.', problem='protocol-error')
1327
1328
1329 @pytest.mark.asyncio
1330 async def test_fsinfo_nofollow_watch(transport: MockTransport) -> None:
1331 await transport.check_open('fsinfo', path='/', attrs=[], watch=True, follow=False, problem='protocol-error')
1332
1333
1334 @pytest.mark.asyncio
1335 async def test_fsinfo_nofollow_targets(transport: MockTransport) -> None:
1336 await transport.check_open('fsinfo', path='/', attrs=['targets'], follow=False, problem='protocol-error')
1337
1338
1339 @pytest.mark.asyncio
1340 async def test_fsinfo_empty_update(transport: MockTransport, tmp_path: Path) -> None:
1341 # test an empty update — make sure nothing lands on the wire
1342 ch = await transport.check_open('fsinfo', path=str(tmp_path), attrs=['type'], watch=True)
1343 assert await transport.next_msg(ch) == {'info': {"type": "dir"}}
1344 tmp_path.touch()
1345 await asyncio.sleep(0.1) # fsinfo waits 0.1 before dispatching updates
1346 await transport.assert_empty() # this waits another 0.1
1347 await transport.check_close(ch)
1348
1349
1350 @pytest.mark.asyncio
1351 async def test_fsinfo(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
1352 for path, expected_state in fsinfo_test_cases.items():
1353 client = await FsInfoClient.open(transport, path)
1354 assert await client.wait() == expected_state
1355
1356
1357 @pytest.mark.asyncio
1358 async def test_fsinfo_nofollow(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
1359 for path, expected_state in fsinfo_test_cases.items():
1360 if path.name == 'loopy':
1361 # with nofollow, this won't fail — we'll see the link itself
1362 expected_state = {"info": {"type": "lnk", "target": str(path)}}
1363 elif path.name == 'dev':
1364 expected_state = {"info": {"type": "lnk", "target": "/dev/null"}}
1365 elif path.name == 'dangling':
1366 expected_state = {"info": {"type": "lnk", "target": "does-not-exist"}}
1367
1368 client = await FsInfoClient.open(transport, path, follow=False)
1369 assert await client.wait() == expected_state
1370
1371
1372 @pytest.mark.asyncio
1373 async def test_fsinfo_onlydir(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
1374 for path, expected_state in fsinfo_test_cases.items():
1375 if 'dir' not in path.name and 'error' not in expected_state:
1376 expected_state = fsinfo_err(errno.ENOTDIR)
1377
1378 # with '/' appended, this should only open dirs
1379 client = await FsInfoClient.open(transport, str(path) + '/')
1380 assert await client.wait() == expected_state, f'for {path}'
1381
1382
1383 @pytest.mark.asyncio
1384 async def test_fsinfo_onlydir_watch(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
1385 for path, expected_state in fsinfo_test_cases.items():
1386 # note the order here: because our check for notdir is implemented
1387 # inside of the bridge, we try inotify first and check for notdir
1388 # second. if systemd_ctypes supports this some day, it may change.
1389 if path.name.startswith('no-r'):
1390 # we need this one because we can't inotify files without +r
1391 expected_state = fsinfo_err(errno.EACCES)
1392 elif 'dir' not in path.name and 'error' not in expected_state:
1393 # and this one to deal with not-dir
1394 expected_state = fsinfo_err(errno.ENOTDIR)
1395
1396 # with '/' appended, this should only open dirs
1397 client = await FsInfoClient.open(transport, str(path) + '/', watch=True)
1398 assert await client.next_state() == expected_state
1399 await client.close()
1400
1401
1402 @pytest.mark.asyncio
1403 async def test_fsinfo_watch_identity_changes(
1404 transport: MockTransport, tmp_path: Path, fsinfo_test_cases: 'dict[Path, JsonObject]'
1405 ) -> None:
1406 # we will now point a symlink to the various possibilities to make sure the
1407 # transitions are correctly handled
1408 link = tmp_path / 'link'
1409 client = await FsInfoClient.open(transport, link, watch=True)
1410
1411 # we didn't make a link yet, so...
1412 assert (await client.next_state()) == fsinfo_err(errno.ENOENT)
1413
1414 # in watch mode we report errors a bit more sensitively: we also report
1415 # them if we can't inotify the inode in question, which requires +r
1416 # permission. as such, we need to modify our 'no-r' tests:
1417 for path in list(fsinfo_test_cases):
1418 if path.name.startswith('no-r'):
1419 fsinfo_test_cases[path] = fsinfo_err(errno.EACCES)
1420 if path.name == 'dangling':
1421 # this breaks our logic below because we transition from ENOENT to ENOENT
1422 del fsinfo_test_cases[path]
1423
1424 possibilities = tuple(fsinfo_test_cases)
1425 for from_file in possibilities:
1426 for to_file in possibilities:
1427 if from_file is to_file:
1428 continue
1429
1430 # link to the original file and check state
1431 link.symlink_to(from_file)
1432 assert await client.next_state() == fsinfo_test_cases[from_file]
1433
1434 # Try to generate some events immediately before we switch the link
1435 # to ensure the event is suppressed. Any one of these could fail
1436 # due to not being a directory or not having permissions.
1437 with contextlib.suppress(OSError):
1438 from_file.touch()
1439 with contextlib.suppress(OSError):
1440 (from_file / 'a.txt').touch()
1441 with contextlib.suppress(OSError):
1442 (from_file / 'a.txt').unlink()
1443
1444 # atomic replace, check state
1445 (tmp_path / 'tmp').symlink_to(to_file)
1446 (tmp_path / 'tmp').rename(link)
1447 assert await client.next_state() == fsinfo_test_cases[to_file]
1448
1449 if to_file.name == 'dir':
1450 # copied from fsinfo_test_cases fixture
1451 dir_entries = {'dir-file.txt': {"type": "reg"}}
1452 expected_state = {"info": {"type": "dir", "entries": dir_entries}}
1453
1454 (to_file / 'a.txt').write_text('a file')
1455 dir_entries['a.txt'] = {"type": "reg"}
1456 (to_file / 'b.txt').write_text('b file')
1457 dir_entries['b.txt'] = {"type": "reg"}
1458 (to_file / 'a.xtx').write_text('b file')
1459 (to_file / 'b.xtx').write_text('b file')
1460 assert await client.next_state() == expected_state
1461
1462 (to_file / 'a.xtx').unlink()
1463 (to_file / 'b.xtx').unlink()
1464 (to_file / 'dir.txt').mkdir()
1465 dir_entries['dir.txt'] = {"type": "dir"}
1466 (to_file / 'sym.txt').symlink_to('/x')
1467 dir_entries['sym.txt'] = {"type": "lnk", "target": "/x"}
1468 assert await client.next_state() == expected_state
1469
1470 (to_file / 'sym.txt').unlink()
1471 del dir_entries['sym.txt']
1472 assert await client.next_state() == expected_state
1473
1474 # we intentionally try not to receive these events — we want
1475 # them to get lost when the identity changes, below
1476 (to_file / 'dir.txt').rmdir()
1477 (to_file / 'a.txt').unlink()
1478 (to_file / 'b.txt').unlink()
1479
1480 # delete link to start over
1481 link.unlink()
1482 assert (await client.next_state()) == fsinfo_err(errno.ENOENT)
1483
1484 # let the pending event handler occasionally run to find nothing to process
1485 await asyncio.sleep(0.15)
1486
1487 await client.close()
1488
1489
1490 @pytest.mark.asyncio
1491 async def test_fsinfo_self_owner(transport: MockTransport, tmp_path: Path) -> None:
1492 client = await FsInfoClient.open(transport, tmp_path, ['user', 'uid', 'group', 'gid'])
1493 state = await client.wait()
1494 info = get_dict(state, 'info')
1495
1496 assert get_int(info, 'uid') == os.getuid()
1497 assert get_int(info, 'gid') == os.getgid()
1498 assert info.get('user') == getpass.getuser()
1499 assert info.get('group') == grp.getgrgid(os.getgid()).gr_name # hopefully true...
1500
1501
1502 @pytest.mark.asyncio
1503 async def test_fsinfo_other_owner(transport: MockTransport, tmp_path: Path) -> None:
1504 tmpfile = tmp_path / 'x'
1505 tmpfile.touch()
1506
1507 # try to get root to own this thing using a couple of tricks that may work
1508 # inside or outside of toolbox or containers
1509 quoted = shlex.quote(str(tmpfile))
1510 subprocess.run(fr'''
1511 podman unshare chown 888:888 {quoted} || SUDO_ASKPASS=true sudo -A chown 0:0 '{quoted}'
1512 ''', shell=True, check=False)
1513
1514 # verify that we ended up with a uid/gid with no user
1515 buf = tmpfile.stat()
1516 try:
1517 pwd.getpwuid(buf.st_uid)
1518 pytest.skip('Failed to find unmapped uid')
1519 except KeyError:
1520 pass # good!
1521 try:
1522 grp.getgrgid(buf.st_gid)
1523 pytest.skip('Failed to find unmapped gid')
1524 except KeyError:
1525 pass # good!
1526
1527 client = await FsInfoClient.open(transport, tmpfile, ['user', 'uid', 'group', 'gid'])
1528 state = await client.wait()
1529 info = get_dict(state, 'info')
1530
1531 assert get_int(info, 'uid') == buf.st_uid
1532 assert get_int(info, 'gid') == buf.st_gid
1533 assert info.get('user') == buf.st_uid # numeric fallback
1534 assert info.get('group') == buf.st_gid # numeric fallback
1535
1536
1537 @pytest.mark.asyncio
1538 async def test_fsinfo_targets(transport: MockTransport, tmp_path: Path) -> None:
1539 # we are only interested in the things that start with 'l'
1540 watch = await FsInfoClient.open(transport, tmp_path, ['type', 'target', 'targets'], fnmatch='l*', watch=True)
1541
1542 entries: JsonDict = {}
1543 targets: JsonDict = {}
1544 state = {"info": {"type": "dir", "entries": entries, "targets": targets}}
1545 assert await watch.next_state() == state
1546
1547 # none of those will show up in entries (not 'l*')
1548 (tmp_path / 'dir').mkdir()
1549 (tmp_path / 'dir' / 'file').write_text('abc')
1550 (tmp_path / 'dir' / 'lonely').write_text('abc')
1551 (tmp_path / 'dir' / 'dir').mkdir()
1552 (tmp_path / 'file').write_text('abc')
1553 (tmp_path / 'Lonely').write_text('abc')
1554
1555 # this one will show up in entries because it matches 'l*'
1556 (tmp_path / 'loved').write_text('abc')
1557 entries['loved'] = {'type': 'reg'}
1558
1559 # a link that won't show up anywhere (no fnmatch)
1560 (tmp_path / 'LonelyLink').symlink_to('dir/lonely')
1561
1562 # link to things that will land in targets because they're not in fnmatch
1563 (tmp_path / 'lfile').symlink_to('file')
1564 entries['lfile'] = {'type': 'lnk', 'target': 'file'}
1565 targets['file'] = {'type': 'reg'}
1566 (tmp_path / 'ldir').symlink_to('dir')
1567 entries['ldir'] = {'type': 'lnk', 'target': 'dir'}
1568 targets['dir'] = {'type': 'dir'}
1569
1570 # link to things that will land in targets because they're in another dir
1571 (tmp_path / 'ldirfile').symlink_to('dir/file')
1572 entries['ldirfile'] = {'type': 'lnk', 'target': 'dir/file'}
1573 targets['dir/file'] = {'type': 'reg'}
1574 (tmp_path / 'ldirdir').symlink_to('dir/dir')
1575 entries['ldirdir'] = {'type': 'lnk', 'target': 'dir/dir'}
1576 targets['dir/dir'] = {'type': 'dir'}
1577 (tmp_path / 'lnull').symlink_to('/dev/null')
1578 entries['lnull'] = {'type': 'lnk', 'target': '/dev/null'}
1579 targets['/dev/null'] = {'type': 'chr'}
1580 (tmp_path / 'lroot').symlink_to('/')
1581 entries['lroot'] = {'type': 'lnk', 'target': '/'}
1582 targets['/'] = {'type': 'dir'}
1583
1584 # link to things that won't land in targets because they're in entries
1585 (tmp_path / 'llfile').symlink_to('lfile')
1586 entries['llfile'] = {'type': 'lnk', 'target': 'lfile'}
1587 (tmp_path / 'lldir').symlink_to('ldir')
1588 entries['lldir'] = {'type': 'lnk', 'target': 'ldir'}
1589 (tmp_path / 'lloved').symlink_to('loved')
1590 entries['lloved'] = {'type': 'lnk', 'target': 'loved'}
1591
1592 # a link to the current directory won't show up in targets since we already
1593 # report its attributes directly as our toplevel state structure
1594 (tmp_path / 'ldot').symlink_to('.')
1595 entries['ldot'] = {'type': 'lnk', 'target': '.'}
1596
1597 # a link to the parent directory should definitely show up, though
1598 (tmp_path / 'ldotdot').symlink_to('..')
1599 entries['ldotdot'] = {'type': 'lnk', 'target': '..'}
1600 targets['..'] = {'type': 'dir'}
1601
1602 # make sure the watch managed to pick that all up
1603 assert await watch.next_state() == state
1604
1605 # double-check with the non-watch variant
1606 client = await FsInfoClient.open(transport, tmp_path, ['type', 'target', 'targets'], fnmatch='l*')
1607 assert await client.wait() == state
1608
1609
1610 @pytest.mark.asyncio
1611 async def test_fsinfo_access_attrs(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
1612 for path, expected_state in fsinfo_test_cases.items():
1613 # these are errors
1614 if path.name == 'dangling' or path.name == 'loopy':
1615 continue
1616
1617 read_ok = True
1618 write_ok = True
1619 exec_ok = path.is_dir()
1620
1621 if path.name == 'no-r-dir':
1622 read_ok = False
1623 elif path.name == 'no-x-dir':
1624 exec_ok = False
1625 elif path.name == 'no-r-file':
1626 read_ok = False
1627 write_ok = False
1628 exec_ok = False
1629
1630 expected_state = {'info': {'r-ok': read_ok, 'w-ok': write_ok, 'x-ok': exec_ok}}
1631
1632 # fnmatch='' to not include entries
1633 client = await FsInfoClient.open(transport, path, attrs=['w-ok', 'r-ok', 'x-ok'], fnmatch='')
1634 assert await client.wait() == expected_state, f'for path={path.name}'
1635
1636 # Symlink access bits are always allowed
1637 for path, expected_state in fsinfo_test_cases.items():
1638 if path.name != 'dev':
1639 continue
1640
1641 expected_state = {'info': {'r-ok': True, 'w-ok': True, 'x-ok': True}}
1642 client = await FsInfoClient.open(transport, path, attrs=['w-ok', 'r-ok', 'x-ok'], follow=False)
1643 assert await client.wait() == expected_state, f'for path={path.name}'
1644
1645
1646 @pytest.mark.parametrize('supports_askpass', [False, True], ids=['no-askpass', 'askpass'])
1647 def test_is_valid_superuser_config_sudo_askpass(tmp_path: Path, *, supports_askpass: bool) -> None:
1648 sudo = tmp_path / 'sudo'
1649 sudo.write_text(f'#!/bin/sh\nexit {"0" if supports_askpass else "1"}\n')
1650 sudo.chmod(0o755)
1651
1652 config = BridgeConfig({
1653 'privileged': True,
1654 'spawn': [str(sudo), '-k', '-A', 'cockpit-bridge', '--privileged'],
1655 })
1656 assert is_valid_superuser_config(config) == supports_askpass
1657
1658
1659 def test_is_valid_superuser_config_not_sudo(tmp_path: Path) -> None:
1660 danger = tmp_path / 'danger'
1661 pkexec = tmp_path / 'pkexec'
1662 pkexec.write_text(f'#!/bin/sh\ntouch {danger}\n')
1663 pkexec.chmod(0o755)
1664
1665 config = BridgeConfig({
1666 'privileged': True,
1667 'spawn': [str(pkexec), 'cockpit-bridge', '--privileged'],
1668 })
1669 assert is_valid_superuser_config(config)
1670 assert not danger.exists()
1671
1672
1673 @pytest.mark.asyncio
1674 @pytest.mark.parametrize('absolute', [False, True], ids=['relpath', 'abspath'])
1675 @pytest.mark.parametrize('custom_path', [False, True], ids=['default-path', 'custom-path'])
1676 @pytest.mark.parametrize('exists', [False, True], ids=['missing', 'exists'])
1677 async def test_is_valid_superuser_config(
1678 tmp_path: Path, *, absolute: bool, custom_path: bool, exists: bool
1679 ) -> None:
1680 args: JsonObject
1681 if absolute:
1682 args = {'spawn': ['/usr/bin/true' if exists else '/nonexistent/path/true']}
1683 elif custom_path:
1684 if exists:
1685 (tmp_path / 'my-bridge').write_text('#!/bin/sh\n')
1686 (tmp_path / 'my-bridge').chmod(0o755)
1687 args = {'spawn': ['my-bridge'], 'environ': [f'PATH={tmp_path}']}
1688 else:
1689 args = {'spawn': ['true' if exists else 'nonexistent-binary']}
1690
1691 config = BridgeConfig({**args, 'privileged': True})
1692 assert is_valid_superuser_config(config) == exists
1693
1694 with contextlib.ExitStack() as expected:
1695 if not exists:
1696 expected.enter_context(pytest.raises(FileNotFoundError))
1697 peer = ConfiguredPeer(unittest.mock.Mock(), config)
1698 await peer.do_connect_transport()
1699 peer.close()