File: test_bridge.py

package info (click to toggle)
cockpit 337-1
  • links: PTS, VCS
  • area: main
  • in suites: trixie
  • size: 36,232 kB
  • sloc: javascript: 47,090; python: 38,766; ansic: 35,470; xml: 6,048; sh: 3,413; makefile: 614
file content (1589 lines) | stat: -rw-r--r-- 63,472 bytes parent folder | download | duplicates (2)
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
1476
1477
1478
1479
1480
1481
1482
1483
1484
1485
1486
1487
1488
1489
1490
1491
1492
1493
1494
1495
1496
1497
1498
1499
1500
1501
1502
1503
1504
1505
1506
1507
1508
1509
1510
1511
1512
1513
1514
1515
1516
1517
1518
1519
1520
1521
1522
1523
1524
1525
1526
1527
1528
1529
1530
1531
1532
1533
1534
1535
1536
1537
1538
1539
1540
1541
1542
1543
1544
1545
1546
1547
1548
1549
1550
1551
1552
1553
1554
1555
1556
1557
1558
1559
1560
1561
1562
1563
1564
1565
1566
1567
1568
1569
1570
1571
1572
1573
1574
1575
1576
1577
1578
1579
1580
1581
1582
1583
1584
1585
1586
1587
1588
1589
import argparse
import asyncio
import contextlib
import errno
import getpass
import grp
import json
import os
import pwd
import shlex
import stat
import subprocess
import sys
import unittest.mock
from collections import deque
from pathlib import Path
from typing import Dict, Generator, Iterable, Iterator, Sequence, Union

import pytest

from cockpit._vendor.systemd_ctypes import bus
from cockpit.bridge import Bridge
from cockpit.channel import AsyncChannel, Channel, ChannelRoutingRule
from cockpit.channels import CHANNEL_TYPES
from cockpit.channels.filesystem import tag_from_path
from cockpit.jsonutil import JsonDict, JsonObject, JsonValue, get_bool, get_dict, get_int, get_str, json_merge_patch
from cockpit.packages import BridgeConfig

from .mocktransport import MOCK_HOSTNAME, MockTransport


class test_iface(bus.Object):
    sig = bus.Interface.Signal('s')
    prop = bus.Interface.Property('s', value='none')

    @bus.Interface.Method('s')
    def get_prop(self) -> str:
        return self.prop


@pytest.fixture
def bridge() -> Bridge:
    bridge = Bridge(argparse.Namespace(privileged=False, beipack=False))
    bridge.superuser_bridges = list(bridge.superuser_rule.bridges)  # type: ignore[attr-defined]
    return bridge


def add_pseudo(bridge: Bridge) -> None:
    bridge.more_superuser_bridges = [*bridge.superuser_bridges, 'pseudo']  # type: ignore[attr-defined]

    assert bridge.packages is not None

    # Add pseudo to the existing set of superuser rules
    bridge.superuser_rule.set_configs([
        *bridge.packages.get_bridge_configs(),
        BridgeConfig({
            'label': 'pseudo',
            'spawn': [
                sys.executable, os.path.abspath(f'{__file__}/../pseudo.py'),
                sys.executable, '-m', 'cockpit.bridge', '--privileged'
            ],
            'environ': [
                f'PYTHONPATH={":".join(sys.path)}'
            ],
            'privileged': True
        })
    ])


@pytest.fixture
def no_init_transport(event_loop: asyncio.AbstractEventLoop, bridge: Bridge) -> Iterable[MockTransport]:
    transport = MockTransport(bridge)
    try:
        yield transport
    finally:
        transport.stop(event_loop)


@pytest.fixture
def transport(no_init_transport: MockTransport) -> MockTransport:
    no_init_transport.init()
    return no_init_transport


@pytest.mark.asyncio
async def test_echo(transport: MockTransport) -> None:
    echo = await transport.check_open('echo')

    transport.send_data(echo, b'foo')
    await transport.assert_data(echo, b'foo')

    transport.send_ping(channel=echo)
    await transport.assert_msg('', command='pong', channel=echo)

    transport.send_done(echo)
    await transport.assert_msg('', command='done', channel=echo)
    await transport.assert_msg('', command='close', channel=echo)


@pytest.mark.asyncio
async def test_host(transport: MockTransport) -> None:
    # try to open a null channel, explicitly naming our host
    await transport.check_open('null', host=MOCK_HOSTNAME)

    # try to open a null channel, no host
    await transport.check_open('null')

    # try to open a null channel, a different host which is sure to fail DNS
    await transport.check_open('null', host='¡invalid!', problem='no-host')

    # make sure host check happens before superuser
    # ie: requesting superuser=True on another host should fail because we
    # can't contact the other host ('no-host'), rather than trying to first
    # go to our superuser bridge ('access-denied')
    await transport.check_open('null', host='¡invalid!', superuser=True, problem='no-host')

    # but make sure superuser is indeed failing as we expect, on our host
    await transport.check_open('null', host=MOCK_HOSTNAME, superuser=True, problem='access-denied')


@pytest.mark.asyncio
async def test_dbus_call_internal(bridge: Bridge, transport: MockTransport) -> None:
    my_object = test_iface()
    bridge.internal_bus.export('/foo', my_object)
    assert my_object._dbus_bus == bridge.internal_bus.server
    assert my_object._dbus_path == '/foo'

    values, = await transport.check_bus_call('/foo', 'org.freedesktop.DBus.Properties',
                                             'GetAll', ["test.iface"])
    assert values == {'Prop': {'t': 's', 'v': 'none'}}

    result, = await transport.check_bus_call('/foo', 'test.iface', 'GetProp', [])
    assert result == 'none'


@pytest.mark.asyncio
async def test_dbus_watch(bridge: Bridge, transport: MockTransport) -> None:
    my_object = test_iface()
    bridge.internal_bus.export('/foo', my_object)
    assert my_object._dbus_bus == bridge.internal_bus.server
    assert my_object._dbus_path == '/foo'

    # Add a watch
    internal = await transport.ensure_internal_bus()

    transport.send_json(internal, watch={'path': '/foo', 'interface': 'test.iface'}, id='4')
    meta = await transport.next_msg(internal)
    assert meta['meta']['test.iface'] == {
        'methods': {'GetProp': {'in': [], 'out': ['s']}},
        'properties': {'Prop': {'flags': 'r', 'type': 's'}},
        'signals': {'Sig': {'in': ['s']}}
    }
    notify = await transport.next_msg(internal)
    assert notify['notify']['/foo'] == {'test.iface': {'Prop': 'none'}}
    reply = await transport.next_msg(internal)
    assert reply == {'id': '4', 'reply': []}

    # Change a property
    my_object.prop = 'xyz'
    notify = await transport.next_msg(internal)
    assert 'notify' in notify
    assert notify['notify']['/foo'] == {'test.iface': {'Prop': 'xyz'}}


async def verify_root_bridge_not_running(bridge: Bridge, transport: MockTransport) -> None:
    assert bridge.superuser_rule.peer is None
    await transport.assert_bus_props('/superuser', 'cockpit.Superuser',
                                     {'Bridges': bridge.more_superuser_bridges, 'Current': 'none'})  # type: ignore[attr-defined]
    null = await transport.check_open('null', superuser=True, problem='access-denied')
    assert null not in bridge.open_channels


@pytest.mark.asyncio
async def verify_root_bridge_running(bridge: Bridge, transport: MockTransport) -> None:
    await transport.assert_bus_props('/superuser', 'cockpit.Superuser',
                                     {'Bridges': bridge.more_superuser_bridges, 'Current': 'pseudo'})  # type: ignore[attr-defined]
    assert bridge.superuser_rule.peer is not None

    # try to open dbus on the root bridge
    root_dbus = await transport.check_open('dbus-json3', bus='internal', superuser=True)

    # verify that the bridge thinks that it's the root bridge
    await transport.assert_bus_props('/superuser', 'cockpit.Superuser',
                                     {'Bridges': [], 'Current': 'root'}, bus=root_dbus)

    # close up
    await transport.check_close(channel=root_dbus)


@pytest.mark.asyncio
async def test_superuser_dbus(bridge: Bridge, transport: MockTransport) -> None:
    add_pseudo(bridge)
    await verify_root_bridge_not_running(bridge, transport)

    # start the superuser bridge -- no password, so it should work straight away
    () = await transport.check_bus_call('/superuser', 'cockpit.Superuser', 'Start', ['pseudo'])

    await verify_root_bridge_running(bridge, transport)

    # open a channel on the root bridge
    root_null = await transport.check_open('null', superuser=True)

    # stop the bridge
    stop = transport.send_bus_call(transport.internal_bus, '/superuser',
                                   'cockpit.Superuser', 'Stop', [])

    # that should have implicitly closed the open channel
    await transport.assert_msg('', command='close', channel=root_null)
    assert root_null not in bridge.open_channels

    # The Stop method call is done now
    await transport.assert_msg(transport.internal_bus, reply=[[]], id=stop)


def format_methods(methods: Dict[str, str]):
    return {name: {'t': 'a{sv}', 'v': {'label': {'t': 's', 'v': label}}} for name, label in methods.items()}


@pytest.mark.asyncio
async def test_superuser_dbus_pw(bridge: Bridge, transport: MockTransport, monkeypatch) -> None:
    monkeypatch.setenv('PSEUDO_PASSWORD', 'p4ssw0rd')
    add_pseudo(bridge)
    await verify_root_bridge_not_running(bridge, transport)

    # watch for signals
    await transport.add_bus_match('/superuser', 'cockpit.Superuser')
    await transport.watch_bus('/superuser', 'cockpit.Superuser',
                              {
                                  'Bridges': bridge.more_superuser_bridges,  # type: ignore[attr-defined]
                                  'Current': 'none',
                                  'Methods': format_methods({'pseudo': 'pseudo'}),
                              })

    # start the bridge.  with a password this is more complicated
    start = transport.send_bus_call(transport.internal_bus, '/superuser',
                                    'cockpit.Superuser', 'Start', ['pseudo'])
    # first, init state
    await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'init'})
    # then, we'll be asked for a password
    await transport.assert_bus_signal('/superuser', 'cockpit.Superuser', 'Prompt',
                                      ['', 'can haz pw?', '', False, ''])
    # give it
    await transport.check_bus_call('/superuser', 'cockpit.Superuser', 'Answer', ['p4ssw0rd'])
    # and now the bridge should be running
    await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'pseudo'})

    # Start call is now done
    await transport.assert_bus_reply(start, [])

    # double-check
    await verify_root_bridge_running(bridge, transport)


@pytest.mark.asyncio
async def test_superuser_dbus_wrong_pw(bridge: Bridge, transport: MockTransport, monkeypatch) -> None:
    monkeypatch.setenv('PSEUDO_PASSWORD', 'p4ssw0rd')
    add_pseudo(bridge)
    await verify_root_bridge_not_running(bridge, transport)

    # watch for signals
    await transport.add_bus_match('/superuser', 'cockpit.Superuser')
    await transport.watch_bus('/superuser', 'cockpit.Superuser',
                              {
                                  'Bridges': bridge.more_superuser_bridges,  # type: ignore[attr-defined]
                                  'Current': 'none',
                                  'Methods': format_methods({'pseudo': 'pseudo'}),
                              })

    # start the bridge.  with a password this is more complicated
    start = transport.send_bus_call(transport.internal_bus, '/superuser',
                                    'cockpit.Superuser', 'Start', ['pseudo'])
    # first, init state
    await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'init'})
    # then, we'll be asked for a password
    await transport.assert_bus_signal('/superuser', 'cockpit.Superuser', 'Prompt',
                                      ['', 'can haz pw?', '', False, ''])
    # give it
    await transport.check_bus_call('/superuser', 'cockpit.Superuser',
                                   'Answer', ['p5ssw0rd'])  # wrong password
    # pseudo fails after the first wrong attempt
    await transport.assert_bus_notify('/superuser', 'cockpit.Superuser', {'Current': 'none'})

    # Start call is now done and returned failure
    await transport.assert_bus_error(start, 'cockpit.Superuser.Error', 'pseudo says: Bad password')

    # double-check
    await verify_root_bridge_not_running(bridge, transport)


@pytest.mark.asyncio
async def test_superuser_init(bridge: Bridge, no_init_transport: MockTransport) -> None:
    add_pseudo(bridge)
    no_init_transport.init(superuser={"id": "pseudo"})
    transport = no_init_transport

    # this should work right away without auth
    await transport.assert_msg('', command='superuser-init-done')

    await verify_root_bridge_running(bridge, transport)


@pytest.mark.asyncio
async def test_superuser_init_pw(bridge: Bridge, no_init_transport: MockTransport, monkeypatch) -> None:
    monkeypatch.setenv('PSEUDO_PASSWORD', 'p4ssw0rd')
    add_pseudo(bridge)
    no_init_transport.init(superuser={"id": "pseudo"})
    transport = no_init_transport

    msg = await transport.assert_msg('', command='authorize')
    transport.send_json('', command='authorize', cookie=msg['cookie'], response='p4ssw0rd')

    # that should have worked
    await transport.assert_msg('', command='superuser-init-done')

    await verify_root_bridge_running(bridge, transport)


@pytest.mark.asyncio
async def test_no_login_messages(transport: MockTransport) -> None:
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Dismiss', [], [])
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])


@pytest.fixture
def login_messages_envvar(monkeypatch):
    if sys.version_info < (3, 8):
        pytest.skip("os.memfd_create new in 3.8")
    fd = os.memfd_create('login messages')
    os.write(fd, b"msg")
    # this is questionable (since it relies on ordering of fixtures), but it works
    monkeypatch.setenv('COCKPIT_LOGIN_MESSAGES_MEMFD', str(fd))
    return None


@pytest.mark.asyncio
async def test_login_messages(login_messages_envvar, transport: MockTransport) -> None:
    del login_messages_envvar

    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["msg"])
    # repeated read should get the messages again
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["msg"])
    # ...but not after they were dismissed
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Dismiss', [], [])
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])
    # idempotency
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Dismiss', [], [])
    await transport.check_bus_call('/LoginMessages', 'cockpit.LoginMessages', 'Get', [], ["{}"])


@pytest.mark.asyncio
async def test_freeze(bridge: Bridge, transport: MockTransport) -> None:
    koelle = await transport.check_open('echo')
    malle = await transport.check_open('echo')

    # send a bunch of data to frozen koelle
    bridge.open_channels[koelle].freeze_endpoint()
    transport.send_data(koelle, b'x1')
    transport.send_data(koelle, b'x2')
    transport.send_data(koelle, b'x3')
    transport.send_done(koelle)

    # malle never freezes
    transport.send_data(malle, b'yy')
    transport.send_done(malle)

    # unfreeze koelle
    bridge.open_channels[koelle].thaw_endpoint()

    # malle should have sent its messages first
    await transport.assert_data(malle, b'yy')
    await transport.assert_msg('', command='done', channel=malle)
    await transport.assert_msg('', command='close', channel=malle)

    # the data from koelle should still be in the right order, though
    await transport.assert_data(koelle, b'x1')
    await transport.assert_data(koelle, b'x2')
    await transport.assert_data(koelle, b'x3')
    await transport.assert_msg('', command='done', channel=koelle)
    await transport.assert_msg('', command='close', channel=koelle)


@pytest.mark.asyncio
async def test_internal_metrics(transport: MockTransport) -> None:
    metrics = [
        {"name": "cpu.core.user", "derive": "rate"},
        {"name": "memory.used"},
    ]
    interval = 100
    source = 'internal'

    await transport.check_open('metrics1', source=source, interval=interval, metrics=metrics)
    _, data = await transport.next_frame()
    # first message is always the meta message
    meta = json.loads(data)
    assert isinstance(meta['timestamp'], float)
    assert meta['interval'] == interval
    assert meta['source'] == source
    assert isinstance(meta['metrics'], list)
    instances = len(next(m['instances'] for m in meta['metrics'] if m['name'] == 'cpu.core.user'))

    # actual data
    _, data = await transport.next_frame()
    data = json.loads(data)
    assert isinstance(data, list)
    # cpu.core.user instances should be the same as meta sent instances
    assert instances == len(data[0][0])
    # all instances should be False, as this is a rate
    assert all(d is False for d in data[0][0])
    # memory.used should be an integer
    assert isinstance(data[0][1], int)

    # next data for rate should not be False
    _, data = await transport.next_frame()
    data = json.loads(data)
    assert all(d is not False for d in data[0][0])


@pytest.mark.asyncio
async def test_fsread1_errors(transport: MockTransport, tmp_path: Path) -> None:
    await transport.check_open('fsread1', path='/etc/shadow', problem='access-denied')
    await transport.check_open('fsread1', path='/', problem='internal-error',
                               reply_keys={'message': "[Errno 21] Is a directory: '/'"})
    await transport.check_open('fsread1', path='/etc/passwd', max_read_size="lol",
                               problem='protocol-error',
                               reply_keys={'message': "attribute 'max_read_size': must have type int"})
    await transport.check_open('fsread1', path='/etc/passwd', max_read_size=1,
                               problem='too-large')
    # default read size limit
    big_file = tmp_path / 'bigfile.img'
    fd = os.open(big_file, os.O_RDWR | os.O_CREAT)
    os.posix_fallocate(fd, 0, 17 * 1024 * 1024)
    os.close(fd)
    await transport.check_open('fsread1', path=str(big_file),
                               problem='too-large')

    # -1 implies no limit
    await transport.check_open('fsread1', path=str(big_file),
                               max_read_size=-1)


@pytest.mark.asyncio
async def test_fsread1_size_hint(transport: MockTransport) -> None:
    data = None
    stat = os.stat('/usr/lib/os-release')
    with open('/usr/lib/os-release', 'rb') as fp:
        data = fp.read()
    ch = await transport.check_open('fsread1', path='/usr/lib/os-release', binary='raw',
                                    reply_keys={'size-hint': stat.st_size})
    await transport.assert_data(ch, data)


@pytest.mark.asyncio
async def test_fsread1_size_hint_absent(transport: MockTransport) -> None:
    # non-binary fsread1 has no size-hint
    await transport.check_open('fsread1', path='/etc/passwd', absent_keys=['size-hint'])


@pytest.mark.asyncio
async def test_fsread1_size_hint_absent_char_device(transport: MockTransport) -> None:
    # character device fsread1 has no size-hint
    await transport.check_open('fsread1', path='/dev/null', binary='raw', absent_keys=['size-hint'])


@pytest.mark.asyncio
async def test_fslist1_no_watch(transport: MockTransport, tmp_path: Path) -> None:
    # empty
    ch = await transport.check_open('fslist1', path=str(tmp_path), watch=False)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)

    # create a file and a directory in some_dir
    (tmp_path / 'somefile').touch()
    (tmp_path / 'somedir').mkdir()

    ch = await transport.check_open('fslist1', path=str(tmp_path), watch=False)
    # don't assume any ordering
    msg1 = await transport.next_msg(ch)
    msg2 = await transport.next_msg(ch)
    if msg1['type'] == 'file':
        msg1, msg2 = msg2, msg1
    assert msg1 == {'event': 'present', 'path': 'somedir', 'type': 'directory'}
    assert msg2 == {'event': 'present', 'path': 'somefile', 'type': 'file'}

    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)


@pytest.mark.asyncio
async def test_fslist1_notexist(transport: MockTransport) -> None:
    await transport.check_open(
        'fslist1', path='/nonexisting', watch=False,
        problem='not-found',
        reply_keys={'message': "[Errno 2] No such file or directory: '/nonexisting'"})


class GrpPwMock:
    def __init__(self, uid: 'int', gid: 'int | None' = None) -> None:
        self.pw_uid = uid
        self.gr_gid = gid

    def __str__(self) -> str:
        return f'uid={self.pw_uid},gid={self.gr_gid}'


@pytest.fixture
def fchown_mock() -> Generator[unittest.mock.MagicMock, unittest.mock.MagicMock, None]:
    with unittest.mock.patch('os.fchown', return_value=True) as fchown_mock:
        yield fchown_mock


@pytest.fixture
def user_group_mock(user_group_mock_arg: GrpPwMock) -> Generator[GrpPwMock, GrpPwMock, None]:
    with unittest.mock.patch('pwd.getpwnam', return_value=user_group_mock_arg):
        with unittest.mock.patch('grp.getgrnam', return_value=user_group_mock_arg):
            yield user_group_mock_arg


@pytest.mark.asyncio
async def test_fsreplace1(transport: MockTransport, tmp_path: Path) -> None:
    # create non-existing file
    myfile = tmp_path / 'newfile'
    ch = await transport.check_open('fsreplace1', path=str(myfile))
    transport.send_data(ch, b'some stuff')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert myfile.read_bytes() == b'some stuff'
    # no leftover files
    assert os.listdir(tmp_path) == ['newfile']
    # default umask is applied
    prev_umask = os.umask(0)
    os.umask(prev_umask)
    assert stat.S_IMODE(myfile.stat().st_mode) == 0o666 & ~prev_umask

    # now update its contents
    ch = await transport.check_open('fsreplace1', path=str(myfile))
    transport.send_data(ch, b'new new new!')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert myfile.read_bytes() == b'new new new!'
    # no leftover files
    assert os.listdir(tmp_path) == ['newfile']

    # set funny permissions to check that they are preserved
    perms = 0o625
    myfile.chmod(perms)

    # get the current tag
    ch = await transport.check_open('fsread1', path=str(myfile))
    transport.send_done(ch)
    await transport.assert_data(ch, b'new new new!')
    await transport.assert_msg('', command='done', channel=ch)
    transport.send_close(ch)
    close_msg = await transport.next_msg('')
    assert close_msg['command'] == 'close'
    tag = close_msg['tag']

    # update contents with expected tag
    ch = await transport.check_open('fsreplace1', path=str(myfile), tag=tag)
    transport.send_data(ch, b'even newer')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert myfile.read_bytes() == b'even newer'

    # preserves existing permissions when giving expected tag
    assert stat.S_IMODE(myfile.stat().st_mode) == perms

    # mode supplied via attrs overrides existing permissions
    new_perms = 0o422
    ch = await transport.check_open('fsreplace1', path=str(myfile), attrs={'mode': new_perms})
    transport.send_data(ch, b'in the future')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert myfile.read_bytes() == b'in the future'
    assert stat.S_IMODE(myfile.stat().st_mode) == new_perms

    # write empty file
    ch = await transport.check_open('fsreplace1', path=str(myfile))
    transport.send_data(ch, b'')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert myfile.read_bytes() == b''

    # delete file
    ch = await transport.check_open('fsreplace1', path=str(myfile))
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert not myfile.exists()

    # acks
    ch = await transport.check_open('fsreplace1', path=str(myfile), send_acks='bytes')
    transport.send_data(ch, b'some stuff')
    await transport.assert_msg('', command='ack', bytes=10, channel=ch)
    transport.send_data(ch, b'some more stuff')
    await transport.assert_msg('', command='ack', bytes=15, channel=ch)
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)

    # tag is "-" and file should not exist
    newfile = tmp_path / 'new'
    ch = await transport.check_open('fsreplace1', path=str(newfile), tag='-')
    transport.send_data(ch, b'some stuff')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert newfile.read_text() == 'some stuff'

    # delete the now written newfile with tag='-' the file should now exist so this should fail
    ch = await transport.check_open('fsreplace1', path=str(newfile), tag='-')
    transport.send_done(ch)
    await transport.assert_msg('', problem='change-conflict', channel=ch)
    assert newfile.exists()

    # create file with a custom mode
    newfile.unlink()
    assert not newfile.exists()
    ch = await transport.check_open('fsreplace1', path=str(newfile), attrs={'mode': perms})
    transport.send_data(ch, b'some stuff')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert newfile.read_text() == 'some stuff'
    assert stat.S_IMODE(newfile.stat().st_mode) == perms

    # create file with tag='-' and custom mode
    newfile.unlink()
    assert not newfile.exists()
    ch = await transport.check_open('fsreplace1', path=str(newfile), tag='-', attrs={'mode': perms})
    transport.send_data(ch, b'some stuff')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(channel=ch)
    assert newfile.read_text() == 'some stuff'
    assert stat.S_IMODE(newfile.stat().st_mode) == perms


@pytest.mark.asyncio
async def test_fsreplace1_change_conflict(transport: MockTransport, tmp_path: Path) -> None:
    myfile = tmp_path / 'data'
    myfile.write_text('hello')

    # get current tag from fsread1
    ch = await transport.check_open('fsread1', path=str(myfile))
    transport.send_done(ch)
    await transport.assert_data(ch, b'hello')
    await transport.assert_msg('', command='done', channel=ch)
    transport.send_close(ch)
    close_msg = await transport.next_msg('')
    assert close_msg['command'] == 'close'
    tag = close_msg['tag']

    # modify the file in between read and replace operations
    # we have to wait a bit, assuming that file systems we run tests on have at least centisecond mtime resolution
    await asyncio.sleep(0.2)
    myfile.write_text('goodbye')

    # try to replace it, expecting the old contents (via tag)
    ch = await transport.check_open('fsreplace1', path=str(myfile), tag=tag)
    transport.send_data(ch, b'newcontent')
    transport.send_done(ch)
    await transport.assert_msg('', command='close', channel=ch, problem='change-conflict')
    transport.send_close(ch)

    # file was not touched by fsreplace1 due to conflict
    assert myfile.read_text() == 'goodbye'


@pytest.mark.asyncio
async def test_fsreplace1_change_conflict_mode(transport: MockTransport, tmp_path: Path) -> None:
    myfile = tmp_path / 'data'
    myfile.write_text('hello')

    # get current tag
    ch = await transport.check_open('fsread1', path=str(myfile))
    transport.send_done(ch)
    await transport.assert_data(ch, b'hello')
    await transport.assert_msg('', command='done', channel=ch)
    transport.send_close(ch)
    close_msg = await transport.next_msg('')
    assert close_msg['command'] == 'close'
    tag = close_msg['tag']

    # modify the stat metadata in between read and replace operations
    new_mode = 0o741
    assert stat.S_IMODE(myfile.stat().st_mode) != new_mode
    myfile.chmod(new_mode)

    # try to replace it, expecting the old mode (via tag)
    ch = await transport.check_open('fsreplace1', path=str(myfile), tag=tag)
    transport.send_data(ch, b'newcontent')
    transport.send_done(ch)
    await transport.assert_msg('', command='close', channel=ch, problem='change-conflict')
    transport.send_close(ch)

    # file was not touched by fsreplace1 due to conflict
    assert stat.S_IMODE(myfile.stat().st_mode) == new_mode
    assert myfile.read_text() == 'hello'


@pytest.mark.asyncio
async def test_fsreplace1_error(transport: MockTransport, tmp_path: Path) -> None:
    # trying to write a directory
    ch = await transport.check_open('fsreplace1', path=str(tmp_path))
    transport.send_data(ch, b'not me')
    transport.send_done(ch)
    await transport.assert_msg('', command='close', channel=ch, problem='access-denied')

    # nonexisting directory
    ch = await transport.check_open('fsreplace1', path='/non/existing/file')
    transport.send_data(ch, b'not me')
    transport.send_done(ch)
    await transport.assert_msg('', command='close', channel=ch, problem='not-found')

    # invalid send-acks option
    await transport.check_open('fsreplace1', path=str(tmp_path), send_acks='not-valid',
                               problem='protocol-error',
                               reply_keys={
                                   'message': """attribute 'send-acks': invalid value "not-valid" not in ['bytes']"""
    })

    await transport.check_open('fsreplace1', path=str(tmp_path / 'test'),
                               attrs={'user': 'cockpit', 'group': 'cockpit', 'selinux': True},
                               problem='protocol-error',
                               reply_keys={
                                   'message': '"attrs" contains unsupported key(s): selinux',
                                   'unsupported_attrs': ['selinux']
    })

    await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'user': 'cockpit'},
                               problem='protocol-error',
                               reply_keys={
                                   'message': '"group" attribute is empty while "user" is provided'
    })

    await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'group': 'cockpit'},
                               problem='protocol-error',
                               reply_keys={
                                   'message': '"user" attribute is empty while "group" is provided'
    })

    await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'user': 'cockpit', 'group': []},
                               problem='protocol-error',
                               reply_keys={
                                   'message': "attribute 'attrs': attribute 'group': must be a string or integer"
    })

    await transport.check_open('fsreplace1', path=str(tmp_path / 'test'), attrs={'user': [], 'group': 'test'},
                               problem='protocol-error',
                               reply_keys={
                                   'message': "attribute 'attrs': attribute 'user': must be a string or integer"
    })

    mock_val = GrpPwMock(uid=0, gid=1000)
    with unittest.mock.patch('pwd.getpwnam', side_effect=KeyError()):
        await transport.check_open('fsreplace1', path=str(tmp_path / 'test'),
                                   attrs={'user': 'bazinga', 'group': 'foo'},
                                   problem='not-found',
                                   reply_keys={
                                       'message': 'uid not found for bazinga'
        })

    with unittest.mock.patch('pwd.getpwnam', return_value=mock_val):
        with unittest.mock.patch('grp.getgrnam', side_effect=KeyError()):
            await transport.check_open('fsreplace1', path=str(tmp_path / 'test'),
                                       attrs={'user': 'bazinga', 'group': 'test'},
                                       problem='not-found',
                                       reply_keys={
                                           'message': 'gid not found for test'
            })


ATTRS_TEST_DATA = [
    (GrpPwMock(1111, 1110), {'user': 1111, 'group': 1110}),
    (GrpPwMock(1111, 1110), {'user': 'monkey', 'group': 'group'}),
]


@pytest.mark.parametrize(('user_group_mock_arg', 'attrs'), ATTRS_TEST_DATA)
@pytest.mark.asyncio
async def test_fsreplace1_attrs(transport: MockTransport, fchown_mock: unittest.mock.MagicMock,
                                tmp_path: Path, user_group_mock, attrs: Dict[str, Union[int, str]]) -> None:
    async def existing_file_with_attrs(filename: str, tag: str) -> None:
        test_file = tmp_path / filename
        ch = await transport.check_open('fsreplace1', path=str(test_file), attrs=attrs, tag=tag)
        transport.send_data(ch, b'content')
        transport.send_done(ch)
        await transport.assert_msg('', command='done', channel=ch)
        await transport.check_close(ch)
        assert test_file.read_bytes() == b'content'

    async def create_file_with_attrs(filename: str) -> None:
        test_file = tmp_path / filename
        ch = await transport.check_open('fsreplace1', path=str(test_file), attrs=attrs)
        transport.send_data(ch, b'content')
        transport.send_done(ch)
        await transport.assert_msg('', command='done', channel=ch)
        await transport.check_close(ch)
        assert test_file.read_bytes() == b'content'

    await create_file_with_attrs('test')
    fchown_mock.assert_called()
    _, call_uid, call_gid = fchown_mock.call_args[0]
    assert call_uid == user_group_mock.pw_uid
    if user_group_mock.gr_gid is None:
        assert call_gid == user_group_mock.pw_uid
    else:
        assert call_gid == user_group_mock.gr_gid

    # Existing file
    existing_file = tmp_path / 'existing'
    existing_file.write_text('new')

    tag = tag_from_path(existing_file)
    assert tag is not None
    await existing_file_with_attrs('existing', tag)
    fchown_mock.assert_called()
    _, call_uid, call_gid = fchown_mock.call_args[0]
    assert call_uid == user_group_mock.pw_uid
    if user_group_mock.gr_gid is None:
        assert call_gid == user_group_mock.pw_uid
    else:
        assert call_gid == user_group_mock.gr_gid


@pytest.mark.asyncio
async def test_fsreplace1_size_hint(transport: MockTransport, tmp_path: Path) -> None:
    myfile = tmp_path / 'myfile'

    # create a file, no size hint
    ch = await transport.check_open('fsreplace1', path=str(myfile))
    assert list(tmp_path.iterdir()) == []  # no temp file should be created yet
    transport.send_data(ch, b'content')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(ch)
    assert list(tmp_path.iterdir()) == [myfile]  # no temp file left
    assert myfile.read_bytes() == b'content'

    # delete it again
    ch = await transport.check_open('fsreplace1', path=str(myfile))
    assert list(tmp_path.iterdir()) == [myfile]  # no temp file created
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(ch)
    assert list(tmp_path.iterdir()) == []  # empty again

    # enospc in advance: 1PB ought to be enough for anybody...
    ch = transport.send_open('fsreplace1', path=str(myfile), size=1 << 50)  # 1PB
    err = await transport.assert_msg('', command='close', channel=ch, problem='internal-error')
    message = get_str(err, 'message')
    assert 'No space left on device' in message or 'File too large' in message
    assert list(tmp_path.iterdir()) == []  # still empty
    assert not myfile.exists()

    # ensure cancellation is always a no-op, even with size specified
    ch = await transport.check_open('fsreplace1', path=str(myfile), size=1 << 20)  # 1MB
    assert len(list(tmp_path.iterdir())) == 1  # observe the temp file created immediately
    await transport.check_close(ch)
    assert list(tmp_path.iterdir()) == []  # no temp file left
    assert not myfile.exists()

    # ...but even size=0 will result in the file being created without payload
    ch = await transport.check_open('fsreplace1', path=str(myfile), size=0)
    assert len(list(tmp_path.iterdir())) == 1  # observe the temp file created immediately
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(ch)
    assert list(tmp_path.iterdir()) == [myfile]  # no temp file left
    assert myfile.read_bytes() == b''

    # check too little data written
    ch = await transport.check_open('fsreplace1', path=str(myfile), size=1 << 20)  # 1 MB
    assert len(list(tmp_path.iterdir())) == 2  # observe the temp file created immediately
    transport.send_data(ch, b'too small')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(ch)
    assert list(tmp_path.iterdir()) == [myfile]  # no temp file left
    assert myfile.read_bytes() == b'too small'

    # check too much data written
    ch = await transport.check_open('fsreplace1', path=str(myfile), size=5)
    assert len(list(tmp_path.iterdir())) == 2  # observe the temp file created immediately
    transport.send_data(ch, b'too large')
    transport.send_done(ch)
    await transport.assert_msg('', command='done', channel=ch)
    await transport.check_close(ch)
    assert list(tmp_path.iterdir()) == [myfile]  # no temp file left
    assert myfile.read_bytes() == b'too large'


@pytest.mark.asyncio
@pytest.mark.parametrize('channeltype', CHANNEL_TYPES)
async def test_channel(bridge: Bridge, transport: MockTransport, channeltype, tmp_path: Path) -> None:
    payload = channeltype.payload
    args = dict(channeltype.restrictions)

    async def serve_page(reader, writer):
        while True:
            line = await reader.readline()
            if line.strip():
                print('HTTP Request line', line)
            else:
                break

        print('Sending HTTP reply')
        writer.write(b'HTTP/1.1 200 OK\r\n\r\nA document\r\n')
        await writer.drain()
        writer.close()

    srv = str(tmp_path / 'sock')
    await asyncio.start_unix_server(serve_page, srv)

    if payload == 'fsinfo':
        args = {'path': '/', 'attrs': []}
    elif payload == 'fslist1':
        args = {'path': '/', 'watch': False}
    elif payload == 'fsread1':
        args = {'path': '/etc/passwd'}
    elif payload == 'fsreplace1':
        args = {'path': 'tmpfile'}
    elif payload == 'fswatch1':
        args = {'path': '/etc'}
    elif payload == 'http-stream1':
        args = {'internal': 'packages', 'method': 'GET', 'path': '/manifests.js',
                'headers': {'X-Forwarded-Proto': 'http', 'X-Forwarded-Host': 'localhost'}}
    elif payload == 'http-stream2':
        args = {'method': 'GET', 'path': '/bzzt', 'unix': srv}
    elif payload == 'stream':
        if 'spawn' in args:
            args = {'spawn': ['cat']}
        else:
            args = {'unix': srv}
    elif payload == 'metrics1' and channeltype.restrictions:
        args['metrics'] = [{'name': 'memory.free'}]
    elif payload == 'metrics1':
        pytest.skip('no PCP metric data')
    elif payload == 'dbus-json3':
        if not os.path.exists('/run/dbus/system_bus_socket'):
            pytest.skip('no dbus')
    else:
        args = {}

    print('sending open', payload, args)
    ch = transport.send_open(payload, **args)
    saw_data = False

    while True:
        channel, msg = await transport.next_frame()
        print(channel, msg)
        if channel == '':
            control = json.loads(msg)
            assert control['channel'] == ch
            command = control['command']
            if command == 'ready':
                if 'spawn' in args:
                    assert isinstance(control['pid'], int)
                    assert os.readlink(f"/proc/{control['pid']}/exe").endswith("/cat")
                # If we get ready, it's our turn to send data first.
                # Hopefully we didn't receive any before.
                assert not saw_data
                break
            else:
                pytest.fail(f'unexpected event: {(payload, args, control)}')
        else:
            saw_data = True

    # If we're here, it's our turn to talk.  Say nothing.
    print('sending done')
    transport.send_done(ch)

    if payload in ['dbus-json3', 'fswatch1', 'metrics1', 'null']:
        transport.send_close(ch)

    while True:
        channel, msg = await transport.next_frame()
        print(channel, msg)
        if channel == '':
            control = json.loads(msg)
            command = control['command']
            if command == 'done':
                continue
            elif command == 'close':
                assert 'problem' not in control
                return


@pytest.mark.parametrize(('os_release', 'expected'), [
    # simple values, with comments and ignored space
    (
        '\n\n# simple\nID=mylinux\nVERSION=1.2\n\n# comment\nFOO=bar\n\n',
        {'ID': 'mylinux', 'VERSION': '1.2', 'FOO': 'bar'}
    ),
    # quoted values
    (
        '''SINGLE='foo:bar '\nDOUBLE=" bar//foo"\n''',
        {'SINGLE': 'foo:bar ', 'DOUBLE': ' bar//foo'}
    ),
    # ignore ungrammatical lines
    (
        'A=a\nNOVALUE\nDOUBLEEQ=a=b\nB=b',
        {'A': 'a', 'B': 'b'}
    ),
    # invalid values; anything outside [A-Za-z0-9] must be quoted; but our parser is more liberal
    (
        'X=a:b\nY=a b\nZ=a-b\nV=a_b',
        {'X': 'a:b', 'Z': 'a-b', 'V': 'a_b'}
    ),
])
def test_get_os_release(os_release: str, expected: str) -> None:
    with unittest.mock.patch('builtins.open', unittest.mock.mock_open(read_data=os_release)):
        assert Bridge.get_os_release() == expected


class AckChannel(AsyncChannel):
    payload = 'ack1'

    async def run(self, options: JsonObject) -> None:
        self.semaphore = asyncio.Semaphore(0)
        self.ready()
        while await self.read():
            await self.semaphore.acquire()


@pytest.mark.asyncio
async def test_async_acks(bridge: Bridge, transport: MockTransport) -> None:
    # Inject our mock channel type
    for rule in bridge.routing_rules:
        if isinstance(rule, ChannelRoutingRule):
            rule.table['ack1'] = [AckChannel]

    # invalid send-acks values
    await transport.check_open('ack1', send_acks=True, problem='protocol-error')
    await transport.check_open('ack1', send_acks='x', problem='protocol-error')

    # open the channel with acks off
    ch = await transport.check_open('ack1')
    # send a bunch of data and get no acks
    for _ in range(20):
        transport.send_data(ch, b'x')
    # this will assert that we receive only the close message (and no acks)
    await transport.check_close(ch)

    # open the channel with acks on
    ch = await transport.check_open('ack1', send_acks='bytes')
    # send a bunch of data
    for _ in range(20):
        transport.send_data(ch, b'x')
    # we should get exactly one ack (from the first read) before things block
    await transport.assert_msg('', channel=ch, command='ack', bytes=1)
    # this will assert that we receive only the close message (and no additional acks)
    await transport.check_close(ch)

    # open the channel with acks on
    ch = await transport.check_open('ack1', send_acks='bytes')
    # fish the open channel out of the bridge
    ack = bridge.open_channels[ch]
    assert isinstance(ack, AckChannel)
    # let's give ourselves a bit more headroom
    for _ in range(5):
        ack.semaphore.release()
    # send a bunch of data and get some acks
    for _ in range(10):
        transport.send_data(ch, b'x')
    for _ in range(6):
        await transport.assert_msg('', channel=ch, command='ack', bytes=1)
    # make sure that as we "consume" the data we get more acks:
    for _ in range(4):
        # no ack in the queue...
        await transport.assert_empty()
        ack.semaphore.release()
        # ... but now there is.
        await transport.assert_msg('', channel=ch, command='ack', bytes=1)
    # make some more room (for data we didn't send)
    for _ in range(5):
        ack.semaphore.release()
    # but we shouldn't have gotten any acks for those
    await transport.check_close(ch)


@pytest.mark.asyncio
async def test_flow_control(transport: MockTransport, tmp_path: Path) -> None:
    bigun = tmp_path / 'bigun'
    total_bytes = 8 * 1024 * 1024
    recvd_bytes = 0
    bigun.write_bytes(b'0' * total_bytes)
    fsread1 = await transport.check_open('fsread1', path=str(bigun), flow_control=True)

    # We should receive a number of blocks of initial data, each with a ping.
    # We save the pings to reply later.
    pings: 'deque[JsonObject]' = deque()

    async def recv_one():
        nonlocal recvd_bytes

        channel, data = await transport.next_frame()
        assert channel == fsread1
        assert data == b'0' * Channel.BLOCK_SIZE
        recvd_bytes += len(data)

        ping = await transport.next_msg('')
        assert ping['command'] == 'ping'
        assert ping['channel'] == fsread1
        assert ping['sequence'] == recvd_bytes
        pings.append(ping)

    while recvd_bytes < Channel.SEND_WINDOW:
        await recv_one()

    # We should stall out here.  Make sure nothing else arrives.
    await transport.assert_empty()

    # Start sending pongs and make sure we receive a new block of data for each
    # one (as the window extends)
    while recvd_bytes < total_bytes:
        ping = pings.popleft()
        transport.send_json('', **dict(ping, command='pong'))
        await recv_one()

    transport.send_close(fsread1)


@pytest.mark.asyncio
async def test_large_upload(transport: MockTransport, tmp_path: Path) -> None:
    fifo = str(tmp_path / 'pipe')
    os.mkfifo(fifo)

    sender = await transport.check_open('stream', spawn=['dd', f'of={fifo}'])
    # cockpit.js doesn't do flow control, so neither do we...
    chunk = b'0' * Channel.BLOCK_SIZE
    loops = 100
    for _ in range(loops):
        transport.send_data(sender, chunk)
    transport.send_done(sender)

    # we should be in a state now where we have a bunch of bytes queued up in
    # the bridge but they can't be delivered because nobody is reading from the
    # pipe...  make sure dd is still running and we didn't get any messages.
    await transport.assert_empty()

    # start draining now, and make sure we get everything we sent.
    with open(fifo, 'rb') as receiver:
        received = await asyncio.get_running_loop().run_in_executor(None, receiver.read)
        assert len(received) == loops * Channel.BLOCK_SIZE

    # and now our done and close messages should come
    await transport.assert_msg('', command='done', channel=sender)
    await transport.assert_msg('', command='close', channel=sender)


class FsInfoClient:
    def __init__(self, transport: MockTransport, channel: str):
        self.transport = transport
        self.channel = channel
        self.state: JsonObject = {}

    @classmethod
    async def open(
            cls,
            transport: MockTransport,
            path: 'str | Path',
            attrs: Sequence[str] = ('type', 'target'),
            fnmatch: str = '*.txt',
            **kwargs: JsonValue
    ) -> 'FsInfoClient':
        channel = await transport.check_open('fsinfo', path=str(path), attrs=attrs,
                                             fnmatch=fnmatch, reply_keys=None,
                                             absent_keys=(), **kwargs)
        return cls(transport, channel)

    async def next_state(self) -> JsonObject:
        while True:
            patch = await self.transport.next_msg(self.channel)
            self.state = json_merge_patch(self.state, patch)
            if not get_bool(self.state, 'partial', None):
                break
        return self.state

    async def wait(self) -> JsonObject:
        state = await self.next_state()
        await self.transport.assert_msg('', command='done', channel=self.channel)
        await self.transport.assert_msg('', command='close', channel=self.channel)
        return state

    async def close(self):
        await self.transport.check_close(self.channel)


def fsinfo_err(err: int) -> JsonObject:
    problems = {
        errno.ENOENT: 'not-found',
        errno.EPERM: 'access-denied',
        errno.EACCES: 'access-denied',
        errno.ENOTDIR: 'not-directory'
    }
    return {
        'error': {
            'problem': problems.get(err, 'internal-error'),
            'message': os.strerror(err),
            'errno': errno.errorcode[err],
        }
    }


@pytest.fixture
def fsinfo_test_cases(tmp_path: Path) -> 'Iterator[dict[Path, JsonObject]]':
    # a normal directory
    normal_dir = tmp_path / 'dir'
    normal_dir.mkdir()
    (normal_dir / 'dir-file.txt').write_text('dir file')
    (normal_dir / 'dir-file.xtx').write_text('do not read this')

    # a directory without +x (search)
    no_x_dir = tmp_path / 'no-x-dir'
    no_x_dir.mkdir()
    (no_x_dir / 'no-x-dir-file.txt').write_text('file')
    no_x_dir.chmod(0o644)

    # a directory without +r (read)
    no_r_dir = tmp_path / 'no-r-dir'
    no_r_dir.mkdir()
    (no_r_dir / 'no-r-dir-file.txt').write_text('file')
    no_r_dir.chmod(0o311)

    # a normal file
    file = tmp_path / 'file'
    file.write_text('normal file')

    # a non-readable file
    no_r_file = tmp_path / 'no-r-file'
    no_r_file.write_text('inaccessible file')
    no_r_file.chmod(0)

    # a device
    dev = tmp_path / 'dev'
    dev.symlink_to('/dev/null')

    # a dangling symlink
    dangling = tmp_path / 'dangling'
    dangling.symlink_to('does-not-exist')

    # a symlink pointing to itself
    loopy = tmp_path / 'loopy'
    loopy.symlink_to(loopy)

    expected_state: 'dict[Path, JsonObject]' = {
        normal_dir: {"info": {"type": "dir", "entries": {'dir-file.txt': {"type": "reg"}}}},

        # can't stat() the file
        no_x_dir: {"info": {"type": "dir", "entries": {"no-x-dir-file.txt": {}}}},

        # can't read the directory, so no entries
        no_r_dir: {"info": {"type": "dir"}},

        # normal file, can read its contents
        file: {"info": {"type": "reg"}},

        # can't read file, so no contents
        no_r_file: {"info": {"type": "reg"}},

        # a device
        dev: {"info": {"type": "chr"}},

        # a dangling symlink
        dangling: fsinfo_err(errno.ENOENT),

        # a link pointing at itself
        loopy: fsinfo_err(errno.ELOOP),
    }

    if os.getuid() == 0:
        # we can't do the permissions-dependent tests as root
        del expected_state[no_x_dir]
        del expected_state[no_r_dir]
        del expected_state[no_r_file]

    try:
        yield expected_state

    finally:
        # restore writable permissions on directories.  pytest has trouble cleaning
        # these up, otherwise...
        for path in expected_state:
            if not path.is_symlink() and path.is_dir():
                path.chmod(0o700)


@pytest.mark.asyncio
async def test_fsinfo_nopath(transport: MockTransport) -> None:
    await transport.check_open('fsinfo', attrs=['type'], problem='protocol-error')


@pytest.mark.asyncio
async def test_fsinfo_noattrs(transport: MockTransport) -> None:
    await transport.check_open('fsinfo', path='/', problem='protocol-error')


@pytest.mark.asyncio
async def test_fsinfo_relative(transport: MockTransport) -> None:
    await transport.check_open('fsinfo', path='rel', problem='protocol-error')
    await transport.check_open('fsinfo', path='.', problem='protocol-error')


@pytest.mark.asyncio
async def test_fsinfo_nofollow_watch(transport: MockTransport) -> None:
    await transport.check_open('fsinfo', path='/', attrs=[], watch=True, follow=False, problem='protocol-error')


@pytest.mark.asyncio
async def test_fsinfo_nofollow_targets(transport: MockTransport) -> None:
    await transport.check_open('fsinfo', path='/', attrs=['targets'], follow=False, problem='protocol-error')


@pytest.mark.asyncio
async def test_fsinfo_empty_update(transport: MockTransport, tmp_path: Path) -> None:
    # test an empty update — make sure nothing lands on the wire
    ch = await transport.check_open('fsinfo', path=str(tmp_path), attrs=['type'], watch=True)
    assert await transport.next_msg(ch) == {'info': {"type": "dir"}}
    tmp_path.touch()
    await asyncio.sleep(0.1)  # fsinfo waits 0.1 before dispatching updates
    await transport.assert_empty()  # this waits another 0.1
    await transport.check_close(ch)


@pytest.mark.asyncio
async def test_fsinfo(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
    for path, expected_state in fsinfo_test_cases.items():
        client = await FsInfoClient.open(transport, path)
        assert await client.wait() == expected_state


@pytest.mark.asyncio
async def test_fsinfo_nofollow(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
    for path, expected_state in fsinfo_test_cases.items():
        if path.name == 'loopy':
            # with nofollow, this won't fail — we'll see the link itself
            expected_state = {"info": {"type": "lnk", "target": str(path)}}
        elif path.name == 'dev':
            expected_state = {"info": {"type": "lnk", "target": "/dev/null"}}
        elif path.name == 'dangling':
            expected_state = {"info": {"type": "lnk", "target": "does-not-exist"}}

        client = await FsInfoClient.open(transport, path, follow=False)
        assert await client.wait() == expected_state


@pytest.mark.asyncio
async def test_fsinfo_onlydir(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
    for path, expected_state in fsinfo_test_cases.items():
        if 'dir' not in path.name and 'error' not in expected_state:
            expected_state = fsinfo_err(errno.ENOTDIR)

        # with '/' appended, this should only open dirs
        client = await FsInfoClient.open(transport, str(path) + '/')
        assert await client.wait() == expected_state


@pytest.mark.asyncio
async def test_fsinfo_onlydir_watch(transport: MockTransport, fsinfo_test_cases: 'dict[Path, JsonObject]') -> None:
    for path, expected_state in fsinfo_test_cases.items():
        # note the order here: because our check for notdir is implemented
        # inside of the bridge, we try inotify first and check for notdir
        # second.  if systemd_ctypes supports this some day, it may change.
        if path.name.startswith('no-r'):
            # we need this one because we can't inotify files without +r
            expected_state = fsinfo_err(errno.EACCES)
        elif 'dir' not in path.name and 'error' not in expected_state:
            # and this one to deal with not-dir
            expected_state = fsinfo_err(errno.ENOTDIR)

        # with '/' appended, this should only open dirs
        client = await FsInfoClient.open(transport, str(path) + '/', watch=True)
        assert await client.next_state() == expected_state
        await client.close()


@pytest.mark.asyncio
async def test_fsinfo_watch_identity_changes(
        transport: MockTransport, tmp_path: Path, fsinfo_test_cases: 'dict[Path, JsonObject]'
) -> None:
    # we will now point a symlink to the various possibilities to make sure the
    # transitions are correctly handled
    link = tmp_path / 'link'
    client = await FsInfoClient.open(transport, link, watch=True)

    # we didn't make a link yet, so...
    assert (await client.next_state()) == fsinfo_err(errno.ENOENT)

    # in watch mode we report errors a bit more sensitively: we also report
    # them if we can't inotify the inode in question, which requires +r
    # permission.  as such, we need to modify our 'no-r' tests:
    for path in list(fsinfo_test_cases):
        if path.name.startswith('no-r'):
            fsinfo_test_cases[path] = fsinfo_err(errno.EACCES)
        if path.name == 'dangling':
            # this breaks our logic below because we transition from ENOENT to ENOENT
            del fsinfo_test_cases[path]

    possibilities = tuple(fsinfo_test_cases)
    for from_file in possibilities:
        for to_file in possibilities:
            if from_file is to_file:
                continue

            # link to the original file and check state
            link.symlink_to(from_file)
            assert await client.next_state() == fsinfo_test_cases[from_file]

            # Try to generate some events immediately before we switch the link
            # to ensure the event is suppressed.  Any one of these could fail
            # due to not being a directory or not having permissions.
            with contextlib.suppress(OSError):
                from_file.touch()
            with contextlib.suppress(OSError):
                (from_file / 'a.txt').touch()
            with contextlib.suppress(OSError):
                (from_file / 'a.txt').unlink()

            # atomic replace, check state
            (tmp_path / 'tmp').symlink_to(to_file)
            (tmp_path / 'tmp').rename(link)
            assert await client.next_state() == fsinfo_test_cases[to_file]

            if to_file.name == 'dir':
                # copied from fsinfo_test_cases fixture
                dir_entries = {'dir-file.txt': {"type": "reg"}}
                expected_state = {"info": {"type": "dir", "entries": dir_entries}}

                (to_file / 'a.txt').write_text('a file')
                dir_entries['a.txt'] = {"type": "reg"}
                (to_file / 'b.txt').write_text('b file')
                dir_entries['b.txt'] = {"type": "reg"}
                (to_file / 'a.xtx').write_text('b file')
                (to_file / 'b.xtx').write_text('b file')
                assert await client.next_state() == expected_state

                (to_file / 'a.xtx').unlink()
                (to_file / 'b.xtx').unlink()
                (to_file / 'dir.txt').mkdir()
                dir_entries['dir.txt'] = {"type": "dir"}
                (to_file / 'sym.txt').symlink_to('/x')
                dir_entries['sym.txt'] = {"type": "lnk", "target": "/x"}
                assert await client.next_state() == expected_state

                (to_file / 'sym.txt').unlink()
                del dir_entries['sym.txt']
                assert await client.next_state() == expected_state

                # we intentionally try not to receive these events — we want
                # them to get lost when the identity changes, below
                (to_file / 'dir.txt').rmdir()
                (to_file / 'a.txt').unlink()
                (to_file / 'b.txt').unlink()

            # delete link to start over
            link.unlink()
            assert (await client.next_state()) == fsinfo_err(errno.ENOENT)

        # let the pending event handler occasionally run to find nothing to process
        await asyncio.sleep(0.15)

    await client.close()


@pytest.mark.asyncio
async def test_fsinfo_self_owner(transport: MockTransport, tmp_path: Path) -> None:
    client = await FsInfoClient.open(transport, tmp_path, ['user', 'uid', 'group', 'gid'])
    state = await client.wait()
    info = get_dict(state, 'info')

    assert get_int(info, 'uid') == os.getuid()
    assert get_int(info, 'gid') == os.getgid()
    assert info.get('user') == getpass.getuser()
    assert info.get('group') == grp.getgrgid(os.getgid()).gr_name  # hopefully true...


@pytest.mark.asyncio
async def test_fsinfo_other_owner(transport: MockTransport, tmp_path: Path) -> None:
    tmpfile = tmp_path / 'x'
    tmpfile.touch()

    # try to get root to own this thing using a couple of tricks that may work
    # inside or outside of toolbox or containers
    quoted = shlex.quote(str(tmpfile))
    subprocess.run(fr'''
        podman unshare chown 888:888 {quoted} || SUDO_ASKPASS=true sudo -A chown 0:0 '{quoted}'
    ''', shell=True, check=False)

    # verify that we ended up with a uid/gid with no user
    buf = tmpfile.stat()
    try:
        pwd.getpwuid(buf.st_uid)
        pytest.skip('Failed to find unmapped uid')
    except KeyError:
        pass  # good!
    try:
        grp.getgrgid(buf.st_gid)
        pytest.skip('Failed to find unmapped gid')
    except KeyError:
        pass  # good!

    client = await FsInfoClient.open(transport, tmpfile, ['user', 'uid', 'group', 'gid'])
    state = await client.wait()
    info = get_dict(state, 'info')

    assert get_int(info, 'uid') == buf.st_uid
    assert get_int(info, 'gid') == buf.st_gid
    assert info.get('user') == buf.st_uid  # numeric fallback
    assert info.get('group') == buf.st_gid  # numeric fallback


@pytest.mark.asyncio
async def test_fsinfo_targets(transport: MockTransport, tmp_path: Path) -> None:
    # we are only interested in the things that start with 'l'
    watch = await FsInfoClient.open(transport, tmp_path, ['type', 'target', 'targets'], fnmatch='l*', watch=True)

    entries: JsonDict = {}
    targets: JsonDict = {}
    state = {"info": {"type": "dir", "entries": entries, "targets": targets}}
    assert await watch.next_state() == state

    # none of those will show up in entries (not 'l*')
    (tmp_path / 'dir').mkdir()
    (tmp_path / 'dir' / 'file').write_text('abc')
    (tmp_path / 'dir' / 'lonely').write_text('abc')
    (tmp_path / 'dir' / 'dir').mkdir()
    (tmp_path / 'file').write_text('abc')
    (tmp_path / 'Lonely').write_text('abc')

    # this one will show up in entries because it matches 'l*'
    (tmp_path / 'loved').write_text('abc')
    entries['loved'] = {'type': 'reg'}

    # a link that won't show up anywhere (no fnmatch)
    (tmp_path / 'LonelyLink').symlink_to('dir/lonely')

    # link to things that will land in targets because they're not in fnmatch
    (tmp_path / 'lfile').symlink_to('file')
    entries['lfile'] = {'type': 'lnk', 'target': 'file'}
    targets['file'] = {'type': 'reg'}
    (tmp_path / 'ldir').symlink_to('dir')
    entries['ldir'] = {'type': 'lnk', 'target': 'dir'}
    targets['dir'] = {'type': 'dir'}

    # link to things that will land in targets because they're in another dir
    (tmp_path / 'ldirfile').symlink_to('dir/file')
    entries['ldirfile'] = {'type': 'lnk', 'target': 'dir/file'}
    targets['dir/file'] = {'type': 'reg'}
    (tmp_path / 'ldirdir').symlink_to('dir/dir')
    entries['ldirdir'] = {'type': 'lnk', 'target': 'dir/dir'}
    targets['dir/dir'] = {'type': 'dir'}
    (tmp_path / 'lnull').symlink_to('/dev/null')
    entries['lnull'] = {'type': 'lnk', 'target': '/dev/null'}
    targets['/dev/null'] = {'type': 'chr'}
    (tmp_path / 'lroot').symlink_to('/')
    entries['lroot'] = {'type': 'lnk', 'target': '/'}
    targets['/'] = {'type': 'dir'}

    # link to things that won't land in targets because they're in entries
    (tmp_path / 'llfile').symlink_to('lfile')
    entries['llfile'] = {'type': 'lnk', 'target': 'lfile'}
    (tmp_path / 'lldir').symlink_to('ldir')
    entries['lldir'] = {'type': 'lnk', 'target': 'ldir'}
    (tmp_path / 'lloved').symlink_to('loved')
    entries['lloved'] = {'type': 'lnk', 'target': 'loved'}

    # a link to the current directory won't show up in targets since we already
    # report its attributes directly as our toplevel state structure
    (tmp_path / 'ldot').symlink_to('.')
    entries['ldot'] = {'type': 'lnk', 'target': '.'}

    # a link to the parent directory should definitely show up, though
    (tmp_path / 'ldotdot').symlink_to('..')
    entries['ldotdot'] = {'type': 'lnk', 'target': '..'}
    targets['..'] = {'type': 'dir'}

    # make sure the watch managed to pick that all up
    assert await watch.next_state() == state

    # double-check with the non-watch variant
    client = await FsInfoClient.open(transport, tmp_path, ['type', 'target', 'targets'], fnmatch='l*')
    assert await client.wait() == state