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
//! Decrypt arc tests (issues #11–#15).

use std::io::{Cursor, Read, Write};

use zip::write::SimpleFileOptions;
use zip::{ZipArchive, ZipWriter};

use crate::classify::classify;
use crate::decrypt::{
    classification_metadata_unchanged, decrypt, decrypt_with_limits, AllocationSite, DecryptError,
};
use crate::test_support::{
    append_stored_member, load_golden, load_ladder_fixture, pgp_two_row_zip, read_member,
    zip_namelist, NONASCII_PASSWORD, PASSWORD,
};
use crate::{BadParameter, Kdf, ManifestField, MemberFault, Mode, Primitive};

// --- S1 ---

#[test]
fn s1_unencrypted_is_not_encrypted() {
    let err = decrypt(&load_golden("lo-unencrypted.odt"), PASSWORD).unwrap_err();
    assert!(matches!(err, DecryptError::NotEncrypted));
}

#[test]
fn s1_empty_password() {
    let err = decrypt(&load_golden("lo-unencrypted.odt"), "").unwrap_err();
    assert!(matches!(err, DecryptError::EmptyPassword));
}

#[test]
fn s1_pgp_zip_unsupported() {
    let zip = pgp_two_row_zip();
    let class = classify(&zip).expect("pgp zip classifies");
    assert!(
        !class.pgp_keys.is_empty(),
        "pgp_keys from first entry KeyInfo"
    );
    let err = decrypt(&zip, PASSWORD).unwrap_err();
    assert!(matches!(err, DecryptError::UnsupportedPgp));
}

#[test]
fn odf12_fatal_encrypted_package_is_refused() {
    let blob = append_stored_member(&load_golden("lo-legacy-aes-cbc.odt"), "extra.bin", b"nope");
    let class = classify(&blob).expect("fixture classifies");
    assert!(
        class.odf12_fatal,
        "unlisted root stream on ODF 1.2 must be fatal"
    );
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::Odf12Fatal
    ));
}

#[test]
fn pre_12_unexpected_stream_still_decrypts() {
    let blob = append_stored_member(
        &load_golden("aoo-blowfish-pbkdf2.odt"),
        "extra.bin",
        b"nope",
    );
    let class = classify(&blob).expect("fixture classifies");
    assert!(class.has_unexpected_streams);
    assert!(
        !class.odf12_fatal,
        "no ODF >= 1.2 root version, so not fatal"
    );
    decrypt(&blob, PASSWORD).expect("ODF 1.1 unexpected streams are not fatal");
}

#[test]
fn s1_goldens_have_empty_pgp_keys() {
    for name in [
        "lo-unencrypted.odt",
        "aoo-blowfish-pbkdf2.odt",
        "lo-odf11-nonascii-password.odt",
        "lo-legacy-aes-cbc.odt",
        "lo-wholesome-gcm-argon2.odt",
    ] {
        let class = classify(&load_golden(name)).expect(name);
        assert!(class.pgp_keys.is_empty(), "{name}");
    }
}

// --- S2 / S3 / S4 goldens ---

fn assert_well_formed_xml(body: &[u8]) {
    let mut reader = quick_xml::Reader::from_reader(body);
    let mut buf = Vec::new();
    loop {
        buf.clear();
        match reader.read_event_into(&mut buf) {
            Ok(quick_xml::events::Event::Eof) => break,
            Ok(_) => {}
            Err(e) => panic!("malformed XML: {e}"),
        }
    }
}

fn assert_decrypts_to_plain(golden: &str, password: &str) {
    let input = load_golden(golden);
    let before = classify(&input).expect("input classifies");
    let out = decrypt(&input, password).expect("decrypt");
    let after = classify(&out).expect("output classifies");
    assert_eq!(after.mode, Mode::Plain);
    assert!(after.encrypted_entries.is_empty());
    assert!(classification_metadata_unchanged(&before, &after));

    let manifest_bytes = read_member(&out, "META-INF/manifest.xml");
    let mf = String::from_utf8_lossy(&manifest_bytes);
    assert!(!mf.contains("encryption-data"), "{golden}");
    assert!(!mf.contains("manifest:size"), "{golden}");
    assert_eq!(zip_namelist(&input), zip_namelist(&out), "{golden} members");

    for row in &before.encrypted_entries {
        if row.path == "encrypted-package" {
            continue;
        }
        let body = read_member(&out, &row.path);
        assert_eq!(body.len() as i64, row.size, "{} {}", golden, row.path);
        if row.path.ends_with(".xml") || row.path.ends_with(".rdf") {
            assert_well_formed_xml(&body);
        }
    }
}

#[test]
fn s2_blowfish_golden() {
    assert_decrypts_to_plain("aoo-blowfish-pbkdf2.odt", PASSWORD);
    let err = decrypt(&load_golden("aoo-blowfish-pbkdf2.odt"), "wrong").unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword));
}

#[test]
fn s2_nonascii_password_golden() {
    assert_decrypts_to_plain("lo-odf11-nonascii-password.odt", NONASCII_PASSWORD);
    let err = decrypt(&load_golden("lo-odf11-nonascii-password.odt"), "wrong").unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword));
}

#[test]
fn s3_aes_cbc_golden() {
    assert_decrypts_to_plain("lo-legacy-aes-cbc.odt", PASSWORD);
    let err = decrypt(&load_golden("lo-legacy-aes-cbc.odt"), "wrong").unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword));
}

#[test]
fn s4_wholesome_gcm_golden() {
    let input = load_golden("lo-wholesome-gcm-argon2.odt");
    let before = classify(&input).unwrap();
    let out = decrypt(&input, PASSWORD).expect("wholesome decrypt");
    let after = classify(&out).unwrap();
    assert_eq!(after.mode, Mode::Plain);
    assert!(after.encrypted_entries.is_empty());
    assert!(zip_namelist(&out).iter().any(|n| n == "content.xml"));
    let row = before
        .encrypted_entries
        .iter()
        .find(|e| e.path == "encrypted-package")
        .unwrap();
    assert_eq!(out.len() as i64, row.size);
    let err = decrypt(&input, "wrong").unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword));
}

// --- S5 constructed negatives ---
//
// `BadParameters` rows are a deliberate divergence in error granularity from LO
// (plan §4 / issue #15): both fail closed; we expose more detail.

/// A fixture transform: takes a member or manifest body, returns the mutated one.
type Rewrite = fn(&[u8]) -> Vec<u8>;

fn mutate_zip(
    golden: &str,
    member: Option<&str>,
    member_mut: Option<Rewrite>,
    manifest_fn: Option<Rewrite>,
) -> Vec<u8> {
    mutate_bytes(&load_golden(golden), member, member_mut, manifest_fn)
}

fn mutate_bytes(
    input: &[u8],
    member: Option<&str>,
    member_mut: Option<Rewrite>,
    manifest_fn: Option<Rewrite>,
) -> Vec<u8> {
    let mut src = ZipArchive::new(Cursor::new(input)).unwrap();
    let mut buf = Vec::new();
    let mut out = ZipWriter::new(Cursor::new(&mut buf));
    for i in 0..src.len() {
        let mut file = src.by_index(i).unwrap();
        let name = file.name().unwrap().to_string();
        let method = file.compression();
        let mut body = Vec::new();
        file.read_to_end(&mut body).unwrap();
        if let (Some(want), Some(f)) = (member, member_mut) {
            if name == want {
                body = f(&body);
            }
        }
        if name == "META-INF/manifest.xml" {
            if let Some(f) = manifest_fn {
                body = f(&body);
            }
        }
        out.start_file(
            &name,
            SimpleFileOptions::default().compression_method(method),
        )
        .unwrap();
        out.write_all(&body).unwrap();
    }
    out.finish().unwrap();
    buf
}

fn flip_checksum_manifest(xml: &[u8]) -> Vec<u8> {
    let s = String::from_utf8_lossy(xml);
    let marker = "checksum=\"";
    let Some(start) = s.find(marker) else {
        return xml.to_vec();
    };
    let b64_start = start + marker.len();
    let mut owned = s.into_owned().into_bytes();
    owned[b64_start] ^= 1;
    owned
}

#[test]
fn s5_constructed_negatives() {
    let blob = mutate_zip(
        "aoo-blowfish-pbkdf2.odt",
        Some("content.xml"),
        Some(|b| b[..b.len().saturating_sub(64)].to_vec()),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::Inflate(_)
    ));

    let blob = mutate_zip(
        "aoo-blowfish-pbkdf2.odt",
        None,
        None,
        Some(flip_checksum_manifest),
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::WrongPassword
    ));

    let blob = mutate_zip(
        "aoo-blowfish-pbkdf2.odt",
        Some("content.xml"),
        Some(|b| {
            let mut v = b.to_vec();
            v[0] ^= 1;
            v
        }),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::WrongPassword
    ));

    let blob = mutate_zip(
        "lo-legacy-aes-cbc.odt",
        None,
        None,
        Some(flip_checksum_manifest),
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::WrongPassword
    ));

    let blob = mutate_zip(
        "lo-legacy-aes-cbc.odt",
        Some("content.xml"),
        Some(|b| b[..b.len() - 1].to_vec()),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::BadParameters(_)
    ));

    let blob = mutate_zip(
        "lo-legacy-aes-cbc.odt",
        Some("content.xml"),
        Some(|b| {
            let mut v = b.to_vec();
            let last = v.len() - 1;
            v[last] ^= 0xff;
            v
        }),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::WrongPassword
    ));

    let blob = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        Some("encrypted-package"),
        Some(|b| {
            let mut v = b.to_vec();
            let last = v.len() - 1;
            v[last] ^= 1;
            v
        }),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::WrongPassword
    ));

    let blob = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        Some("encrypted-package"),
        Some(|b| b[..20].to_vec()),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::BadParameters(_)
    ));

    let blob = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        Some("encrypted-package"),
        Some(|b| {
            let mut v = b.to_vec();
            v[0] ^= 1;
            v
        }),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::BadParameters(_)
    ));

    let blob = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        Some("encrypted-package"),
        Some(|b| {
            let mut v = b.to_vec();
            v[40] ^= 1;
            v
        }),
        None,
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::WrongPassword
    ));
}

// --- regressions ---

/// Replace `manifest:key-size` on key-derivation only, leaving start-key-generation's.
fn rewrite_kdf_key_size(xml: &str, to: &str) -> String {
    let mut out = String::with_capacity(xml.len());
    let mut rest = xml;
    while let Some(pos) = rest.find("<manifest:key-derivation") {
        let (head, tail) = rest.split_at(pos);
        out.push_str(head);
        let end = tail.find("/>").map(|e| e + 2).unwrap_or(tail.len());
        let (elem, after) = tail.split_at(end);
        out.push_str(&elem.replace(
            "manifest:key-size=\"32\"",
            &format!("manifest:key-size=\"{to}\""),
        ));
        rest = after;
    }
    out.push_str(rest);
    out
}

/// Re-encrypt every row of the AES-256 golden under a 16-byte derived key and declare
/// it as `#aes128-cbc` with `manifest:key-size="16"`. NSS picks the AES variant from
/// the derived key length, so LibreOffice opens this file; `classify` accepts the URI
/// and reports `derived_key_len == 16`. Salt, iteration count, IV and checksum are
/// untouched - the checksum covers the compressed plaintext, which does not change.
fn reencrypt_cbc_as_aes128(golden: &str) -> Vec<u8> {
    use aes::{Aes128, Aes256};
    use cbc::cipher::{BlockDecryptMut, BlockEncryptMut, KeyIvInit};
    use pbkdf2::pbkdf2_hmac;
    use sha1::Sha1;
    use sha2::{Digest, Sha256};

    let input = load_golden(golden);
    let class = classify(&input).unwrap();
    let start = Sha256::digest(PASSWORD.as_bytes()).to_vec();
    let mut bodies: std::collections::HashMap<String, Vec<u8>> = Default::default();

    for row in &class.encrypted_entries {
        let (salt, iters) = match &row.kdf {
            Kdf::Pbkdf2 { iterations, salt } => (salt.clone(), *iterations as u32),
            other => panic!("expected PBKDF2, got {other:?}"),
        };
        let mut k32 = vec![0u8; 32];
        pbkdf2_hmac::<Sha1>(&start, &salt, iters, &mut k32);
        let mut buf = read_member(&input, &row.path);
        let mut dec = cbc::Decryptor::<Aes256>::new_from_slices(&k32, &row.iv).unwrap();
        for chunk in buf.chunks_mut(16) {
            dec.decrypt_block_mut(cbc::cipher::Block::<Aes256>::from_mut_slice(chunk));
        }
        let pad = *buf.last().unwrap() as usize;
        buf.truncate(buf.len() - pad);

        let mut k16 = vec![0u8; 16];
        pbkdf2_hmac::<Sha1>(&start, &salt, iters, &mut k16);
        let padlen = 16 - (buf.len() % 16);
        buf.resize(buf.len() + padlen - 1, 0);
        buf.push(padlen as u8);
        let mut enc = cbc::Encryptor::<Aes128>::new_from_slices(&k16, &row.iv).unwrap();
        for chunk in buf.chunks_mut(16) {
            enc.encrypt_block_mut(cbc::cipher::Block::<Aes128>::from_mut_slice(chunk));
        }
        bodies.insert(row.path.clone(), buf);
    }

    let manifest = String::from_utf8(read_member(&input, "META-INF/manifest.xml")).unwrap();
    let manifest = rewrite_kdf_key_size(&manifest.replace("#aes256-cbc", "#aes128-cbc"), "16");

    let mut src = ZipArchive::new(Cursor::new(&input)).unwrap();
    let mut buf = Vec::new();
    let mut out = ZipWriter::new(Cursor::new(&mut buf));
    for i in 0..src.len() {
        let mut file = src.by_index(i).unwrap();
        let name = file.name().unwrap().to_string();
        let method = file.compression();
        let mut body = Vec::new();
        file.read_to_end(&mut body).unwrap();
        let body = if name == "META-INF/manifest.xml" {
            manifest.clone().into_bytes()
        } else {
            bodies.get(&name).cloned().unwrap_or(body)
        };
        out.start_file(
            &name,
            SimpleFileOptions::default().compression_method(method),
        )
        .unwrap();
        out.write_all(&body).unwrap();
    }
    out.finish().unwrap();
    buf
}

/// AES-128 and AES-192 are in the accepted URI table, and an absent `manifest:key-size`
/// derives 16 bytes even under an `aes256-cbc` URI. Hardcoding AES-256 refused those
/// files as `BadParameters` - claiming the package was malformed when it was not.
#[test]
fn s3_aes128_cbc_decrypts_rather_than_being_refused() {
    let bytes = reencrypt_cbc_as_aes128("lo-legacy-aes-cbc.odt");
    let before = classify(&bytes).unwrap();
    assert!(!before.encrypted_entries.is_empty());
    assert!(
        before
            .encrypted_entries
            .iter()
            .all(|e| e.derived_key_len == 16),
        "fixture must derive 16-byte keys"
    );

    let out = decrypt(&bytes, PASSWORD).expect("AES-128 package must decrypt");
    let after = classify(&out).unwrap();
    assert_eq!(after.mode, Mode::Plain);
    assert!(after.encrypted_entries.is_empty());

    // byte-identical to what the AES-256 original yields
    let want = decrypt(&load_golden("lo-legacy-aes-cbc.odt"), PASSWORD).unwrap();
    for path in ["content.xml", "styles.xml", "meta.xml"] {
        assert_eq!(read_member(&out, path), read_member(&want, path), "{path}");
    }
    assert!(matches!(
        decrypt(&bytes, "wrong").unwrap_err(),
        DecryptError::WrongPassword
    ));
}

fn add_size_to_self_closing_entry(xml: &[u8]) -> Vec<u8> {
    String::from_utf8_lossy(xml)
        .replacen(
            "<manifest:file-entry manifest:full-path=\"Configurations2/\"",
            "<manifest:file-entry manifest:size=\"99\" manifest:full-path=\"Configurations2/\"",
            1,
        )
        .into_bytes()
}

/// A file-entry with no children is an `Event::Empty`, and it can still carry
/// `manifest:size`. Filtering only `Event::Start` left those behind - invisible to the
/// goldens, where every entry with a size also has an `encryption-data` child.
#[test]
fn s2_manifest_size_stripped_from_self_closing_entry() {
    let bytes = mutate_zip(
        "aoo-blowfish-pbkdf2.odt",
        None,
        None,
        Some(add_size_to_self_closing_entry),
    );
    let fixture = String::from_utf8(read_member(&bytes, "META-INF/manifest.xml")).unwrap();
    assert!(
        fixture.contains("manifest:size=\"99\""),
        "fixture must carry the attribute it is testing"
    );

    let out = decrypt(&bytes, PASSWORD).unwrap();
    let mf = String::from_utf8(read_member(&out, "META-INF/manifest.xml")).unwrap();
    assert!(
        !mf.contains("manifest:size"),
        "manifest:size must be dropped from self-closing entries too:\n{mf}"
    );
    assert_eq!(classify(&out).unwrap().mode, Mode::Plain);
}

/// Plan section 2 wants two post-conditions after inflate: the stream reaches its end
/// marker, and the length equals `manifest:size`. The length check is explicit in
/// `inflate_into`; this pins the other one, which is a property of the inflater rather
/// than of our code, so a dependency swap cannot quietly remove it.
///
/// Pinned against `decompress_slice_iter_to_slice`, which is the function the decrypt
/// path actually calls. That matters more than it used to: the slice API is documented
/// to leave whatever it managed to write *in the caller's buffer* when it fails, so
/// this test also records why the per-entry caller builds through `try_new_with` --
/// the wrapper is live for the whole fill and zeroizes that partial document on `Err`.
#[test]
fn truncated_deflate_stream_errors_rather_than_returning_partial_output() {
    use miniz_oxide::inflate::decompress_slice_iter_to_slice;

    let data: Vec<u8> = (0..4096u32).map(|i| (i % 251) as u8).collect();
    let compressed = miniz_oxide::deflate::compress_to_vec(&data, 6);

    let mut slot = vec![0u8; data.len()];
    assert_eq!(
        decompress_slice_iter_to_slice(&mut slot, std::iter::once(&compressed[..]), false, true)
            .unwrap(),
        data.len()
    );
    assert_eq!(slot, data);

    for cut in [1usize, 4, 16] {
        let truncated = &compressed[..compressed.len() - cut];
        let mut slot = vec![0u8; data.len()];
        assert!(
            decompress_slice_iter_to_slice(&mut slot, std::iter::once(truncated), false, true)
                .is_err(),
            "a stream truncated by {cut} B must be an error, not a short success"
        );
    }
}

fn rewrite_manifest_size(xml: &[u8], from: &str, to: &str) -> Vec<u8> {
    let before = format!("manifest:size=\"{from}\"");
    let after = format!("manifest:size=\"{to}\"");
    let s = String::from_utf8_lossy(xml);
    assert!(s.contains(&before), "fixture must carry {before}");
    s.replace(&before, &after).into_bytes()
}

/// `manifest:size` became an allocation length when the inflate moved into a sized
/// slot, so it needs the same treatment `manifest:key-size` already had. It is an
/// `i64` the manifest controls, and `vec![0u8; 9_000_000_000]` is a 9 GB allocation
/// -- or on a 32-bit target a capacity-overflow panic -- reached before any cipher
/// could object. Under the old grown-`Vec` inflate this was the decompressor's
/// ceiling to enforce; now it is ours, and it is enforced before key derivation so a
/// hostile row costs a comparison rather than a 64 MiB Argon2id.
#[test]
fn hostile_manifest_size_is_refused_before_allocating() {
    let bytes = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        None,
        None,
        Some(|xml| rewrite_manifest_size(xml, "6977", "9000000000")),
    );
    let class = classify(&bytes).expect("classify passes manifest:size through");
    assert!(
        class
            .encrypted_entries
            .iter()
            .any(|e| e.size == 9_000_000_000),
        "fixture must carry the hostile size"
    );
    match decrypt(&bytes, PASSWORD) {
        Err(DecryptError::BadParameters(BadParameter::OutOfRange {
            field: ManifestField::Size,
            got,
            ..
        })) => assert_eq!(got, 9_000_000_000),
        other => panic!("expected the manifest:size refusal, got {other:?}"),
    }
}

/// The hazard the sized slot introduces, and the reason the length check is
/// load-bearing rather than belt-and-braces. A slot is zero-filled before the
/// closure runs, so a manifest that OVERSTATES `size` inflates fewer bytes than the
/// slot holds and the decoder still reports success -- the difference is a tail of
/// zeros. Without comparing the written count to the slot length, a truncated
/// document would be accepted as a whole one and handed to the caller padded.
#[test]
fn overstated_manifest_size_is_rejected_rather_than_zero_padded() {
    let bytes = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        None,
        None,
        Some(|xml| rewrite_manifest_size(xml, "6977", "7000")),
    );
    match decrypt(&bytes, PASSWORD) {
        Err(DecryptError::Inflate(msg)) => assert!(
            msg.contains("6977") && msg.contains("7000"),
            "message should name both lengths: {msg}"
        ),
        other => panic!("expected Inflate, got {other:?}"),
    }
}

// --- shared kdf.rs (encrypt arc review): hostile Argon2 tuples ---
//
// `t`/`m`/`p` come straight off an attacker-supplied manifest, and until the
// encrypt arc factored key derivation into `kdf.rs` the only guard was
// `> 0` in `manifest.rs`. Both cases below reach a public `decrypt()` call:
// neither may panic, abort, or hang -- `BadParameters` is the whole contract.

fn set_argon2_lanes_to_overflow(xml: &[u8]) -> Vec<u8> {
    // 2^29: `Params::new` computes `m_cost < p_cost * 8` *before* range-checking
    // `p_cost`, so this overflows u32 and panics in any overflow-checks build
    // (argon2 0.5.3 params.rs:119) unless `kdf.rs` rejects it first. argon2 0.6
    // range-checks `p` first, so the hazard is upstream history now; the test
    // still pins that the answer is `BadParameters`.
    String::from_utf8_lossy(xml)
        .replace(
            "loext:argon2-lanes=\"4\"",
            "loext:argon2-lanes=\"536870912\"",
        )
        .into_bytes()
}

fn set_argon2_memory_to_2gib(xml: &[u8]) -> Vec<u8> {
    // Above `ARGON2_MAX_M_COST_KIB_READ`, so `decrypt` refuses it by comparison
    // before allocating anything. That refusal is the whole point of keeping a
    // read-path cap: the number came from the package, and `decrypt` must run
    // the KDF before it can verify a password, so without this the file chooses
    // how much memory and time one attempt spends. Measured on a build without
    // it: 8 GiB here is `WrongPassword` after 29 minutes.
    String::from_utf8_lossy(xml)
        .replace(
            "loext:argon2-memory=\"65536\"",
            "loext:argon2-memory=\"2147483647\"",
        )
        .into_bytes()
}

fn set_argon2_memory_below_lanes(xml: &[u8]) -> Vec<u8> {
    // m < 8p: argon2's own `MemoryTooLittle`, surfaced rather than panicked on.
    String::from_utf8_lossy(xml)
        .replace("loext:argon2-memory=\"65536\"", "loext:argon2-memory=\"1\"")
        .into_bytes()
}

#[test]
fn argon2_hostile_parameters_are_bad_parameters_not_a_panic() {
    for (label, rewrite) in [
        (
            "lanes 2^29 (overflows Params::new's m < 8p test)",
            set_argon2_lanes_to_overflow as Rewrite,
        ),
        (
            "memory 2 GiB KiB (~2 TiB of blocks)",
            set_argon2_memory_to_2gib,
        ),
        (
            "memory 1 KiB (below 8 * lanes)",
            set_argon2_memory_below_lanes,
        ),
    ] {
        let blob = mutate_zip("lo-wholesome-gcm-argon2.odt", None, None, Some(rewrite));
        // The fixture must still be a complete row, or this proves nothing:
        // classify has to hand decrypt an Argon2id tuple to reject.
        let class = classify(&blob).unwrap_or_else(|e| panic!("{label}: {e}"));
        assert_eq!(class.mode, Mode::Wholesome, "{label}");
        assert!(
            matches!(class.encrypted_entries[0].kdf, Kdf::Argon2id { .. }),
            "{label}: fixture must still carry an Argon2id row"
        );

        let err = decrypt(&blob, PASSWORD).unwrap_err();
        assert!(
            matches!(err, DecryptError::BadParameters(_)),
            "{label}: expected BadParameters, got {err:?}"
        );
    }
}

/// A hostile `manifest:key-size` used to reach `vec![0u8; n]` before any cipher had
/// a chance to reject the length. `derived_key_len` is an `i32`, so the worst case
/// is a ~2 GiB allocation followed by a PBKDF2 over all of it - a hang no `Result`
/// can report. `derive_key` bounds the length before allocating and returns
/// `BadParameters`. `classify` is checked to pass the value through unchanged, so
/// the guard - not the parser - is what this exercises.
///
/// **The refusal moved earlier in `0.1.0-rc.7` and the message changed with it**
/// (issue #79). `decrypt_member` now screens the length against the *cipher*
/// before calling `derive_key` at all, so a 2,000,000,000-byte key is refused by
/// `cipher_accepts_key_len` and never reaches the range check that used to report
/// it. The assertion follows the message rather than being loosened to accept
/// both: two guards sit on this input now, and a test that passes whichever fires
/// would stop noticing if the first one were removed.
#[test]
fn hostile_derived_key_len_is_refused_before_allocating() {
    fn huge_key_size(xml: &[u8]) -> Vec<u8> {
        rewrite_kdf_key_size(std::str::from_utf8(xml).unwrap(), "2000000000").into_bytes()
    }
    let bytes = mutate_zip("lo-legacy-aes-cbc.odt", None, None, Some(huge_key_size));
    let class = classify(&bytes).expect("classify passes the manifest key-size through");
    assert!(
        class
            .encrypted_entries
            .iter()
            .all(|e| e.derived_key_len == 2_000_000_000),
        "fixture must carry the hostile key-size"
    );
    match decrypt(&bytes, PASSWORD) {
        Err(DecryptError::BadParameters(BadParameter::KeySizeForCipher { got, .. })) => {
            assert_eq!(got, 2_000_000_000)
        }
        other => panic!("expected the key-size refusal, got {other:?}"),
    }
}

fn set_pbkdf2_iterations(xml: &[u8], value: &str) -> Vec<u8> {
    String::from_utf8_lossy(xml)
        .replace(
            "manifest:iteration-count=\"100000\"",
            &format!("manifest:iteration-count=\"{value}\""),
        )
        .into_bytes()
}

#[test]
fn hostile_pbkdf2_iterations_are_bad_parameters_not_a_hang() {
    let blob = mutate_zip(
        "lo-legacy-aes-cbc.odt",
        None,
        None,
        Some(|xml| set_pbkdf2_iterations(xml, "2147483647")),
    );
    let class = classify(&blob).expect("classify passes iteration-count through");
    assert!(
        class.encrypted_entries.iter().any(|e| matches!(
            e.kdf,
            Kdf::Pbkdf2 {
                iterations: 2_147_483_647,
                ..
            }
        )),
        "fixture must carry hostile iteration count"
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::BadParameters(_)
    ));
}

#[test]
fn pbkdf2_zero_iterations_is_bad_parameters() {
    let blob = mutate_zip(
        "lo-legacy-aes-cbc.odt",
        None,
        None,
        Some(|xml| set_pbkdf2_iterations(xml, "0")),
    );
    let class = classify(&blob).expect("classify still accepts a complete row with 0 iterations");
    assert!(
        class
            .encrypted_entries
            .iter()
            .any(|e| matches!(e.kdf, Kdf::Pbkdf2 { iterations: 0, .. })),
        "fixture must carry iteration-count 0"
    );
    assert!(matches!(
        decrypt(&blob, PASSWORD).unwrap_err(),
        DecryptError::BadParameters(_)
    ));
}

#[test]
fn encrypted_entry_count_ceiling_refuses_without_running_kdf() {
    assert!(super::ensure_encrypted_entry_count(1, 1).is_ok());
    let err = super::ensure_encrypted_entry_count(2, 1).unwrap_err();
    assert_eq!(
        err.to_string(),
        DecryptError::BadParameters(BadParameter::OutOfRange {
            field: ManifestField::EncryptedEntries,
            got: 2,
            min: 0,
            max: 1,
        })
        .to_string()
    );
    assert!(matches!(
        err,
        DecryptError::BadParameters(BadParameter::OutOfRange {
            field: ManifestField::EncryptedEntries,
            got: 2,
            max: 1,
            ..
        })
    ));
}

#[test]
fn gcm_iv_tag_only_frame_is_not_rejected_as_too_short() {
    fn iv_tag_only_member(_body: &[u8]) -> Vec<u8> {
        let input = load_golden("lo-wholesome-gcm-argon2.odt");
        let iv = classify(&input)
            .unwrap()
            .encrypted_entries
            .into_iter()
            .find(|e| e.path == "encrypted-package")
            .unwrap()
            .iv;
        let mut frame = vec![0u8; crate::limits::AES_GCM_IV_LEN + crate::limits::AES_GCM_TAG_LEN];
        frame[..crate::limits::AES_GCM_IV_LEN].copy_from_slice(&iv);
        frame
    }
    let blob = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        Some("encrypted-package"),
        Some(iv_tag_only_member),
        None,
    );
    let err = decrypt(&blob, PASSWORD).unwrap_err();
    assert!(
        !matches!(
            err,
            DecryptError::BadParameters(BadParameter::Member(MemberFault::ShorterThanIvAndTag))
        ),
        "IV||tag-only member must reach the cipher, not BadParameters: {err:?}"
    );
}

// --- the inflate at its zero-length boundary ---
//
// `manifest:size = 0` is legal: an empty member is a normal thing for an ODF
// package to carry, and none of the goldens has an empty encrypted member. The
// rc.9 sized-slot inflate pinned this at its own boundary; the streaming
// inflater that replaced it in rc.10 (`stream::InflateReader`) is pinned here
// at the same one.

/// An empty member inflates to nothing, not to an error.
#[test]
fn an_empty_member_inflates_to_nothing() {
    use std::io::Read as _;
    let compressed = miniz_oxide::deflate::compress_to_vec(&[], 6);
    let mut inflate = crate::stream::InflateReader::new(&compressed[..], 0, u64::MAX).unwrap();
    let mut out = Vec::new();
    inflate
        .read_to_end(&mut out)
        .expect("an empty member must inflate to nothing, not error");
    assert!(out.is_empty());
}

/// The half that would lose data: a member whose manifest claims 0 but whose
/// ciphertext holds content must not decrypt to nothing.
#[test]
fn a_zero_size_refuses_a_stream_that_has_content() {
    use std::io::Read as _;
    let compressed = miniz_oxide::deflate::compress_to_vec(b"not empty", 6);
    let mut inflate = crate::stream::InflateReader::new(&compressed[..], 0, u64::MAX).unwrap();
    let err = inflate.read_to_end(&mut Vec::new()).unwrap_err();
    assert!(
        matches!(
            crate::stream::Fault::take(err),
            Ok(crate::stream::Fault::Inflate(_))
        ),
        "a non-empty stream must not pass as a zero-size member"
    );
}

/// The bound exists to stop a hostile `manifest:size` becoming a huge
/// allocation, so it must not also reject the legal small end. Zero is in
/// range; negative is not, because `size as usize` on a negative `i64` is an
/// enormous length rather than an error.
#[test]
fn zero_is_a_legal_manifest_size_and_negative_is_not() {
    assert_eq!(
        crate::decrypt::inflated_len(0).expect("0 must be in range"),
        0
    );
    assert!(matches!(
        crate::decrypt::inflated_len(-1),
        Err(DecryptError::BadParameters(_))
    ));
}

// --- kdf.rs's block buffer: fallible, not an abort ---
//
// `derive_argon2id` reserves its Argon2 working buffer with
// `Vec::try_reserve_exact` rather than `vec![]` specifically so a host that
// cannot supply the memory gets a `KdfError::HostCannotAllocate` back instead
// of `handle_alloc_error` aborting the process with `PasswordDigest`/
// `DerivedKey` still live and unwiped (see the doc comment on
// `kdf::derive_argon2id`). A fallible path nobody has ever seen fail is
// decoration, not evidence, so this drives the call with `m` at the crate's
// own ceiling (`ARGON2_MAX_M_COST_KIB_READ`, 1 GiB of blocks -- the scope this
// crate accepts, not a value beyond it) and asserts the specific error.
//
// This is a genuine allocation attempt sized by how much memory the host
// actually has free right now, so it can only witness `HostCannotAllocate`
// on a host that is this tight on memory at the moment the test runs; it is
// deliberately not manufactured with a value beyond `ARGON2_MAX_M_COST_KIB_READ`,
// which would only prove the earlier range check, not this one. On a
// generously-provisioned host the request may simply succeed.
//
// `#[ignore]`, recording a real result rather than a hoped-for one: run in
// isolation on the machine this was written on (16 GiB RAM, `Get-CimInstance
// Win32_OperatingSystem` reporting `FreeVirtualMemory` fluctuating around
// 1.8-2.3 GiB), this 1 GiB request `Ok`'d -- the crate's own legal ceiling
// was not, on that occasion, above what the host could satisfy. Getting a
// deterministic `Err` from here would mean either raising the request past
// `ARGON2_MAX_M_COST_KIB_READ` (out of scope -- see this arc's scope fence) or
// deliberately exhausting the host's memory first, which was not done
// because this suite may run on a live, shared machine where that is not a
// safe thing for a test to do. Run explicitly with `cargo test -- --ignored
// argon2_block_buffer_reports_host_capacity_not_an_abort` on a host you know
// is this tight on memory (or under a container/`ulimit`/cgroup memory cap
// below 1 GiB) to see the assertion actually pass.
#[test]
#[ignore = "host-capacity-dependent: passes only when the host has under ~1 GiB free at call time; not reliably true on a well-provisioned machine or CI runner"]
fn argon2_block_buffer_reports_host_capacity_not_an_abort() {
    let salt = [0u8; 16];
    let mut out = [0u8; 32];
    let result = crate::kdf::derive_argon2id(
        b"start-key-bytes-are-arbitrary-for-this-probe",
        &salt,
        1,                                                // t: minimum iterations
        crate::limits::ARGON2_MAX_M_COST_KIB_READ as i32, // 1 GiB: the read-path ceiling
        1,                                                // p: minimum lanes
        &crate::DecryptLimits::default(),                 // the ceilings decrypt passes
        &mut out,
    );
    let requested_bytes = match result {
        Err(crate::kdf::KdfError::HostCannotAllocate { requested_bytes }) => requested_bytes,
        other => panic!(
            "expected KdfError::HostCannotAllocate on this host; got {other:?} instead \
             -- this machine had enough free memory to satisfy a 1 GiB Argon2 request, \
             so the failure path was not exercised here"
        ),
    };
    assert_eq!(requested_bytes, 1 << 30, "1 GiB of Argon2 blocks");
    // Reaching this line at all is the point: `try_reserve_exact` returned
    // `Err` and unwound normally rather than the allocator aborting the
    // process, which is the one thing a `vec![]`-based version could never
    // let this test observe.
}

#[test]
fn a_host_capacity_failure_is_not_a_bad_parameter() {
    // A refusal the ALLOCATOR makes still cannot be tested deterministically:
    // that needs a #[global_allocator] shim, and `unsafe_code = "forbid"` in
    // Cargo.toml makes one impossible -- `forbid` cannot be lifted by `allow`.
    // The ignored test above drives a real 1 GiB request and is the only thing
    // that exercises the allocator itself saying no, on a host small enough.
    //
    // A refusal `try_reserve_exact` makes on its own IS deterministic, and
    // `try_reserve_exact_refuses_an_impossible_request` below covers it on
    // every host. Two different failures reaching one variant; neither test
    // stands in for the other.
    //
    // Everything downstream of that refusal IS deterministic, and it is where
    // the damage would be done: a host failure reported as `BadParameters`
    // tells the user their manifest is wrong when it may be perfectly legal
    // and decrypt fine on a bigger machine.
    let mapped = crate::decrypt::kdf_error(crate::kdf::KdfError::HostCannotAllocate {
        requested_bytes: 1 << 30,
    });
    assert!(
        matches!(
            mapped,
            DecryptError::HostCannotAllocate {
                site: AllocationSite::KeyDerivation,
                requested_bytes: 1_073_741_824
            }
        ),
        "host capacity must not collapse into BadParameters, got {mapped:?}"
    );

    // And the other arm still lands where it did, so the split is real rather
    // than everything becoming HostCannotAllocate.
    let reason = BadParameter::OutOfRange {
        field: ManifestField::Argon2(crate::Argon2Axis::T),
        got: 0,
        min: 1,
        max: 10,
    };
    let params = crate::decrypt::kdf_error(crate::kdf::KdfError::Params(reason));
    assert!(matches!(params, DecryptError::BadParameters(r) if r == reason));
}

#[test]
fn try_reserve_exact_refuses_an_impossible_request() {
    // Deterministic on every host, and it is the guard firing rather than a
    // proxy for it: `try_reserve_exact` rejects a request whose byte count
    // overflows before it asks the allocator for anything, so no machine is
    // large enough to make this pass by accident. The `#[ignore]`d 1 GiB test
    // covers the other half -- the allocator itself refusing -- and cannot run
    // on a well-provisioned box.
    //
    // What it proves is the property the change is for: an allocation sized
    // from the package RETURNS instead of aborting. A `vec![0u8; n]` here would
    // end the test process, not fail the test.
    for site in [
        AllocationSite::MemberPlaintext,
        AllocationSite::PackagePlaintext,
        AllocationSite::DerivedKey,
        AllocationSite::CipherBuffer,
    ] {
        let got = crate::decrypt::try_zeroed(usize::MAX, site);
        assert!(
            matches!(
                got,
                Err(DecryptError::HostCannotAllocate { site: s, requested_bytes })
                    if s == site && requested_bytes == usize::MAX
            ),
            "{site:?} must return, and must carry its own site, got {got:?}"
        );
    }
}

#[test]
fn a_fallible_allocation_that_succeeds_is_exact_and_filled() {
    // The success path of both helpers, because a guard that only ever returns
    // Err would pass the test above and break every decrypt.
    let zeroed = crate::decrypt::try_zeroed(64, AllocationSite::DerivedKey)
        .expect("64 bytes is not a host-capacity failure");
    assert_eq!(zeroed.len(), 64);
    assert!(zeroed.iter().all(|b| *b == 0));
    // Exact capacity is the half that matters for residue: a buffer with spare
    // capacity would still be correct, but `try_reserve_exact` asking for more
    // than it needs is worth catching here rather than in a heap dump.
    assert_eq!(zeroed.capacity(), 64);
}

#[test]
fn every_allocation_site_renders_distinctly() {
    // The site exists because the message was wrong without it -- the variant's
    // Display said "for key derivation" unconditionally. Two sites sharing a
    // string would put that back for one of them.
    let sites = [
        AllocationSite::KeyDerivation,
        AllocationSite::DerivedKey,
        AllocationSite::MemberPlaintext,
        AllocationSite::PackagePlaintext,
        AllocationSite::CipherBuffer,
    ];
    let mut seen: Vec<String> = sites.iter().map(|s| s.to_string()).collect();
    seen.sort();
    let before = seen.len();
    seen.dedup();
    assert_eq!(seen.len(), before, "two sites render the same: {seen:?}");

    // And the rendered message names the site rather than the KDF.
    let e = DecryptError::HostCannotAllocate {
        site: AllocationSite::MemberPlaintext,
        requested_bytes: 4096,
    };
    assert_eq!(
        e.to_string(),
        "host could not allocate 4096 bytes for a decrypted package member"
    );
}

// --- #48: the rewrite's read error is unreachable, and this keeps it so -----

/// A complete per-entry manifest: one latch row on `content.xml` with a full
/// `encryption-data`, so `parse_manifest` yields a row and `classify` reports
/// [`Mode::PerEntry`].
fn complete_per_entry_manifest() -> String {
    format!(
        r#"<?xml version="1.0" encoding="UTF-8"?>
<manifest:manifest xmlns:manifest="urn:oasis:names:tc:opendocument:xmlns:manifest:1.0" manifest:version="1.2">
 <manifest:file-entry manifest:full-path="/" manifest:version="1.2" manifest:media-type="{mime}"/>
 <manifest:file-entry manifest:full-path="content.xml" manifest:media-type="text/xml" manifest:size="64">
  <manifest:encryption-data manifest:checksum-type="{sha1_1k}" manifest:checksum="{b64}">
   <manifest:algorithm manifest:algorithm-name="{aes}" manifest:initialisation-vector="{b64}"/>
   <manifest:start-key-generation manifest:start-key-generation-name="{sha1}"/>
   <manifest:key-derivation manifest:key-derivation-name="{pbkdf2}" manifest:salt="{b64}" manifest:iteration-count="1024" manifest:key-size="32"/>
  </manifest:encryption-data>
 </manifest:file-entry>
</manifest:manifest>
"#,
        mime = crate::test_support::MIME_TEXT,
        sha1_1k = crate::uris::SHA1_1K_NAME,
        aes = crate::uris::AES256_URL,
        sha1 = crate::uris::SHA1_NAME,
        pbkdf2 = crate::uris::PBKDF2_NAME,
        b64 = crate::test_support::B64,
    )
}

/// **The guard behind [`DecryptError::Zip`]'s "why it is not elided" section.**
///
/// That variant can carry a `quick-xml` error whose payload is an element name
/// taken from the document, unbounded — the same shape `DetectError::Inconsistent`
/// was elided for. It is *not* elided here, on the argument that the path cannot
/// be reached: `parse_manifest` maps any read error to an empty row list,
/// `classify` then reports `Mode::Plain`, and `decrypt` refuses that with
/// `NotEncrypted` before the rewrite runs.
///
/// That argument rests on quick-xml 0.38.4 internals — specifically that
/// `expand_empty_elements`, the only configuration difference between the two
/// readers, cannot change *which* inputs are ill-formed. A dependency bump could
/// falsify it with no diff in this crate at all, which is exactly the kind of
/// claim that should not live only in prose.
///
/// So: mutate a complete manifest every way that is cheap, and assert the
/// implication directly. **Any failure here means the elision is now required.**
#[test]
fn classify_accepting_a_manifest_implies_the_rewrite_accepts_it() {
    let base = complete_per_entry_manifest();

    // The premise. If this stops holding the corpus below is vacuous — every
    // mutation would trivially satisfy an implication whose antecedent is never
    // true — so it is asserted rather than assumed.
    assert!(
        !crate::manifest::parse_manifest(base.as_bytes()).is_empty(),
        "baseline manifest must yield rows, or this test proves nothing"
    );
    assert!(crate::decrypt::strip_manifest(base.as_bytes()).is_ok());

    let injections = [
        "<x/>",
        "</x>",
        "<x>",
        "<a/></a>",
        "<a></a>",
        "<a/><a/>",
        "<!--c-->",
        "<?pi?>",
        "<a/></b>",
        "</a>",
        "<a></b>",
        "&",
        "<![CDATA[]]>",
        "<a/>t",
        "</manifest:manifest>",
        "<manifest:file-entry/>",
        "]]>",
        "<!DOCTYPE m>",
    ];

    let mut candidates: Vec<String> = Vec::new();
    // Truncation at every char boundary: catches unterminated everything.
    for i in 0..base.len() {
        if base.is_char_boundary(i) {
            candidates.push(base[..i].to_string());
        }
    }
    // Injection at every inter-tag boundary, which is where a manifest's
    // structure can actually be perturbed.
    for (i, _) in base.match_indices('>') {
        for inj in injections {
            let mut m = String::with_capacity(base.len() + inj.len());
            m.push_str(&base[..=i]);
            m.push_str(inj);
            m.push_str(&base[i + 1..]);
            candidates.push(m);
        }
    }

    let mut antecedent_true = 0usize;
    let mut strip_refused = 0usize;
    for m in &candidates {
        let rows_exist = !crate::manifest::parse_manifest(m.as_bytes()).is_empty();
        let strip_ok = crate::decrypt::strip_manifest(m.as_bytes()).is_ok();
        if !strip_ok {
            strip_refused += 1;
        }
        if rows_exist {
            antecedent_true += 1;
            assert!(
                strip_ok,
                "REACHABLE: classify accepts this manifest and the rewrite refuses it, \
                 so DecryptError::Zip can carry unbounded document text and must now be \
                 elided (see its rustdoc). Manifest:\n{m}"
            );
        }
    }

    // Coverage, not just a pass: a corpus that never exercised either side of
    // the implication would pass silently and mean nothing.
    assert!(
        antecedent_true > 100,
        "too few mutations kept classify happy ({antecedent_true}); corpus is not exercising the implication"
    );
    assert!(
        strip_refused > 100,
        "too few mutations made the rewrite refuse ({strip_refused}); corpus is not hostile enough"
    );
}

/// `PBKDF2_MAX_ITER` pinned to the value, not read from the constant.
///
/// Reading the constant to build both the accept and the reject case makes a
/// test self-referential: it passes at any value, which is what
/// `the_t_ceiling_still_refuses_the_expensive_direction` was corrected for in
/// the same release. The decision here was specifically 10_000_000 over
/// `1 << 23`, so the number has to be named.
#[test]
fn the_pbkdf2_ceiling_is_nists_figure_not_a_round_exponent() {
    assert_eq!(
        crate::limits::PBKDF2_MAX_ITER,
        10_000_000,
        "NIST SP 800-132 5.2's own example; `1 << 23` = 8_388_608 refused it.          Pinning the exact value also pins that it is above the 600_000          LibreOffice writes -- clippy rejects that as a separate assertion,          because both sides are consts and it is decided at compile time."
    );
}

// --- DecryptLimits: the override, and what the defaults refuse --------------

/// The defaults must not refuse anything LibreOffice writes. If they do, the
/// crate has stopped being able to open real files, which is the only failure
/// mode that matters here.
#[test]
fn the_default_limits_accept_every_real_libreoffice_golden() {
    for name in [
        "lo-wholesome-gcm-argon2.odt",
        "lo-legacy-aes-cbc.odt",
        "aoo-blowfish-pbkdf2.odt",
        "lo-opens-our-encrypt-output.odt",
    ] {
        let pw = if name.contains("nonascii") {
            NONASCII_PASSWORD
        } else {
            PASSWORD
        };
        decrypt(&load_golden(name), pw)
            .unwrap_or_else(|e| panic!("{name}: default limits must open real output: {e}"));
    }
}

/// A cost above the defaults is refused, and the SAME file opens once the
/// caller raises the ceiling. That pairing is the whole point: the refusal is
/// this crate declining, not the file being malformed.
#[test]
fn a_raised_ceiling_opens_what_the_default_refuses() {
    // t = 12 is above the default of 10 and far below anything expensive.
    fn set_argon2_t_to_12(xml: &[u8]) -> Vec<u8> {
        String::from_utf8_lossy(xml)
            .replace(
                "loext:argon2-iterations=\"3\"",
                "loext:argon2-iterations=\"12\"",
            )
            .into_bytes()
    }
    let blob = mutate_zip(
        "lo-wholesome-gcm-argon2.odt",
        None,
        None,
        Some(set_argon2_t_to_12 as Rewrite),
    );

    // The fixture has to still be a complete Argon2 row, or this proves nothing.
    let class = classify(&blob).expect("still classifies");
    assert!(matches!(
        class.encrypted_entries[0].kdf,
        Kdf::Argon2id { t: 12, .. }
    ));

    let err = decrypt(&blob, PASSWORD).expect_err("12 is above the default ceiling of 10");
    assert!(
        matches!(err, DecryptError::BadParameters(_)),
        "a ceiling of ours is BadParameters, got {err:?}"
    );

    // Same bytes, raised ceiling. It will not decrypt -- the password no longer
    // matches a manifest whose t was rewritten -- but it must get PAST the
    // ceiling, which is what WrongPassword proves and BadParameters would not.
    let err = decrypt_with_limits(
        &blob,
        PASSWORD,
        crate::DecryptLimits::default().with_argon2_max_t(16),
    )
    .expect_err("the rewritten manifest cannot actually decrypt");
    assert!(
        matches!(err, DecryptError::WrongPassword),
        "raising the ceiling must let the derivation run, got {err:?}"
    );
}

/// `PERMISSIVE` is not "no limits" -- the cipher and the host still refuse.
#[test]
fn permissive_still_defers_to_the_cipher_and_the_host() {
    let l = crate::DecryptLimits::PERMISSIVE;
    assert_eq!(l.argon2_max_t, i32::MAX as u32);
    assert_eq!(l.argon2_max_m_kib, i32::MAX as u32);

    // argon2's own floor, which no ceiling of ours can waive.
    let salt = [0u8; 16];
    let mut out = [0u8; 32];
    let err = crate::kdf::derive_argon2id(b"probe", &salt, 1, 8, 4, &l, &mut out)
        .expect_err("m = 8 with p = 4 is below argon2's own m >= 8p");
    // Refused by our own check, before `Params::new`, and named as argon2's
    // rule. Falsify: drop the `m < 8p` check in `derive_argon2id`, and argon2's
    // own refusal arrives instead, as `KdfError::Internal`.
    assert!(
        matches!(
            err,
            crate::kdf::KdfError::Params(BadParameter::CipherRejects {
                field: ManifestField::Argon2(crate::Argon2Axis::MKib),
                by: Primitive::Argon2,
                got: 8,
                min: 32,
                ..
            })
        ),
        "{err:?}"
    );
}

/// #105: a salt under argon2's 8-byte floor is refused before the KDF runs,
/// named as argon2's rule. Nothing screened it before, and argon2's own
/// refusal used to be formatted into the message.
///
/// Falsify: drop the salt-length check in `derive_argon2id`; argon2 refuses it
/// itself, which now arrives as `KdfError::Internal`.
#[test]
fn a_salt_under_eight_bytes_is_refused_before_the_kdf() {
    let mut out = [0u8; 32];
    let err = crate::kdf::derive_argon2id(
        b"probe",
        &[0u8; 7],
        1,
        8,
        1,
        &crate::DecryptLimits::default(),
        &mut out,
    )
    .expect_err("a 7-byte salt is below argon2's floor");
    assert!(
        matches!(
            err,
            crate::kdf::KdfError::Params(BadParameter::CipherRejects {
                field: ManifestField::SaltLen,
                by: Primitive::Argon2,
                got: 7,
                min: 8,
                ..
            })
        ),
        "{err:?}"
    );
}

/// #105: the lanes refusal names whose bound was the tighter one: ours (the
/// default 16) under the default limits, argon2's own 0xFFFFFF under
/// `PERMISSIVE`, and a negative value keeps its sign.
///
/// Falsify: always report `OutOfRange` for lanes.
#[test]
fn the_lanes_refusal_names_whose_bound_it_was() {
    let salt = [0u8; 16];
    // `m` within every limit, so the lanes check is the one that answers.
    let derive = |p: i32, l: &crate::DecryptLimits| {
        let mut out = [0u8; 32];
        crate::kdf::derive_argon2id(b"probe", &salt, 1, 1024, p, l, &mut out)
    };
    let ours = derive(17, &crate::DecryptLimits::default());
    assert!(
        matches!(
            ours,
            Err(crate::kdf::KdfError::Params(BadParameter::OutOfRange {
                field: ManifestField::Argon2(crate::Argon2Axis::P),
                got: 17,
                max: 16,
                ..
            }))
        ),
        "{ours:?}"
    );
    let argon2s = derive(0x0100_0000, &crate::DecryptLimits::PERMISSIVE);
    assert!(
        matches!(
            argon2s,
            Err(crate::kdf::KdfError::Params(BadParameter::CipherRejects {
                by: Primitive::Argon2,
                got: 0x0100_0000,
                max: 0x00FF_FFFF,
                ..
            }))
        ),
        "{argon2s:?}"
    );
    let negative = derive(-3, &crate::DecryptLimits::default());
    assert!(
        matches!(
            negative,
            Err(crate::kdf::KdfError::Params(BadParameter::OutOfRange {
                got: -3,
                ..
            }))
        ),
        "{negative:?}"
    );
}

/// #105: a row naming no zip member is reported by its index, and no byte of
/// its `manifest:full-path` reaches the error, its `Display` or its `Debug`.
/// The old message quoted the path with no bound (up to the 8 MiB manifest
/// cap) and the CLI printed it.
///
/// Falsify: give `NoMember` a field holding the path, or format the path into
/// the refusal.
#[test]
fn a_missing_member_is_named_by_index_and_carries_no_path() {
    let hostile = format!("evil-{}-path", "X".repeat(1 << 20));
    let blob = {
        let mut w = ZipWriter::new(Cursor::new(Vec::new()));
        w.start_file("mimetype", SimpleFileOptions::default())
            .unwrap();
        w.write_all(b"application/vnd.oasis.opendocument.text")
            .unwrap();
        w.finish().unwrap().into_inner()
    };
    let mut archive = ZipArchive::new(Cursor::new(blob)).unwrap();
    let err =
        crate::decrypt::member_for_archive(&mut archive, &hostile, crate::decrypt::no_member(3))
            .expect_err("no member has that name");
    assert!(matches!(
        err,
        DecryptError::BadParameters(BadParameter::NoMember { row: 3 })
    ));
    for rendered in [err.to_string(), format!("{err:?}")] {
        assert!(
            !rendered.contains("XXXX"),
            "{}",
            &rendered[..80.min(rendered.len())]
        );
        assert!(!rendered.contains("evil"), "{rendered}");
        assert!(rendered.len() < 200, "{}", rendered.len());
    }
}

/// The defaults are the constants, so raising one in `limits.rs` cannot leave
/// the documented table behind.
#[test]
fn the_defaults_are_the_constants() {
    let d = crate::DecryptLimits::default();
    assert_eq!(d.argon2_max_t, 10);
    assert_eq!(d.argon2_max_m_kib, 1 << 20);
    assert_eq!(d.argon2_max_p, 16);
    assert_eq!(d.pbkdf2_max_iter, 10_000_000);
}

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

/// Every [`DecryptError`] 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 [`DecryptError`] is
/// `#[non_exhaustive]`, so rustc *requires* `decrypt_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::DecryptError` 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
/// `decrypt_exit`, add it to `the_decrypt_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_decrypt_error_variant_is_accounted_for_in_the_cli_exit_map() {
    fn accounted_for(e: &DecryptError) {
        match e {
            DecryptError::Classify(_) => (),
            DecryptError::NotEncrypted => (),
            DecryptError::EmptyPassword => (),
            DecryptError::UnsupportedPgp => (),
            DecryptError::Odf12Fatal => (),
            DecryptError::WrongPassword => (),
            DecryptError::BadParameters(_) => (),
            DecryptError::Internal(_) => (),
            DecryptError::HostCannotAllocate { .. } => (),
            DecryptError::Inflate(_) => (),
            DecryptError::Zip(_) => (),
            DecryptError::OutputLimit { .. } => (),
            DecryptError::Io(_) => (),
        }
    }
    accounted_for(&DecryptError::NotEncrypted);
}

/// The screen in `decrypt_member` must accept and refuse exactly what the cipher
/// does. Anything else is a fidelity change wearing a performance fix's clothes:
/// too strict refuses a package LibreOffice opens, too loose puts the old
/// derive-then-refuse cost straight back.
///
/// Constructs the real ciphers at every length rather than restating their rules.
/// A hand-copied constraint is a proxy for the dependency's actual behaviour, and
/// this repo's recurring defect is a proxy quietly taking the property's name.
#[test]
fn screen_matches_what_the_cipher_accepts() {
    use crate::types::Cipher;
    use aes::{Aes128, Aes192, Aes256};
    use aes_gcm::aead::consts::U12;
    use aes_gcm::{AesGcm, KeyInit};
    use blowfish::Blowfish;
    use cfb_mode::cipher::KeyIvInit;

    for n in 0i32..=80 {
        let k = vec![0u8; n as usize];
        let actual = |c: Cipher| match c {
            // The union of the three arms `decrypt_aes_gcm` dispatches to.
            Cipher::AesGcmW3c => {
                AesGcm::<Aes128, U12>::new_from_slice(&k).is_ok()
                    || AesGcm::<Aes192, U12>::new_from_slice(&k).is_ok()
                    || AesGcm::<Aes256, U12>::new_from_slice(&k).is_ok()
            }
            Cipher::AesCbcW3c => {
                cbc::Decryptor::<Aes128>::new_from_slices(&k, &[0u8; 16]).is_ok()
                    || cbc::Decryptor::<Aes192>::new_from_slices(&k, &[0u8; 16]).is_ok()
                    || cbc::Decryptor::<Aes256>::new_from_slices(&k, &[0u8; 16]).is_ok()
            }
            Cipher::BlowfishCfb8 => {
                cfb_mode::BufDecryptor::<Blowfish>::new_from_slices(&k, &[0u8; 8]).is_ok()
            }
        };
        for c in [Cipher::AesGcmW3c, Cipher::AesCbcW3c, Cipher::BlowfishCfb8] {
            assert_eq!(
                crate::decrypt::cipher_accepts_key_len(c, n),
                actual(c),
                "screen and cipher disagree for {c:?} at key length {n}"
            );
        }
    }
}

/// The screen runs *before* the key derivation, which is the entire fix.
///
/// Proved without a clock. The row carries two faults at once: a `key-size` of 64
/// that no AES variant can take, and an `iteration-count` past
/// `PBKDF2_MAX_ITER`. Each is reported by a different check, and the two checks
/// sit on opposite sides of the KDF -- so **which error comes back says which ran
/// first**. Before this fix the answer was the iteration message, because
/// `derive_key` was reached first; it must now be the key-length one.
///
/// A timing assertion would have been the obvious test and a worse one: it
/// measures the machine as much as the code, and it passes on a slow host for the
/// wrong reason.
#[test]
fn key_length_is_screened_before_the_kdf_runs() {
    let bytes = mutate_zip(
        "lo-legacy-aes-cbc.odt",
        None,
        None,
        Some(|xml: &[u8]| {
            let s = rewrite_kdf_key_size(std::str::from_utf8(xml).unwrap(), "64");
            set_pbkdf2_iterations(s.as_bytes(), "2147483647")
        }),
    );
    let class = classify(&bytes).expect("classify passes both values through");
    assert!(
        class
            .encrypted_entries
            .iter()
            .all(|e| e.derived_key_len == 64),
        "fixture must carry the incompatible key-size"
    );
    match decrypt(&bytes, PASSWORD) {
        Err(DecryptError::BadParameters(BadParameter::KeySizeForCipher { got: 64, .. })) => {}
        other => panic!(
            "expected the key-size refusal, got {other:?} -- an iteration refusal \
             means the KDF was reached first and the screen did not run"
        ),
    }
}

/// Every fault that can be decided from the manifest and the member must live in
/// `screen_before_deriving`, because that is the function proven to run ahead of
/// the KDF by `key_length_is_screened_before_the_kdf_runs`.
///
/// The ordering is established once, there, and inherited by everything inside
/// the screen — so this test does not repeat it six times. What it checks is
/// membership: that each of these is decided *in* the screen rather than by the
/// cipher afterwards, which is where they all sat before #79.
#[test]
fn every_pre_key_fault_is_decided_in_the_screen() {
    use crate::decrypt::screen_before_deriving;
    use crate::types::{Checksum, Cipher, EntryEncryption, StartKeyAlg};

    fn row(cipher: Cipher, iv: Vec<u8>, key_len: i32) -> EntryEncryption {
        EntryEncryption {
            path: "encrypted-package".into(),
            cipher,
            kdf: Kdf::Pbkdf2 {
                iterations: 100_000,
                salt: vec![0u8; 16],
            },
            start_key: StartKeyAlg::Sha256,
            checksum: Checksum::None,
            size: 64,
            iv,
            derived_key_len: key_len,
        }
    }
    let gcm_ok = vec![0u8; 12];
    // A well-formed GCM member: the IV repeated up front, then tag-sized filler.
    let mut body = gcm_ok.clone();
    body.extend_from_slice(&[0u8; 16]);

    // The baseline must pass, or every case below would pass for the wrong reason.
    assert!(screen_before_deriving(&row(Cipher::AesGcmW3c, gcm_ok.clone(), 32), &body).is_ok());

    let iv = |by, got: i64, want: i64| BadParameter::CipherRejects {
        field: ManifestField::IvLen,
        by,
        got,
        min: want,
        max: want,
    };
    let cases: Vec<(BadParameter, EntryEncryption, Vec<u8>)> = vec![
        (
            BadParameter::KeySizeForCipher {
                got: 64,
                cipher: Cipher::AesGcmW3c,
            },
            row(Cipher::AesGcmW3c, gcm_ok.clone(), 64),
            body.clone(),
        ),
        (
            iv(Primitive::AesGcm, 11, 12),
            row(Cipher::AesGcmW3c, vec![0u8; 11], 32),
            body.clone(),
        ),
        (
            BadParameter::Member(MemberFault::ShorterThanIvAndTag),
            row(Cipher::AesGcmW3c, gcm_ok.clone(), 32),
            vec![0u8; 20],
        ),
        (
            BadParameter::Member(MemberFault::IvMismatch),
            row(Cipher::AesGcmW3c, vec![9u8; 12], 32),
            body.clone(),
        ),
        (
            iv(Primitive::AesCbc, 15, 16),
            row(Cipher::AesCbcW3c, vec![0u8; 15], 32),
            vec![0u8; 32],
        ),
        (
            BadParameter::Member(MemberFault::NotBlockMultiple),
            row(Cipher::AesCbcW3c, vec![0u8; 16], 32),
            vec![0u8; 31],
        ),
        (
            iv(Primitive::Blowfish, 7, 8),
            row(Cipher::BlowfishCfb8, vec![0u8; 7], 16),
            vec![0u8; 32],
        ),
    ];
    for (expected, r, blob) in cases {
        match screen_before_deriving(&r, &blob) {
            Err(DecryptError::BadParameters(got)) => assert_eq!(got, expected),
            other => panic!("expected {expected:?} to be screened, got {other:?}"),
        }
    }
}

// --- LibreOffice's legacy SHA-1 read ladder -----------------------------------
//
// Fixtures in `tests/ladder/`: `lo-odf11-nonascii-password.odt` with every
// encrypted member re-encrypted under one start key. Its 52-char password puts
// both encodings inside `rtl_digest_SHA1`'s broken window, so every rung's key
// differs. LibreOffice opens the three rungs and refuses the control
// (`lo_accepts.py`, both orders).

const LADDER_RUNGS: [&str; 3] = [
    "ladder-staroffice-utf8.odt",
    "ladder-forced-sha256.odt",
    "ladder-staroffice-ms1252.odt",
];

#[test]
fn each_ladder_rung_decrypts_to_what_the_golden_does() {
    let want = decrypt(
        &load_golden("lo-odf11-nonascii-password.odt"),
        NONASCII_PASSWORD,
    )
    .expect("golden decrypts");
    for name in LADDER_RUNGS {
        let got = decrypt(&load_ladder_fixture(name), NONASCII_PASSWORD)
            .unwrap_or_else(|e| panic!("{name}: LibreOffice opens this; got {e:?}"));
        assert_eq!(got, want, "{name}");
    }
}

#[test]
fn the_ladder_does_not_rescue_a_wrong_password() {
    for name in LADDER_RUNGS {
        let err = decrypt(&load_ladder_fixture(name), "wrong").unwrap_err();
        assert!(
            matches!(err, DecryptError::WrongPassword),
            "{name}: {err:?}"
        );
    }
}

/// Correct SHA-1 over MS-1252 is not a rung: upstream pairs MS-1252 only with
/// the StarOffice digest. LibreOffice refuses this file, so it must fail here.
#[test]
fn a_key_on_no_rung_is_a_wrong_password() {
    let err = decrypt(
        &load_ladder_fixture("ladder-not-a-rung.odt"),
        NONASCII_PASSWORD,
    )
    .unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword), "{err:?}");
}

/// The ladder runs only for a row whose start key is SHA-1
/// (`ZipPackageStream.cxx:1024-1025`). The StarOffice fixture, relabeled as a
/// SHA-256 row, opens only if the ladder is walked where upstream does not.
#[test]
fn a_sha256_row_does_not_walk_the_ladder() {
    fn declare_sha256(xml: &[u8]) -> Vec<u8> {
        String::from_utf8_lossy(xml)
            .replace(
                "<manifest:key-derivation ",
                "<manifest:start-key-generation                  manifest:start-key-generation-name=\"http://www.w3.org/2000/09/xmldsig#sha256\"                  manifest:key-size=\"32\"/><manifest:key-derivation ",
            )
            .into_bytes()
    }
    let blob = mutate_bytes(
        &load_ladder_fixture("ladder-staroffice-utf8.odt"),
        None,
        None,
        Some(declare_sha256),
    );
    let class = classify(&blob).expect("classifies");
    assert!(class
        .encrypted_entries
        .iter()
        .all(|r| r.start_key == crate::StartKeyAlg::Sha256));
    let err = decrypt(&blob, NONASCII_PASSWORD).unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword), "{err:?}");
}

// --- The unlatched shape: encrypted rows, no latch row ------------------------

/// The decision recorded for EFV in rc.9: `decrypt` keeps decrypting this
/// shape when given the password, which is what LibreOffice does when given
/// it. A GUI user cannot get that far, because LibreOffice never asks.
#[test]
fn an_unlatched_package_decrypts_with_its_password() {
    let pkg = crate::test_support::unlatched_package();
    let class = classify(&pkg).expect("classifies");
    assert_eq!(class.mode, Mode::PerEntry);
    assert!(
        !class.package_encrypted,
        "no row on content.xml, so no latch"
    );
    assert!(
        class.has_non_encrypted_entries,
        "content.xml is a plain stream row"
    );

    let want = decrypt(&load_golden("lo-legacy-aes-cbc.odt"), PASSWORD).unwrap();
    let got = decrypt(&pkg, PASSWORD).expect("decrypts");
    for member in ["content.xml", "styles.xml", "settings.xml", "meta.xml"] {
        assert_eq!(
            read_member(&got, member),
            read_member(&want, member),
            "{member}"
        );
    }
    let err = decrypt(&pkg, "wrong").unwrap_err();
    assert!(matches!(err, DecryptError::WrongPassword), "{err:?}");
}

// --- #87: `DecryptLimits::max_output_bytes` in the whole-buffer path ---------

/// Sum of `manifest:size` over the rows `decrypt` inflates -- the figure the
/// screen compares, computed independently of it.
fn declared_output(bytes: &[u8]) -> u64 {
    let class = classify(bytes).unwrap();
    let rows: Vec<_> = match class.mode {
        Mode::Wholesome => class.wholesome_row().into_iter().collect(),
        _ => class.encrypted_entries.iter().collect(),
    };
    rows.iter().map(|r| u64::try_from(r.size).unwrap()).sum()
}

/// At the limit decrypts; one byte under is refused. Both modes, so neither
/// arm of the screen is untested.
#[test]
fn max_output_bytes_is_inclusive_in_both_modes() {
    for name in ["lo-wholesome-gcm-argon2.odt", "lo-legacy-aes-cbc.odt"] {
        let bytes = load_golden(name);
        let n = declared_output(&bytes);
        assert!(n > 0, "{name}");
        let at = crate::DecryptLimits::default().with_max_output_bytes(n);
        decrypt_with_limits(&bytes, PASSWORD, at).unwrap_or_else(|e| panic!("{name}: {e:?}"));
        let under = at.with_max_output_bytes(n - 1);
        let err = decrypt_with_limits(&bytes, PASSWORD, under).unwrap_err();
        assert!(
            matches!(err, DecryptError::OutputLimit { limit } if limit == n - 1),
            "{name}: {err:?}"
        );
    }
}

/// The screen runs before key derivation: with a wrong password the answer is
/// still `OutputLimit`, which it could not be if a key had been derived and
/// checked first.
#[test]
fn max_output_bytes_is_screened_before_derivation() {
    let bytes = load_golden("lo-legacy-aes-cbc.odt");
    let limits = crate::DecryptLimits::default().with_max_output_bytes(0);
    let err = decrypt_with_limits(&bytes, "not the password", limits).unwrap_err();
    assert!(matches!(err, DecryptError::OutputLimit { .. }), "{err:?}");
}

// --- S8 (#94): the whole-buffer `decrypt` on the streaming core -------------

/// SHA-256 of what rc.9's own `decrypt` returned for every fixture and password
/// it opened, recorded from rc.9's code on 2026-10-15 before that code was
/// replaced by the streaming core. The whole-buffer API is a contract EFV
/// NATIVE builds on: its bytes must not move.
const RC9_DECRYPT_SHA256: &[(&str, &str, &str)] = &[
    (
        "goldens/aoo-blowfish-pbkdf2.odt",
        "PASSWORD",
        "002922efaa0a8cf3ace01b5126f929a1554d4d8241555dd1481a8cf593db71b9",
    ),
    (
        "goldens/lo-legacy-aes-cbc-image.odt",
        "PASSWORD",
        "a73047d500a8679ef56b9ec54c0ab60b56c3f3b9b6b786b8bea3d55db7cf6b41",
    ),
    (
        "goldens/lo-legacy-aes-cbc.odt",
        "PASSWORD",
        "22de9ef3b590d90f40dcaa62b3c60971ee0b296da90d412fef90c48f9326da3c",
    ),
    (
        "goldens/lo-odf11-nonascii-password.odt",
        "NONASCII_PASSWORD",
        "fc5ef0ff39da211eac0ae0ef58f9c52c336a6d8bea99bfd3b5ca9fc7fc9cfe26",
    ),
    (
        "goldens/lo-opens-our-encrypt-output.odt",
        "PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
    (
        "goldens/lo-wholesome-gcm-argon2.odt",
        "PASSWORD",
        "49465b813861a7e53b17f511dd7403db44a3053a0df89a77dd5a19e2aa2681da",
    ),
    (
        "ladder/ladder-forced-sha256.odt",
        "NONASCII_PASSWORD",
        "fc5ef0ff39da211eac0ae0ef58f9c52c336a6d8bea99bfd3b5ca9fc7fc9cfe26",
    ),
    (
        "ladder/ladder-staroffice-ms1252.odt",
        "NONASCII_PASSWORD",
        "fc5ef0ff39da211eac0ae0ef58f9c52c336a6d8bea99bfd3b5ca9fc7fc9cfe26",
    ),
    (
        "ladder/ladder-staroffice-utf8.odt",
        "NONASCII_PASSWORD",
        "fc5ef0ff39da211eac0ae0ef58f9c52c336a6d8bea99bfd3b5ca9fc7fc9cfe26",
    ),
    (
        "artifacts/argon2-1-1024-1.odt",
        "PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
    (
        "artifacts/argon2-above-lo-default.odt",
        "PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
    (
        "artifacts/argon2-floor-1-8-1.odt",
        "PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
    (
        "artifacts/argon2-lanes-only.odt",
        "PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
    (
        "artifacts/wholesome-default.odt",
        "PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
    (
        "artifacts/wholesome-nonascii-password.odt",
        "NONASCII_PASSWORD",
        "7ac5e81e7207b42e0939c50fad59f82da3af4f680c0220c436df5db1199e07b5",
    ),
];

/// The whole-buffer `decrypt` returns rc.9's bytes, byte for byte, on every
/// fixture rc.9 opened -- wholesome and per-entry alike.
#[test]
fn whole_buffer_decrypt_returns_rc9_bytes() {
    use sha2::{Digest as _, Sha256};
    let root = crate::test_support::goldens_dir();
    for (path, pw, want) in RC9_DECRYPT_SHA256 {
        let (dir, name) = path.split_once('/').unwrap();
        let bytes = std::fs::read(root.with_file_name(dir).join(name)).unwrap();
        let pw = if *pw == "PASSWORD" {
            PASSWORD
        } else {
            NONASCII_PASSWORD
        };
        let out = decrypt(&bytes, pw).unwrap_or_else(|e| panic!("{path}: {e:?}"));
        let got: String = Sha256::digest(&out)
            .iter()
            .map(|b| format!("{b:02x}"))
            .collect();
        assert_eq!(&got, want, "{path}");
    }
    assert!(RC9_DECRYPT_SHA256.len() >= 15);
}