cyberbrain 0.4.0

Cited, trust-tiered, local-first memory for AI coding agents
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
1590
1591
1592
1593
1594
1595
1596
1597
1598
1599
1600
1601
1602
1603
1604
1605
1606
1607
1608
1609
1610
1611
1612
1613
1614
1615
1616
1617
1618
1619
1620
1621
1622
1623
1624
1625
1626
1627
1628
1629
1630
1631
1632
1633
1634
1635
1636
1637
1638
1639
1640
1641
1642
1643
1644
1645
1646
1647
1648
1649
1650
1651
1652
1653
1654
1655
1656
1657
1658
1659
1660
1661
1662
1663
1664
1665
1666
1667
1668
1669
1670
1671
1672
1673
1674
1675
1676
1677
1678
1679
1680
1681
1682
1683
1684
1685
1686
1687
1688
1689
1690
1691
1692
1693
1694
1695
1696
1697
1698
1699
1700
1701
1702
1703
1704
1705
1706
1707
1708
1709
1710
1711
1712
1713
1714
1715
1716
1717
1718
1719
1720
1721
1722
1723
1724
1725
1726
1727
1728
1729
1730
1731
1732
1733
1734
1735
1736
1737
1738
1739
1740
1741
1742
1743
1744
1745
1746
1747
1748
1749
1750
1751
1752
1753
1754
1755
1756
1757
1758
1759
1760
1761
1762
1763
1764
1765
1766
1767
1768
1769
1770
1771
1772
1773
1774
1775
1776
1777
1778
1779
1780
1781
1782
1783
1784
1785
1786
1787
1788
1789
1790
1791
1792
1793
1794
1795
1796
1797
1798
1799
1800
1801
1802
1803
1804
1805
1806
1807
1808
1809
1810
1811
1812
1813
1814
1815
1816
1817
1818
1819
1820
1821
1822
1823
1824
1825
1826
1827
1828
1829
1830
1831
1832
1833
1834
1835
1836
1837
1838
1839
1840
1841
1842
1843
1844
1845
1846
1847
1848
1849
1850
1851
1852
1853
1854
1855
1856
1857
1858
1859
1860
1861
1862
1863
1864
1865
1866
1867
1868
1869
1870
1871
1872
1873
1874
1875
1876
1877
1878
1879
1880
1881
1882
1883
1884
1885
1886
1887
1888
1889
1890
1891
1892
1893
1894
1895
1896
1897
1898
1899
1900
1901
1902
1903
1904
1905
1906
1907
1908
1909
1910
1911
1912
1913
1914
1915
1916
1917
1918
1919
1920
1921
1922
1923
1924
1925
1926
1927
1928
1929
1930
1931
1932
1933
1934
1935
1936
1937
1938
1939
1940
1941
1942
1943
1944
1945
1946
1947
1948
1949
1950
1951
1952
1953
1954
1955
1956
1957
1958
1959
1960
1961
1962
1963
1964
1965
1966
1967
1968
1969
1970
1971
1972
1973
1974
1975
1976
1977
1978
1979
1980
1981
1982
1983
1984
1985
1986
1987
1988
1989
1990
1991
1992
1993
1994
1995
1996
1997
1998
1999
2000
2001
2002
2003
2004
2005
2006
2007
2008
2009
2010
2011
2012
2013
2014
2015
2016
2017
2018
2019
2020
2021
2022
2023
2024
2025
2026
2027
2028
2029
2030
2031
2032
2033
2034
2035
2036
2037
2038
2039
2040
2041
2042
2043
2044
2045
2046
2047
2048
2049
2050
2051
2052
2053
2054
2055
2056
2057
2058
2059
2060
2061
2062
2063
2064
2065
2066
2067
2068
2069
2070
2071
2072
2073
2074
2075
2076
2077
2078
2079
2080
2081
2082
2083
2084
2085
2086
2087
2088
2089
2090
2091
2092
2093
2094
//! What a hub has to get right, tested against real bundles rather than fixtures: every
//! delivery in here was written by the same code that writes one on a client.

use super::*;
use cyberbrain_policy::{Actor, AuditAction, AuditLog, MemoryAuditSink};
use std::sync::Arc;

/// A client's log, and bundles cut from it.
struct Client {
    log: AuditLog,
    sink: Arc<MemoryAuditSink>,
}

impl Client {
    fn new() -> Self {
        let (log, sink) = AuditLog::in_memory();
        Self { log, sink }
    }

    fn act(&self, subject: &str) {
        self.log
            .record(
                &Actor::Operator,
                AuditAction::NoteWrite,
                subject,
                serde_json::json!({ "note": subject }),
            )
            .unwrap();
    }

    /// A bundle over rows `from..`, the way a client would send what is new since last time.
    fn bundle_from(&self, from: usize) -> String {
        let rows = self.sink.rows();
        bundle::render(
            &rows[from..],
            None,
            None,
            "test-client",
            "2026-09-07T00:00:00Z",
        )
    }

    fn all(&self) -> String {
        self.bundle_from(0)
    }
}

fn hub_with_device() -> (HubStore, Device, String) {
    let hub = HubStore::in_memory().unwrap();
    let (device, token) = hub.add_device("laptop", "2026-09-07T00:00:00Z").unwrap();
    (hub, device, token)
}

const NOW: &str = "2026-09-07T12:00:00Z";

/// A licence that allows collecting, for the tests that are about delivery rather than
/// about licensing.
fn collecting() -> LicenceState {
    LicenceState::Valid {
        customer: "Test GmbH".into(),
        seats: 5,
        valid_until: "2099-01-01T00:00:00Z".into(),
        warning: None,
    }
}

fn lapsed() -> LicenceState {
    LicenceState::Expired {
        customer: "Test GmbH".into(),
        valid_until: "2026-01-01T00:00:00Z".into(),
    }
}

#[test]
fn a_first_delivery_is_taken_and_moves_the_anchor() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");

    let a = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        Some("0.2.1"),
        NOW,
    )
    .unwrap();
    assert_eq!(a.accepted, 2);
    assert_eq!(a.total_rows, 2);

    let device = hub.device_by_token(&token).unwrap().unwrap();
    assert_eq!(device.anchor, a.next_anchor);
    assert_ne!(device.anchor, store::GENESIS);
    assert_eq!(device.version.as_deref(), Some("0.2.1"));
    assert_eq!(device.last_seen.as_deref(), Some(NOW));
}

#[test]
fn the_second_delivery_continues_the_first() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    client.act("b");
    client.act("c");
    let a = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.bundle_from(1),
        None,
        NOW,
    )
    .unwrap();
    assert_eq!(a.accepted, 2);
    assert_eq!(a.total_rows, 3, "the device's chain is three rows long");
}

/// The failure this whole design exists to catch: a period that was never delivered.
#[test]
fn a_skipped_period_does_not_anchor() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    client.act("b"); // never delivered
    client.act("c");
    let err = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.bundle_from(2),
        None,
        NOW,
    )
    .unwrap_err();
    assert!(err.to_string().contains("something is missing"), "{err}");
    match &err {
        Refusal::WrongAnchor { expected, got } => assert_ne!(expected, got),
        other => panic!("expected WrongAnchor, got {other:?}"),
    }
}

/// Sending the same thing twice is what a client with a retry does, so it must be safe —
/// and it must not double the record, which is a quieter corruption than losing a row
/// because the numbers still add up.
#[test]
fn the_same_delivery_twice_changes_nothing_the_second_time() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    let b = client.all();
    assert_eq!(
        ingest(&mut hub, &collecting(), Some(&token), &b, None, NOW)
            .unwrap()
            .accepted,
        1
    );
    let again = ingest(&mut hub, &collecting(), Some(&token), &b, None, NOW).unwrap();
    assert_eq!(again.accepted, 0, "nothing in it was new");
    assert_eq!(hub.total_entries().unwrap(), 1);
}

/// The case that made this rule: a client cannot know the hub's anchor, so it sends more
/// than it has to and the hub takes the part it does not have.
#[test]
fn an_overlapping_delivery_contributes_only_what_is_new() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    client.act("c");
    client.act("d");
    // Everything from the start, including the two rows the hub already has.
    let a = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();
    assert_eq!(a.accepted, 2, "only c and d were new");
    assert_eq!(a.total_rows, 4);

    let device = hub.device_by_token(&token).unwrap().unwrap();
    assert_eq!(device.rows, 4, "no row was stored twice");
}

#[test]
fn an_edited_row_never_reaches_the_record() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    let tampered = client
        .all()
        .replace("\"subject\":\"b\"", "\"subject\":\"c\"");

    let err = ingest(&mut hub, &collecting(), Some(&token), &tampered, None, NOW).unwrap_err();
    assert!(matches!(err, Refusal::BadBundle(_)), "{err:?}");
    assert!(err.to_string().contains("does not match its hash"), "{err}");
    assert_eq!(hub.total_entries().unwrap(), 0, "nothing was stored");
}

#[test]
fn a_delivery_without_a_token_is_not_parsed_at_all() {
    let (mut hub, _, _) = hub_with_device();
    let client = Client::new();
    client.act("a");
    let err = ingest(&mut hub, &collecting(), None, &client.all(), None, NOW).unwrap_err();
    assert!(matches!(err, Refusal::NotAuthorised(_)), "{err:?}");
}

#[test]
fn an_unknown_token_is_refused() {
    let (mut hub, _, _) = hub_with_device();
    let client = Client::new();
    client.act("a");
    let err = ingest(
        &mut hub,
        &collecting(),
        Some("cbh_nonsense"),
        &client.all(),
        None,
        NOW,
    )
    .unwrap_err();
    assert!(err.to_string().contains("unknown device token"), "{err}");
}

#[test]
fn a_revoked_device_may_not_send_but_keeps_what_it_sent() {
    let (mut hub, device, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    assert!(hub.revoke(&device.id, NOW).unwrap());
    client.act("b");
    let err = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.bundle_from(1),
        None,
        NOW,
    )
    .unwrap_err();
    assert!(err.to_string().contains("revoked"), "{err}");
    assert_eq!(
        hub.total_entries().unwrap(),
        1,
        "revoking is not a deletion"
    );
}

#[test]
fn an_empty_delivery_is_contact_without_rows() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    let a = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        Some("0.2.1"),
        NOW,
    )
    .unwrap();
    assert_eq!(a.accepted, 0);
    assert_eq!(
        a.next_anchor,
        store::GENESIS,
        "nothing to move the anchor to"
    );

    let device = hub.device_by_token(&token).unwrap().unwrap();
    assert_eq!(
        device.last_seen.as_deref(),
        Some(NOW),
        "a device with nothing to say is not a device that has stopped saying anything"
    );
}

#[test]
fn two_devices_keep_separate_chains() {
    let hub = HubStore::in_memory().unwrap();
    let (_, token_a) = hub.add_device("a", "2026-09-07T00:00:00Z").unwrap();
    let (_, token_b) = hub.add_device("b", "2026-09-07T00:00:00Z").unwrap();
    let mut hub = hub;

    let ca = Client::new();
    ca.act("from-a");
    let cb = Client::new();
    cb.act("from-b");
    cb.act("from-b-2");

    ingest(
        &mut hub,
        &collecting(),
        Some(&token_a),
        &ca.all(),
        None,
        NOW,
    )
    .unwrap();
    ingest(
        &mut hub,
        &collecting(),
        Some(&token_b),
        &cb.all(),
        None,
        NOW,
    )
    .unwrap();

    let a = hub.device_by_token(&token_a).unwrap().unwrap();
    let b = hub.device_by_token(&token_b).unwrap().unwrap();
    assert_eq!(a.rows, 1);
    assert_eq!(b.rows, 2);
    assert_ne!(a.anchor, b.anchor, "one chain each, not one shared");

    // And a bundle from one device does not continue the other's chain.
    let ca2 = ca.bundle_from(1);
    assert!(matches!(
        ingest(&mut hub, &collecting(), Some(&token_b), &ca2, None, NOW),
        Err(Refusal::WrongAnchor { .. }) | Ok(_)
    ));
}

#[test]
fn a_failed_delivery_leaves_the_anchor_where_it_was() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();
    let before = hub.device_by_token(&token).unwrap().unwrap();

    client.act("b");
    let tampered = client.bundle_from(1).replace("note.write", "note.forge");
    assert!(ingest(&mut hub, &collecting(), Some(&token), &tampered, None, NOW).is_err());

    let after = hub.device_by_token(&token).unwrap().unwrap();
    assert_eq!(
        before.anchor, after.anchor,
        "a refused delivery must not move the chain, or the next honest one cannot follow"
    );
    assert_eq!(before.rows, after.rows);
}

// ---- what the licence gates, and what it does not (slice 4) ----

/// The test for the promise in the design: expiry stops collection and touches nothing else.
#[test]
fn an_expired_licence_stops_collection_and_keeps_everything_else() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();
    assert_eq!(hub.total_entries().unwrap(), 1);

    client.act("b");
    let err = ingest(&mut hub, &lapsed(), Some(&token), &client.all(), None, NOW).unwrap_err();
    assert!(matches!(err, Refusal::NotCollecting(_)), "{err:?}");
    assert!(err.to_string().contains("Keep buffering"), "{err}");
    assert!(err.to_string().contains("stays readable"), "{err}");

    // Nothing was lost, nothing was locked, and the record still reads.
    assert_eq!(hub.total_entries().unwrap(), 1);
    assert_eq!(hub.devices().unwrap().len(), 1);
    assert_eq!(hub.device_by_token(&token).unwrap().unwrap().rows, 1);
}

/// Renewing picks up exactly where it stopped: what the client held lands, chain unbroken.
#[test]
fn renewing_takes_what_the_client_held() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    assert!(ingest(&mut hub, &lapsed(), Some(&token), &client.all(), None, NOW).is_err());

    let a = ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();
    assert_eq!(a.accepted, 2, "the rows held during the lapse arrive");
}

#[test]
fn a_hub_without_a_licence_collects_nothing() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    let err = ingest(
        &mut hub,
        &LicenceState::Missing,
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap_err();
    assert!(matches!(err, Refusal::NotCollecting(_)), "{err:?}");
    assert!(err.to_string().contains("no licence installed"), "{err}");
}

/// This one goes through the real reader, because the question is whether a properly signed
/// licence from the wrong key is accepted — and that is exactly what the reader decides.
#[test]
fn a_licence_signed_by_somebody_else_does_not_count() {
    let hub = HubStore::in_memory().unwrap();
    let (other_private, _) = licence::generate_key().unwrap();
    let l = licence::Licence {
        version: 1,
        id: "lic_forged".into(),
        customer: "Somebody Else".into(),
        seats: 9_999,
        valid_from: "2020-01-01T00:00:00Z".into(),
        valid_until: "2099-01-01T00:00:00Z".into(),
        issued_at: "2026-01-01T00:00:00Z".into(),
    };
    hub.set_licence(&licence::issue(&l, &other_private).unwrap().render())
        .unwrap();

    let state = LicenceState::read(&hub, jiff::Timestamp::now());
    assert!(matches!(state, LicenceState::Invalid(_)), "{state:?}");
    assert!(!state.may_collect(), "9999 seats signed by nobody we know");
}

/// An empty settings row is what an untouched installation looks like.
#[test]
fn a_hub_that_was_never_licensed_reads_as_missing() {
    let hub = HubStore::in_memory().unwrap();
    let state = LicenceState::read(&hub, jiff::Timestamp::now());
    assert_eq!(state, LicenceState::Missing);
    assert!(!state.may_collect());
    assert_eq!(state.seats(), None);
}

#[test]
fn seats_count_devices_that_can_still_send() {
    let hub = HubStore::in_memory().unwrap();
    let (a, _) = hub.add_device("one", "2026-09-07T00:00:00Z").unwrap();
    hub.add_device("two", "2026-09-07T00:00:00Z").unwrap();
    assert_eq!(hub.active_device_count().unwrap(), 2);

    // Revoking frees the seat — the rows stay, the person left.
    hub.revoke(&a.id, NOW).unwrap();
    assert_eq!(hub.active_device_count().unwrap(), 1);
    assert_eq!(hub.devices().unwrap().len(), 2, "both are still on record");
}

#[test]
fn a_warning_is_not_a_stop() {
    let warned = LicenceState::Valid {
        customer: "Test GmbH".into(),
        seats: 5,
        valid_until: "2026-09-17T00:00:00Z".into(),
        warning: Some(
            "ends in 10 day(s). After that the hub stops accepting rows; nothing is deleted."
                .into(),
        ),
    };
    assert!(warned.may_collect());
    let line = warned.line();
    assert!(line.contains("nothing is deleted"), "{line}");
}

// ---- what the hub can tell an administrator, and what it can hand an auditor (slice 6) ----

use super::report::{self, Concern};

const HUB_VERSION: &str = "0.2.1";

fn now_ts() -> jiff::Timestamp {
    NOW.parse().unwrap()
}

/// The case the refusal record exists for. A gap is refused, so it leaves no rows — without
/// remembering the refusal, the fleet view would show a device that merely went quiet, which
/// is a different problem with a different fix.
#[test]
fn a_refused_delivery_shows_up_as_a_concern() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    client.act("b"); // never delivered
    client.act("c");
    assert!(
        ingest(
            &mut hub,
            &collecting(),
            Some(&token),
            &client.bundle_from(2),
            None,
            NOW
        )
        .is_err()
    );

    let rows = report::fleet(&hub, now_ts(), HUB_VERSION).unwrap();
    let concerns = &rows[0].concerns;
    assert!(
        concerns
            .iter()
            .any(|c| matches!(c, Concern::Refused { .. })),
        "{concerns:?}"
    );
    let line = concerns[0].line();
    assert!(line.contains("refused"), "{line}");
}

/// And a later good delivery clears it: a stale complaint is worse than none.
#[test]
fn a_successful_delivery_clears_the_concern() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    assert!(
        ingest(
            &mut hub,
            &collecting(),
            Some(&token),
            &client.bundle_from(1),
            None,
            NOW
        )
        .is_err()
    );
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    let rows = report::fleet(&hub, now_ts(), HUB_VERSION).unwrap();
    assert!(rows[0].concerns.is_empty(), "{:?}", rows[0].concerns);
}

#[test]
fn silence_becomes_a_concern_after_the_threshold() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    let soon = now_ts() + std::time::Duration::from_secs(3600);
    assert!(
        report::fleet(&hub, soon, HUB_VERSION).unwrap()[0]
            .concerns
            .is_empty(),
        "an hour is not silence"
    );

    let later = now_ts() + std::time::Duration::from_secs(72 * 3600);
    let concerns = &report::fleet(&hub, later, HUB_VERSION).unwrap()[0].concerns;
    assert!(
        matches!(concerns.first(), Some(Concern::Quiet { hours }) if *hours >= 48),
        "{concerns:?}"
    );
}

#[test]
fn an_older_client_is_named_and_a_newer_or_odd_one_is_not() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        Some("0.1.0"),
        NOW,
    )
    .unwrap();
    let concerns = &report::fleet(&hub, now_ts(), HUB_VERSION).unwrap()[0].concerns;
    assert!(
        concerns.iter().any(|c| matches!(c, Concern::Behind { .. })),
        "{concerns:?}"
    );

    // A client ahead of the hub, and one with a version nobody can parse, are both left
    // alone: nagging about either would train people to ignore the column.
    for v in ["9.9.9", "my-build"] {
        let (mut hub, _, token) = hub_with_device();
        let client = Client::new();
        client.act("a");
        ingest(
            &mut hub,
            &collecting(),
            Some(&token),
            &client.all(),
            Some(v),
            NOW,
        )
        .unwrap();
        let concerns = &report::fleet(&hub, now_ts(), HUB_VERSION).unwrap()[0].concerns;
        assert!(
            !concerns.iter().any(|c| matches!(c, Concern::Behind { .. })),
            "{v} was called behind: {concerns:?}"
        );
    }
}

#[test]
fn a_revoked_device_is_not_a_problem_to_solve() {
    let (mut hub, device, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();
    hub.revoke(&device.id, NOW).unwrap();

    let much_later = now_ts() + std::time::Duration::from_secs(500 * 3600);
    let rows = report::fleet(&hub, much_later, HUB_VERSION).unwrap();
    assert!(
        rows[0].concerns.is_empty(),
        "a decision somebody made is not an alert: {:?}",
        rows[0].concerns
    );
}

#[test]
fn devices_that_need_attention_come_first() {
    let hub = HubStore::in_memory().unwrap();
    let (_, quiet_token) = hub.add_device("zzz-quiet", "2026-09-07T00:00:00Z").unwrap();
    let (_, fine_token) = hub.add_device("aaa-fine", "2026-09-07T00:00:00Z").unwrap();
    let mut hub = hub;

    for token in [&quiet_token, &fine_token] {
        let c = Client::new();
        c.act("a");
        ingest(&mut hub, &collecting(), Some(token), &c.all(), None, NOW).unwrap();
    }
    // One of them then fails a delivery.
    let c = Client::new();
    c.act("x");
    c.act("y");
    let _ = ingest(
        &mut hub,
        &collecting(),
        Some(&quiet_token),
        &c.bundle_from(1),
        None,
        NOW,
    );

    let rows = report::fleet(&hub, now_ts(), HUB_VERSION).unwrap();
    assert_eq!(
        rows[0].device.name, "zzz-quiet",
        "trouble sorts above a name that would come first alphabetically"
    );
}

#[test]
fn verify_re_derives_the_chains_from_what_is_on_disk() {
    let (mut hub, _, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    let r = report::verify(&hub).unwrap();
    assert!(r.ok);
    assert_eq!(r.rows, 2);
    assert_eq!(r.devices[0].chain.as_ref().unwrap(), &2);
}

#[test]
fn a_period_comes_out_as_a_bundle_that_verifies_on_its_own() {
    let (mut hub, device, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    let (text, n) = report::device_bundle(&hub, &device.id, None, None, "test").unwrap();
    assert_eq!(n, 2);
    // The same check an outsider runs, over rows that made a round trip through the hub's
    // database. If storage lost or reordered anything, this is where it shows.
    let verdict = cyberbrain_policy::bundle::verify(&text).unwrap();
    assert_eq!(verdict.rows, 2);
}

#[test]
fn a_device_with_nothing_in_the_period_still_gets_a_file() {
    let (mut hub, _, token) = hub_with_device();
    let (silent, _) = hub.add_device("silent", "2026-09-07T00:00:00Z").unwrap();
    let client = Client::new();
    client.act("a");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();

    let dir = tempfile::tempdir().unwrap();
    let out = report::write_report(&hub, dir.path(), None, None, "test").unwrap();
    let files = out["files"].as_array().unwrap();
    assert_eq!(files.len(), 2, "both devices, including the silent one");
    let quiet_file = dir.path().join(format!("{}.jsonl", silent.id));
    assert!(quiet_file.is_file());
    // "This machine did nothing that week" is a finding, and it verifies like any other.
    let text = std::fs::read_to_string(&quiet_file).unwrap();
    assert_eq!(cyberbrain_policy::bundle::verify(&text).unwrap().rows, 0);
    assert!(dir.path().join("summary.txt").is_file());
}

/// A record created by an older build must keep working when the program is upgraded.
#[test]
fn an_older_record_gains_the_new_columns() {
    let file = tempfile::NamedTempFile::new().unwrap();
    {
        // The devices table as an earlier version wrote it: no version, no refusal columns.
        let conn = rusqlite::Connection::open(file.path()).unwrap();
        conn.execute_batch(
            "CREATE TABLE devices (
                 id TEXT PRIMARY KEY, name TEXT NOT NULL, token_hash TEXT NOT NULL UNIQUE,
                 created_at TEXT NOT NULL, revoked_at TEXT, last_seen TEXT,
                 anchor TEXT NOT NULL, rows INTEGER NOT NULL DEFAULT 0
             );
             INSERT INTO devices (id, name, token_hash, created_at, anchor)
             VALUES ('dev_old', 'from-an-older-build', 'hash', '2026-01-01T00:00:00Z', 'genesis');",
        )
        .unwrap();
    }

    let hub = HubStore::open(file.path()).unwrap();
    let devices = hub.devices().unwrap();
    assert_eq!(
        devices.len(),
        1,
        "the row from the old build is still there"
    );
    assert_eq!(devices[0].name, "from-an-older-build");
    assert_eq!(devices[0].version, None);
    assert_eq!(devices[0].last_refusal, None);
}

// ---- the two-person rule (slice 7) ----

use super::access::{Denied, RequestState, Role};

fn people(hub: &HubStore) -> (String, String, String) {
    let (_, auditor) = hub.add_principal("M. Kraus", Role::Auditor, NOW).unwrap();
    let (_, council) = hub
        .add_principal("Works council", Role::Countersigner, NOW)
        .unwrap();
    let (_, admin) = hub.add_principal("A. Weber", Role::Admin, NOW).unwrap();
    (auditor, council, admin)
}

/// A hub with one device that has delivered, and the three roles.
fn hub_with_activity() -> (HubStore, String, String, String, String) {
    let (mut hub, device, token) = hub_with_device();
    let client = Client::new();
    client.act("a");
    client.act("b");
    ingest(
        &mut hub,
        &collecting(),
        Some(&token),
        &client.all(),
        None,
        NOW,
    )
    .unwrap();
    let (auditor, council, admin) = people(&hub);
    (hub, device.id, auditor, council, admin)
}

fn tmpdir() -> tempfile::TempDir {
    tempfile::tempdir().unwrap()
}

#[test]
fn activity_cannot_be_read_without_a_countersignature() {
    let (hub, device, auditor, _, _) = hub_with_activity();
    let who = hub.principal_for(Some(&auditor), Role::Auditor).unwrap();
    let req = hub
        .create_request(&who, Some(&device), None, None, "a reason", NOW)
        .unwrap();

    let dir = tmpdir();
    let err =
        report::disclose(&hub, Some(&auditor), &req.id, dir.path(), now_ts(), "test").unwrap_err();
    assert!(matches!(err, Denied::NotApproved(_)), "{err:?}");
    assert!(err.to_string().contains("somebody else approves"), "{err}");
    assert_eq!(std::fs::read_dir(dir.path()).unwrap().count(), 0);
}

#[test]
fn the_administrator_cannot_read_activity_at_all() {
    let (hub, _, _, _, admin) = hub_with_activity();
    // Not "no approved request" — the wrong role, which is a different sentence and a
    // different fix.
    let err = hub.principal_for(Some(&admin), Role::Auditor).unwrap_err();
    assert!(
        matches!(err, Denied::WrongRole { .. }),
        "an administrator asking for activity: {err:?}"
    );
}

#[test]
fn an_auditor_cannot_countersign() {
    let (hub, _, auditor, _, _) = hub_with_activity();
    let err = hub
        .principal_for(Some(&auditor), Role::Countersigner)
        .unwrap_err();
    assert!(matches!(err, Denied::WrongRole { .. }), "{err:?}");
}

/// Defence in depth: roles make this unreachable today, because one principal has one role
/// and only an auditor can create a request. If roles ever become plural, this is the check
/// that still holds — so it is tested at the level where it lives.
#[test]
fn a_request_cannot_be_approved_by_the_person_who_made_it() {
    let (hub, device, auditor, _, _) = hub_with_activity();
    let who = hub.principal_for(Some(&auditor), Role::Auditor).unwrap();
    let req = hub
        .create_request(&who, Some(&device), None, None, "a reason", NOW)
        .unwrap();

    let err = hub
        .approve_request(&req.id, &who, "2099-01-01T00:00:00Z", NOW)
        .unwrap_err();
    assert_eq!(err, Denied::SamePerson);
    assert!(err.to_string().contains("not an obstacle to work around"));
}

#[test]
fn an_approved_request_opens_a_window_that_closes_itself() {
    let (hub, device, auditor, council, _) = hub_with_activity();
    let who = hub.principal_for(Some(&auditor), Role::Auditor).unwrap();
    let signer = hub
        .principal_for(Some(&council), Role::Countersigner)
        .unwrap();
    let req = hub
        .create_request(&who, Some(&device), None, None, "a reason", NOW)
        .unwrap();
    assert_eq!(req.state(now_ts()), RequestState::Pending);

    let expires = (now_ts() + std::time::Duration::from_secs(3600)).to_string();
    let approved = hub
        .approve_request(&req.id, &signer, &expires, NOW)
        .unwrap();
    assert_eq!(approved.state(now_ts()), RequestState::Open);

    // Inside the window it works.
    let dir = tmpdir();
    let out =
        report::disclose(&hub, Some(&auditor), &req.id, dir.path(), now_ts(), "test").unwrap();
    assert_eq!(out["rows"].as_i64(), Some(2));

    // Two hours later it does not, and the message says to ask again rather than extend.
    let later = now_ts() + std::time::Duration::from_secs(2 * 3600);
    assert_eq!(approved.state(later), RequestState::Closed);
    let err =
        report::disclose(&hub, Some(&auditor), &req.id, dir.path(), later, "test").unwrap_err();
    assert!(matches!(err, Denied::WindowClosed(_)), "{err:?}");
    assert!(err.to_string().contains("Make a new request"), "{err}");
}

#[test]
fn another_auditor_cannot_collect_somebody_elses_approval() {
    let (hub, device, auditor, council, _) = hub_with_activity();
    let (_, second) = hub
        .add_principal("second auditor", Role::Auditor, NOW)
        .unwrap();

    let who = hub.principal_for(Some(&auditor), Role::Auditor).unwrap();
    let signer = hub
        .principal_for(Some(&council), Role::Countersigner)
        .unwrap();
    let req = hub
        .create_request(&who, Some(&device), None, None, "a reason", NOW)
        .unwrap();
    hub.approve_request(&req.id, &signer, "2099-01-01T00:00:00Z", NOW)
        .unwrap();

    let dir = tmpdir();
    let err =
        report::disclose(&hub, Some(&second), &req.id, dir.path(), now_ts(), "test").unwrap_err();
    assert!(err.to_string().contains("not by you"), "{err}");
}

/// The record the works council reads. Every step of the procedure is in it, in order, and
/// the chain says nothing was removed afterwards.
#[test]
fn every_step_is_in_the_hubs_own_chain() {
    let (hub, device, auditor, council, _) = hub_with_activity();
    let who = hub.principal_for(Some(&auditor), Role::Auditor).unwrap();
    let signer = hub
        .principal_for(Some(&council), Role::Countersigner)
        .unwrap();
    let req = hub
        .create_request(&who, Some(&device), None, None, "why we looked", NOW)
        .unwrap();
    hub.approve_request(&req.id, &signer, "2099-01-01T00:00:00Z", NOW)
        .unwrap();
    let dir = tmpdir();
    report::disclose(&hub, Some(&auditor), &req.id, dir.path(), now_ts(), "test").unwrap();

    let events = hub.hub_events(100).unwrap();
    let actions: Vec<&str> = events.iter().map(|e| e.action.as_str()).collect();
    assert_eq!(
        actions,
        [
            "role.granted",
            "role.granted",
            "role.granted",
            "access.requested",
            "access.approved",
            "access.disclosed",
        ]
    );
    // The reason is in the record, not only in somebody's memory of the conversation.
    let requested = &events[3];
    assert_eq!(requested.detail["reason"], "why we looked");
    assert_eq!(hub.verify_hub_chain().unwrap(), 6);
}

#[test]
fn the_hubs_own_chain_notices_an_edited_entry() {
    let (hub, _, _, _, _) = hub_with_activity();
    assert!(hub.verify_hub_chain().is_ok());

    // The triggers stop an UPDATE, so a tamperer would have to rebuild the table. This is
    // what the chain is for: the row count still adds up, and the arithmetic does not.
    hub.conn
        .execute_batch(
            "DROP TRIGGER hub_audit_no_update;
             UPDATE hub_audit SET action = 'role.revoked' WHERE seq = 1;",
        )
        .unwrap();
    let err = hub.verify_hub_chain().unwrap_err().to_string();
    assert!(err.contains("was edited"), "{err}");
}

#[test]
fn a_revoked_credential_stops_working_immediately() {
    let (hub, _, auditor, _, _) = hub_with_activity();
    let who = hub.principal_for(Some(&auditor), Role::Auditor).unwrap();
    assert!(hub.revoke_principal(&who.id, NOW).unwrap());
    let err = hub
        .principal_for(Some(&auditor), Role::Auditor)
        .unwrap_err();
    assert!(err.to_string().contains("revoked"), "{err}");
}

// ---- the licence a customer drops next to the record (0.3.0) ----
//
// The service route has to work without a command prompt, so licensing a hub is copying a
// file into the data directory. These are about what that does when the file is missing or
// wrong — the cases a support call is made of. The happy path needs the issuer's real
// signing key, which lives outside this repository, so it is covered by the licence tests
// against a generated key pair rather than here.

#[test]
fn the_licence_is_dropped_next_to_the_record() {
    let p = super::service::licence_drop_path(std::path::Path::new("/var/lib/cyberbrain"));
    assert_eq!(p, std::path::Path::new("/var/lib/cyberbrain/licence.txt"));
}

#[test]
fn the_names_people_actually_end_up_with_are_taken_too() {
    // Explorer hides known extensions, so saving the attachment as "licence.txt" produces
    // licence.txt.txt and shows it as licence.txt. There is no way for the person to see
    // what went wrong, so refusing it would be a support call about an invisible character.
    for name in [
        "licence.txt",
        "licence.txt.txt",
        "license.txt",
        "license.txt.txt",
    ] {
        let dir = tempfile::tempdir().unwrap();
        std::fs::write(dir.path().join(name), "x").unwrap();
        assert_eq!(
            super::service::find_licence_file(dir.path()),
            Some(dir.path().join(name)),
            "{name} was not found"
        );
    }
    // Calibration: it is not simply returning the first thing it sees.
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("HOW-TO-LICENCE.txt"), "x").unwrap();
    std::fs::write(dir.path().join("notes.txt"), "x").unwrap();
    assert_eq!(super::service::find_licence_file(dir.path()), None);
}

#[test]
fn the_documented_name_wins_over_the_typo() {
    let dir = tempfile::tempdir().unwrap();
    std::fs::write(dir.path().join("licence.txt.txt"), "the accident").unwrap();
    std::fs::write(dir.path().join("licence.txt"), "the one that was meant").unwrap();
    assert_eq!(
        super::service::find_licence_file(dir.path()),
        Some(dir.path().join("licence.txt"))
    );
}

#[test]
fn a_hub_with_no_licence_is_told_where_it_looked() {
    let said = super::service::where_it_looked(std::path::Path::new("C:\\ProgramData\\Cyberbrain"));
    // The log line that was missing said only "no licence installed", which leaves the
    // reader unable to tell whether the file was looked for, looked for somewhere else,
    // or found and rejected.
    assert!(said.contains("C:\\ProgramData\\Cyberbrain"), "{said}");
    assert!(said.contains("licence.txt"), "{said}");
    assert!(
        said.contains("restart"),
        "it has to say what to do next: {said}"
    );
}

#[test]
fn no_licence_file_is_not_worth_a_word() {
    let dir = tempfile::tempdir().unwrap();
    let hub = HubStore::in_memory().unwrap();
    // A hub licensed months ago has no file lying about, and a line every start would
    // teach whoever reads the log to skip it.
    assert_eq!(
        super::service::adopt_dropped_licence(&hub, dir.path()),
        super::service::Dropped::None
    );
}

#[test]
fn an_unusable_licence_file_is_named_and_changes_nothing() {
    let dir = tempfile::tempdir().unwrap();
    let hub = HubStore::in_memory().unwrap();
    hub.set_licence("the one that is already installed")
        .unwrap();
    std::fs::write(dir.path().join("licence.txt"), "not a licence at all").unwrap();

    let super::service::Dropped::Problem(note) =
        super::service::adopt_dropped_licence(&hub, dir.path())
    else {
        panic!("somebody put that file there on purpose; silence would be the wrong answer");
    };
    assert!(note.contains("not usable"), "{note}");
    assert!(
        note.contains("licence.txt"),
        "the message has to say which file: {note}"
    );
    // The point: a bad file must not take away the licence the hub is running on.
    assert_eq!(
        hub.licence_text().unwrap().as_deref(),
        Some("the one that is already installed")
    );
}

#[test]
fn the_same_licence_twice_is_not_news() {
    let dir = tempfile::tempdir().unwrap();
    let hub = HubStore::in_memory().unwrap();
    let text = "whatever is installed";
    hub.set_licence(text).unwrap();
    std::fs::write(dir.path().join("licence.txt"), text).unwrap();
    // Left in place after the first start, as people do.
    assert_eq!(
        super::service::adopt_dropped_licence(&hub, dir.path()),
        super::service::Dropped::Unchanged
    );

    // Calibration: the same call does speak up when the file is not what is installed, so
    // the silence above comes from the comparison and not from the function being mute.
    std::fs::write(dir.path().join("licence.txt"), "something else entirely").unwrap();
    assert!(matches!(
        super::service::adopt_dropped_licence(&hub, dir.path()),
        super::service::Dropped::Problem(_)
    ));
}

// ---- what a failed service registration says ----
//
// The first person to tick the installer's hub box got:
//
//     cannot register the service: IO error in winapi call
//
// which names nothing, suggests nothing, and cannot be looked up. The wrapper's Display
// says that; the operating system's message and number are one level down in `source()`.

#[test]
fn an_os_error_is_reported_with_its_number() {
    // 5 is ERROR_ACCESS_DENIED on Windows and EIO here; the number is the point, not which
    // number this machine happens to give it.
    let io = std::io::Error::from_raw_os_error(5);
    let said = super::service::describe_os_error(&io);
    assert!(
        said.contains("(Windows error 5)"),
        "the number a person can look up is missing: {said}"
    );
    assert!(
        said.len() > "(Windows error 5)".len(),
        "the number without the sentence is not much better: {said}"
    );
    assert!(
        !said.contains("winapi"),
        "this is the layer that told nobody anything: {said}"
    );
}

#[test]
fn an_error_without_a_number_still_says_something() {
    let io = std::io::Error::other("the pipe went away");
    let said = super::service::describe_os_error(&io);
    assert_eq!(said, "the pipe went away");
}

#[test]
fn a_file_that_cannot_be_read_is_not_the_same_as_no_file() {
    let dir = tempfile::tempdir().unwrap();
    let hub = HubStore::in_memory().unwrap();
    // What "Save as > Unicode" in Notepad produces: UTF-16, which is not valid UTF-8 and
    // looks entirely correct in every way the person who saved it can check.
    std::fs::write(dir.path().join("licence.txt"), [0xff, 0xfe, 0x7b, 0x00]).unwrap();

    let said = super::service::adopt_dropped_licence(&hub, dir.path());
    let super::service::Dropped::Problem(msg) = said else {
        panic!("a file that is there but unreadable must not read as no file: {said:?}");
    };
    assert!(msg.contains("licence.txt"), "{msg}");
    assert!(msg.contains("UTF-8"), "it has to say what to do: {msg}");
}

// ---- the hub's own page ----

use super::page::{self, View};

fn view_of(
    hub: &HubStore,
    record: &str,
    flash: Option<std::result::Result<String, String>>,
) -> View {
    View::gather(
        hub,
        std::path::Path::new(record),
        7788,
        // The hub these tests describe is a properly set up one; the unencrypted case has
        // its own test below, because what it shows is different on purpose.
        true,
        NOW.parse().unwrap(),
        flash,
    )
}

#[test]
fn the_page_is_only_for_the_machine_the_hub_runs_on() {
    let yes = ["127.0.0.1:51000", "[::1]:51000"];
    let no = ["192.168.1.20:51000", "10.0.0.5:51000", "[2001:db8::1]:443"];
    for a in yes {
        assert!(
            super::api::at_the_machine(&a.parse().unwrap()),
            "{a} is the machine itself"
        );
    }
    // It shows who is on the network and it can install a licence, on a port the whole
    // network can reach. Getting this backwards is the difference between a status page and
    // an open console.
    for a in no {
        assert!(!super::api::at_the_machine(&a.parse().unwrap()), "{a}");
    }
}

#[test]
fn an_unlicensed_hub_says_so_where_a_person_is_looking() {
    let hub = HubStore::in_memory().unwrap();
    let html = page::render(&view_of(&hub, "/var/lib/cyberbrain/hub.db", None));
    assert!(html.contains("not licensed"), "{html}");
    assert!(html.contains("accepts nothing"));
    // And offers the way out on the same screen, opened, rather than behind a command.
    assert!(html.contains("<details open"), "the form should be open");
    assert!(html.contains("action=\"/licence\""));
}

#[test]
fn a_collecting_hub_shows_the_seats() {
    // Built by hand rather than from a real licence file: only the issuer can sign one, and
    // a test that skips itself when the key is absent is a test that passes by agreeing
    // with itself on every machine but one.
    let v = View {
        version: "0.3.0".into(),
        record: "C:\\ProgramData\\Cyberbrain\\hub.db".into(),
        licence: LicenceState::Valid {
            customer: "Beispiel GmbH".into(),
            seats: 5,
            valid_until: "2027-01-01T00:00:00Z".into(),
            warning: None,
        },
        seats: Some((2, 5)),
        fleet: Vec::new(),
        found_file: None,
        suggested_url: "https://hub:7788".into(),
        encrypted: true,
        flash: None,
    };
    let html = page::render(&v);
    assert!(html.contains("collecting"), "{html}");
    assert!(html.contains("Beispiel GmbH"));
    assert!(
        html.contains("<strong>2</strong> of <strong>5</strong>"),
        "{html}"
    );
    // A hub that is already collecting should not be shouting a form at anybody.
    assert!(!html.contains("<details open"));
}

#[test]
fn a_licence_about_to_run_out_says_it_on_the_page() {
    let v = View {
        version: "0.3.0".into(),
        record: "hub.db".into(),
        licence: LicenceState::Valid {
            customer: "Beispiel GmbH".into(),
            seats: 5,
            valid_until: "2026-10-01T00:00:00Z".into(),
            warning: Some(
                "the licence for Beispiel GmbH ends on 2026-10-01 — 24 day(s) left.".into(),
            ),
        },
        seats: Some((5, 5)),
        fleet: Vec::new(),
        found_file: None,
        suggested_url: "https://hub:7788".into(),
        encrypted: true,
        flash: None,
    };
    let html = page::render(&v);
    // The warning replaces the calm line rather than sitting beside it: the whole point of
    // the thirty days is that somebody acts inside them.
    assert!(html.contains("24 day(s) left"), "{html}");
}

#[test]
fn a_device_name_cannot_carry_markup_into_the_page() {
    let hub = HubStore::in_memory().unwrap();
    // Device names arrive from whoever registers one and are shown back on this page.
    hub.add_device("<script>alert(1)</script>", NOW).unwrap();
    let html = page::render(&view_of(&hub, "hub.db", None));
    assert!(
        !html.contains("<script>alert"),
        "unescaped name in the page"
    );
    assert!(
        html.contains("&lt;script&gt;alert(1)&lt;/script&gt;"),
        "{html}"
    );
}

#[test]
fn a_licence_file_that_is_already_installed_is_not_offered_again() {
    let dir = tempfile::tempdir().unwrap();
    let hub = HubStore::in_memory().unwrap();
    let text = "whatever is installed";
    std::fs::write(dir.path().join("licence.txt"), text).unwrap();
    let record = dir.path().join("hub.db");

    // Before: there is something to click.
    let before = View::gather(&hub, &record, 7788, true, NOW.parse().unwrap(), None);
    assert!(before.found_file.is_some());

    // After: the file is still lying there, as files do, and the button is gone.
    hub.set_licence(text).unwrap();
    let after = View::gather(&hub, &record, 7788, true, NOW.parse().unwrap(), None);
    assert_eq!(after.found_file, None);
}

// ---- the administrator account ----
//
// One account for the machine's administration, which is what the fleet view is. It is not
// the roles model: nothing reachable with this password can read an activity row.

use super::admin;

#[test]
fn a_hub_starts_unclaimed_and_the_first_visit_claims_it() {
    let hub = HubStore::in_memory().unwrap();
    assert!(!admin::is_claimed(&hub));
    admin::set_password(&hub, "korrektpferd1").unwrap();
    assert!(admin::is_claimed(&hub));
}

#[test]
fn there_is_no_password_to_look_up_before_one_is_set() {
    let hub = HubStore::in_memory().unwrap();
    // The point of having no default: nothing works until somebody at the machine chooses.
    for guess in ["", "admin", "password", "cyberbrain", "changeme"] {
        assert!(!admin::verify(&hub, guess), "{guess:?} was accepted");
    }
}

#[test]
fn a_short_password_is_refused_with_the_reason() {
    let hub = HubStore::in_memory().unwrap();
    let e = admin::set_password(&hub, "kurz").unwrap_err();
    assert!(e.contains("10 characters"), "{e}");
    assert!(
        !admin::is_claimed(&hub),
        "a refused password must not be stored"
    );
}

#[test]
fn the_password_is_checked_and_not_stored() {
    let hub = HubStore::in_memory().unwrap();
    admin::set_password(&hub, "korrektpferd1").unwrap();
    assert!(admin::verify(&hub, "korrektpferd1"));
    assert!(!admin::verify(&hub, "korrektpferd2"));
    // What is kept is a PHC string: the algorithm, its parameters, a salt and the hash.
    // The password itself is nowhere in the record, which is the whole point of the hashing.
    let stored = hub.setting("admin_password").unwrap().unwrap();
    assert!(stored.starts_with("$argon2"), "{stored}");
    assert!(!stored.contains("korrektpferd1"));
}

#[test]
fn two_hubs_with_the_same_password_store_different_hashes() {
    let (a, b) = (
        HubStore::in_memory().unwrap(),
        HubStore::in_memory().unwrap(),
    );
    admin::set_password(&a, "korrektpferd1").unwrap();
    admin::set_password(&b, "korrektpferd1").unwrap();
    // A salt, in other words. Without one, one stolen record would answer for every hub
    // whose administrator picked the same thing.
    assert_ne!(
        a.setting("admin_password").unwrap(),
        b.setting("admin_password").unwrap()
    );
}

#[test]
fn resetting_puts_the_hub_back_to_its_first_run() {
    let hub = HubStore::in_memory().unwrap();
    admin::set_password(&hub, "korrektpferd1").unwrap();
    hub.set_setting("admin_password", "").unwrap();
    assert!(!admin::is_claimed(&hub));
    assert!(!admin::verify(&hub, "korrektpferd1"));
}

#[test]
fn a_session_lasts_until_it_is_closed() {
    let s = admin::Sessions::default();
    let now: jiff::Timestamp = NOW.parse().unwrap();
    let token = s.open(now);
    assert!(s.holds(&token, now));
    assert!(
        !s.holds("something else", now),
        "an unknown cookie is not a session"
    );
    s.close(&token);
    assert!(!s.holds(&token, now), "signing out has to mean something");
}

#[test]
fn a_session_does_not_last_forever_and_using_it_keeps_it_alive() {
    let s = admin::Sessions::default();
    let now: jiff::Timestamp = NOW.parse().unwrap();
    let token = s.open(now);
    let day = now + jiff::Span::new().hours(24);
    // Untouched for a day: gone.
    assert!(!s.holds(&token, day));

    // Used every few hours: still there a day later, because each use pushes it out.
    let token = s.open(now);
    let mut t = now;
    for _ in 0..6 {
        t += jiff::Span::new().hours(4);
        assert!(s.holds(&token, t), "a session in use was dropped at {t}");
    }
}

#[test]
fn two_sessions_are_not_the_same_string() {
    let s = admin::Sessions::default();
    let now: jiff::Timestamp = NOW.parse().unwrap();
    let (a, b) = (s.open(now), s.open(now));
    assert_ne!(a, b);
    assert_eq!(a.len(), 64, "32 bytes of randomness, hex");
}

#[test]
fn our_cookie_is_found_among_other_peoples() {
    assert_eq!(
        admin::cookie_from(Some("theme=dark; cyberbrain_hub=abc123; other=1")),
        Some("abc123".to_string())
    );
    assert_eq!(admin::cookie_from(Some("theme=dark")), None);
    assert_eq!(admin::cookie_from(None), None);
    // Not a prefix match: a cookie called cyberbrain_hub_something is not ours.
    assert_eq!(admin::cookie_from(Some("cyberbrain_hub_x=abc")), None);
}

// ---- TLS, and who may type a password into a hub without it ----
//
// The guardrail and the encryption are one subject: what the certificate buys is that the
// password may be typed from a desk at all. Both halves are tested here, and both were
// written against a hub that did neither.

use axum::body::Body;
use axum::extract::connect_info::ConnectInfo;
use axum::http::{Request, StatusCode};
use rustls_pki_types::pem::PemObject;
use tower::ServiceExt;

const TESTDATA: &str = concat!(env!("CARGO_MANIFEST_DIR"), "/src/hub/testdata");

fn hub_with_password(password: &str) -> HubStore {
    let hub = HubStore::in_memory().unwrap();
    admin::set_password(&hub, password).unwrap();
    hub
}

fn state_for(hub: HubStore, encrypted: bool) -> Arc<super::api::HubState> {
    Arc::new(super::api::HubState {
        hub: std::sync::Mutex::new(hub),
        record: std::path::PathBuf::from("hub.db"),
        port: 7788,
        sessions: Default::default(),
        flash: std::sync::Mutex::new(None),
        encrypted,
    })
}

/// A sign-in attempt from `from`, the way the router will see it.
async fn sign_in_from(
    state: Arc<super::api::HubState>,
    from: &str,
    password: &str,
) -> axum::response::Response {
    let mut req = Request::builder()
        .method("POST")
        .uri("/login")
        .header("content-type", "application/x-www-form-urlencoded")
        .body(Body::from(format!("password={password}")))
        .unwrap();
    req.extensions_mut()
        .insert(ConnectInfo(from.parse::<std::net::SocketAddr>().unwrap()));
    super::api::router(state).oneshot(req).await.unwrap()
}

fn cookie_of(r: &axum::response::Response) -> String {
    r.headers()
        .get(axum::http::header::SET_COOKIE)
        .map(|v| v.to_str().unwrap().to_string())
        .unwrap_or_default()
}

#[tokio::test]
async fn a_password_is_not_taken_over_the_network_in_the_clear() {
    let state = state_for(hub_with_password("correct horse battery"), false);
    let r = sign_in_from(state, "192.168.1.20:51000", "correct horse battery").await;
    // Refused, not "wrong password": the hub knows perfectly well it is right, and saying
    // so would be a sentence that teaches the administrator to keep trying.
    assert_eq!(r.status(), StatusCode::FORBIDDEN);
    assert!(cookie_of(&r).is_empty(), "no session may come of this");
    let body = axum::body::to_bytes(r.into_body(), 64 * 1024)
        .await
        .unwrap();
    let body = String::from_utf8_lossy(&body);
    assert!(body.contains("not encrypted"), "{body}");
    // Both ways out, because the person reading it may only be able to take one of them.
    assert!(body.contains("machine the hub runs on"), "{body}");
    assert!(body.contains("--tls-cert"), "{body}");
}

#[tokio::test]
async fn at_the_machine_a_password_still_works_without_a_certificate() {
    // The hub in the cupboard has to stay administrable, or the guardrail above is a way of
    // locking an operator out of their own collector.
    let state = state_for(hub_with_password("correct horse battery"), false);
    let r = sign_in_from(state, "127.0.0.1:51000", "correct horse battery").await;
    assert_eq!(r.status(), StatusCode::SEE_OTHER);
    let cookie = cookie_of(&r);
    assert!(cookie.contains("cyberbrain_hub="), "{cookie}");
    // No `Secure` here: over http a browser would drop it, and the sign-in would appear to
    // succeed and then not have happened.
    assert!(!cookie.contains("Secure"), "{cookie}");
}

#[tokio::test]
async fn with_a_certificate_a_password_may_come_from_a_desk() {
    let state = state_for(hub_with_password("correct horse battery"), true);
    let r = sign_in_from(state, "192.168.1.20:51000", "correct horse battery").await;
    assert_eq!(r.status(), StatusCode::SEE_OTHER);
    assert!(cookie_of(&r).contains("Secure"), "{}", cookie_of(&r));
}

#[tokio::test]
async fn a_wrong_password_from_a_desk_is_still_wrong() {
    // The guardrail must not become an accidental way in: an encrypted hub checks the
    // password like any other.
    let state = state_for(hub_with_password("correct horse battery"), true);
    let r = sign_in_from(state, "192.168.1.20:51000", "hunter2").await;
    assert_eq!(r.status(), StatusCode::OK); // the sign-in page again
    assert!(cookie_of(&r).is_empty());
}

#[test]
fn the_page_says_when_the_hub_is_not_encrypted() {
    let hub = HubStore::in_memory().unwrap();
    let v = View::gather(
        &hub,
        std::path::Path::new("hub.db"),
        7788,
        false,
        NOW.parse().unwrap(),
        None,
    );
    // The address it suggests for invitations follows the hub it is actually being served
    // over, or the first thing an operator does with this page is send clients to a door
    // that is shut.
    assert!(
        v.suggested_url.starts_with("http://"),
        "{}",
        v.suggested_url
    );
    let html = page::render(&v);
    assert!(html.contains("not encrypted"), "{html}");

    let encrypted = View::gather(
        &hub,
        std::path::Path::new("hub.db"),
        7788,
        true,
        NOW.parse().unwrap(),
        None,
    );
    assert!(encrypted.suggested_url.starts_with("https://"));
    assert!(!page::render(&encrypted).contains("not encrypted"));
}

#[test]
fn the_fingerprint_is_the_one_a_browser_shows() {
    let cert = super::tls::load(
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf.pem")
            .as_path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf-key.pem")
            .as_path(),
    )
    .unwrap();
    // The value openssl prints for the same file. Written out rather than computed here:
    // a fingerprint checked against our own hashing would agree with itself even if it
    // hashed the wrong bytes.
    assert_eq!(
        cert.fingerprint,
        "63:4E:3F:E0:BE:0A:13:3F:D4:CB:2B:AA:19:2F:C4:FD:52:C6:0F:00:5C:13:BF:41:03:89:34:03:CD:5B:65:9F"
    );
}

#[test]
fn a_certificate_and_a_key_that_are_not_a_pair_are_refused_by_name() {
    // The CA's certificate with the leaf's key: both files are real, and neither is the
    // other's half. The message has to name the files, because at this point the operator
    // is looking at four paths and one of them is wrong.
    let e = super::tls::load(
        std::path::Path::new(TESTDATA)
            .join("hub-test-ca.pem")
            .as_path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf-key.pem")
            .as_path(),
    )
    .err()
    .expect("a certificate and a key that are not a pair cannot be served with")
    .to_string();
    assert!(e.contains("do not go together"), "{e}");
    assert!(e.contains("hub-test-ca.pem"), "{e}");
}

#[tokio::test]
async fn a_hub_with_a_certificate_answers_over_tls_and_stops_when_told() {
    use tokio::io::{AsyncReadExt, AsyncWriteExt};

    let cert = super::tls::load(
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf.pem")
            .as_path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf-key.pem")
            .as_path(),
    )
    .unwrap();
    let listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
        .await
        .unwrap();
    let addr = listener.local_addr().unwrap();
    let make = super::api::router(state_for(HubStore::in_memory().unwrap(), true))
        .into_make_service_with_connect_info::<std::net::SocketAddr>();
    let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
    let served = tokio::spawn(async move {
        super::tls::serve(listener, make, cert, async {
            let _ = stopped.await;
        })
        .await
    });

    // A client that trusts the test CA and nothing else. Trusting everything would make
    // this a test that the socket works, not that the hub presents a certificate for it.
    let mut roots = rustls::RootCertStore::empty();
    for c in rustls_pki_types::CertificateDer::pem_file_iter(
        std::path::Path::new(TESTDATA).join("hub-test-ca.pem"),
    )
    .unwrap()
    {
        roots.add(c.unwrap()).unwrap();
    }
    let mut config = rustls::ClientConfig::builder()
        .with_root_certificates(roots)
        .with_no_client_auth();
    config.alpn_protocols = vec![b"http/1.1".to_vec()];
    let connector = tokio_rustls::TlsConnector::from(Arc::new(config));
    let tcp = tokio::net::TcpStream::connect(addr).await.unwrap();
    // Bounded, because the interesting failure is a hub that answers in plain text: the
    // handshake then waits for a server hello that is never coming, and an unbounded wait
    // turns a failing test into a build that hangs until somebody kills it.
    let mut tls = tokio::time::timeout(
        std::time::Duration::from_secs(10),
        connector.connect("localhost".try_into().unwrap(), tcp),
    )
    .await
    .expect("the hub should answer the handshake rather than leave it open")
    .expect("the hub should present a certificate the test CA signed");
    tls.write_all(b"GET /health HTTP/1.1\r\nHost: localhost\r\nConnection: close\r\n\r\n")
        .await
        .unwrap();
    let mut answer = String::new();
    tls.read_to_string(&mut answer).await.unwrap();
    assert!(answer.starts_with("HTTP/1.1 200"), "{answer}");
    assert!(answer.contains("\"role\":\"hub\""), "{answer}");

    // And it comes back when asked to stop, rather than being left for the test harness to
    // kill: a hub that cannot be stopped cannot be upgraded either.
    stop.send(()).unwrap();
    tokio::time::timeout(std::time::Duration::from_secs(5), served)
        .await
        .expect("the server should return when it is told to stop")
        .unwrap()
        .unwrap();
}

// ---- the hub's own certificate, and the pin that goes with it ----

#[test]
fn a_hub_makes_one_certificate_and_keeps_it() {
    let dir = tempfile::tempdir().unwrap();
    let first = super::tls::own(dir.path(), &["hub.example.internal".into()]).unwrap();
    assert!(first.pinnable, "its own certificate is the pinnable one");
    assert!(dir.path().join("hub-cert.pem").exists());
    assert!(dir.path().join("hub-key.pem").exists());

    // The pin in every invitation ever issued is this certificate. A second start must not
    // quietly mint a new one, or every enrolled machine stops delivering at once.
    let second = super::tls::own(dir.path(), &["hub.example.internal".into()]).unwrap();
    assert_eq!(first.fingerprint, second.fingerprint);

    // And a certificate that came from the operator is never pinned: it has an issuer, and
    // issuers renew.
    let supplied = super::tls::load(
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf.pem")
            .as_path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf-key.pem")
            .as_path(),
    )
    .unwrap();
    assert!(!supplied.pinnable);
}

#[test]
fn half_a_certificate_is_refused_rather_than_replaced() {
    let dir = tempfile::tempdir().unwrap();
    super::tls::own(dir.path(), &["hub".into()]).unwrap();
    std::fs::remove_file(dir.path().join("hub-cert.pem")).unwrap();
    // Making a fresh pair here would look like a repair and would silently invalidate every
    // pin. The key that is still lying there is the evidence that this was a hub.
    let e = super::tls::own(dir.path(), &["hub".into()])
        .err()
        .expect("a missing half is not something to paper over")
        .to_string();
    assert!(e.contains("come as a pair"), "{e}");
}

#[test]
fn the_names_in_the_certificate_follow_the_address() {
    let wildcard: std::net::SocketAddr = "0.0.0.0:7788".parse().unwrap();
    let names = super::tls::names_for(&wildcard);
    assert!(names.contains(&"localhost".to_string()));
    assert!(names.contains(&"127.0.0.1".to_string()));
    // A wildcard bind is not a name. A certificate for "0.0.0.0" would be a mismatch on
    // every address the hub is actually reached at.
    assert!(!names.contains(&"0.0.0.0".to_string()), "{names:?}");

    let concrete: std::net::SocketAddr = "192.168.1.20:7788".parse().unwrap();
    assert!(super::tls::names_for(&concrete).contains(&"192.168.1.20".to_string()));
}

#[test]
fn the_pin_offered_to_invitations_is_what_the_running_hub_serves() {
    let hub = HubStore::in_memory().unwrap();
    assert_eq!(super::pin_to_offer(&hub), None);
    super::remember_pin(&hub, Some("AB:CD")).unwrap();
    assert_eq!(super::pin_to_offer(&hub).as_deref(), Some("AB:CD"));
    // Restarted without a certificate: an invitation issued now must not promise one. A
    // stale fingerprint sends a machine off to expect something nobody serves.
    super::remember_pin(&hub, None).unwrap();
    assert_eq!(super::pin_to_offer(&hub), None);
}

#[test]
fn an_invitation_without_a_pin_is_still_an_invitation() {
    // Version 1 files exist in the field: hubs issued them before there was a pin, and a
    // client that refused them would mean upgrading every hub and every machine on the same
    // afternoon.
    let v1 = r#"{"kind":"cyberbrain.hub.invitation","version":1,"device":"dev_1",
        "name":"ws","token":"t","hub_url":"https://hub.internal:7788"}"#;
    let inv = super::client::parse_invitation(v1).unwrap();
    assert_eq!(inv.hub_cert_sha256, None);

    let v2 = r#"{"kind":"cyberbrain.hub.invitation","version":2,"device":"dev_1",
        "name":"ws","token":"t","hub_url":"https://hub.internal:7788",
        "hub_cert_sha256":"63:4E:3F"}"#;
    assert_eq!(
        super::client::parse_invitation(v2).unwrap().hub_cert_sha256,
        Some("63:4E:3F".to_string())
    );

    // Something newer than this program: say so rather than guess at it.
    let v3 = r#"{"kind":"cyberbrain.hub.invitation","version":3,"device":"d","name":"w",
        "token":"t","hub_url":"https://hub.internal:7788"}"#;
    let e = super::client::parse_invitation(v3).unwrap_err().to_string();
    assert!(e.contains("newer than this program"), "{e}");
}

#[test]
fn a_fingerprint_is_read_the_way_it_is_written_down() {
    use cyberbrain_policy::egress::transport::CertificatePin;
    let colons = "63:4E:3F:E0:BE:0A:13:3F:D4:CB:2B:AA:19:2F:C4:FD:52:C6:0F:00:5C:13:BF:41:03:89:34:03:CD:5B:65:9F";
    assert!(CertificatePin::parse(colons).is_ok());
    // The same thing pasted out of a script, and in the case a terminal gave it.
    assert!(CertificatePin::parse(&colons.replace(':', "")).is_ok());
    assert!(CertificatePin::parse(&colons.to_lowercase()).is_ok());
    // And the shapes that are not a fingerprint at all. Half of one is the dangerous case:
    // a truncated paste must not become a pin that matches nothing and is never checked.
    for bad in ["", "63:4E:3F", "not a fingerprint", &colons[..40]] {
        assert!(CertificatePin::parse(bad).is_err(), "{bad:?}");
    }
}

/// The real delivery path, against a hub that is really serving TLS.
///
/// Through `client::deliver` rather than the transport underneath it, so that what is tested
/// is what `hub push` does — including whether the pin it was given ever reaches the wire.
async fn deliver_to_pinned_hub(hub_url: &str, pin: Option<&str>) -> Result<super::client::Reply> {
    use cyberbrain_policy::{Actor, AuditLog, Egress, PolicyConfig};
    let cfg = PolicyConfig {
        hub_endpoint: Some(hub_url.to_string()),
        ..Default::default()
    };
    let (log, _sink) = AuditLog::in_memory();
    let egress = Egress::new(cfg, log, Actor::Cli);
    super::client::deliver(
        &egress,
        &Actor::Cli,
        hub_url,
        "a-token",
        pin,
        "0.0.0-test",
        String::new(),
    )
    .await
}

#[tokio::test]
async fn a_pinned_client_talks_to_that_hub_and_to_no_other() {
    let dir = tempfile::tempdir().unwrap();
    let cert = super::tls::own(dir.path(), &["localhost".into(), "127.0.0.1".into()]).unwrap();
    let ours = cert.fingerprint.clone();
    let listener = tokio::net::TcpListener::bind((std::net::Ipv4Addr::LOCALHOST, 0))
        .await
        .unwrap();
    let port = listener.local_addr().unwrap().port();
    let make = super::api::router(state_for(HubStore::in_memory().unwrap(), true))
        .into_make_service_with_connect_info::<std::net::SocketAddr>();
    let (stop, stopped) = tokio::sync::oneshot::channel::<()>();
    let served = tokio::spawn(async move {
        super::tls::serve(listener, make, cert, async {
            let _ = stopped.await;
        })
        .await
    });
    let url = format!("https://127.0.0.1:{port}");

    // Pinned to what this hub actually serves: the delivery goes through. The hub has no
    // licence, so its answer is "not collecting" — an answer, and therefore proof that TLS
    // and the delivery both worked. The pin's job is to get us to a refusal we can read.
    let ok = deliver_to_pinned_hub(&url, Some(&ours)).await.unwrap();
    assert!(
        matches!(ok, super::client::Reply::NotCollecting(_)),
        "reached the hub and got its own answer, not a transport error: {ok:?}"
    );

    // Pinned to a different, perfectly valid certificate: refused. This is the whole point.
    // It is the certificate of the test CA's leaf, so the failure cannot be blamed on the
    // fingerprint being malformed.
    let other = super::tls::load(
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf.pem")
            .as_path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf-key.pem")
            .as_path(),
    )
    .unwrap()
    .fingerprint;
    assert_ne!(other, ours);
    let wrong = deliver_to_pinned_hub(&url, Some(&other))
        .await
        .expect_err("a hub presenting another certificate is not this hub")
        .to_string();
    // And it says so. reqwest prints "error sending request" and keeps the reason in a
    // source chain nothing shows by default; an operator whose hub was reinstalled would
    // otherwise be told only that something went wrong with the network.
    assert!(
        wrong.contains("different certificate"),
        "the error should say what was wrong: {wrong}"
    );

    // And with no pin at all: also refused, because a certificate the hub made itself is in
    // nobody's trust store. Without this case the first one would only prove that the
    // connection works, not that the pin is what made it work.
    let unpinned = deliver_to_pinned_hub(&url, None)
        .await
        .expect_err("a self-signed certificate is not trusted by the platform");
    assert!(unpinned.to_string().contains("POST"), "{unpinned}");

    stop.send(()).unwrap();
    tokio::time::timeout(std::time::Duration::from_secs(5), served)
        .await
        .expect("the server should stop")
        .unwrap()
        .unwrap();
}

#[tokio::test]
async fn a_pin_refuses_to_be_used_over_plain_http() {
    // A pin on an unencrypted connection is a promise about a certificate that is not being
    // presented. Refused before anything is sent, rather than delivering in the clear while
    // the operator believes the hub is pinned.
    let e = deliver_to_pinned_hub("http://127.0.0.1:7788", Some("AB"))
        .await
        .err();
    // The malformed pin is caught first; use a real one to reach the scheme check.
    let real = "63:4E:3F:E0:BE:0A:13:3F:D4:CB:2B:AA:19:2F:C4:FD:52:C6:0F:00:5C:13:BF:41:03:89:34:03:CD:5B:65:9F";
    assert!(e.is_some());
    let e = deliver_to_pinned_hub("http://127.0.0.1:7788", Some(real))
        .await
        .expect_err("pinned and unencrypted is a contradiction")
        .to_string();
    assert!(e.contains("pinned to a certificate"), "{e}");
    assert!(e.contains("no certificate is presented"), "{e}");
}

#[test]
fn the_fingerprint_can_be_read_without_the_key() {
    // `hub cert show` runs beside a hub that is already running, as a second process with no
    // business reading the key — and under a service account, possibly no way to.
    let dir = tempfile::tempdir().unwrap();
    let made = super::tls::own(dir.path(), &["hub".into()]).unwrap();
    let read = super::tls::fingerprint_of(&dir.path().join(super::tls::OWN_CERT)).unwrap();
    assert_eq!(read, made.fingerprint);

    // And it is the same number for a certificate that came from somewhere else, so the two
    // ways of asking cannot drift apart.
    let supplied = std::path::Path::new(TESTDATA).join("hub-test-leaf.pem");
    assert_eq!(
        super::tls::fingerprint_of(&supplied).unwrap(),
        "63:4E:3F:E0:BE:0A:13:3F:D4:CB:2B:AA:19:2F:C4:FD:52:C6:0F:00:5C:13:BF:41:03:89:34:03:CD:5B:65:9F"
    );

    // A key is not a certificate, and the message has to say which file was wrong.
    let e = super::tls::fingerprint_of(&dir.path().join(super::tls::OWN_KEY))
        .unwrap_err()
        .to_string();
    assert!(e.contains(super::tls::OWN_KEY), "{e}");
}

#[test]
fn the_pair_beside_the_record_stays_ours_when_it_arrives_as_two_paths() {
    // The Windows installer makes the certificate and then registers the service with
    // --tls-cert and --tls-key pointing at it. On the first build that reached a Windows
    // machine the hub therefore treated its own certificate as somebody else's, issued
    // invitations with no pin, and every client would have refused a certificate it was
    // never told to expect. The log line said so — the "(invitations pin this)" was missing
    // — and nothing here noticed, because on this machine the flag was never used.
    let dir = tempfile::tempdir().unwrap();
    let made = super::tls::own(dir.path(), &["hub".into()]).unwrap();
    assert!(made.pinnable);

    let as_registered = super::tls::named(
        dir.path(),
        &dir.path().join(super::tls::OWN_CERT),
        &dir.path().join(super::tls::OWN_KEY),
    )
    .unwrap();
    assert!(
        as_registered.pinnable,
        "the same two files, named on a command line, are still the hub's own"
    );
    assert_eq!(as_registered.fingerprint, made.fingerprint);

    // And a certificate that really did come from somewhere else stays unpinnable, whatever
    // directory it is asked about.
    let elsewhere = super::tls::named(
        dir.path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf.pem")
            .as_path(),
        std::path::Path::new(TESTDATA)
            .join("hub-test-leaf-key.pem")
            .as_path(),
    )
    .unwrap();
    assert!(!elsewhere.pinnable);
}

#[cfg(unix)]
#[test]
fn a_generated_key_is_not_readable_by_everybody() {
    use std::os::unix::fs::PermissionsExt;
    let dir = tempfile::tempdir().unwrap();
    super::tls::own(dir.path(), &["hub".into()]).unwrap();
    let mode = std::fs::metadata(dir.path().join(super::tls::OWN_KEY))
        .unwrap()
        .permissions()
        .mode()
        & 0o777;
    assert_eq!(
        mode, 0o600,
        "the key is the one file that must not be shared"
    );
    // The certificate is the opposite: it is handed out on purpose.
    assert!(std::fs::read_to_string(dir.path().join(super::tls::OWN_CERT)).is_ok());
}

#[test]
fn a_record_that_cannot_be_written_says_what_to_do_about_it() {
    // What an operator gets for running `hub add` in an ordinary prompt: the record belongs
    // to the service account, so SQLite opened it read-only. "attempt to write a readonly
    // database" is true and useless — it is not a sentence somebody can act on.
    //
    // The mapping is tested rather than the situation. These tests run as root, and root
    // ignores a read-only file: the first version of this test set the file read-only,
    // wrote to it anyway, and would have passed for a reason that had nothing to do with
    // the code.
    let readonly = rusqlite::Error::SqliteFailure(
        rusqlite::ffi::Error::new(8), // SQLITE_READONLY
        Some("attempt to write a readonly database".into()),
    );
    let e = super::store::explain(readonly);
    assert!(e.contains("readonly database"), "{e}");
    assert!(
        e.contains("elevated") || e.contains("sudo"),
        "the message has to name the way out: {e}"
    );

    // Everything else is passed on as SQLite said it, with no guess bolted on: a wrong
    // suggestion under a real error sends the reader away from it.
    let other = rusqlite::Error::SqliteFailure(
        rusqlite::ffi::Error::new(11), // SQLITE_CORRUPT
        Some("database disk image is malformed".into()),
    );
    assert_eq!(
        super::store::explain(other),
        "database disk image is malformed"
    );
}