File: test_tar.py

package info (click to toggle)
python-securetar 2026.2.0-1
  • links: PTS, VCS
  • area: main
  • in suites: forky, sid
  • size: 21,848 kB
  • sloc: python: 2,639; makefile: 12; sh: 6
file content (1821 lines) | stat: -rw-r--r-- 65,464 bytes parent folder | download
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
"""Test Tarfile functions."""

from collections.abc import Callable, Hashable
from contextlib import AbstractContextManager, nullcontext as does_not_raise
import gzip
import io
import os
import shutil
import tarfile
import time
from dataclasses import dataclass
from pathlib import Path, PurePath
from typing import Any
from unittest.mock import Mock, patch

import nacl
import pytest

from securetar import (
    SECURETAR_MAGIC,
    SECURETAR_V2_HEADER_SIZE,
    SECURETAR_V3_HEADER_SIZE,
    V3_SECRETSTREAM_ABYTES,
    V3_SECRETSTREAM_CHUNK_SIZE,
    AddFileError,
    InnerSecureTarFile,
    InvalidPasswordError,
    SecureTarArchive,
    SecureTarError,
    SecureTarFile,
    SecureTarHeader,
    SecureTarReadError,
    SecureTarRootKeyContext,
    atomic_contents_add,
    secure_path,
)


def get_ciphertext_size_v2(plaintext_size: int) -> int:
    """Get expected ciphertext size for v2."""
    # Padding to next 16 byte block
    padding = 16 - (plaintext_size % 16)
    return plaintext_size + padding + SECURETAR_V2_HEADER_SIZE


def get_ciphertext_size_v3(plaintext_size: int) -> int:
    """Get expected ciphertext size for v3."""
    num_chunks = (
        plaintext_size + V3_SECRETSTREAM_CHUNK_SIZE - 1
    ) // V3_SECRETSTREAM_CHUNK_SIZE
    if num_chunks == 0:
        num_chunks = 1
    return (
        plaintext_size + num_chunks * V3_SECRETSTREAM_ABYTES + SECURETAR_V3_HEADER_SIZE
    )


get_ciphertext_size: dict[int, Callable[[int], int]] = {
    2: get_ciphertext_size_v2,
    3: get_ciphertext_size_v3,
}


@dataclass
class TarInfo:
    """Fake TarInfo."""

    name: str


def test_secure_path() -> None:
    """Test Secure Path."""
    test_list = [
        TarInfo("test.txt"),
        TarInfo("data/xy.blob"),
        TarInfo("bla/blu/ble"),
        TarInfo("data/../xy.blob"),
    ]
    assert test_list == list(secure_path(test_list))


def test_not_secure_path() -> None:
    """Test Not secure path."""
    test_list = [
        TarInfo("/test.txt"),
        TarInfo("data/../../xy.blob"),
        TarInfo("/bla/blu/ble"),
    ]
    assert [] == list(secure_path(test_list))


@pytest.mark.parametrize(
    ("file_filter", "expected_filter_calls", "expected_tar_items"),
    [
        (
            Mock(return_value=False),
            {
                ".",
                "README.md",
                "large_file",
                "test_symlink",
                "test1",
                "test1/script.sh",
            },
            {
                ".",
                "README.md",
                "large_file",
                "test_symlink",
                "test1",
                "test1/script.sh",
            },
        ),
        (
            Mock(return_value=True),
            {"."},
            set(),
        ),
        (
            Mock(wraps=lambda path: path.name == "README.md"),
            {
                ".",
                "README.md",
                "large_file",
                "test_symlink",
                "test1",
                "test1/script.sh",
            },
            {".", "large_file", "test_symlink", "test1", "test1/script.sh"},
        ),
    ],
)
def test_file_filter(
    tmp_path: Path,
    file_filter: Mock,
    expected_filter_calls: set[str],
    expected_tar_items: set[str],
) -> None:
    """Test exclude filter."""
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create Tarfile
    temp_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(temp_tar, "w") as archive:
        with archive.create_tar("core.tar") as inner_tar_file:
            atomic_contents_add(
                inner_tar_file,
                temp_orig,
                file_filter=file_filter,
                arcname=".",
            )
    paths = [call[1][0] for call in file_filter.mock_calls]
    assert len(paths) == len(expected_filter_calls)
    assert set(paths) == {PurePath(path) for path in expected_filter_calls}

    with SecureTarArchive(temp_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as inner_tar_file_obj:
            with tarfile.open(fileobj=inner_tar_file_obj, mode="r") as inner_tar_file:
                members = {tar_info.name for tar_info in inner_tar_file}
    assert members == expected_tar_items


@pytest.mark.parametrize(
    ("target", "attribute", "expected_error"),
    [
        (
            tarfile.TarFile,
            "addfile",
            r"Error adding {temp_orig} to tarfile: Boom! \(OSError\)",
        ),
        (
            tarfile,
            "copyfileobj",
            r"Error adding {temp_orig}/.+ to tarfile: Boom! \(OSError\)",
        ),
        (
            Path,
            "is_dir",
            r"Error adding {temp_orig}/.+ to tarfile: Boom! \(OSError\)",
        ),
        (
            Path,
            "is_symlink",
            r"Error adding {temp_orig}/.+ to tarfile: Boom! \(OSError\)",
        ),
        (
            Path,
            "iterdir",
            r"Error iterating over {temp_orig}: Boom! \(OSError\)",
        ),
    ],
)
def test_create_with_error(
    tmp_path: Path, target: Any, attribute: str, expected_error: str
) -> None:
    """Test error in atomic_contents_add."""
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create Tarfile
    temp_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(temp_tar, "w") as archive:
        with (
            patch.object(target, attribute, side_effect=OSError("Boom!")),
            pytest.raises(
                AddFileError,
                match=expected_error.format(temp_orig=temp_orig),
            ),
            archive.create_tar("core.tar") as inner_tar_file,
        ):
            atomic_contents_add(
                inner_tar_file,
                temp_orig,
                file_filter=lambda _: False,
                arcname=".",
            )


@pytest.mark.parametrize("bufsize", [333, 10240, 4 * 2**20])
@pytest.mark.parametrize("enable_gzip", [True, False])
@pytest.mark.parametrize("version", [2, 3])
def test_create_encrypted_tar_validate(
    tmp_path: Path, bufsize: int, enable_gzip: bool, version: int
) -> None:
    """Test to create a tar file with encryption."""
    password = "hunter2"

    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)
    with open(temp_orig / "randbytes1", "wb") as file:
        file.write(os.urandom(12345))
    with open(temp_orig / "randbytes2", "wb") as file:
        file.write(os.urandom(12345))

    # Create Tarfile
    temp_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(
        temp_tar,
        "w",
        password=password,
        bufsize=bufsize,
        create_version=version,
    ) as archive:
        with archive.create_tar("core.tar", gzip=enable_gzip) as inner_tar_file:
            atomic_contents_add(
                inner_tar_file,
                temp_orig,
                file_filter=lambda _: False,
                arcname=".",
            )

    assert temp_tar.exists()

    # Attempt to validate password with wrong password
    with SecureTarArchive(temp_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as inner_tar_file_obj:
            secure_tar_file = SecureTarFile(
                None,
                bufsize=bufsize,
                fileobj=inner_tar_file_obj,
                password="wrong_password",
                gzip=enable_gzip,
            )
            assert not secure_tar_file.validate_password()

    # Attempt to validate password with correct password
    with SecureTarArchive(temp_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as inner_tar_file_obj:
            secure_tar_file = SecureTarFile(
                None,
                bufsize=bufsize,
                fileobj=inner_tar_file_obj,
                password=password,
                gzip=enable_gzip,
            )
            assert secure_tar_file.validate_password()

    # Attempt to validate with wrong password
    with SecureTarArchive(temp_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as inner_tar_file_obj:
            secure_tar_file = SecureTarFile(
                None,
                bufsize=bufsize,
                fileobj=inner_tar_file_obj,
                password="wrong_password",
                gzip=enable_gzip,
            )
            assert not secure_tar_file.validate()

    # Attempt to validate with correct password
    with SecureTarArchive(temp_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as inner_tar_file_obj:
            secure_tar_file = SecureTarFile(
                None,
                bufsize=bufsize,
                fileobj=inner_tar_file_obj,
                password=password,
                gzip=enable_gzip,
            )
            assert secure_tar_file.validate()


@patch("securetar.time.time", new=Mock(return_value=1765362043.0))
@pytest.mark.parametrize(
    ("derived_key_id", "root_key_context_func", "password", "expect_same_content"),
    [
        (None, lambda: None, "hunter2", False),
        ("inner_file", lambda: SecureTarRootKeyContext("hunter2"), None, True),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_create_encrypted_archive_fixed_nonce(
    tmp_path: Path,
    derived_key_id: Hashable | None,
    root_key_context_func: Callable[[str | None], SecureTarRootKeyContext],
    password: str | None,
    expect_same_content: bool,
    version: int,
) -> None:
    """Test to create an archive with fixed nonce."""
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)
    with open(temp_orig / "randbytes1", "wb") as file:
        file.write(os.urandom(12345))
    with open(temp_orig / "randbytes2", "wb") as file:
        file.write(os.urandom(12345))

    root_key_context = root_key_context_func()

    # Create Archive 1
    temp_tar1 = tmp_path.joinpath("backup1.tar")
    with SecureTarArchive(
        temp_tar1,
        "w",
        create_version=version,
        password=password,
        root_key_context=root_key_context,
    ) as archive:
        with archive.create_tar(
            "core.tar", derived_key_id=derived_key_id
        ) as inner_tar_file:
            atomic_contents_add(
                inner_tar_file,
                temp_orig,
                file_filter=lambda _: False,
                arcname=".",
            )

    # Create Archive 2
    temp_tar2 = tmp_path.joinpath("backup2.tar")
    with SecureTarArchive(
        temp_tar2,
        "w",
        create_version=version,
        password=password,
        root_key_context=root_key_context,
    ) as archive:
        with archive.create_tar(
            "core.tar", derived_key_id=derived_key_id
        ) as inner_tar_file:
            atomic_contents_add(
                inner_tar_file,
                temp_orig,
                file_filter=lambda _: False,
                arcname=".",
            )

    assert expect_same_content == (temp_tar1.read_bytes() == temp_tar2.read_bytes())


@patch("securetar.time.time", new=Mock(return_value=1765362043.0))
@pytest.mark.parametrize(
    ("derived_key_id", "root_key_context_func", "password", "expect_same_content"),
    [
        (None, lambda: None, "hunter2", False),
        ("inner_file", lambda: SecureTarRootKeyContext("hunter2"), None, True),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_encrypt_archive_fixed_nonce(
    tmp_path: Path,
    derived_key_id: Hashable | None,
    root_key_context_func: Callable[[str | None], SecureTarRootKeyContext],
    password: str | None,
    expect_same_content: bool,
    version: int,
) -> None:
    """Test to encrypt a plaintext archive with fixed nonce."""
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)
    with open(temp_orig / "randbytes1", "wb") as file:
        file.write(os.urandom(12345))
    with open(temp_orig / "randbytes2", "wb") as file:
        file.write(os.urandom(12345))

    # Create plaintext archive to encrypt from
    temp_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(
        temp_tar,
        "w",
    ) as archive:
        with archive.create_tar("core.tar") as inner_tar_file:
            atomic_contents_add(
                inner_tar_file,
                temp_orig,
                file_filter=lambda _: False,
                arcname=".",
            )

    root_key_context = root_key_context_func()

    # Create encrypted archive 1
    temp_tar1 = tmp_path.joinpath("backup1.tar")
    with (
        SecureTarArchive(
            temp_tar1,
            "w",
            create_version=version,
            password=password,
            root_key_context=root_key_context,
        ) as encrypted_archive,
        SecureTarArchive(
            temp_tar,
            "r",
        ) as plaintext_archive,
    ):
        for tar_info in plaintext_archive.tar:
            encrypted_archive.import_tar(
                plaintext_archive.tar.extractfile(tar_info),
                tar_info,
                derived_key_id=derived_key_id,
            )

    # Create encrypted archive 2
    temp_tar2 = tmp_path.joinpath("backup2.tar")
    with (
        SecureTarArchive(
            temp_tar2,
            "w",
            create_version=version,
            password=password,
            root_key_context=root_key_context,
        ) as encrypted_archive,
        SecureTarArchive(
            temp_tar,
            "r",
        ) as plaintext_archive,
    ):
        for tar_info in plaintext_archive.tar:
            encrypted_archive.import_tar(
                plaintext_archive.tar.extractfile(tar_info),
                tar_info,
                derived_key_id=derived_key_id,
            )

    assert expect_same_content == (temp_tar1.read_bytes() == temp_tar2.read_bytes())


@pytest.mark.parametrize(
    ("enable_gzip", "inner_tar_files"),
    [
        (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")),
        (False, ("core.tar", "core2.tar", "core3.tar")),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_tar_inside_tar(
    tmp_path: Path, enable_gzip: bool, inner_tar_files: tuple[str, ...], version: int
) -> None:
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create Tarfile
    main_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(
        main_tar, "w", create_version=version
    ) as outer_secure_tar_archive:
        for inner_tar_file in inner_tar_files:
            with outer_secure_tar_archive.create_tar(
                inner_tar_file, gzip=enable_gzip
            ) as inner_tar_file:
                atomic_contents_add(
                    inner_tar_file,
                    temp_orig,
                    file_filter=lambda _: False,
                    arcname=".",
                )

        assert len(outer_secure_tar_archive.tar.getmembers()) == 3

        raw_bytes = b'{"test": "test"}'
        fileobj = io.BytesIO(raw_bytes)
        tar_info = tarfile.TarInfo(name="backup.json")
        tar_info.size = len(raw_bytes)
        tar_info.mtime = time.time()
        outer_secure_tar_archive.tar.addfile(tar_info, fileobj=fileobj)
        assert len(outer_secure_tar_archive.tar.getmembers()) == 4

    assert main_tar.exists()

    # Iterate over the tar file, and check there's no securetar header
    files = set()
    with SecureTarFile(main_tar, gzip=False) as tar_file:
        for tar_info in tar_file:
            inner_tar = tar_file.extractfile(tar_info)
            assert inner_tar.read(len(SECURETAR_MAGIC)) != SECURETAR_MAGIC
            files.add(tar_info.name)
    assert files == {"backup.json", *inner_tar_files}

    # Restore
    temp_new = tmp_path.joinpath("new")
    with SecureTarFile(main_tar, gzip=False) as tar_file:
        tar_file.extractall(path=temp_new)

    assert temp_new.is_dir()
    core_tar = temp_new.joinpath(inner_tar_files[0])
    assert core_tar.is_file()
    if enable_gzip:
        compressed = core_tar.read_bytes()
        uncompressed = gzip.decompress(core_tar.read_bytes())
        assert len(uncompressed) > len(compressed)

    assert temp_new.joinpath(inner_tar_files[1]).is_file()
    assert temp_new.joinpath(inner_tar_files[2]).is_file()
    backup_json = temp_new.joinpath("backup.json")
    assert backup_json.is_file()
    assert backup_json.read_bytes() == raw_bytes

    # Extract inner tars
    for inner_tar_file in inner_tar_files:
        temp_inner_new = tmp_path.joinpath(f"{inner_tar_file}_inner_new")

        with SecureTarFile(
            temp_new.joinpath(inner_tar_file), gzip=enable_gzip
        ) as tar_file:
            tar_file.extractall(path=temp_inner_new, members=tar_file)

        assert temp_inner_new.is_dir()
        assert temp_inner_new.joinpath("test_symlink").is_symlink()
        assert temp_inner_new.joinpath("test1").is_dir()
        assert temp_inner_new.joinpath("test1/script.sh").is_file()

        # 775 is correct for local, but in GitHub action it's 755, both is fine
        assert oct(temp_inner_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [
            "755",
            "775",
        ]
        assert temp_inner_new.joinpath("README.md").is_file()


@pytest.mark.parametrize(
    ("outer_tar_header_format", "expected_result"),
    [
        (
            tarfile.PAX_FORMAT,
            does_not_raise(),
        ),
        (
            tarfile.GNU_FORMAT,
            pytest.raises(ValueError, match="Outer tarfile must be in PAX format"),
        ),
        (
            tarfile.USTAR_FORMAT,
            pytest.raises(ValueError, match="Outer tarfile must be in PAX format"),
        ),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_inner_tar_header_format(
    tmp_path: Path,
    outer_tar_header_format: str,
    expected_result: AbstractContextManager[None],
    version: int,
) -> None:
    """Test inner tar with different outer tar header formats."""
    # Create Tarfile
    main_tar = tmp_path.joinpath("backup.tar")
    with tarfile.TarFile(
        main_tar, "w", format=outer_tar_header_format
    ) as outer_tar_file:
        with expected_result:
            InnerSecureTarFile(
                outer_tar_file,
                bufsize=10240,
                gzip=False,
                name=Path("inner.tar"),
                derived_key_id=None,
                root_key_context=None,
                create_version=version,
            )


@pytest.mark.parametrize("version", [2, 3])
def test_inner_tar_force_pax_header(tmp_path: Path, version: int) -> None:
    """Test inner tar forces PAX header format."""
    # Create Tarfile
    main_tar = tmp_path.joinpath("backup.tar")
    with tarfile.TarFile(main_tar, "w", format=tarfile.PAX_FORMAT) as outer_tar_file:
        inner_tar = InnerSecureTarFile(
            outer_tar_file,
            bufsize=10240,
            gzip=False,
            name=Path("inner.tar"),
            derived_key_id=None,
            root_key_context=None,
            create_version=version,
        )
        with inner_tar as inner_tar_file:
            assert inner_tar_file.format == tarfile.PAX_FORMAT
            assert type(inner_tar._tar_info.mtime) is float


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
@pytest.mark.parametrize(
    ("enable_gzip", "inner_tar_files"),
    [
        (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")),
        (False, ("core.tar", "core2.tar", "core3.tar")),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_tar_inside_tar_encrypt(
    tmp_path: Path,
    bufsize: int,
    enable_gzip: bool,
    inner_tar_files: tuple[str, ...],
    version: int,
) -> None:
    """Test we can make encrypted versions of plaintext tars."""

    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create an archive with plaintext inner tars
    main_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(main_tar, "w") as outer_secure_tar_archive:
        for inner_tar_file in inner_tar_files:
            with outer_secure_tar_archive.create_tar(
                inner_tar_file, gzip=enable_gzip
            ) as inner_tar_file:
                atomic_contents_add(
                    inner_tar_file,
                    temp_orig,
                    file_filter=lambda _: False,
                    arcname=".",
                )

        assert len(outer_secure_tar_archive.tar.getmembers()) == 3

        raw_bytes = b'{"test": "test"}'
        fileobj = io.BytesIO(raw_bytes)
        tar_info = tarfile.TarInfo(name="backup.json")
        tar_info.size = len(raw_bytes)
        tar_info.mtime = time.time()
        outer_secure_tar_archive.tar.addfile(tar_info, fileobj=fileobj)
        assert len(outer_secure_tar_archive.tar.getmembers()) == 4

    assert main_tar.exists()

    # Iterate over the archive, and check there are no securetar headers in
    # the inner tars
    files = set()
    with SecureTarArchive(main_tar, "r") as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            inner_tar = outer_secure_tar_archive.tar.extractfile(tar_info)
            assert inner_tar.read(len(SECURETAR_MAGIC)) != SECURETAR_MAGIC
            files.add(tar_info.name)
    assert files == {"backup.json", *inner_tar_files}

    # Create an archive with encrypted inner tars, streamed from the archive
    # with plaintext inner tars
    password = "hunter2"
    temp_encrypted = tmp_path.joinpath("encrypted")
    main_tar_encrypted = temp_encrypted.joinpath("backup.tar")
    os.makedirs(temp_encrypted, exist_ok=True)
    with (
        SecureTarArchive(
            main_tar_encrypted,
            mode="w",
            password=password,
            bufsize=bufsize,
            create_version=version,
            streaming=True,
        ) as encrypted_archive,
        SecureTarArchive(
            main_tar, "r", bufsize=bufsize, streaming=True
        ) as plain_archive,
    ):
        for tar_info in plain_archive.tar:
            encrypted_archive.import_tar(
                plain_archive.tar.extractfile(tar_info), tar_info
            )

    # Check size of encrypted inner tars
    with (
        SecureTarArchive(
            main_tar_encrypted, mode="r", password=password, bufsize=bufsize
        ) as encrypted_archive,
        SecureTarArchive(main_tar, "r", bufsize=bufsize) as plain_archive,
    ):
        for inner_tar_file in inner_tar_files:
            encrypted_tar_info = encrypted_archive.tar.getmember(inner_tar_file)
            plain_tar_info = plain_archive.tar.getmember(inner_tar_file)
            assert encrypted_tar_info.size == get_ciphertext_size[version](
                plain_tar_info.size
            )

    # Check the encrypted inner tars can be opened
    temp_decrypted = tmp_path.joinpath("decrypted")
    os.makedirs(temp_decrypted, exist_ok=True)
    with (
        SecureTarArchive(main_tar_encrypted, password=password) as encrypted_archive,
        SecureTarArchive(main_tar, "r", bufsize=bufsize) as plain_archive,
    ):
        for inner_tar_file in inner_tar_files:
            encrypted_tar_info = encrypted_archive.tar.getmember(inner_tar_file)
            with encrypted_archive.extract_tar(encrypted_tar_info) as decrypted:
                # Check DecryptReader.plaintext_size is correct
                assert (
                    decrypted.plaintext_size
                    == plain_archive.tar.getmember(inner_tar_file).size
                )
                decrypted_inner_tar_path = temp_decrypted.joinpath(inner_tar_file)
                with open(decrypted_inner_tar_path, "wb") as file:
                    while data := decrypted.read(bufsize):
                        file.write(data)

            # Check decrypted file is valid gzip, this fails if the padding is not
            # handled correctly
            if enable_gzip:
                assert decrypted_inner_tar_path.stat().st_size > 0
                gzip.decompress(decrypted_inner_tar_path.read_bytes())

            # Check the tar file can be opened and iterate over it
            files = set()
            with tarfile.open(decrypted_inner_tar_path, "r") as itf:
                for tar_info in itf:
                    files.add(tar_info.name)
            assert files == {
                ".",
                "README.md",
                "large_file",
                "test1",
                "test1/script.sh",
                "test_symlink",
            }


def test_gzipped_tar_inside_tar_failure(tmp_path: Path) -> None:
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create Tarfile
    main_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(main_tar, "w") as outer_secure_tar_archive:
        # Make the first tar file to ensure that
        # the second tar file can still be created
        with pytest.raises(ValueError, match="Test"):
            with outer_secure_tar_archive.create_tar(
                "failed.tar.gz", gzip=True
            ) as inner_tar_file:
                raise ValueError("Test")

        with pytest.raises(ValueError, match="Test"):
            with outer_secure_tar_archive.create_tar(
                "good.tar.gz", gzip=True
            ) as inner_tar_file:
                atomic_contents_add(
                    inner_tar_file,
                    temp_orig,
                    file_filter=lambda _: False,
                    arcname=".",
                )
                raise ValueError("Test")

        assert len(outer_secure_tar_archive.tar.getmembers()) == 2

    assert main_tar.exists()
    # Restore
    temp_new = tmp_path.joinpath("new")
    with SecureTarFile(main_tar, gzip=False) as tar_file:
        tar_file.extractall(path=temp_new)

    assert temp_new.is_dir()
    assert temp_new.joinpath("good.tar.gz").is_file()

    failed_path = temp_new.joinpath("failed.tar.gz")
    assert failed_path.is_file()

    # Extract inner tar
    temp_inner_new = tmp_path.joinpath("good.tar.gz_inner_new")

    with SecureTarFile(temp_new.joinpath("good.tar.gz"), gzip=True) as tar_file:
        tar_file.extractall(path=temp_inner_new, members=tar_file)

    assert temp_inner_new.is_dir()
    assert temp_inner_new.joinpath("test_symlink").is_symlink()
    assert temp_inner_new.joinpath("test1").is_dir()
    assert temp_inner_new.joinpath("test1/script.sh").is_file()

    # 775 is correct for local, but in GitHub action it's 755, both is fine
    assert oct(temp_inner_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [
        "755",
        "775",
    ]
    assert temp_inner_new.joinpath("README.md").is_file()

    # Extract failed inner tar (should not raise but will be empty)
    temp_inner_new = tmp_path.joinpath("failed.tar.gz_inner_new")

    with SecureTarFile(temp_new.joinpath("failed.tar.gz"), gzip=True) as tar_file:
        tar_file.extractall(path=temp_inner_new, members=tar_file)


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
@pytest.mark.parametrize(
    ("enable_gzip", "inner_tar_files"),
    [
        (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")),
        (False, ("core.tar", "core2.tar", "core3.tar")),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_encrypted_tar_inside_tar(
    tmp_path: Path,
    bufsize: int,
    enable_gzip: bool,
    inner_tar_files: tuple[str, ...],
    version: int,
) -> None:
    password = "hunter2"

    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create an archive with encrypted inner tars
    main_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(
        main_tar, "w", bufsize=bufsize, create_version=version, password=password
    ) as outer_secure_tar_archive:
        for inner_tar_file in inner_tar_files:
            with outer_secure_tar_archive.create_tar(
                inner_tar_file, gzip=enable_gzip
            ) as inner_tar_file:
                atomic_contents_add(
                    inner_tar_file,
                    temp_orig,
                    file_filter=lambda _: False,
                    arcname=".",
                )

        assert len(outer_secure_tar_archive.tar.getmembers()) == 3

    assert main_tar.exists()

    # Iterate over the archive
    file_sizes: dict[str, int] = {}
    with SecureTarArchive(main_tar, "r", bufsize=bufsize) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            inner_tar = outer_secure_tar_archive.tar.extractfile(tar_info)
            assert inner_tar.read(len(SECURETAR_MAGIC)) == SECURETAR_MAGIC
            # Skip version and reserved bytes
            inner_tar.read(7)
            file_sizes[tar_info.name] = int.from_bytes(inner_tar.read(8), "big")
    assert set(file_sizes) == {*inner_tar_files}

    # Attempt to decrypt the inner tars with wrong key
    temp_decrypted = tmp_path.joinpath("decrypted")
    os.makedirs(temp_decrypted, exist_ok=True)
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password="wrong_password", streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            inner_tar_path = temp_decrypted.joinpath(tar_info.name)
            with open(inner_tar_path, "wb") as file:
                # TODO: Check SecureTarReadError message
                with pytest.raises((SecureTarReadError, InvalidPasswordError)):
                    with outer_secure_tar_archive.extract_tar(tar_info) as decrypted:
                        while data := decrypted.read(bufsize):
                            file.write(data)

    # Decrypt the inner tar
    temp_decrypted = tmp_path.joinpath("decrypted")
    os.makedirs(temp_decrypted, exist_ok=True)
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password=password, streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            inner_tar_path = temp_decrypted.joinpath(tar_info.name)
            with open(inner_tar_path, "wb") as file:
                with outer_secure_tar_archive.extract_tar(tar_info) as decrypted:
                    # Check DecryptReader.plaintext_size is correct
                    assert decrypted.plaintext_size == file_sizes[tar_info.name]
                    while data := decrypted.read(bufsize):
                        file.write(data)

            # Check the indicated size is correct
            assert inner_tar_path.stat().st_size == file_sizes[tar_info.name]

            # Check decrypted file is valid gzip, this fails if the padding is not
            # discarded correctly
            if enable_gzip:
                assert inner_tar_path.stat().st_size > 0
                gzip.decompress(inner_tar_path.read_bytes())

            # Check the tar file can be opened and iterate over it
            files = set()
            with tarfile.open(inner_tar_path, "r") as inner_tar_file:
                for tar_info in inner_tar_file:
                    files.add(tar_info.name)
            assert files == {
                ".",
                "README.md",
                "large_file",
                "test1",
                "test1/script.sh",
                "test_symlink",
            }

    # Restore
    temp_new = tmp_path.joinpath("new")
    with SecureTarFile(main_tar, gzip=False, bufsize=bufsize) as tar_file:
        tar_file.extractall(path=temp_new)

    assert temp_new.is_dir()
    for inner_tar_file in inner_tar_files:
        assert temp_new.joinpath(inner_tar_file).is_file()

    # Extract inner encrypted tars
    for inner_tar_file in inner_tar_files:
        temp_inner_new = tmp_path.joinpath(f"{inner_tar_file}_inner_new")

        with SecureTarFile(
            temp_new.joinpath(inner_tar_file),
            password=password,
            gzip=enable_gzip,
            bufsize=bufsize,
        ) as tar_file:
            tar_file.extractall(path=temp_inner_new, members=tar_file)

        assert temp_inner_new.is_dir()
        assert temp_inner_new.joinpath("test_symlink").is_symlink()
        assert temp_inner_new.joinpath("test1").is_dir()
        assert temp_inner_new.joinpath("test1/script.sh").is_file()

        # 775 is correct for local, but in GitHub action it's 755, both is fine
        assert oct(temp_inner_new.joinpath("test1/script.sh").stat().st_mode)[-3:] in [
            "755",
            "775",
        ]
        assert temp_inner_new.joinpath("README.md").is_file()


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
@pytest.mark.parametrize(
    ("enable_gzip", "inner_tar_files"),
    [
        (True, ("core.tar.gz", "core2.tar.gz", "core3.tar.gz")),
        (False, ("core.tar", "core2.tar", "core3.tar")),
    ],
)
@pytest.mark.parametrize("version", [2, 3])
def test_encrypted_tar_inside_tar_validate(
    tmp_path: Path,
    bufsize: int,
    enable_gzip: bool,
    inner_tar_files: tuple[str, ...],
    version: int,
) -> None:
    password = "hunter2"

    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create an archive with encrypted inner tars
    main_tar = tmp_path.joinpath("backup.tar")
    with SecureTarArchive(
        main_tar, "w", bufsize=bufsize, create_version=version, password=password
    ) as outer_secure_tar_archive:
        for inner_tar_file in inner_tar_files:
            with outer_secure_tar_archive.create_tar(
                inner_tar_file, gzip=enable_gzip
            ) as inner_tar_file:
                atomic_contents_add(
                    inner_tar_file,
                    temp_orig,
                    file_filter=lambda _: False,
                    arcname=".",
                )

        assert len(outer_secure_tar_archive.tar.getmembers()) == 3

    assert main_tar.exists()

    # Attempt to validate the inner tars with wrong password
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password="wrong_password", streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert not outer_secure_tar_archive.validate_password(tar_info)

    # Attempt to validate the inner tars with correct password
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password=password, streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert outer_secure_tar_archive.validate_password(tar_info)

    # Attempt to validate the inner tars with wrong password
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password="wrong_password", streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert not outer_secure_tar_archive.validate(tar_info)

    # Attempt to validate the inner tars with correct password
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password=password, streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert outer_secure_tar_archive.validate(tar_info)


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
@pytest.mark.parametrize(
    ("main_tar_file", "password_validation_result"),
    [
        # Files where the beginning of the file is correct, but there's a
        # secretstream error later in the file. We expect password validation
        # to succeed.
        ("backup_no_final_tag.tar", True),
        ("backup_truncated.tar", True),
        # Files where there's a secretstream error already in the first block,
        # we expect password validation to fail.
        ("backup_early_final_tag.tar", False),
        ("backup_empty.tar", False),
    ],
)
def test_encrypted_tar_inside_tar_validate_secretstream_errors(
    bufsize: int,
    main_tar_file: str,
    password_validation_result: bool,
) -> None:
    password = "hunter2"

    fixture_path = Path(__file__).parent.joinpath("fixtures")
    main_tar = fixture_path.joinpath(f"./{main_tar_file}")

    # Attempt to validate the inner tars with wrong password, we always expect
    # this to fail
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password="wrong_password", streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert not outer_secure_tar_archive.validate_password(tar_info)

    # Attempt to validate the inner tars with correct password
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password=password, streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert (
                outer_secure_tar_archive.validate_password(tar_info)
                == password_validation_result
            )

    # Attempt to validate the inner tars with wrong password, we always expect
    # this to fail
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password="wrong_password", streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert not outer_secure_tar_archive.validate(tar_info)

    # Attempt to validate the inner tars with correct password. All the fixtures
    # have some kind of secretstream error, so we expect validation to fail for
    # all of them.
    with SecureTarArchive(
        main_tar, "r", bufsize=bufsize, password=password, streaming=True
    ) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            assert not outer_secure_tar_archive.validate(tar_info)


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
def test_encrypted_gzipped_tar_inside_tar_legacy_format(
    tmp_path: Path, bufsize: int
) -> None:
    password = "not_correct"

    fixture_path = Path(__file__).parent.joinpath("fixtures")
    main_tar = fixture_path.joinpath("./backup_encrypted_gzipped_legacy_format.tar")

    # Iterate over the tar file, and check there's no securetar header
    files: set[str] = set()
    with SecureTarArchive(main_tar, "r", bufsize=bufsize) as outer_secure_tar_archive:
        for tar_info in outer_secure_tar_archive.tar:
            inner_tar = outer_secure_tar_archive.tar.extractfile(tar_info)
            assert inner_tar.read(len(SECURETAR_MAGIC)) != SECURETAR_MAGIC
            files.add(tar_info.name)
    assert files == {
        "core.tar.gz",
        "core2.tar.gz",
        "core3.tar.gz",
    }

    # Decrypt the inner tar
    temp_decrypted = tmp_path.joinpath("decrypted")
    os.makedirs(temp_decrypted, exist_ok=True)
    with (
        # The fixture was created when passing a key directly, so we mock the key
        patch(
            "securetar.KeyDerivationV2._password_to_key",
            return_value=b"0123456789abcdef",
        ),
        SecureTarArchive(
            main_tar, "r", bufsize=bufsize, password=password
        ) as outer_secure_tar_archive,
    ):
        for tar_info in outer_secure_tar_archive.tar:
            inner_tar_path = temp_decrypted.joinpath(tar_info.name)
            with open(inner_tar_path, "wb") as file:
                with outer_secure_tar_archive.extract_tar(tar_info) as decrypted:
                    while data := decrypted.read(bufsize):
                        file.write(data)

            shutil.copy(inner_tar_path, f"./{inner_tar_path.name}.orig")
            # Rewrite the gzip footer
            # Version 1 of SecureTarFile split the gzip footer in two 16-byte parts,
            # combine them back into a single footer.
            with open(inner_tar_path, "r+b") as file:
                file.seek(-4, io.SEEK_END)
                size_bytes = file.read(4)
                file.seek(-20, io.SEEK_END)
                crc = file.read(4)
                file.seek(-36, io.SEEK_END)
                last_block = file.read(16)
                padding = last_block[-1]
                # Note: This is not a full implementation of the padding removal. Version 1
                # did not add any padding if the inner tar size was a multiple of 16. This
                # means a full implementation needs to try to first treat the file as unpadded.
                # If it fails and the tail is in the range 1..15, it may be padded. Remove
                # the padding and try again. If this also fails, the file is corrupted.
                # In this test case, we only handle the case where the padding is 1..15.
                assert 1 <= padding <= 15
                file.seek(-20 - last_block[-1], io.SEEK_END)
                file.write(crc)
                file.write(size_bytes)
                file.truncate()
            shutil.copy(inner_tar_path, f"./{inner_tar_path.name}.fixed")

            # Check decrypted file is valid gzip, this fails if the padding is not
            # discarded correctly
            assert inner_tar_path.stat().st_size > 0
            gzip.decompress(inner_tar_path.read_bytes())

            # Check the tar file can be opened and iterate over it
            files = set()
            with tarfile.open(inner_tar_path, "r:gz") as inner_tar_file:
                for tar_info in inner_tar_file:
                    files.add(tar_info.name)
            assert files == {
                ".",
                "README.md",
                "test1",
                "test1/script.sh",
                "test_symlink",
            }


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
@pytest.mark.parametrize(
    ("archive", "inner_tar", "expected_exception", "expected_message"),
    [
        (
            "backup_early_final_tag.tar",
            "core_early_final_tag.tar.gz",
            SecureTarError,
            "Unexpected final tag in secretstream decryption",
        ),
        (
            "backup_no_final_tag.tar",
            "core_no_final_tag.tar.gz",
            SecureTarError,
            "Missing final tag in secretstream decryption",
        ),
        (
            "backup_empty.tar",
            "core_empty.tar.gz",
            nacl.exceptions.ValueError,
            "Ciphertext is too short",
        ),
        (
            "backup_truncated.tar",
            "core_truncated.tar.gz",
            nacl.exceptions.RuntimeError,
            "Unexpected failure",
        ),
    ],
)
def test_archive_secretstream_errors(
    tmp_path: Path,
    bufsize: int,
    archive: str,
    inner_tar: str,
    expected_exception: type[Exception],
    expected_message: str,
) -> None:
    password = "hunter2"

    fixture_path = Path(__file__).parent.joinpath("fixtures")
    main_tar = fixture_path.joinpath(archive)

    # Attempt decrypting the inner tar
    with (
        SecureTarArchive(
            main_tar, "r", bufsize=bufsize, password=password
        ) as outer_secure_tar_archive,
    ):
        tar_info = outer_secure_tar_archive.tar.getmember(inner_tar)
        with outer_secure_tar_archive.extract_tar(tar_info) as decrypted:
            with pytest.raises(expected_exception, match=expected_message):
                while decrypted.read(bufsize):
                    pass


@pytest.mark.parametrize("bufsize", [33, 333, 10240, 4 * 2**20])
@pytest.mark.parametrize(
    ("tar_name", "expected_exception", "expected_message"),
    [
        (
            "core_early_final_tag.tar.gz",
            SecureTarError,
            "Unexpected final tag in secretstream decryption",
        ),
        (
            "core_no_final_tag.tar.gz",
            SecureTarError,
            "Missing final tag in secretstream decryption",
        ),
        (
            "core_empty.tar.gz",
            nacl.exceptions.ValueError,
            "Ciphertext is too short",
        ),
        (
            "core_truncated.tar.gz",
            nacl.exceptions.RuntimeError,
            "Unexpected failure",
        ),
    ],
)
def test_secretstream_errors(
    tmp_path: Path,
    bufsize: int,
    tar_name: str,
    expected_exception: type[Exception],
    expected_message: str,
) -> None:
    password = "hunter2"

    fixture_path = Path(__file__).parent.joinpath("fixtures")
    tar_path = fixture_path.joinpath(tar_name)

    # Attempt decrypting the inner tar
    temp_decrypted = tmp_path.joinpath("decrypted")
    os.makedirs(temp_decrypted, exist_ok=True)
    with pytest.raises(expected_exception, match=expected_message):
        with SecureTarFile(tar_path, bufsize=bufsize, password=password) as tar:
            for tar_info in tar:
                if not tar_info.size:
                    continue
                with tar.extractfile(tar_info) as file:
                    while file.read(bufsize):
                        pass


def test_outer_tar_open_close(tmp_path: Path) -> None:
    # Prepare test folder
    temp_orig = tmp_path.joinpath("orig")
    fixture_data = Path(__file__).parent.joinpath("fixtures/tar_data")
    shutil.copytree(fixture_data, temp_orig, symlinks=True)

    # Create Tarfile
    main_tar = tmp_path.joinpath("backup.tar")
    outer_secure_tar_archive = SecureTarArchive(main_tar, "w")

    outer_secure_tar_archive.open()
    with outer_secure_tar_archive.create_tar("any.tgz", gzip=True) as tar_file:
        atomic_contents_add(
            tar_file,
            temp_orig,
            file_filter=lambda _: False,
            arcname=".",
        )

    outer_secure_tar_archive.close()

    # Restore
    temp_new = tmp_path.joinpath("new")
    with SecureTarFile(main_tar, gzip=False) as tar_file:
        tar_file.extractall(path=temp_new, members=tar_file)

    assert temp_new.is_dir()
    assert temp_new.joinpath("any.tgz").is_file()


def test_outer_tar_exclusive_mode(tmp_path: Path) -> None:
    # Create Tarfile
    main_tar = tmp_path.joinpath("backup.tar")
    password = "hunter2"
    outer_secure_tar_archive = SecureTarArchive(main_tar, "x", password=password)

    with outer_secure_tar_archive:
        with outer_secure_tar_archive.create_tar("any.tgz", gzip=True):
            pass

    assert main_tar.exists()

    outer_secure_tar_archive = SecureTarArchive(main_tar, "x")
    with pytest.raises(FileExistsError):
        outer_secure_tar_archive.open()


@pytest.mark.parametrize(
    ("params", "expected_exception", "expected_message"),
    [
        (
            {"create_version": 1},
            ValueError,
            "Version must be None when reading a SecureTar file",
        ),
        (
            {"create_version": 1, "mode": "w"},
            ValueError,
            "Unsupported SecureTar version: 1",
        ),
        (
            {"create_version": 4, "mode": "w"},
            ValueError,
            "Unsupported SecureTar version: 4",
        ),
        (
            {"password": "hunter2", "root_key_context": SecureTarRootKeyContext("abc")},
            ValueError,
            "Cannot specify both 'root_key_context' and 'password'",
        ),
        (
            {},
            ValueError,
            "Either name or fileobj must be provided",
        ),
        (
            {"name": "test.tar", "mode": "invalid_mode"},
            ValueError,
            "Mode must be 'x', 'r', or 'w'",
        ),
    ],
)
def test_securetararchive_error_handling(
    params: dict[str, Any],
    expected_exception: type[Exception],
    expected_message: str,
) -> None:
    """Test SecureTarArchive constructor error handling."""
    with pytest.raises(expected_exception, match=expected_message):
        SecureTarArchive(**params)


def test_securetararchive_tar_before_open() -> None:
    """Test SecureTarArchive.tar access before open."""
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="r")
    with pytest.raises(SecureTarError, match="Archive not open"):
        secure_tar_archive.tar


def test_securetararchive_create_inner_tar_before_open() -> None:
    """Test SecureTarArchive.create_tar call before open."""
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with pytest.raises(SecureTarError, match="Archive not open"):
        secure_tar_archive.create_tar("any.tgz")


def test_securetararchive_create_inner_tar_read_mode() -> None:
    """Test SecureTarArchive.create_tar in read mode."""
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with secure_tar_archive:
        pass
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="r")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="Archive not open for writing"):
            secure_tar_archive.create_tar("any.tgz")


def test_securetararchive_create_inner_tar_streaming(tmp_path: Path) -> None:
    """Test SecureTarArchive.create_tar in streaming mode."""
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w", streaming=True)
    with secure_tar_archive:
        with pytest.raises(
            SecureTarError, match="create_tar not supported in streaming mode"
        ):
            secure_tar_archive.create_tar("any.tgz")


def test_securetararchive_create_inner_tar_derived_key_unencrypted(
    tmp_path: Path,
) -> None:
    """Test SecureTarArchive.create_tar specify derived key without encryption."""
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w")
    with secure_tar_archive:
        with pytest.raises(
            ValueError,
            match="Cannot specify 'derived_key_id' when encryption is disabled",
        ):
            secure_tar_archive.create_tar("any.tgz", derived_key_id="123")


def test_securetararchive_extract_inner_tar_before_open() -> None:
    """Test SecureTarArchive.extract_tar call before open."""
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with pytest.raises(SecureTarError, match="Archive not open"):
        secure_tar_archive.extract_tar(tarfile.TarInfo("blah"))


def test_securetararchive_extract_inner_tar_write_mode() -> None:
    """Test SecureTarArchive.extract_tar in write mode."""
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="Archive not open for reading"):
            secure_tar_archive.extract_tar(tarfile.TarInfo("blah"))


def test_securetararchive_extract_inner_tar_unencrypted(tmp_path: Path) -> None:
    """Test SecureTarArchive.extract_tar without encryption."""
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w")
    with secure_tar_archive:
        pass
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="r")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="No password provided"):
            secure_tar_archive.extract_tar(tarfile.TarInfo("blah"))


def test_securetararchive_extract_non_regular_inner_tar(tmp_path: Path) -> None:
    """Test SecureTarArchive.extract_tar with unknown inner tar."""
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w", password="hunter2")
    tarinfo = tarfile.TarInfo("blah")
    tarinfo.type = tarfile.DIRTYPE
    with secure_tar_archive:
        secure_tar_archive.tar.addfile(tarinfo)
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="r", password="hunter2")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="Cannot extract blah"):
            secure_tar_archive.extract_tar(tarinfo)


def test_securetararchive_import_tar_before_open() -> None:
    """Test SecureTarArchive.import_tar call before open."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with pytest.raises(SecureTarError, match="Archive not open"):
        secure_tar_archive.import_tar(Mock(), tarinfo)


def test_securetararchive_import_tar_read_mode() -> None:
    """Test SecureTarArchive.import_tar in read mode."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with secure_tar_archive:
        pass
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="r")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="Archive not open for writing"):
            secure_tar_archive.import_tar(Mock(), tarinfo)


def test_securetararchive_import_tar_unencrypted(tmp_path: Path) -> None:
    """Test SecureTarArchive.import_tar specify derived key without encryption."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="No password provided"):
            secure_tar_archive.import_tar(Mock(), tarinfo)


def test_securetararchive_validate_password_before_open() -> None:
    """Test SecureTarArchive.validate_password call before open."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with pytest.raises(SecureTarError, match="Archive not open"):
        secure_tar_archive.validate_password(tarinfo)


def test_securetararchive_validate_password_write_mode() -> None:
    """Test SecureTarArchive.validate_password in write mode."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="Archive not open for reading"):
            secure_tar_archive.validate_password(tarinfo)


def test_securetararchive_validate_password_unencrypted(tmp_path: Path) -> None:
    """Test SecureTarArchive.validate_password specify derived key without encryption."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w")
    with secure_tar_archive:
        pass
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="r")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="No password provided"):
            secure_tar_archive.validate_password(tarinfo)


def test_securetararchive_validate_before_open() -> None:
    """Test SecureTarArchive.validate call before open."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with pytest.raises(SecureTarError, match="Archive not open"):
        secure_tar_archive.validate(tarinfo)


def test_securetararchive_validate_write_mode() -> None:
    """Test SecureTarArchive.validate in write mode."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    secure_tar_archive = SecureTarArchive(name=Path("test.tar"), mode="w")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="Archive not open for reading"):
            secure_tar_archive.validate(tarinfo)


def test_securetararchive_validate_unencrypted(tmp_path: Path) -> None:
    """Test SecureTarArchive.validate specify derived key without encryption."""
    tarinfo = tarfile.TarInfo("any.tgz")
    tarinfo.size = 1234
    main_tar = tmp_path.joinpath("test.tar")
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="w")
    with secure_tar_archive:
        pass
    secure_tar_archive = SecureTarArchive(name=main_tar, mode="r")
    with secure_tar_archive:
        with pytest.raises(SecureTarError, match="No password provided"):
            secure_tar_archive.validate(tarinfo)


@pytest.mark.parametrize(
    ("params", "expected_exception", "expected_message"),
    [
        (
            {"create_version": 1},
            ValueError,
            "Version must be None when reading a SecureTar file",
        ),
        (
            {"derived_key_id": "123"},
            ValueError,
            "Cannot specify 'derived_key_id' without 'root_key_context'",
        ),
        (
            {"password": "hunter2", "root_key_context": SecureTarRootKeyContext("abc")},
            ValueError,
            "Cannot specify both 'root_key_context' and 'password'",
        ),
        (
            {},
            ValueError,
            "Either filename or fileobj must be provided",
        ),
    ],
)
def test_securetarfile_error_handling(
    params: dict[str, Any],
    expected_exception: type[Exception],
    expected_message: str,
) -> None:
    """Test SecureTarFile constructor error handling."""
    with pytest.raises(expected_exception, match=expected_message):
        SecureTarFile(**params)


@pytest.mark.parametrize(
    ("params", "expected_exception", "expected_message"),
    [
        (
            {"create_version": 1},
            ValueError,
            "Unsupported SecureTar version: 1",
        ),
        (
            {"create_version": 4},
            ValueError,
            "Unsupported SecureTar version: 4",
        ),
    ],
)
def test_innersecuretarfile_error_handling(
    params: dict[str, Any],
    expected_exception: type[Exception],
    expected_message: str,
) -> None:
    """Test SecureTarFile constructor error handling."""
    with pytest.raises(expected_exception, match=expected_message):
        InnerSecureTarFile(
            outer_tar=Mock(),
            name=Mock(),
            bufsize=1024,
            derived_key_id=None,
            gzip=False,
            root_key_context=None,
            **params,
        )


@pytest.mark.parametrize(
    ("params", "expected_result"),
    [
        # Writing to a file path is supported for non encrypted InnerSecureTarFile
        (
            {"root_key_context": None},
            does_not_raise(),
        ),
        # Writing to a file path is not supported for encrypted InnerSecureTarFile
        (
            {"root_key_context": Mock()},
            pytest.raises(
                NotImplementedError,
                match="Writing SecureTarFile to a file path is not supported",
            ),
        ),
    ],
)
def test_innersecuretarfile_open_error_handling(
    params: dict[str, Any],
    expected_result: AbstractContextManager[None],
) -> None:
    """Test SecureTarFile.open error handling."""
    outer_tar = Mock()
    outer_tar.fileobj = None
    outer_tar.format = tarfile.PAX_FORMAT
    istf = InnerSecureTarFile(
        outer_tar=outer_tar,
        name=Mock(),
        bufsize=1024,
        create_version=2,
        derived_key_id=None,
        gzip=False,
        **params,
    )
    with expected_result:
        istf.open()


def test_securetarfile_validate_password_unencrypted(tmp_path: Path) -> None:
    """Test SecureTarFile.validate_password specify derived key without encryption."""
    main_tar = tmp_path.joinpath("test.tar")
    with SecureTarArchive(main_tar, "w") as archive:
        with archive.create_tar("core.tar"):
            pass
    with SecureTarArchive(main_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as fileobj:
            secure_tar_file = SecureTarFile(fileobj=fileobj)
            with pytest.raises(SecureTarError, match="File is not encrypted"):
                secure_tar_file.validate_password()


def test_securetarfile_validate_password_write_mode(tmp_path: Path) -> None:
    """Test SecureTarFile.validate_password in write mode."""
    main_tar = tmp_path.joinpath("test.tar")
    with SecureTarArchive(main_tar, "w", password="hunter2") as archive:
        inner_tar = archive.create_tar("core.tar")
        with pytest.raises(
            SecureTarError, match="Can only validate password in read mode"
        ):
            inner_tar.validate_password()


def test_securetarfile_validate_password_after_open(tmp_path: Path) -> None:
    """Test SecureTarFile.validate_password call after open."""
    main_tar = tmp_path.joinpath("test.tar")
    with SecureTarArchive(main_tar, "w", password="hunter2") as archive:
        with archive.create_tar("core.tar"):
            pass
    with SecureTarArchive(main_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as fileobj:
            secure_tar_file = SecureTarFile(fileobj=fileobj, password="hunter2")
            with secure_tar_file:
                with pytest.raises(SecureTarError, match="File is already open"):
                    secure_tar_file.validate_password()


def test_securetarfile_validate_unencrypted(tmp_path: Path) -> None:
    """Test SecureTarFile.validate specify derived key without encryption."""
    main_tar = tmp_path.joinpath("test.tar")
    with SecureTarArchive(main_tar, "w") as archive:
        with archive.create_tar("core.tar"):
            pass
    with SecureTarArchive(main_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as fileobj:
            secure_tar_file = SecureTarFile(fileobj=fileobj)
            with pytest.raises(SecureTarError, match="File is not encrypted"):
                secure_tar_file.validate()


def test_securetarfile_validate_write_mode(tmp_path: Path) -> None:
    """Test SecureTarFile.validate in write mode."""
    main_tar = tmp_path.joinpath("test.tar")
    with SecureTarArchive(main_tar, "w", password="hunter2") as archive:
        inner_tar = archive.create_tar("core.tar")
        with pytest.raises(
            SecureTarError, match="Can only validate password in read mode"
        ):
            inner_tar.validate()


def test_securetarfile_validate_after_open(tmp_path: Path) -> None:
    """Test SecureTarFile.validate call after open."""
    main_tar = tmp_path.joinpath("test.tar")
    with SecureTarArchive(main_tar, "w", password="hunter2") as archive:
        with archive.create_tar("core.tar"):
            pass
    with SecureTarArchive(main_tar, "r") as archive:
        with archive.tar.extractfile("core.tar") as fileobj:
            secure_tar_file = SecureTarFile(fileobj=fileobj, password="hunter2")
            with secure_tar_file:
                with pytest.raises(SecureTarError, match="File is already open"):
                    secure_tar_file.validate()


def test_securetarfile_path_fileobj() -> None:
    """Test SecureTarFile.path property when fileobj is used."""
    secure_tar_file = SecureTarFile(fileobj=io.BytesIO())
    assert secure_tar_file.path is None


def test_securetarfile_path_name() -> None:
    """Test SecureTarFile.path property when name is used."""
    secure_tar_file = SecureTarFile(name=Path("test.tar"))
    assert secure_tar_file.path == Path("test.tar")


def test_securetarfile_size_fileobj() -> None:
    """Test SecureTarFile.size property when fileobj is used."""
    secure_tar_file = SecureTarFile(fileobj=io.BytesIO())
    assert secure_tar_file.size == 0


def test_securetarfile_size_name() -> None:
    """Test SecureTarFile.size property when name is used."""
    secure_tar_file = SecureTarFile(name=Path("test.tar"))
    assert secure_tar_file.size == 0.01


def test_securetarfile_v1_fallback() -> None:
    """Test SecureTarFile with invalid magic."""
    header_data = b"invalid magicabc"
    header = SecureTarHeader.from_bytes(io.BytesIO(header_data))
    assert header.version == 1
    assert header.cipher_initialization == header_data


@pytest.mark.parametrize(
    ("header", "expected_exception", "expected_message"),
    [
        (
            b"SecureTar\x01\x00\x00\x00\x00\x00\x00",
            ValueError,
            "Unsupported SecureTar version: 1",
        ),
        (
            b"SecureTar\x04\x00\x00\x00\x00\x00\x00",
            ValueError,
            "Unsupported SecureTar version: 4",
        ),
        (
            b"SecureTar\x02\x00\x00\x00\x00\x00\x01",
            ValueError,
            "Invalid reserved bytes in SecureTar header",
        ),
    ],
)
def test_securetarfile_invalid_magic(
    header, expected_exception, expected_message
) -> None:
    """Test SecureTarFile with invalid magic."""
    with pytest.raises(expected_exception, match=expected_message):
        SecureTarHeader.from_bytes(io.BytesIO(header))