odf-crypto 0.1.1

LibreOffice-faithful encryption for ODF packages (.odt, .ods, .odp): detect it, decrypt it, write it
Documentation
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
//! Constructed zip+manifest fixtures for S1–S5, plus real-file goldens (S6).

use super::*;
use crate::manifest::parse_manifest_for_test;
use crate::test_support::{load_golden, zip_with, B64, MIME_TEXT};
use crate::uris;

const MIME_WRONG: &str = "text/plain";

fn manifest_wrap(package_version: Option<&str>, body: &str) -> String {
    let ver = match package_version {
        Some(v) => format!(" manifest:version=\"{v}\""),
        None => String::new(),
    };
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0"{ver}>
{body}
</manifest:manifest>
"#
    )
}

struct PwOpts<'a> {
    path: &'a str,
    media_type: &'a str,
    size: Option<i64>,
    cipher: &'a str,
    checksum: bool,
    start_key: Option<&'a str>,
    kdf: &'a str,
    iteration_count: Option<i32>,
    key_size: Option<i32>,
    argon2: Option<(i32, i32, i32)>,
    kdf_before_algorithm: bool,
}

impl Default for PwOpts<'_> {
    fn default() -> Self {
        Self {
            path: "content.xml",
            media_type: "text/xml",
            size: Some(100),
            cipher: uris::AES256_URL,
            checksum: true,
            start_key: Some(uris::SHA1_NAME),
            kdf: uris::PBKDF2_NAME,
            iteration_count: Some(1024),
            key_size: Some(32),
            argon2: None,
            kdf_before_algorithm: false,
        }
    }
}

fn file_entry(opts: PwOpts<'_>) -> String {
    let size = match opts.size {
        Some(n) => format!(" manifest:size=\"{n}\""),
        None => String::new(),
    };
    let checksum = if opts.checksum {
        format!(
            " manifest:checksum-type=\"{}\" manifest:checksum=\"{B64}\"",
            uris::SHA1_1K_NAME
        )
    } else {
        String::new()
    };
    let algorithm = format!(
        r#"  <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>"#,
        opts.cipher
    );
    let start_key = match opts.start_key {
        Some(name) => format!(
            r#"  <manifest:start-key-generation manifest:start-key-generation-name="{name}"/>"#
        ),
        None => String::new(),
    };
    let key_size = match opts.key_size {
        Some(n) => format!(" manifest:key-size=\"{n}\""),
        None => String::new(),
    };
    let kdf = if let Some((t, m, p)) = opts.argon2 {
        format!(
            r#"  <manifest:key-derivation manifest:key-derivation-name="{kdf}" manifest:salt="{B64}" manifest:argon2-iterations="{t}" manifest:argon2-memory="{m}" manifest:argon2-lanes="{p}"{key_size}/>"#,
            kdf = opts.kdf,
        )
    } else {
        let count = match opts.iteration_count {
            Some(n) => format!(" manifest:iteration-count=\"{n}\""),
            None => String::new(),
        };
        format!(
            r#"  <manifest:key-derivation manifest:key-derivation-name="{kdf}" manifest:salt="{B64}"{count}{key_size}/>"#,
            kdf = opts.kdf,
        )
    };
    let children = if opts.kdf_before_algorithm {
        format!("{kdf}\n{start_key}\n{algorithm}")
    } else {
        format!("{algorithm}\n{start_key}\n{kdf}")
    };
    format!(
        r#" <manifest:file-entry manifest:full-path="{path}" manifest:media-type="{mt}"{size}>
  <manifest:encryption-data{checksum}>
{children}
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
        path = opts.path,
        mt = opts.media_type,
    )
}

fn root_row(version: &str, media_type: &str) -> String {
    format!(
        r#" <manifest:file-entry manifest:full-path="/" manifest:version="{version}" manifest:media-type="{media_type}"/>
"#
    )
}

fn plain_row(path: &str, media_type: &str) -> String {
    format!(
        r#" <manifest:file-entry manifest:full-path="{path}" manifest:media-type="{media_type}"/>
"#
    )
}

fn classify_pkg(manifest: &str, files: &[(&str, &[u8])]) -> Classification {
    let mut all = vec![("META-INF/manifest.xml", manifest.as_bytes())];
    all.extend_from_slice(files);
    classify(&zip_with(&all)).expect("constructed package should classify")
}

const UNENCRYPTED_MANIFEST: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.3">
 <manifest:file-entry manifest:full-path="/" manifest:version="1.3" manifest:media-type="application/vnd.oasis.opendocument.text"/>
 <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml"/>
 <manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml"/>
 <manifest:file-entry manifest:full-path="meta.xml" manifest:media-type="text/xml"/>
 <manifest:file-entry manifest:full-path="settings.xml" manifest:media-type="text/xml"/>
</manifest:manifest>
"#;

const CONTENT_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document-content xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" xmlns:text="urn:oasis:names:tc:opendocument:xmlns:text:1.0" office:version="1.3">
 <office:body>
  <office:text>
   <text:p>Hello</text:p>
  </office:text>
 </office:body>
</office:document-content>
"#;

const STYLES_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document-styles xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3"/>
"#;

const META_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document-meta xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3"/>
"#;

const SETTINGS_XML: &str = r#"<?xml version="1.0" encoding="UTF-8"?>
<office:document-settings xmlns:office="urn:oasis:names:tc:opendocument:xmlns:office:1.0" office:version="1.3"/>
"#;

fn unencrypted_odt() -> Vec<u8> {
    zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("META-INF/manifest.xml", UNENCRYPTED_MANIFEST.as_bytes()),
        ("content.xml", CONTENT_XML.as_bytes()),
        ("styles.xml", STYLES_XML.as_bytes()),
        ("meta.xml", META_XML.as_bytes()),
        ("settings.xml", SETTINGS_XML.as_bytes()),
    ])
}

/// First file-entry gets KeyInfo; `styles.xml` has no encrypted-key of its own.
fn pgp_two_row_manifest() -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" xmlns:loext="urn:org:documentfoundation:names:experimental:office:xmlns:loext:1.0" manifest:version="1.3">
 <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="100">
  <loext:encrypted-key>
   <loext:encryption-method loext:PGPAlgorithm="http://www.w3.org/2001/04/xmlenc#rsa-oaep-mgf1p"/>
   <loext:KeyInfo>
    <loext:PGPData>
     <loext:PGPKeyID>{B64}</loext:PGPKeyID>
     <loext:PGPKeyPacket>{B64}</loext:PGPKeyPacket>
    </loext:PGPData>
   </loext:KeyInfo>
   <loext:CipherData>
    <loext:CipherValue>{B64}</loext:CipherValue>
   </loext:CipherData>
  </loext:encrypted-key>
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="http://www.w3.org/2009/xmlenc11#aes256-gcm" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"/>
  </manifest:encryption-data>
 </manifest:file-entry>
 <manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml" manifest:size="50">
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="http://www.w3.org/2009/xmlenc11#aes256-gcm" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"/>
  </manifest:encryption-data>
 </manifest:file-entry>
</manifest:manifest>
"#
    )
}

fn pgp_two_row_zip() -> Vec<u8> {
    let manifest = pgp_two_row_manifest();
    zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("META-INF/manifest.xml", manifest.as_bytes()),
        ("content.xml", b"encrypted-content"),
        ("styles.xml", b"encrypted-styles"),
    ])
}

/// Issue #2 close-when 1 / plan §7 S1. A real LibreOffice `.odt`: `mimetype`
/// stored first, an explicit `Configurations2/` directory entry, an implicit
/// `Thumbnails/` folder with no directory entry of its own, and every stream
/// listed in the manifest. This is the only fixture that runs the non-wholesome
/// unexpected-stream scan over a member set a producer actually writes.
#[test]
fn classify_real_unencrypted_odt_is_plain() {
    let class = classify(&load_golden("lo-unencrypted.odt")).expect("real unencrypted");
    assert_eq!(class.mode, Mode::Plain);
    assert!(!class.package_encrypted);
    assert!(class.common.is_none());
    assert!(class.encrypted_entries.is_empty());
    assert!(!class.zip_has_encrypted_package);
    // Root row carries both; no mimetype fallback is needed.
    assert_eq!(class.odf_version.as_deref(), Some("1.4"));
    assert_eq!(class.media_type.as_deref(), Some(MIME_TEXT));
    // Every stream is in the manifest, so the scan stays quiet even though the
    // root version is >= 1.2 and would make an unlisted stream fatal.
    assert!(!class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
}

#[test]
fn classify_unencrypted_odt_is_plain() {
    let bytes = unencrypted_odt();
    let class = classify(&bytes).expect("unencrypted ODT should classify");
    assert_eq!(class.mode, Mode::Plain);
    assert!(!class.package_encrypted);
    assert!(class.encrypted_entries.is_empty());
    assert!(class.common.is_none());
    assert!(!class.zip_has_encrypted_package);
    assert!(!class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
}

#[test]
fn pgp_two_row_key_info_leaks_to_styles() {
    let xml = pgp_two_row_manifest();
    let bags = parse_manifest_for_test(&xml);
    assert_eq!(bags.len(), 2, "two file-entry bags");
    assert!(bags[0].key_info.is_some(), "first entry carries KeyInfo");
    assert!(
        bags[1].key_info.is_none(),
        "second entry has no KeyInfo of its own"
    );
    assert_eq!(bags[0].full_path, "content.xml");
    assert_eq!(bags[1].full_path, "styles.xml");
    assert_eq!(bags[0].kdf, Some(KdfId::PgpRsaOaepMgf1p));
    assert_eq!(bags[1].kdf, Some(KdfId::PgpRsaOaepMgf1p));

    let class = classify(&pgp_two_row_zip()).expect("constructed PGP zip should classify");
    assert_eq!(class.encrypted_entries.len(), 2);
    assert!(
        class
            .encrypted_entries
            .iter()
            .any(|e| e.path == "styles.xml" && matches!(e.kdf, Kdf::PgpRsaOaepMgf1p)),
        "styles.xml satisfies the PGP predicate because of sticky key_info"
    );
    assert!(class
        .encrypted_entries
        .iter()
        .any(|e| e.path == "content.xml" && matches!(e.kdf, Kdf::PgpRsaOaepMgf1p)));
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(class.package_encrypted);
    assert_eq!(
        class.common.as_ref().map(|e| e.path.as_str()),
        Some("content.xml")
    );
}

// --- S2: accept predicates, first-wins latch, constructed fixtures ---

enum S2Expect {
    Plain,
    PerEntryLatch { check: fn(&EntryEncryption) },
}

fn s2_min_zip() -> [(&'static str, &'static [u8]); 2] {
    [("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")]
}

#[test]
fn s2_accept_predicate_fixtures() {
    struct Row {
        name: &'static str,
        body: String,
        expect: S2Expect,
        pre: Option<fn(&str)>,
    }

    let rows = [
        Row {
            name: "missing manifest:size",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    size: None,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::Plain,
            pre: None,
        },
        Row {
            name: "GCM without checksum",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: uris::AESGCM256_URL,
                    checksum: false,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| {
                    assert_eq!(e.cipher, Cipher::AesGcmW3c);
                    assert_eq!(e.checksum, Checksum::None);
                },
            },
            pre: None,
        },
        Row {
            name: "CBC without checksum",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    checksum: false,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::Plain,
            pre: None,
        },
        Row {
            name: "Argon2 t=0",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: uris::AESGCM256_URL,
                    checksum: false,
                    kdf: uris::ARGON2ID_URL,
                    argon2: Some((0, 65536, 4)),
                    iteration_count: None,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::Plain,
            pre: Some(|xml| {
                let bags = parse_manifest_for_test(xml);
                let content = bags
                    .iter()
                    .find(|b| b.full_path == "content.xml")
                    .expect("content row");
                assert_eq!(content.kdf, Some(KdfId::Argon2id));
                assert!(content.argon2_args.is_none());
            }),
        },
        Row {
            name: "missing start-key",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    start_key: None,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| assert_eq!(e.start_key, StartKeyAlg::Sha1),
            },
            pre: None,
        },
        Row {
            name: "unknown cipher URI",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: "not-a-cipher",
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::Plain,
            pre: None,
        },
        Row {
            name: "KDF before algorithm, aes256-cbc, no key-size",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: uris::AES256_URL,
                    key_size: None,
                    kdf_before_algorithm: true,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| {
                    assert_eq!(e.cipher, Cipher::AesCbcW3c);
                    assert_eq!(e.derived_key_len, 16);
                    assert_eq!(e.size, 100);
                    assert_eq!(e.iv, vec![1, 2, 3, 4]);
                },
            },
            pre: None,
        },
        Row {
            name: "algorithm before KDF, aes256-cbc, no key-size",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: uris::AES256_URL,
                    key_size: None,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| assert_eq!(e.derived_key_len, 32),
            },
            pre: None,
        },
        Row {
            name: "algorithm before KDF, aes192-gcm, no key-size",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: uris::AESGCM192_URL,
                    checksum: false,
                    key_size: None,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| {
                    assert_eq!(e.cipher, Cipher::AesGcmW3c);
                    assert_eq!(e.derived_key_len, 24);
                },
            },
            pre: None,
        },
        Row {
            name: "key-size 256 is sal_Int32 not u8",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    key_size: Some(256),
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| assert_eq!(e.derived_key_len, 256),
            },
            pre: None,
        },
        Row {
            name: "argon2 iterations +3",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    cipher: uris::AESGCM256_URL,
                    checksum: false,
                    kdf: uris::ARGON2ID_URL,
                    argon2: Some((3, 65536, 4)),
                    iteration_count: None,
                    ..PwOpts::default()
                })
                .replace(
                    "manifest:argon2-iterations=\"3\"",
                    "manifest:argon2-iterations=\"+3\""
                )
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| match &e.kdf {
                    Kdf::Argon2id { t, m, p, .. } => {
                        assert_eq!((*t, *m, *p), (3, 65536, 4));
                    }
                    other => panic!("{other:?}"),
                },
            },
            pre: None,
        },
        Row {
            name: "missing iteration-count, PBKDF2",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts {
                    iteration_count: None,
                    ..PwOpts::default()
                })
            ),
            expect: S2Expect::PerEntryLatch {
                check: |e| match &e.kdf {
                    Kdf::Pbkdf2 { iterations, .. } => assert_eq!(*iterations, 0),
                    other => panic!("expected PBKDF2 with 0 iterations, got {other:?}"),
                },
            },
            pre: None,
        },
        Row {
            name: "slash file-entry applies root version and media-type",
            body: format!(
                "{}{}",
                root_row("1.2", MIME_TEXT),
                file_entry(PwOpts::default())
            ),
            expect: S2Expect::PerEntryLatch { check: |_| {} },
            pre: None,
        },
    ];

    for row in rows {
        let manifest = manifest_wrap(Some("1.2"), &row.body);
        if let Some(pre) = row.pre {
            pre(&manifest);
        }
        let class = classify_pkg(&manifest, &s2_min_zip());
        match row.expect {
            S2Expect::Plain => {
                assert_eq!(class.mode, Mode::Plain, "{}", row.name);
                assert!(!class.package_encrypted, "{}", row.name);
                assert!(class.encrypted_entries.is_empty(), "{}", row.name);
            }
            S2Expect::PerEntryLatch { check } => {
                assert_eq!(class.mode, Mode::PerEntry, "{}", row.name);
                assert!(class.package_encrypted, "{}", row.name);
                let entry = class.common.as_ref().expect(row.name);
                check(entry);
                if row.name == "slash file-entry applies root version and media-type" {
                    assert_eq!(class.odf_version.as_deref(), Some("1.2"));
                    assert_eq!(class.media_type.as_deref(), Some(MIME_TEXT));
                }
            }
        }
    }
}

/// Issue #3 row 10 / plan F11. The resolution itself is pinned directly by
/// `zip_tree::tests::implicit_folder_from_member_path` (a `Pictures/` lookup
/// returns `Folder` with no directory entry in the zip) and, at this layer, by
/// `pictures_folder_row_poisons_nested_content_xml_onto_root`, where the row has
/// to resolve for the A10 cache write to happen at all. What this fixture adds
/// is the surrounding package: a folder synthesized purely from a member path
/// does not disturb the scan, and the unlisted `Pictures/photo.png` under it is
/// still reported.
#[test]
fn s2_pictures_folder_resolves_without_zip_dir_entry() {
    let body = format!(
        "{}{}{}",
        root_row("1.2", MIME_TEXT),
        plain_row("Pictures/", "application/vnd.oasis.opendocument.text"),
        file_entry(PwOpts::default())
    );
    let bytes = zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        (
            "META-INF/manifest.xml",
            manifest_wrap(Some("1.2"), &body).as_bytes(),
        ),
        ("content.xml", b"x"),
        ("Pictures/photo.png", b"png"),
    ]);
    let names: Vec<String> = {
        let mut archive = zip::ZipArchive::new(Cursor::new(&bytes)).unwrap();
        (0..archive.len())
            .map(|i| archive.by_index(i).unwrap().name().unwrap().to_string())
            .collect()
    };
    assert!(
        !names.iter().any(|n| n == "Pictures/" || n == "Pictures"),
        "fixture must not include an explicit Pictures/ zip directory entry"
    );
    let class = classify(&bytes).expect("Pictures/ row must resolve");
    assert_eq!(class.mode, Mode::PerEntry);
    assert_eq!(class.odf_version.as_deref(), Some("1.2"));
    assert!(
        class.has_unexpected_streams,
        "Pictures/photo.png is in the zip but not the manifest"
    );
}

#[test]
fn s2_first_wins_latch_encrypted_package_before_content() {
    let body = format!(
        "{}{}{}",
        file_entry(PwOpts {
            path: "encrypted-package",
            media_type: MIME_TEXT,
            ..PwOpts::default()
        }),
        file_entry(PwOpts::default()),
        root_row("1.2", MIME_TEXT)
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
            ("content.xml", b"x"),
        ],
    );
    assert_eq!(class.mode, Mode::Wholesome);
    assert_eq!(
        class.common.as_ref().map(|e| e.path.as_str()),
        Some("encrypted-package")
    );
}

#[test]
fn s2_first_wins_latch_content_before_encrypted_package() {
    let body = format!(
        "{}{}",
        file_entry(PwOpts::default()),
        file_entry(PwOpts {
            path: "encrypted-package",
            media_type: MIME_TEXT,
            ..PwOpts::default()
        })
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
            ("content.xml", b"x"),
        ],
    );
    assert_eq!(class.mode, Mode::Wholesome);
    assert_eq!(
        class.common.as_ref().map(|e| e.path.as_str()),
        Some("content.xml")
    );
}

// --- S3: wholesome zip member vs XML-only; mimetype fallback ---

fn wholesome_body(include_slash: bool) -> String {
    let mut body = String::new();
    if include_slash {
        body.push_str(&root_row("1.3", MIME_TEXT));
    }
    body.push_str(&file_entry(PwOpts {
        path: "encrypted-package",
        media_type: MIME_TEXT,
        cipher: uris::AESGCM256_URL,
        checksum: false,
        kdf: uris::ARGON2ID_URL,
        argon2: Some((3, 65536, 4)),
        iteration_count: None,
        start_key: Some(uris::SHA256_URL),
        ..PwOpts::default()
    }));
    body
}

#[test]
fn s3_zip_member_and_complete_bag_is_wholesome() {
    let class = classify_pkg(
        &manifest_wrap(Some("1.3"), &wholesome_body(false)),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
        ],
    );
    assert_eq!(class.mode, Mode::Wholesome);
    assert!(class.package_encrypted);
    assert!(class.zip_has_encrypted_package);
    assert_eq!(
        class.common.as_ref().map(|e| e.path.as_str()),
        Some("encrypted-package")
    );
}

#[test]
fn s3_xml_only_encrypted_package_is_not_wholesome() {
    let class = classify_pkg(
        &manifest_wrap(Some("1.3"), &wholesome_body(false)),
        &[("mimetype", MIME_TEXT.as_bytes())],
    );
    assert_ne!(class.mode, Mode::Wholesome);
    assert!(!class.zip_has_encrypted_package);
    assert!(!class.package_encrypted);
    assert!(class.encrypted_entries.is_empty());
}

#[test]
fn s3_package_version_copied_onto_first_entry_when_slash_omitted() {
    let xml = manifest_wrap(Some("1.3"), &wholesome_body(false));
    let bags = parse_manifest_for_test(&xml);
    assert_eq!(bags[0].full_path, "encrypted-package");
    assert_eq!(bags[0].version.as_deref(), Some("1.3"));

    let class = classify_pkg(
        &xml,
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
        ],
    );
    assert_eq!(class.odf_version.as_deref(), Some("1.3"));
}

#[test]
fn s3_mimetype_fallback_only_with_vnd_prefix() {
    let xml = manifest_wrap(Some("1.3"), &wholesome_body(false));
    let present = classify_pkg(
        &xml,
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
        ],
    );
    assert_eq!(present.odf_version.as_deref(), Some("1.3"));
    assert_eq!(present.media_type.as_deref(), Some(MIME_TEXT));

    let missing = classify_pkg(&xml, &[("encrypted-package", b"inner")]);
    assert!(missing.odf_version.is_none());
    assert!(missing.media_type.is_none());

    let wrong = classify_pkg(
        &xml,
        &[
            ("mimetype", MIME_WRONG.as_bytes()),
            ("encrypted-package", b"inner"),
        ],
    );
    assert!(wrong.odf_version.is_none());
    assert!(wrong.media_type.is_none());
}

// --- S4: unexpected-stream scan; zip check not mode ---

#[test]
fn s4_extra_root_stream_version_12_is_fatal() {
    let body = format!(
        "{}{}{}",
        root_row("1.2", MIME_TEXT),
        file_entry(PwOpts::default()),
        plain_row("content.xml", "text/xml")
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("content.xml", b"x"),
            ("extra.bin", b"nope"),
        ],
    );
    assert!(class.has_unexpected_streams);
    assert!(class.odf12_fatal);
}

#[test]
fn s4_extra_root_stream_pre_12_is_not_fatal() {
    let body = format!(
        "{}{}",
        root_row("1.1", MIME_TEXT),
        file_entry(PwOpts::default())
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.1"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("content.xml", b"x"),
            ("extra.bin", b"nope"),
        ],
    );
    assert!(class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
}

#[test]
fn s4_incomplete_encrypted_package_member_still_uses_wholesome_allow_list() {
    let body = file_entry(PwOpts {
        path: "encrypted-package",
        media_type: MIME_TEXT,
        size: None,
        cipher: uris::AESGCM256_URL,
        checksum: false,
        kdf: uris::ARGON2ID_URL,
        argon2: Some((3, 65536, 4)),
        iteration_count: None,
        ..PwOpts::default()
    });
    let extra_listed = format!(
        "{}{}",
        body,
        plain_row("extra.bin", "application/octet-stream")
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.3"), &extra_listed),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
            ("extra.bin", b"listed"),
        ],
    );
    assert_ne!(class.mode, Mode::Wholesome);
    assert!(class.zip_has_encrypted_package);
    assert!(
        class.has_unexpected_streams,
        "wholesome allow-list flags extra.bin even when listed"
    );
}

#[test]
fn s4_xml_only_encrypted_package_uses_non_wholesome_scan() {
    let body = format!(
        "{}{}",
        file_entry(PwOpts {
            path: "encrypted-package",
            media_type: MIME_TEXT,
            cipher: uris::AESGCM256_URL,
            checksum: false,
            kdf: uris::ARGON2ID_URL,
            argon2: Some((3, 65536, 4)),
            iteration_count: None,
            ..PwOpts::default()
        }),
        plain_row("extra.bin", "application/octet-stream")
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.3"), &body),
        &[("mimetype", MIME_TEXT.as_bytes()), ("extra.bin", b"listed")],
    );
    assert!(!class.zip_has_encrypted_package);
    assert_ne!(class.mode, Mode::Wholesome);
    assert!(
        !class.has_unexpected_streams,
        "non-wholesome scan accepts a listed extra.bin"
    );
}

#[test]
fn s4_nested_mimetype_is_not_exempt() {
    let body = format!(
        "{}{}",
        root_row("1.2", MIME_TEXT),
        file_entry(PwOpts::default())
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("content.xml", b"x"),
            ("foo/mimetype", b"nested"),
        ],
    );
    assert!(class.has_unexpected_streams);
    assert!(class.odf12_fatal);
}

// --- S5: PGP bag typed; loext and manifest trees ---

fn loext_encrypted_key(wrap_uri: &str) -> String {
    format!(
        r#"  <loext:encrypted-key>
   <loext:encryption-method loext:PGPAlgorithm="{wrap_uri}"/>
   <loext:KeyInfo>
    <loext:PGPData>
     <loext:PGPKeyID>{B64}</loext:PGPKeyID>
     <loext:PGPKeyPacket>{B64}</loext:PGPKeyPacket>
    </loext:PGPData>
   </loext:KeyInfo>
   <loext:CipherData>
    <loext:CipherValue>{B64}</loext:CipherValue>
   </loext:CipherData>
  </loext:encrypted-key>
"#
    )
}

fn manifest_encrypted_key(wrap_uri: &str) -> String {
    format!(
        r#" <manifest:encrypted-key>
  <manifest:encryption-method manifest:PGPAlgorithm="{wrap_uri}"/>
  <manifest:keyinfo>
   <manifest:PGPData>
    <manifest:PGPKeyID>{B64}</manifest:PGPKeyID>
    <manifest:PGPKeyPacket>{B64}</manifest:PGPKeyPacket>
   </manifest:PGPData>
  </manifest:keyinfo>
  <manifest:CipherData>
   <manifest:CipherValue>{B64}</manifest:CipherValue>
  </manifest:CipherData>
 </manifest:encrypted-key>
"#
    )
}

fn pgp_row(path: &str, size: i64, key_size: Option<i32>, cipher: &str) -> String {
    let key_size = match key_size {
        Some(n) => format!(" manifest:key-size=\"{n}\""),
        None => String::new(),
    };
    format!(
        r#" <manifest:file-entry manifest:full-path="{path}" manifest:media-type="text/xml" manifest:size="{size}">
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="{cipher}" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"{key_size}/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#
    )
}

#[test]
fn s5_loext_tree_classifies_as_pgp() {
    let xml = manifest_wrap(
        Some("1.3"),
        &format!(
            r#" <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="100">
{}
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
            loext_encrypted_key(uris::PGP_WRAP_URI),
            uris::AESGCM256_URL
        ),
    );
    let class = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(matches!(
        class.common.as_ref().map(|e| &e.kdf),
        Some(Kdf::PgpRsaOaepMgf1p)
    ));
}

#[test]
fn s5_manifest_tree_classifies_as_pgp_without_version_gate() {
    let xml = manifest_wrap(
        Some("1.2"),
        &format!(
            "{}{}",
            manifest_encrypted_key(uris::PGP_WRAP_URI),
            pgp_row("content.xml", 100, None, uris::AESGCM256_URL)
        ),
    );
    let class = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(matches!(
        class.common.as_ref().map(|e| &e.kdf),
        Some(Kdf::PgpRsaOaepMgf1p)
    ));
}

#[test]
fn s5_wrong_wrap_uri_discards_key_and_suppresses_keyinfo() {
    let xml = manifest_wrap(
        Some("1.3"),
        &format!(
            r#" <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="100">
{}
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
            loext_encrypted_key("http://www.w3.org/2001/04/xmlenc#rsa-1_5"),
            uris::AESGCM256_URL
        ),
    );
    let bags = parse_manifest_for_test(&xml);
    assert!(
        bags[0].key_info.is_none(),
        "malformed wrap suppresses package KeyInfo"
    );
    assert_ne!(bags[0].kdf, Some(KdfId::PgpRsaOaepMgf1p));

    let class = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert!(class.encrypted_entries.is_empty());
    assert!(!class.package_encrypted);
}

#[test]
fn s5_pgp_derived_key_len_ignores_lying_key_size() {
    let xml = manifest_wrap(
        Some("1.3"),
        &format!(
            "{}{}",
            manifest_encrypted_key(uris::PGP_WRAP_URI),
            pgp_row("content.xml", 100, Some(16), uris::AESGCM256_URL)
        ),
    );
    let gcm = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(gcm.common.as_ref().unwrap().derived_key_len, 32);
    assert_eq!(gcm.common.as_ref().unwrap().cipher, Cipher::AesGcmW3c);

    let cbc_row = format!(
        r#" <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="100">
  <manifest:encryption-data manifest:checksum-type="{}" manifest:checksum="{B64}">
   <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP" manifest:key-size="16"/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
        uris::SHA1_1K_NAME,
        uris::AES256_URL
    );
    let xml = manifest_wrap(
        Some("1.3"),
        &format!("{}{}", manifest_encrypted_key(uris::PGP_WRAP_URI), cbc_row),
    );
    let cbc = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(cbc.common.as_ref().unwrap().derived_key_len, 32);
    assert_eq!(cbc.common.as_ref().unwrap().cipher, Cipher::AesCbcW3c);
}

// --- S6: real LO/AOO goldens ---

#[test]
fn s6_wholesome_gcm_argon2() {
    let class = classify(&load_golden("lo-wholesome-gcm-argon2.odt")).expect("golden");
    assert_eq!(class.mode, Mode::Wholesome);
    assert!(class.package_encrypted);
    assert!(class.zip_has_encrypted_package);
    let common = class.common.as_ref().expect("latch");
    assert_eq!(common.path, "encrypted-package");
    assert_eq!(common.cipher, Cipher::AesGcmW3c);
    assert!(matches!(
        common.kdf,
        Kdf::Argon2id {
            t: 3,
            m: 65536,
            p: 4,
            ..
        }
    ));
    assert_eq!(common.start_key, StartKeyAlg::Sha256);
    assert_eq!(common.checksum, Checksum::None);
    assert_eq!(common.derived_key_len, 32);
    assert_eq!(class.odf_version.as_deref(), Some("1.4"));
    assert!(!class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
    assert_eq!(class.encrypted_entries.len(), 1);
    assert_eq!(common.size, 6977);
    assert!(!common.iv.is_empty());
}

#[test]
fn s6_legacy_aes_cbc() {
    let class = classify(&load_golden("lo-legacy-aes-cbc.odt")).expect("golden");
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(class.package_encrypted);
    assert!(!class.zip_has_encrypted_package);
    let common = class.common.as_ref().expect("latch");
    assert_eq!(common.path, "content.xml");
    assert_eq!(common.cipher, Cipher::AesCbcW3c);
    assert!(matches!(
        common.kdf,
        Kdf::Pbkdf2 {
            iterations: 100000,
            ..
        }
    ));
    assert_eq!(common.start_key, StartKeyAlg::Sha256);
    assert!(matches!(common.checksum, Checksum::Sha256_1K(_)));
    assert_eq!(common.derived_key_len, 32);
    assert_eq!(class.odf_version.as_deref(), Some("1.2"));
    assert!(!class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
    assert!(class.encrypted_entries.len() >= 2);
    assert_eq!(common.size, 4251);
    assert!(!common.iv.is_empty());
}

#[test]
fn s6_blowfish_pbkdf2() {
    let class = classify(&load_golden("aoo-blowfish-pbkdf2.odt")).expect("golden");
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(class.package_encrypted);
    assert!(!class.zip_has_encrypted_package);
    let common = class.common.as_ref().expect("latch");
    assert_eq!(common.path, "content.xml");
    assert_eq!(common.cipher, Cipher::BlowfishCfb8);
    assert!(matches!(
        common.kdf,
        Kdf::Pbkdf2 {
            iterations: 100000,
            ..
        }
    ));
    assert_eq!(common.start_key, StartKeyAlg::Sha1);
    assert!(matches!(common.checksum, Checksum::Sha1_1K(_)));
    assert_eq!(common.derived_key_len, 16);
    assert!(!class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
    assert!(class.odf_version.is_none() || class.odf_version.as_deref() == Some(""));
    assert!(class.encrypted_entries.len() >= 2);
    assert!(!common.iv.is_empty());
    assert!(common.size > 0);
}

fn classify_err(bytes: &[u8]) -> DetectError {
    classify(bytes).expect_err("expected classify to refuse")
}

#[test]
fn hostile_media_type_cannot_flood_the_diagnostic() {
    // Both sides of the mimetype-conflict message come out of the package, and
    // only one was ever bounded: the `mimetype` member is capped at
    // MIMETYPE_CEILING, but nothing caps a `manifest:media-type` attribute
    // except the 8 MiB manifest read. Measured without `elide`: padding the
    // attribute by 512 KiB produced a 524,447-character Display, linear to the
    // cap. Delete the `elide` calls in classify.rs and this test fails on
    // length -- which is the point of asserting on length rather than shape.
    let padded = format!("{MIME_TEXT}{}", "A".repeat(512 * 1024));
    let xml = manifest_wrap(Some("1.2"), &root_row("1.2", &padded));
    let bytes = zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("META-INF/manifest.xml", xml.as_bytes()),
        ("content.xml", b"x"),
    ]);

    let err = classify_err(&bytes);
    assert!(matches!(err, DetectError::Inconsistent(_)));

    let msg = err.to_string();
    assert!(
        msg.len() < 512,
        "diagnostic grew with attacker input: {} chars",
        msg.len()
    );
    assert!(
        !msg.contains(&"A".repeat(DIAGNOSTIC_ELISION + 1)),
        "more than the elision bound of the hostile value survived"
    );
    assert!(
        msg.contains("bytes elided]"),
        "elision should say it happened, and how much was cut: {msg}"
    );
}

#[test]
fn elision_cuts_on_a_character_boundary() {
    // `manifest:media-type` is arbitrary UTF-8 and slicing a &str at an
    // arbitrary byte index panics. A multi-byte char straddling the bound is
    // the case that would do it, so put one exactly there.
    let straddling = "ä".repeat(DIAGNOSTIC_ELISION);
    let xml = manifest_wrap(Some("1.2"), &root_row("1.2", &straddling));
    let bytes = zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("META-INF/manifest.xml", xml.as_bytes()),
        ("content.xml", b"x"),
    ]);

    let msg = classify_err(&bytes).to_string();
    assert!(msg.contains("bytes elided]"), "{msg}");
}

#[test]
fn not_zip_is_detect_error() {
    assert!(matches!(classify_err(b"not a zip"), DetectError::NotZip));
}

/// LibreOffice reads the central directory at the offset the end record names
/// and supports no data before the zip (`ZipFile.cxx:1336`), so a package with
/// bytes prepended is corrupt to it and never prompts for a password.
/// `ZipArchive::new`'s `ArchiveOffset::Detect` shifts past the prefix and
/// reads it fine. The first assertion is the witness that this input separates
/// the two openers. Without it, the test would pass for an unrelated reason.
#[test]
fn data_before_the_zip_is_not_zip_as_in_libreoffice() {
    for name in ["lo-wholesome-gcm-argon2.odt", "lo-legacy-aes-cbc.odt"] {
        let golden = load_golden(name);
        assert!(classify(&golden).unwrap().package_encrypted, "{name}");

        let mut prefixed = b"#!/bin/sh\nexit 0\n".to_vec();
        prefixed.extend_from_slice(&golden);
        assert!(
            zip::ZipArchive::new(std::io::Cursor::new(&prefixed)).is_ok(),
            "{name}: Detect must still open it, or this tests nothing"
        );
        assert!(
            matches!(classify_err(&prefixed), DetectError::NotZip),
            "{name}"
        );
    }
}

#[test]
fn missing_manifest_is_detect_error() {
    let bytes = zip_with(&[("mimetype", MIME_TEXT.as_bytes())]);
    assert!(matches!(classify_err(&bytes), DetectError::MissingManifest));
}

#[test]
fn invalid_zip_entry_name_is_refused() {
    let bytes = zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("META-INF/manifest.xml", UNENCRYPTED_MANIFEST.as_bytes()),
        ("a/../content.xml", b"x"),
    ]);
    assert!(matches!(classify_err(&bytes), DetectError::Zip(_)));
}

#[test]
fn s3_slash_first_and_versionless_gets_package_version() {
    let slash = format!(
        r#" <manifest:file-entry manifest:full-path="/" manifest:media-type="{MIME_TEXT}"/>
"#
    );
    let body = format!(
        "{}{}{}",
        slash,
        file_entry(PwOpts::default()),
        plain_row("content.xml", "text/xml")
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("content.xml", b"x"),
            ("extra.bin", b"nope"),
        ],
    );
    assert_eq!(class.odf_version.as_deref(), Some("1.2"));
    assert!(class.has_unexpected_streams);
    assert!(class.odf12_fatal);
}

#[test]
fn s4_extra_root_stream_empty_root_version_is_not_fatal() {
    let xml = manifest_wrap(Some("1.3"), &wholesome_body(false));
    let class = classify_pkg(
        &xml,
        &[("encrypted-package", b"inner"), ("extra.bin", b"nope")],
    );
    assert!(class.odf_version.is_none());
    assert!(class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
}

#[test]
fn s5_malformed_key_poisons_only_first_entry() {
    let poisoned = format!(
        r#" <manifest:file-entry manifest:full-path="styles.xml" manifest:media-type="text/xml" manifest:size="100">
{}
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
        loext_encrypted_key("http://www.w3.org/2001/04/xmlenc#rsa-1_5"),
        uris::AESGCM256_URL
    );
    let body = format!("{}{}", poisoned, file_entry(PwOpts::default()));
    let class = classify_pkg(
        &manifest_wrap(Some("1.3"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("styles.xml", b"s"),
            ("content.xml", b"x"),
        ],
    );
    assert!(class.package_encrypted);
    assert_eq!(
        class.common.as_ref().map(|e| e.path.as_str()),
        Some("content.xml")
    );
}

#[test]
fn s5_pgp_start_key_clamps_to_sha256() {
    let xml = manifest_wrap(
        Some("1.3"),
        &format!(
            r#" <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="100">
{}
  <manifest:encryption-data>
   <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>
   <manifest:start-key-generation manifest:start-key-generation-name="{}"/>
   <manifest:key-derivation manifest:key-derivation-name="PGP"/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
            loext_encrypted_key(uris::PGP_WRAP_URI),
            uris::AESGCM256_URL,
            uris::SHA1_NAME
        ),
    );
    let class = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(
        class.common.as_ref().map(|e| e.start_key),
        Some(StartKeyAlg::Sha256)
    );
}

#[test]
fn derived_key_size_resets_per_encryption_data() {
    let first = file_entry(PwOpts {
        key_size: Some(32),
        ..PwOpts::default()
    });
    let second = file_entry(PwOpts {
        path: "styles.xml",
        key_size: None,
        kdf_before_algorithm: true,
        ..PwOpts::default()
    });
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &format!("{}{}", first, second)),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("content.xml", b"x"),
            ("styles.xml", b"s"),
        ],
    );
    let styles = class
        .encrypted_entries
        .iter()
        .find(|e| e.path == "styles.xml")
        .expect("styles");
    assert_eq!(styles.derived_key_len, 16);
}

#[test]
fn typo_root_element_still_imports_file_entries() {
    let body = file_entry(PwOpts::default());
    let xml = format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest-typo xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0">
{body}
</manifest:manifest-typo>
"#
    );
    let class = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(class.package_encrypted);
}

#[test]
fn truncated_manifest_is_plain_not_partial() {
    let body = file_entry(PwOpts::default());
    let xml = manifest_wrap(Some("1.3"), &body);
    let truncated = &xml[..xml.len().saturating_sub(20)];
    let class = classify_pkg(
        truncated,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(class.mode, Mode::Plain);
    assert!(!class.package_encrypted);
}

#[test]
fn nested_encrypted_package_row_is_not_wholesome() {
    let body = format!(
        "{}{}",
        file_entry(PwOpts {
            path: "encrypted-package",
            media_type: "text/plain",
            size: None,
            cipher: uris::AESGCM256_URL,
            checksum: false,
            kdf: uris::ARGON2ID_URL,
            argon2: Some((3, 65536, 4)),
            iteration_count: None,
            ..PwOpts::default()
        }),
        file_entry(PwOpts {
            path: "Object 1/encrypted-package",
            media_type: MIME_TEXT,
            cipher: uris::AESGCM256_URL,
            checksum: false,
            kdf: uris::ARGON2ID_URL,
            argon2: Some((3, 65536, 4)),
            iteration_count: None,
            ..PwOpts::default()
        })
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.3"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("encrypted-package", b"inner"),
            ("Object 1/encrypted-package", b"nested"),
        ],
    );
    assert_ne!(class.mode, Mode::Wholesome);
    assert!(class.zip_has_encrypted_package);
}

#[test]
fn later_bare_slash_row_clears_root_version() {
    let body = format!(
        "{}{}{}",
        root_row("1.2", MIME_TEXT),
        r#" <manifest:file-entry manifest:full-path="/"/>
"#,
        file_entry(PwOpts::default())
    );
    // No mimetype: fallback cannot restore `o_first_version`. A sticky first
    // `/` version would make this fatal; clearing it does not.
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[("content.xml", b"x"), ("stray.txt", b"x")],
    );
    assert!(class.has_unexpected_streams);
    assert!(!class.odf12_fatal);
    assert!(class.odf_version.is_none() || class.odf_version.as_deref() == Some(""));
}

#[test]
fn double_slash_member_resolves_and_latches() {
    let body = file_entry(PwOpts {
        path: "a//content.xml",
        ..PwOpts::default()
    });
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[("mimetype", MIME_TEXT.as_bytes()), ("a//content.xml", b"x")],
    );
    assert!(class.package_encrypted);
    assert_eq!(class.mode, Mode::PerEntry);
}

#[test]
fn second_encryption_data_rereads_checksum() {
    let xml = manifest_wrap(
        Some("1.2"),
        &format!(
            r#" <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="100">
  <manifest:encryption-data manifest:checksum-type="{}" manifest:checksum="{B64}">
   <manifest:algorithm manifest:algorithm-name="{}" manifest:initialisation-vector="{B64}"/>
   <manifest:key-derivation manifest:key-derivation-name="PBKDF2" manifest:salt="{B64}" manifest:iteration-count="1" manifest:key-size="32"/>
  </manifest:encryption-data>
  <manifest:encryption-data manifest:checksum-type="bogus" manifest:checksum="QUJDRA==">
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
            uris::SHA1_1K_NAME,
            uris::AES256_URL
        ),
    );
    let class = classify_pkg(
        &xml,
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    match class.common.as_ref().map(|e| &e.checksum) {
        Some(Checksum::Sha1_1K(d)) => assert_eq!(d, b"ABCD"),
        other => panic!("{other:?}"),
    }
}

/// A deep subtree must not swallow the rest of the manifest. LO invalidates
/// everything past level 6 but keeps parsing; a depth cap that unbalanced the
/// element stack made the whole document read as malformed (zero rows → Plain).
#[test]
fn deep_subtree_does_not_drop_later_entries() {
    let mut deep = String::from(
        " <manifest:file-entry manifest:full-path=\"junk\" manifest:media-type=\"text/xml\" \
         xmlns:m2=\"urn:oasis:names:tc:opendocument:xmlns:manifest:1.0\">\n",
    );
    for _ in 0..40 {
        deep.push_str("<m2:foo>");
    }
    for _ in 0..40 {
        deep.push_str("</m2:foo>");
    }
    deep.push_str(" </manifest:file-entry>\n");

    let body = format!(
        "{}{}{}",
        root_row("1.2", MIME_TEXT),
        deep,
        file_entry(PwOpts::default())
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[
            ("mimetype", MIME_TEXT.as_bytes()),
            ("content.xml", b"x"),
            ("junk", b"x"),
        ],
    );
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(class.package_encrypted);
    assert_eq!(class.encrypted_entries.len(), 1);
    assert_eq!(class.odf_version.as_deref(), Some("1.2"));
}

/// `hasByHierarchicalName("/content.xml")` is false in LO: the walk breaks on
/// the empty first segment and then looks up the whole remainder, leading slash
/// included, as a single child name. The row must not latch.
#[test]
fn leading_slash_stream_row_is_not_applied() {
    let body = format!(
        "{}{}",
        root_row("1.2", MIME_TEXT),
        file_entry(PwOpts {
            path: "/content.xml",
            ..PwOpts::default()
        })
    );
    let class = classify_pkg(
        &manifest_wrap(Some("1.2"), &body),
        &[("mimetype", MIME_TEXT.as_bytes()), ("content.xml", b"x")],
    );
    assert_eq!(class.mode, Mode::Plain);
    assert!(!class.package_encrypted);
    assert!(class.encrypted_entries.is_empty());
}

/// A10: nested `Pictures/album/photo.png` seeds `m_aRecent["Pictures/album"]`
/// only. A `Pictures/` folder row then caches `pPrevious` (root). The following
/// `Pictures/content.xml` complete row resolves as **root** `content.xml` and
/// latches. Folder meta from `Pictures/` still lands on the Pictures folder
/// (`pCurrent`), not the poisoned cache parent.
#[test]
fn pictures_folder_row_poisons_nested_content_xml_onto_root() {
    let body = format!(
        r#" <manifest:file-entry manifest:full-path="Pictures/" manifest:version="1.2" manifest:media-type="image/"/>
{}"#,
        file_entry(PwOpts {
            path: "Pictures/content.xml",
            ..PwOpts::default()
        })
    );
    let class = classify_pkg(
        &manifest_wrap(None, &body),
        &[
            ("content.xml", b"plain-root"),
            ("Pictures/album/photo.png", b"png"),
        ],
    );
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(class.package_encrypted);
    assert_eq!(
        class.common.as_ref().map(|e| e.path.as_str()),
        Some("content.xml")
    );
    assert_eq!(class.encrypted_entries.len(), 1);
    assert_eq!(class.encrypted_entries[0].path, "content.xml");
    // Pictures/ version and media-type must not have landed on the root.
    assert!(class.odf_version.is_none());
    assert!(class.media_type.is_none());
}

/// A10 control: the same zip as the poison case, minus the `Pictures/` folder
/// row. Seeding `m_aRecent["Pictures/album"]` at insert is not itself enough —
/// the folder row is what writes the shallow entry — so the nested row does not
/// resolve and nothing latches.
#[test]
fn nested_row_without_a_folder_row_does_not_latch() {
    let class = classify_pkg(
        &manifest_wrap(
            None,
            &file_entry(PwOpts {
                path: "Pictures/content.xml",
                ..PwOpts::default()
            }),
        ),
        &[
            ("content.xml", b"plain-root"),
            ("Pictures/album/photo.png", b"png"),
        ],
    );
    assert_eq!(class.mode, Mode::Plain);
    assert!(!class.package_encrypted);
    assert!(class.common.is_none());
    assert!(class.encrypted_entries.is_empty());
}

/// A10 negative: `Pictures/photo.png` insert already cached `"Pictures"`
/// correctly, so a later `Pictures/` is a hit and does not poison.
#[test]
fn pictures_photo_insert_then_folder_row_does_not_poison() {
    let body = format!(
        r#" <manifest:file-entry manifest:full-path="Pictures/" manifest:version="1.2" manifest:media-type="image/"/>
{}"#,
        file_entry(PwOpts {
            path: "Pictures/content.xml",
            ..PwOpts::default()
        })
    );
    let class = classify_pkg(
        &manifest_wrap(None, &body),
        &[
            ("content.xml", b"plain-root"),
            ("Pictures/photo.png", b"png"),
        ],
    );
    assert_eq!(class.mode, Mode::Plain);
    assert!(!class.package_encrypted);
    assert!(class.common.is_none());
    assert!(class.encrypted_entries.is_empty());
    assert!(class.odf_version.is_none());
    assert!(class.media_type.is_none());
}

// --- CLI exit-code tripwire (#40) ----------------------------------------

/// Every [`DetectError`] variant has an exit code assigned in `src/bin/odf-crypto.rs`
/// -- approximated by "every variant is named in the match below", because the
/// real property is not observable from where the mapping lives.
///
/// The binary is a separate crate from this one, and [`DetectError`] is
/// `#[non_exhaustive]`, so rustc *requires* `detect_exit` to carry a `_` arm.
/// A variant added tomorrow compiles, falls through that arm, and silently
/// becomes EX_MALFORMED -- which is the whole of #40. A canary written beside
/// the mapping inherits the same `_` arm and cannot catch it either; measured,
/// not assumed (E0004: "`odf_crypto::DetectError` is marked as non-exhaustive, so a
/// wildcard `_` is necessary to match exhaustively").
///
/// Inside the defining crate the attribute does not apply, so this match needs
/// no `_` arm and does not have one. That is the entire mechanism.
///
/// **If this stopped compiling, you added a variant.** Give it an exit code in
/// `detect_exit`, add it to `the_detect_exit_map_is_the_documented_one` in `src/bin/odf-crypto_tests.rs`, then name
/// it here.
///
/// It maps to `()` deliberately. A number here would be a second copy of the
/// mapping, free to drift from the one the binary actually runs: this half
/// checks that every variant is *considered*, the binary's half checks that
/// each one is *right*.
#[test]
fn every_detect_error_variant_is_accounted_for_in_the_cli_exit_map() {
    fn accounted_for(e: &DetectError) {
        match e {
            DetectError::NotZip => (),
            DetectError::MissingManifest => (),
            DetectError::Zip(_) => (),
            DetectError::Inconsistent(_) => (),
            DetectError::Io(_) => (),
        }
    }
    accounted_for(&DetectError::NotZip);
}

// --- #70: `common` is the latch row, not the payload row --------------------

/// A wholesome manifest carrying a complete `content.xml` row **before** a
/// complete `encrypted-package` row.
///
/// LibreOffice does not write this. It is constructible, which is the point:
/// the latch is first-wins (`ZipPackage.cxx`), so `common` comes from
/// `content.xml` while the `Wholesome` verdict comes from `encrypted-package`.
fn two_row_wholesome(first_is_modern: bool) -> Vec<u8> {
    let (a_cipher, a_kdf, b_cipher, b_kdf) = if first_is_modern {
        (uris::AESGCM256_URL, "argon2", uris::AES256_URL, "pbkdf2")
    } else {
        (uris::AES256_URL, "pbkdf2", uris::AESGCM256_URL, "argon2")
    };
    let row = |path: &str, media: &str, cipher: &str, kdf: &str| {
        let (kdf_attrs, checksum) = if kdf == "argon2" {
            (
                format!(
                    r#"manifest:key-derivation-name="{}" manifest:salt="{B64}" manifest:argon2-iterations="3" manifest:argon2-memory="65536" manifest:argon2-lanes="4" manifest:key-size="32""#,
                    uris::ARGON2ID_URL
                ),
                String::new(),
            )
        } else {
            (
                format!(
                    r#"manifest:key-derivation-name="{}" manifest:salt="{B64}" manifest:iteration-count="1024" manifest:key-size="32""#,
                    uris::PBKDF2_NAME
                ),
                format!(
                    r#" manifest:checksum-type="{}" manifest:checksum="{B64}""#,
                    uris::SHA1_1K_NAME
                ),
            )
        };
        format!(
            r#" <manifest:file-entry manifest:full-path="{path}" manifest:media-type="{media}" manifest:size="64">
  <manifest:encryption-data{checksum}>
   <manifest:algorithm manifest:algorithm-name="{cipher}" manifest:initialisation-vector="{B64}"/>
   <manifest:start-key-generation manifest:start-key-generation-name="{}"/>
   <manifest:key-derivation {kdf_attrs}/>
  </manifest:encryption-data>
 </manifest:file-entry>
"#,
            uris::SHA256_URL
        )
    };
    let manifest = manifest_wrap(
        Some("1.4"),
        &format!(
            "{}{}",
            row("content.xml", "text/xml", a_cipher, a_kdf),
            row("encrypted-package", MIME_TEXT, b_cipher, b_kdf),
        ),
    );
    zip_with(&[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("META-INF/manifest.xml", manifest.as_bytes()),
        ("content.xml", b"x"),
        ("encrypted-package", b"y"),
    ])
}

/// **The defect #70 was filed for**, pinned in the direction that is unsafe.
///
/// `common` reports the modern profile while the row `decrypt` acts on is
/// AES-CBC/PBKDF2. A consumer gating a write path on "is this the profile we
/// write" would pass a package whose payload is neither — which is exactly what
/// `wholesome_row` exists to let them ask instead.
#[test]
fn common_can_report_a_profile_the_payload_does_not_have() {
    let pkg = two_row_wholesome(true);
    let class = classify(&pkg).expect("constructed package classifies");

    assert_eq!(class.mode, Mode::Wholesome);
    assert!(class.package_encrypted);

    // The latch row: first in manifest order, and NOT the payload.
    let latch = class
        .common
        .as_ref()
        .expect("wholesome carries a latch row");
    assert_eq!(latch.path, "content.xml");
    assert_eq!(latch.cipher, Cipher::AesGcmW3c);

    // The payload row: what `decrypt` will actually use.
    let payload = class
        .wholesome_row()
        .expect("Wholesome implies a payload row");
    assert_eq!(payload.path, "encrypted-package");
    assert_eq!(payload.cipher, Cipher::AesCbcW3c);

    // The whole point: they disagree, so reading the wrong one is a wrong answer.
    assert_ne!(
        latch.cipher, payload.cipher,
        "fixture must actually exercise the divergence, or this test proves nothing"
    );
}

/// The mirror image, so the test cannot pass by the fixture only ever being
/// built one way round.
#[test]
fn the_divergence_runs_both_directions() {
    let class = classify(&two_row_wholesome(false)).expect("classifies");
    assert_eq!(
        class.common.as_ref().expect("latch").cipher,
        Cipher::AesCbcW3c
    );
    assert_eq!(
        class.wholesome_row().expect("payload").cipher,
        Cipher::AesGcmW3c
    );
}

/// `wholesome_row` is `None` off the wholesome path, where there is no single
/// payload row to name.
#[test]
fn wholesome_row_is_none_for_plain_and_per_entry() {
    let plain = classify(&load_golden("lo-unencrypted.odt")).expect("plain");
    assert_eq!(plain.mode, Mode::Plain);
    assert!(plain.wholesome_row().is_none());

    let per_entry = classify(&load_golden("lo-legacy-aes-cbc.odt")).expect("per-entry");
    assert_eq!(per_entry.mode, Mode::PerEntry);
    assert!(
        per_entry.wholesome_row().is_none(),
        "per-entry has no single payload row -- decrypt acts on every entry"
    );
    assert!(per_entry.common.is_some(), "but it still has a latch row");
}

/// On a package LibreOffice actually writes, the two agree — so the accessor is
/// not a different answer in the normal case, only a correct one in the crafted
/// case.
#[test]
fn latch_and_payload_agree_on_a_real_libreoffice_package() {
    let class = classify(&load_golden("lo-wholesome-gcm-argon2.odt")).expect("real wholesome");
    let latch = class.common.as_ref().expect("latch");
    let payload = class.wholesome_row().expect("payload");
    assert_eq!(latch.path, payload.path);
    assert_eq!(latch.cipher, payload.cipher);
}

// --- #60: `has_non_encrypted_entries`, LibreOffice's `HasNonEncryptedEntries` ---

fn non_encrypted_flag(body: &str, files: &[(&str, &[u8])]) -> (bool, bool) {
    let manifest = manifest_wrap(Some("1.3"), body);
    let class = classify_pkg(&manifest, files);
    (class.package_encrypted, class.has_non_encrypted_entries)
}

/// The shape `objmisc.cxx` warns about: an encrypted package with a plaintext
/// stream listed beside the encrypted one.
#[test]
fn a_plaintext_stream_beside_an_encrypted_one_sets_the_flag() {
    let body = root_row("1.3", MIME_TEXT)
        + &file_entry(PwOpts::default())
        + &plain_row("styles.xml", "text/xml");
    let files: &[(&str, &[u8])] = &[("content.xml", b"x"), ("styles.xml", b"y")];
    assert_eq!(non_encrypted_flag(&body, files), (true, true));
}

#[test]
fn every_listed_stream_encrypted_leaves_the_flag_clear() {
    // Folder rows and unlisted members (`mimetype`, the manifest itself, a file
    // under a folder) are not stream rows upstream, so none of them count.
    let body = root_row("1.3", MIME_TEXT)
        + &file_entry(PwOpts::default())
        + &file_entry(PwOpts {
            path: "styles.xml",
            ..PwOpts::default()
        })
        + &plain_row(
            "Configurations2/",
            "application/vnd.sun.xml.ui.configuration",
        );
    let files: &[(&str, &[u8])] = &[
        ("mimetype", MIME_TEXT.as_bytes()),
        ("content.xml", b"x"),
        ("styles.xml", b"y"),
        ("Configurations2/accelerator/current.xml", b""),
    ];
    assert_eq!(non_encrypted_flag(&body, files), (true, false));
}

/// A row naming no member resolves to nothing upstream (`hasByHierarchicalName`
/// is false), so it sets neither flag.
#[test]
fn a_row_naming_no_member_does_not_count() {
    let body = root_row("1.3", MIME_TEXT)
        + &file_entry(PwOpts::default())
        + &plain_row("missing.xml", "text/xml");
    assert_eq!(
        non_encrypted_flag(&body, &[("content.xml", b"x")]),
        (true, false)
    );
}

/// Incomplete `encryption-data` is the same `else` upstream as none at all.
#[test]
fn an_incomplete_encryption_row_counts_as_non_encrypted() {
    let body = root_row("1.3", MIME_TEXT)
        + &file_entry(PwOpts::default())
        + &file_entry(PwOpts {
            path: "styles.xml",
            checksum: false,
            ..PwOpts::default()
        });
    let files: &[(&str, &[u8])] = &[("content.xml", b"x"), ("styles.xml", b"y")];
    assert_eq!(non_encrypted_flag(&body, files), (true, true));
}

/// Set on a plaintext package too, as upstream does: the flag means "a stream
/// row without encryption", not "partly encrypted". The warning needs both.
#[test]
fn a_plaintext_package_sets_the_flag_without_the_latch() {
    let class = classify(&unencrypted_odt()).expect("classifies");
    assert!(!class.package_encrypted);
    assert!(class.has_non_encrypted_entries);
}

/// LibreOffice does not trip its own incomplete-encryption warning: every
/// encrypted golden it wrote reads `false`. Discovered, not listed, with a
/// floor so an empty glob cannot pass.
#[test]
fn no_encrypted_libreoffice_golden_has_non_encrypted_entries() {
    let dir = crate::test_support::goldens_dir();
    let mut checked = 0;
    for entry in std::fs::read_dir(&dir).expect("goldens dir") {
        let path = entry.expect("dir entry").path();
        if path.extension().is_none_or(|x| x != "odt") {
            continue;
        }
        let name = path.file_name().unwrap().to_string_lossy().into_owned();
        let class = classify(&load_golden(&name)).expect(&name);
        if class.package_encrypted {
            assert!(!class.has_non_encrypted_entries, "{name}");
            checked += 1;
        }
    }
    assert!(checked > 0, "no encrypted golden found under {dir:?}");
}

// --- #87: `classify_reader` ---------------------------------------------------

/// Every `.odt` the crate ships, from all three fixture directories. Asserts
/// none is empty: a glob matching nothing passes every test that loops over it.
fn every_fixture() -> Vec<std::path::PathBuf> {
    let goldens = crate::test_support::goldens_dir();
    let mut out = Vec::new();
    for dir in ["goldens", "ladder", "artifacts"] {
        let dir = goldens.with_file_name(dir);
        let before = out.len();
        for entry in std::fs::read_dir(&dir).expect("fixture dir") {
            let path = entry.expect("dir entry").path();
            if path.extension().is_some_and(|x| x == "odt") {
                out.push(path);
            }
        }
        assert!(out.len() > before, "no .odt under {dir:?}");
    }
    out
}

/// The same machines over the same reads: a package classifies identically
/// from a file as from its bytes.
#[test]
fn classify_reader_agrees_with_classify_on_every_fixture() {
    for path in every_fixture() {
        let bytes = std::fs::read(&path).unwrap();
        let from_file = classify_reader(std::fs::File::open(&path).unwrap());
        match (classify(&bytes), from_file) {
            (Ok(a), Ok(b)) => assert_eq!(a, b, "{path:?}"),
            (a, b) => panic!("{path:?}: slice {a:?}, reader {b:?}"),
        }
    }
}

/// The caller's own error type, so the test can check it comes back intact.
#[derive(Debug)]
struct Cancelled;
impl std::fmt::Display for Cancelled {
    fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
        f.write_str("cancelled by the caller")
    }
}
impl std::error::Error for Cancelled {}

/// A `Cursor` that fails its `fail_at`-th read or seek (counting both), and
/// every one after it, as a cancelling reader would.
struct FailingReader<'a> {
    inner: Cursor<&'a [u8]>,
    calls: usize,
    fail_at: usize,
}

impl FailingReader<'_> {
    fn tick(&mut self) -> std::io::Result<()> {
        self.calls += 1;
        if self.calls >= self.fail_at {
            return Err(std::io::Error::other(Cancelled));
        }
        Ok(())
    }
}

impl std::io::Read for FailingReader<'_> {
    fn read(&mut self, buf: &mut [u8]) -> std::io::Result<usize> {
        self.tick()?;
        self.inner.read(buf)
    }
}

impl std::io::Seek for FailingReader<'_> {
    fn seek(&mut self, pos: std::io::SeekFrom) -> std::io::Result<u64> {
        self.tick()?;
        self.inner.seek(pos)
    }
}

/// A reader failure is the caller's, and comes back as `Io` carrying the
/// caller's own error -- at every point the reader can fail, not only the
/// first. Without the latch the zip layer would turn an early failure into
/// `NotZip` and a later one into `Zip`, or swallow it.
#[test]
fn a_failing_reader_is_reported_as_io_at_every_call() {
    let bytes = load_golden("lo-legacy-aes-cbc.odt");
    let mut fail_at = 1;
    loop {
        let reader = FailingReader {
            inner: Cursor::new(&bytes),
            calls: 0,
            fail_at,
        };
        match classify_reader(reader) {
            Err(DetectError::Io(err)) => {
                let inner = err.get_ref().expect("the caller's error, not a stand-in");
                assert!(inner.is::<Cancelled>(), "call {fail_at}: {err}");
            }
            // Past the last call the reader never fails, and the result must
            // then be the slice's own.
            Ok(class) => {
                assert_eq!(class, classify(&bytes).unwrap());
                assert!(fail_at > 1, "succeeded although the first call failed");
                break;
            }
            Err(other) => panic!("call {fail_at}: expected Io, got {other:?}"),
        }
        fail_at += 1;
    }
}

/// The latch must not reach the slice path: a truncated buffer is still a
/// statement about the file, never an `Io`.
#[test]
fn a_truncated_slice_is_not_an_io_error() {
    let bytes = load_golden("lo-legacy-aes-cbc.odt");
    for cut in [0, 1, 22, bytes.len() / 2, bytes.len() - 1] {
        let err = classify(&bytes[..cut]).unwrap_err();
        assert!(!matches!(err, DetectError::Io(_)), "cut {cut}: {err:?}");
    }
}