inklog 0.3.0-rc.4

Enterprise-grade Rust logging infrastructure
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
// Copyright (c) 2026 Kirky.X
// SPDX-License-Identifier: MIT
use aes_gcm::Aes256Gcm;
use aes_gcm::aead::{Aead, KeyInit};
use anyhow::{Context, Result, anyhow};
#[cfg(test)]
use base64::{Engine as _, engine::general_purpose};
#[cfg(test)]
use inklog::sink::encryption::derive_key_from_password;
#[cfg(test)]
use sha2::Digest as Sha256Digest;
#[cfg(test)]
use sha2::Sha256;
#[cfg(test)]
use std::fs::File;
use std::io::{Read, Write};
use std::path::{Path, PathBuf};
use zeroize::Zeroizing;

/// 检查路径中是否包含可疑字符或遍历模式(共享逻辑)
fn check_path_syntax(path: &Path) -> Result<()> {
    let path_str = path.to_string_lossy();
    let suspicious_chars = ['~', '\0', '\u{2024}', '\u{2025}', '\u{FE52}'];
    for c in path_str.chars() {
        if suspicious_chars.contains(&c) {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", path.display().to_string());
            return Err(anyhow!(
                "{}",
                inklog::i18n::tr_args("cli-decrypt-err-path-char", args)
            ));
        }
    }
    let path_str_lower = path_str.to_lowercase();
    if path_str_lower.contains("..") || path_str_lower.contains("~/") {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", path.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-traversal", args)
        ));
    }
    Ok(())
}

/// 验证文件路径是否在允许的目录内,防止路径遍历攻击。
/// 要求路径已存在(用于输入路径验证)。
fn validate_file_path(file_path: &Path, base_dir: &Path) -> Result<()> {
    check_path_syntax(file_path)?;

    // 检查符号链接 — 必须在 canonicalize 之前执行,防止 TOCTOU 竞态
    if let Ok(metadata) = file_path.symlink_metadata()
        && metadata.file_type().is_symlink()
    {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", file_path.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-symlink", args)
        ));
    }

    // 规范化路径
    let canonical_path = file_path.canonicalize().map_err(|e| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("err", e.to_string());
        anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-canonical", args)
        )
    })?;

    let canonical_base = base_dir.canonicalize().map_err(|e| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("err", e.to_string());
        anyhow!("{}", inklog::i18n::tr_args("cli-decrypt-err-base", args))
    })?;

    if !canonical_path.starts_with(&canonical_base) {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", file_path.display().to_string());
        args.set("base", base_dir.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-traversal-detail", args)
        ));
    }

    Ok(())
}

/// 验证输出路径安全性(不要求路径已存在)。
/// 通过验证父目录的 canonicalize 结果来确保输出在 base_dir 内。
fn validate_output_path(output_path: &Path, base_dir: &Path) -> Result<()> {
    check_path_syntax(output_path)?;

    // 检查输出路径本身是否为符号链接 — 防止符号链接绕过
    if let Ok(metadata) = output_path.symlink_metadata()
        && metadata.file_type().is_symlink()
    {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_path.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-output-symlink", args)
        ));
    }

    // 验证文件名部分不含路径遍历
    if let Some(file_name) = output_path.file_name() {
        let name_str = file_name.to_string_lossy();
        if name_str.contains('\0') || name_str.contains('/') || name_str.contains('\\') {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", output_path.display().to_string());
            return Err(anyhow!(
                "{}",
                inklog::i18n::tr_args("cli-decrypt-err-output-name", args)
            ));
        }
    }

    // 验证父目录:canonicalize 父目录(应已存在)并检查前缀
    let parent = output_path
        .parent()
        .ok_or_else(|| anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-no-parent")))?;

    let canonical_parent = parent.canonicalize().map_err(|e| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", parent.display().to_string());
        args.set("err", e.to_string());
        anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-canonical-parent", args)
        )
    })?;

    let canonical_base = base_dir.canonicalize().map_err(|e| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", base_dir.display().to_string());
        args.set("err", e.to_string());
        anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-canonical-base", args)
        )
    })?;

    if !canonical_parent.starts_with(&canonical_base) {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_path.display().to_string());
        args.set("base", base_dir.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-traversal-output", args)
        ));
    }

    Ok(())
}

/// 验证 glob 模式是否安全
fn validate_glob_pattern(pattern: &str) -> Result<()> {
    // 检查绝对路径
    if pattern.starts_with('/') || pattern.starts_with('\\') {
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr("cli-decrypt-err-glob-absolute")
        ));
    }

    // 检查路径遍历
    if pattern.contains("..") || pattern.contains("~") {
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr("cli-decrypt-err-glob-traversal")
        ));
    }

    // 检查可疑字符(包括 Unicode 变体)
    let suspicious_chars = ['\0', '\u{2024}', '\u{2025}', '\u{FE52}'];
    for c in pattern.chars() {
        if suspicious_chars.contains(&c) {
            return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-glob-char")));
        }
    }

    // 尝试解析为路径,确保不包含危险元素
    let path = Path::new(pattern);
    if path.is_absolute() {
        return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-glob-abs")));
    }

    // 检查组件
    for component in path.components() {
        match component {
            std::path::Component::ParentDir => {
                return Err(anyhow!(
                    "{}",
                    inklog::i18n::tr("cli-decrypt-err-glob-parent")
                ));
            }
            std::path::Component::Prefix(_) => {
                return Err(anyhow!(
                    "{}",
                    inklog::i18n::tr("cli-decrypt-err-glob-prefix")
                ));
            }
            std::path::Component::RootDir => {
                return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-glob-root")));
            }
            _ => {}
        }
    }

    Ok(())
}

const MAGIC_HEADER: &[u8] = b"ENCLOG1\0";

/// Decrypt a single encrypted file (legacy format).
///
/// Supports the original header-less encryption format.
#[cfg(test)]
pub fn decrypt_file(input_path: &PathBuf, output_path: &PathBuf, key_env: &str) -> Result<()> {
    let mut file = File::open(input_path).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", input_path.display().to_string());
        inklog::i18n::tr_args("config-open_input_failed", args)
    })?;

    let mut header = [0u8; 24];
    file.read_exact(&mut header)
        .with_context(|| inklog::i18n::tr("config-read_header_failed"))?;

    if &header[..8] != MAGIC_HEADER {
        return Err(anyhow!("{}", inklog::i18n::tr("config-invalid_header")));
    }

    let version = u16::from_le_bytes([header[8], header[9]]);
    if version != 1 {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("version", version.to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("config-unsupported_version", args)
        ));
    }

    let algo = u16::from_le_bytes([header[10], header[11]]);
    if algo != 1 {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("algo", algo.to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("config-unsupported_algorithm", args)
        ));
    }

    let key = get_encryption_key_cli(key_env).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("env", key_env);
        inklog::i18n::tr_args("config-get_key_failed", args)
    })?;

    let nonce_arr: [u8; 12] = header[12..24]
        .try_into()
        .expect("nonce slice must be 12 bytes");
    let nonce = aes_gcm::Nonce::from(nonce_arr);

    let mut ciphertext = Vec::new();
    file.read_to_end(&mut ciphertext)
        .with_context(|| inklog::i18n::tr("config-read_ciphertext_failed"))?;

    let cipher = Aes256Gcm::new((&*key).into());

    let plaintext = cipher.decrypt(&nonce, ciphertext.as_ref()).map_err(|e| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("err", e.to_string());
        anyhow!(
            "{}",
            inklog::i18n::tr_args("config-decryption_failed", args)
        )
    })?;

    let mut output_file = File::create(output_path).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_path.display().to_string());
        inklog::i18n::tr_args("config-create_output_failed", args)
    })?;

    output_file
        .write_all(&plaintext)
        .with_context(|| inklog::i18n::tr("config-write_decrypted_failed"))?;

    Ok(())
}

pub fn decrypt_file_compatible(input_path: &Path, output_path: &Path, key_env: &str) -> Result<()> {
    // O_NOFOLLOW 打开:关闭校验后输入路径被替换为符号链接的竞态
    let mut file = inklog::open_validated_file(input_path).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", input_path.display().to_string());
        inklog::i18n::tr_args("cli-decrypt-err-open", args)
    })?;

    // v2 头最大 40 字节:magic(8) + version(2) + algo(2) + salt(16) + nonce(12)
    let mut header = [0u8; 40];
    let read_count = file
        .read(&mut header)
        .with_context(|| inklog::i18n::tr("cli-decrypt-err-read-header"))?;

    if read_count < 10 {
        return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-small")));
    }

    if &header[..8] != MAGIC_HEADER {
        return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-header")));
    }

    let version = u16::from_le_bytes([header[8], header[9]]);

    // 注:初次 read 一次最多读入 40 字节;对 v1/legacy(头 < 40 字节)格式,
    // 超出头的部分属于密文,须回填,否则密文被静默截断。
    let plaintext = match version {
        1 => {
            // v1 头未存储 PBKDF2 盐:若密钥环境变量是普通密码(派生路径),
            // 加密时使用的随机盐已不可恢复,任何尝试都必然失败。
            // 提前给出明确诊断,而非误导性的 "decryption failed"。
            if inklog::sink::encryption::env_key_is_password(key_env) {
                return Err(anyhow!(
                    "v1 encrypted files written with a password-derived key are \
                     unrecoverable: the v1 header does not store the PBKDF2 salt, so \
                     the original key cannot be re-derived (fixed in v2). Re-encrypt \
                     the source with the current inklog version, or supply the \
                     original raw/Base64 32-byte key."
                ));
            }
            let key = get_encryption_key_cli(key_env).with_context(|| {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("env", key_env.to_string());
                inklog::i18n::tr_args("cli-decrypt-err-key", args)
            })?;
            let algo = u16::from_le_bytes([header[10], header[11]]);
            if algo == 1 {
                if read_count < 24 {
                    return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-small-v1")));
                }
                let nonce_slice: [u8; 12] = header[12..24].try_into().unwrap();
                let nonce = aes_gcm::Nonce::from(nonce_slice);

                let mut ciphertext = Vec::new();
                ciphertext.extend_from_slice(&header[24..read_count]);
                file.read_to_end(&mut ciphertext)
                    .with_context(|| inklog::i18n::tr("cli-decrypt-err-read-cipher"))?;

                let cipher = Aes256Gcm::new((&*key).into());
                cipher.decrypt(&nonce, ciphertext.as_ref()).map_err(|e| {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("err", e.to_string());
                    anyhow!("{}", inklog::i18n::tr_args("cli-decrypt-err-decrypt", args))
                })?
            } else {
                // Assume Legacy format (MAGIC + VER + NONCE + CIPHERTEXT)
                // Legacy header is 22 bytes (8 MAGIC + 2 VER + 12 NONCE)
                if read_count < 22 {
                    return Err(anyhow!("{}", inklog::i18n::tr("cli-decrypt-err-small")));
                }

                let mut nonce_bytes = [0u8; 12];
                nonce_bytes.copy_from_slice(&header[10..22]);
                let nonce = aes_gcm::Nonce::from(nonce_bytes);

                let mut ciphertext = Vec::new();
                // If we read more than 22 bytes, the extras are part of the ciphertext
                ciphertext.extend_from_slice(&header[22..read_count]);
                file.read_to_end(&mut ciphertext)
                    .with_context(|| inklog::i18n::tr("cli-decrypt-err-read-cipher"))?;

                let cipher = Aes256Gcm::new((&*key).into());
                cipher.decrypt(&nonce, ciphertext.as_ref()).map_err(|e| {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("err", e.to_string());
                    anyhow!("{}", inklog::i18n::tr_args("cli-decrypt-err-decrypt", args))
                })?
            }
        }
        2 => {
            // v2 头:magic(8) + version(2) + algo(2) + salt(16) + nonce(12) = 40 字节。
            // 盐随头存储,密码模式密钥可确定性重导出。
            if read_count < 40 {
                return Err(anyhow!(
                    "truncated v2 header: expected 40 bytes (including the 16-byte PBKDF2 salt), got {read_count}"
                ));
            }
            let header_salt: [u8; 16] = header[12..28].try_into().unwrap();
            let key =
                get_encryption_key_with_salt_cli(key_env, &header_salt).with_context(|| {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("env", key_env.to_string());
                    inklog::i18n::tr_args("cli-decrypt-err-key", args)
                })?;

            let nonce_slice: [u8; 12] = header[28..40].try_into().unwrap();
            let nonce = aes_gcm::Nonce::from(nonce_slice);

            let mut ciphertext = Vec::new();
            file.read_to_end(&mut ciphertext)
                .with_context(|| inklog::i18n::tr("cli-decrypt-err-read-cipher"))?;

            let cipher = Aes256Gcm::new((&*key).into());
            cipher.decrypt(&nonce, ciphertext.as_ref()).map_err(|e| {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("err", e.to_string());
                anyhow!("{}", inklog::i18n::tr_args("cli-decrypt-err-decrypt", args))
            })?
        }
        other => {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("version", other.to_string());
            return Err(anyhow!(
                "{}",
                inklog::i18n::tr_args("cli-decrypt-err-version", args)
            ));
        }
    };

    // O_NOFOLLOW 创建:关闭校验后输出路径被替换为符号链接的竞态
    let mut output_file = inklog::create_validated_file(output_path).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_path.display().to_string());
        inklog::i18n::tr_args("cli-decrypt-err-create", args)
    })?;

    output_file
        .write_all(&plaintext)
        .with_context(|| inklog::i18n::tr("cli-decrypt-err-write"))?;

    Ok(())
}

fn get_encryption_key_cli(env_var: &str) -> Result<Zeroizing<[u8; 32]>> {
    inklog::sink::encryption::get_encryption_key(env_var).map_err(|e| anyhow!("{}", e))
}

/// v2 路径的密钥获取:密码模式用**文件头中的盐**确定性派生,
/// 与加密端 `FileSink::encrypt_file` 的派生方式严格对齐。
fn get_encryption_key_with_salt_cli(env_var: &str, salt: &[u8]) -> Result<Zeroizing<[u8; 32]>> {
    inklog::sink::encryption::get_encryption_key_with_salt(env_var, salt)
        .map_err(|e| anyhow!("{}", e))
}

pub fn decrypt_directory_compatible(
    input_dir: &PathBuf,
    output_dir: &PathBuf,
    key_env: &str,
    recursive: bool,
) -> Result<()> {
    if !input_dir.exists() {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", input_dir.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-input-dir", args)
        ));
    }

    // 检查输入目录是否为符号链接 — 防止符号链接绕过
    if let Ok(metadata) = input_dir.symlink_metadata()
        && metadata.file_type().is_symlink()
    {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", input_dir.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-input-dir-symlink", args)
        ));
    }

    // 先创建输出目录,再验证(canonicalize 要求目录存在)
    std::fs::create_dir_all(output_dir).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_dir.display().to_string());
        inklog::i18n::tr_args("cli-decrypt-err-create-dir", args)
    })?;

    // 输出目录自身不得为符号链接 — 防止符号链接绕过
    if let Ok(metadata) = output_dir.symlink_metadata()
        && metadata.file_type().is_symlink()
    {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_dir.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-symlink", args)
        ));
    }

    let entries = std::fs::read_dir(input_dir).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", input_dir.display().to_string());
        inklog::i18n::tr_args("cli-decrypt-err-read-dir", args)
    })?;

    let mut failure_count = 0u32;

    for entry in entries.flatten() {
        let path = entry.path();

        if path.is_file() {
            if let Some(ext) = path.extension()
                && ext == "enc"
            {
                // 验证待解密文件相对其所在输入目录的包含关系(含符号链接检查)
                if let Err(e) = validate_file_path(&path, input_dir) {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("path", path.display().to_string());
                    args.set("err", e.to_string());
                    eprintln!("{}", inklog::i18n::tr_args("cli-decrypt-path-fail", args));
                    failure_count += 1;
                    continue;
                }

                let file_name = path.file_name().ok_or_else(|| {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("path", path.display().to_string());
                    anyhow!(
                        "{}",
                        inklog::i18n::tr_args("cli-decrypt-err-no-filename", args)
                    )
                })?;
                let output_path = output_dir.join(file_name).with_extension("log");

                // 验证输出路径(不要求文件已存在)
                if let Err(e) = validate_output_path(&output_path, output_dir) {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("path", output_path.display().to_string());
                    args.set("err", e.to_string());
                    eprintln!("{}", inklog::i18n::tr_args("cli-decrypt-path-fail", args));
                    failure_count += 1;
                    continue;
                }

                let mut args = fluent_bundle::FluentArgs::new();
                args.set("input", path.display().to_string());
                args.set("output", output_path.display().to_string());
                println!("{}", inklog::i18n::tr_args("cli-decrypt-progress", args));

                if let Err(e) = decrypt_file_compatible(&path, &output_path, key_env) {
                    let mut args = fluent_bundle::FluentArgs::new();
                    args.set("path", path.display().to_string());
                    args.set("err", e.to_string());
                    eprintln!("{}", inklog::i18n::tr_args("cli-decrypt-fail", args));
                    failure_count += 1;
                }
            }
        } else if recursive && path.is_dir() {
            // 检查子目录是否为符号链接 — 防止递归遍历时符号链接绕过
            if let Ok(metadata) = path.symlink_metadata()
                && metadata.file_type().is_symlink()
            {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("path", path.display().to_string());
                eprintln!(
                    "{}",
                    inklog::i18n::tr_args("cli-decrypt-err-subdir-symlink", args)
                );
                failure_count += 1;
                continue;
            }

            let file_name = path.file_name().ok_or_else(|| {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("path", path.display().to_string());
                anyhow!(
                    "{}",
                    inklog::i18n::tr_args("cli-decrypt-err-no-filename", args)
                )
            })?;
            let sub_output_dir = output_dir.join(file_name);

            // 验证子目录输出路径(不要求目录已存在)
            if let Err(e) = validate_output_path(&sub_output_dir, output_dir) {
                let mut args = fluent_bundle::FluentArgs::new();
                args.set("path", sub_output_dir.display().to_string());
                args.set("err", e.to_string());
                eprintln!("{}", inklog::i18n::tr_args("cli-decrypt-path-fail", args));
                failure_count += 1;
                continue;
            }

            decrypt_directory_compatible(&path, &sub_output_dir, key_env, recursive)?;
        }
    }

    if failure_count > 0 {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("count", failure_count.to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-partial", args)
        ));
    }
    Ok(())
}

pub fn batch_decrypt(input_pattern: &str, output_dir: &PathBuf, key_env: &str) -> Result<()> {
    // 验证 glob 模式安全性 - 防止路径遍历
    validate_glob_pattern(input_pattern)?;

    // 先创建输出目录,再验证(canonicalize 要求目录存在)
    std::fs::create_dir_all(output_dir).with_context(|| {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_dir.display().to_string());
        inklog::i18n::tr_args("cli-decrypt-err-create-dir", args)
    })?;

    // 输出目录自身不得为符号链接 — 防止符号链接绕过
    if let Ok(metadata) = output_dir.symlink_metadata()
        && metadata.file_type().is_symlink()
    {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("path", output_dir.display().to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-err-symlink", args)
        ));
    }

    let _canonical_output = output_dir.canonicalize()?;

    // validate_glob_pattern 已拒绝绝对模式,相对模式以 CWD 为基准目录,
    // glob 展开结果不得逃逸出基准目录
    let canonical_base = std::env::current_dir()
        .and_then(|base| base.canonicalize())
        .map_err(|e| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("err", e.to_string());
            anyhow!("{}", inklog::i18n::tr_args("cli-decrypt-err-base", args))
        })?;

    let paths = glob::glob(input_pattern)
        .map_err(|e| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("err", e.to_string());
            anyhow!("{}", inklog::i18n::tr_args("cli-decrypt-err-glob", args))
        })?
        .filter_map(|p| p.ok())
        .filter(|p| p.is_file() && p.extension().is_some_and(|e| e == "enc"));

    let mut failure_count = 0u32;
    let mut success_count = 0u32;

    for path in paths {
        // 无条件检查符号链接 — 无论路径在输出目录内还是外
        if let Ok(metadata) = path.symlink_metadata()
            && metadata.file_type().is_symlink()
        {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", path.display().to_string());
            eprintln!(
                "{}",
                inklog::i18n::tr_args("cli-decrypt-skip-symlink", args)
            );
            failure_count += 1;
            continue;
        }

        // 验证 glob 展开的输入路径仍在基准目录内 — 展开逃逸(如经符号链接目录)时跳过
        if let Ok(canonical_input) = path.canonicalize()
            && !canonical_input.starts_with(&canonical_base)
        {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", path.display().to_string());
            args.set("base", canonical_base.display().to_string());
            eprintln!(
                "{}",
                inklog::i18n::tr_args("cli-decrypt-err-traversal-detail", args)
            );
            failure_count += 1;
            continue;
        }

        let file_name = path.file_name().ok_or_else(|| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", path.display().to_string());
            anyhow!(
                "{}",
                inklog::i18n::tr_args("cli-decrypt-err-no-filename", args)
            )
        })?;
        let output_path = output_dir.join(file_name).with_extension("log");

        // 验证输出路径(不要求文件已存在)
        if let Err(e) = validate_output_path(&output_path, output_dir) {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", output_path.display().to_string());
            args.set("err", e.to_string());
            eprintln!("{}", inklog::i18n::tr_args("cli-decrypt-path-fail", args));
            failure_count += 1;
            continue;
        }

        let mut args = fluent_bundle::FluentArgs::new();
        args.set("input", path.display().to_string());
        args.set("output", output_path.display().to_string());
        println!("{}", inklog::i18n::tr_args("cli-decrypt-progress", args));

        if let Err(e) = decrypt_file_compatible(&path, &output_path, key_env) {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("path", path.display().to_string());
            args.set("err", e.to_string());
            eprintln!("{}", inklog::i18n::tr_args("cli-decrypt-fail", args));
            failure_count += 1;
        } else {
            success_count += 1;
        }
    }

    if failure_count > 0 {
        let mut args = fluent_bundle::FluentArgs::new();
        args.set("ok", success_count.to_string());
        args.set("fail", failure_count.to_string());
        return Err(anyhow!(
            "{}",
            inklog::i18n::tr_args("cli-decrypt-batch-result", args)
        ));
    }
    Ok(())
}

#[cfg(test)]
mod tests {
    use super::*;
    use aes_gcm::Aes256Gcm;
    use aes_gcm::aead::{Aead, KeyInit};
    use rand::RngExt;
    use std::io::Write;

    /// Generate a test key from a seed (allows deterministic or environment-based keys)
    fn get_test_key(seed: &str) -> [u8; 32] {
        let seed = std::env::var("INKLOG_TEST_KEY_SEED").unwrap_or_else(|_| seed.to_string());
        let hash = Sha256::digest(seed);
        let mut key = [0u8; 32];
        key.copy_from_slice(hash.as_slice());
        key
    }

    /// Generate a test encryption key (with optional seed for determinism)
    fn generate_test_key() -> [u8; 32] {
        get_test_key("inklog-test-seed-2024")
    }

    fn create_encrypted_file_v1(path: &PathBuf, plaintext: &[u8], key: &[u8; 32]) -> Result<()> {
        let mut file = File::create(path)?;

        file.write_all(MAGIC_HEADER)?;
        file.write_all(&1u16.to_le_bytes())?;
        file.write_all(&1u16.to_le_bytes())?;

        let mut nonce_bytes = [0u8; 12];
        let mut rng = rand::rng();
        rng.fill(&mut nonce_bytes);
        file.write_all(&nonce_bytes)?;

        let cipher = Aes256Gcm::new(key.into());
        let nonce = aes_gcm::Nonce::from(nonce_bytes);
        let ciphertext = cipher.encrypt(&nonce, plaintext).map_err(|e| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("err", e.to_string());
            anyhow!("{}", inklog::i18n::tr_args("config-encryption_error", args))
        })?;

        file.write_all(&ciphertext)?;

        Ok(())
    }

    fn create_encrypted_file_legacy(
        path: &PathBuf,
        plaintext: &[u8],
        key: &[u8; 32],
    ) -> Result<()> {
        let mut file = File::create(path)?;

        file.write_all(MAGIC_HEADER)?;
        file.write_all(&1u16.to_le_bytes())?;

        let mut nonce_bytes = [0u8; 12];
        let mut rng = rand::rng();
        rng.fill(&mut nonce_bytes);
        file.write_all(&nonce_bytes)?;

        let cipher = Aes256Gcm::new(key.into());
        let nonce = aes_gcm::Nonce::from(nonce_bytes);
        let ciphertext = cipher.encrypt(&nonce, plaintext).map_err(|e| {
            let mut args = fluent_bundle::FluentArgs::new();
            args.set("err", e.to_string());
            anyhow!("{}", inklog::i18n::tr_args("config-encryption_error", args))
        })?;

        file.write_all(&ciphertext)?;

        Ok(())
    }

    #[test]
    fn test_magic_header_validation() {
        let temp_dir = tempfile::tempdir().unwrap();
        let invalid_file = temp_dir.path().join("invalid.enc");
        let mut file = File::create(&invalid_file).unwrap();
        let mut invalid_header = [0u8; 24];
        invalid_header[..14].copy_from_slice(b"INVALID_HEADER");
        file.write_all(&invalid_header).unwrap();

        let result = decrypt_file(&invalid_file, &PathBuf::from("output.log"), "TEST_KEY");
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Invalid file header"),
            "Expected error about invalid header, got: {}",
            err_msg
        );
    }

    #[test]
    fn test_version_validation() {
        let temp_dir = tempfile::tempdir().unwrap();
        let invalid_file = temp_dir.path().join("invalid_version.enc");
        let mut file = File::create(&invalid_file).unwrap();
        let mut header = [0u8; 24];
        header[..8].copy_from_slice(MAGIC_HEADER);
        header[8..10].copy_from_slice(&999u16.to_le_bytes());
        header[10..12].copy_from_slice(&1u16.to_le_bytes());
        file.write_all(&header).unwrap();

        let result = decrypt_file(&invalid_file, &PathBuf::from("output.log"), "TEST_KEY");
        assert!(result.is_err());
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Unsupported file version"),
            "Expected error about unsupported version, got: {}",
            err_msg
        );
    }

    #[test]
    fn test_get_encryption_key_base64() {
        let test_key = generate_test_key();
        let key_base64 = general_purpose::STANDARD.encode(test_key);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_ENCRYPTION_KEY", &key_base64) };

        let key = get_encryption_key_cli("TEST_ENCRYPTION_KEY").unwrap();
        assert_eq!(*key, test_key);

        unsafe { std::env::remove_var("TEST_ENCRYPTION_KEY") };
    }

    #[test]
    fn test_get_encryption_key_password_derivation() {
        // 使用明确的盐值进行测试,以确保可重现性
        let salt = b"test-salt-16b";
        let (key1, returned_salt) =
            derive_key_from_password("my-secret-password", Some(salt)).unwrap();
        assert_eq!(key1.len(), 32);
        assert_eq!(returned_salt, salt);

        // 使用相同密码和盐值再次派生,应该得到相同的密钥
        let (key2, _) = derive_key_from_password("my-secret-password", Some(salt)).unwrap();
        assert_eq!(key1, key2);

        // 使用不同盐值派生,应该得到不同的密钥
        let (key3, _) =
            derive_key_from_password("my-secret-password", Some(b"different-salt!")).unwrap();
        assert_ne!(key1, key3);
    }

    #[test]
    fn test_get_encryption_key_raw_32_bytes() {
        let raw_key = [0x42u8; 32];
        // SAFETY: test-only env var mutation under single-threaded test
        unsafe { std::env::set_var("TEST_RAW_KEY", std::str::from_utf8(&raw_key).unwrap()) };

        let key = get_encryption_key_cli("TEST_RAW_KEY").unwrap();
        assert_eq!(*key, raw_key);

        unsafe { std::env::remove_var("TEST_RAW_KEY") };
    }

    #[test]
    fn test_decrypt_file_v1_format() {
        let temp_dir = tempfile::tempdir().unwrap();
        let input_file = temp_dir.path().join("test_v1.enc");
        let output_file = temp_dir.path().join("test_v1.log");
        let plaintext = b"Hello, World! V1 format test.";
        let test_key = generate_test_key();

        create_encrypted_file_v1(&input_file, plaintext, &test_key).unwrap();

        let key_base64 = general_purpose::STANDARD.encode(test_key);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_KEY_V1", &key_base64) };

        decrypt_file(&input_file, &output_file, "TEST_KEY_V1").unwrap();

        let decrypted_content = std::fs::read(&output_file).unwrap();
        assert_eq!(decrypted_content, plaintext);

        unsafe { std::env::remove_var("TEST_KEY_V1") };
    }

    #[test]
    fn test_decrypt_file_compatible() {
        let temp_dir = tempfile::tempdir().unwrap();
        let test_key = generate_test_key();
        let key_base64 = general_purpose::STANDARD.encode(test_key);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_KEY_COMPAT", &key_base64) };

        // Test V1 format
        let v1_file = temp_dir.path().join("v1.enc");
        let v1_out = temp_dir.path().join("v1.log");
        let v1_text = b"V1 Content";
        create_encrypted_file_v1(&v1_file, v1_text, &test_key).unwrap();

        decrypt_file_compatible(&v1_file, &v1_out, "TEST_KEY_COMPAT").unwrap();
        assert_eq!(std::fs::read(&v1_out).unwrap(), v1_text);

        // Test Legacy format
        let legacy_file = temp_dir.path().join("legacy.enc");
        let legacy_out = temp_dir.path().join("legacy.log");
        let legacy_text = b"Legacy Content";
        create_encrypted_file_legacy(&legacy_file, legacy_text, &test_key).unwrap();

        decrypt_file_compatible(&legacy_file, &legacy_out, "TEST_KEY_COMPAT").unwrap();
        assert_eq!(std::fs::read(&legacy_out).unwrap(), legacy_text);

        unsafe { std::env::remove_var("TEST_KEY_COMPAT") };
    }

    #[test]
    fn test_library_encrypted_file_decryptable_by_cli() {
        // 回归测试:库内 FileSink::encrypt_file 产出的文件必须能被 CLI 解密工具读取
        let temp_dir = tempfile::tempdir().unwrap();
        let input_path = temp_dir.path().join("lib_encrypted.log");
        let encrypted_path = temp_dir.path().join("lib_encrypted.log.enc");
        let output_path = temp_dir.path().join("lib_decrypted.log");
        let plaintext = b"Library-encrypted content must roundtrip through the CLI";
        std::fs::write(&input_path, plaintext).unwrap();

        let test_key = generate_test_key();
        let key_base64 = general_purpose::STANDARD.encode(test_key);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_LIB_ENC_KEY", &key_base64) };

        let config = inklog::FileSinkConfig {
            enabled: true,
            path: temp_dir.path().join("dummy.log"),
            encrypt: true,
            encryption_key_env: Some("TEST_LIB_ENC_KEY".to_string()),
            ..Default::default()
        };
        let sink = inklog::support::io::sink::FileSink::new(config).unwrap();
        sink.encrypt_file(&input_path, &encrypted_path).unwrap();

        // v2 头:Base64 密钥与盐无关,但 version 字段必须是 2
        let encrypted = std::fs::read(&encrypted_path).unwrap();
        assert_eq!(&encrypted[..8], b"ENCLOG1\0");
        assert_eq!(
            u16::from_le_bytes([encrypted[8], encrypted[9]]),
            2,
            "library-produced encrypted files must use the v2 header (salt-carrying)"
        );

        decrypt_file_compatible(&encrypted_path, &output_path, "TEST_LIB_ENC_KEY").unwrap();
        assert_eq!(std::fs::read(&output_path).unwrap(), plaintext);

        unsafe { std::env::remove_var("TEST_LIB_ENC_KEY") };
    }

    // ==================== v2 密码模式 round-trip(Critical 缺陷补漏) ====================

    /// 借助 FileSink::encrypt_file(lib)加密的辅助函数,供 CLI 侧 round-trip 测试使用
    fn encrypt_with_file_sink(
        temp_dir: &Path,
        input_path: &Path,
        encrypted_path: &Path,
        key_env: &str,
    ) {
        let config = inklog::FileSinkConfig {
            enabled: true,
            path: temp_dir.join("dummy.log"),
            encrypt: true,
            encryption_key_env: Some(key_env.to_string()),
            ..Default::default()
        };
        let sink = inklog::support::io::sink::FileSink::new(config).unwrap();
        sink.encrypt_file(input_path, encrypted_path).unwrap();
    }

    #[test]
    fn test_password_mode_v2_roundtrip() {
        // Critical 修复补漏 (a):普通密码 env → encrypt_file(v2) →
        // decrypt_file_compatible 同密码 env → 内容一致。
        // v1 时该场景必败(头中无盐,解密方随机盐派生出不同密钥)。
        let temp_dir = tempfile::tempdir().unwrap();
        let input_path = temp_dir.path().join("pwd_plain.log");
        let encrypted_path = temp_dir.path().join("pwd_plain.log.enc");
        let output_path = temp_dir.path().join("pwd_decrypted.log");
        let plaintext = b"Password-mode roundtrip must succeed with the v2 header";
        std::fs::write(&input_path, plaintext).unwrap();

        // 测试用假密码向量(非真实凭据):非 Base64、非 32 字节、>= 12 字符
        unsafe { std::env::set_var("TEST_PWD_RT_KEY", "round-trip-password-01") };

        encrypt_with_file_sink(
            temp_dir.path(),
            &input_path,
            &encrypted_path,
            "TEST_PWD_RT_KEY",
        );

        // 头中必须携带盐(version 2)
        let encrypted = std::fs::read(&encrypted_path).unwrap();
        assert_eq!(u16::from_le_bytes([encrypted[8], encrypted[9]]), 2);
        assert!(
            encrypted[12..28].iter().any(|&b| b != 0),
            "v2 header must store the PBKDF2 salt"
        );

        decrypt_file_compatible(&encrypted_path, &output_path, "TEST_PWD_RT_KEY").unwrap();
        assert_eq!(std::fs::read(&output_path).unwrap(), plaintext);

        unsafe { std::env::remove_var("TEST_PWD_RT_KEY") };
    }

    #[test]
    fn test_v1_password_key_returns_clear_error() {
        // v1 头未存盐:密码模式密钥不可恢复,必须返回明确诊断
        // 而非误导性的 "decryption failed"。
        let temp_dir = tempfile::tempdir().unwrap();
        let input_file = temp_dir.path().join("v1_pwd.enc");
        let output_file = temp_dir.path().join("v1_pwd.log");
        let test_key = generate_test_key();
        create_encrypted_file_v1(&input_file, b"v1 secret", &test_key).unwrap();

        // 测试用假密码向量(非真实凭据)
        unsafe { std::env::set_var("TEST_V1_PWD_KEY", "some-plain-password-01") };

        let result = decrypt_file_compatible(&input_file, &output_file, "TEST_V1_PWD_KEY");
        assert!(result.is_err(), "v1 + password key must not decrypt");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("v1") && err_msg.contains("salt"),
            "error must explain the v1 missing-salt limitation, got: {err_msg}"
        );
        assert!(
            !output_file.exists(),
            "no output file should be created on failure"
        );

        unsafe { std::env::remove_var("TEST_V1_PWD_KEY") };
    }

    #[test]
    fn test_v2_wrong_password_fails() {
        // v2 密码模式:密码错误时盐虽可读出,但派生密钥不同 → 解密失败
        let temp_dir = tempfile::tempdir().unwrap();
        let input_path = temp_dir.path().join("wrong_pwd.log");
        let encrypted_path = temp_dir.path().join("wrong_pwd.log.enc");
        let output_path = temp_dir.path().join("wrong_pwd_out.log");
        std::fs::write(&input_path, b"secret").unwrap();

        unsafe {
            std::env::set_var("TEST_V2_PWD_A", "correct-horse-battery-01");
            std::env::set_var("TEST_V2_PWD_B", "wrong-password-entry-99");
        }

        encrypt_with_file_sink(
            temp_dir.path(),
            &input_path,
            &encrypted_path,
            "TEST_V2_PWD_A",
        );

        let result = decrypt_file_compatible(&encrypted_path, &output_path, "TEST_V2_PWD_B");
        assert!(result.is_err(), "wrong password must fail to decrypt");
        assert!(!output_path.exists());

        unsafe {
            std::env::remove_var("TEST_V2_PWD_A");
            std::env::remove_var("TEST_V2_PWD_B");
        }
    }

    #[test]
    fn test_v2_base64_key_roundtrip_via_cli() {
        // Critical 修复补漏 (b):Base64 32 字节 env → v2 round-trip
        let temp_dir = tempfile::tempdir().unwrap();
        let input_path = temp_dir.path().join("b64_plain.log");
        let encrypted_path = temp_dir.path().join("b64_plain.log.enc");
        let output_path = temp_dir.path().join("b64_decrypted.log");
        let plaintext = b"Base64-key v2 roundtrip content";
        std::fs::write(&input_path, plaintext).unwrap();

        let test_key = generate_test_key();
        let key_base64 = general_purpose::STANDARD.encode(test_key);
        unsafe { std::env::set_var("TEST_V2_B64_RT_KEY", &key_base64) };

        encrypt_with_file_sink(
            temp_dir.path(),
            &input_path,
            &encrypted_path,
            "TEST_V2_B64_RT_KEY",
        );
        decrypt_file_compatible(&encrypted_path, &output_path, "TEST_V2_B64_RT_KEY").unwrap();
        assert_eq!(std::fs::read(&output_path).unwrap(), plaintext);

        unsafe { std::env::remove_var("TEST_V2_B64_RT_KEY") };
    }

    #[test]
    fn test_path_traversal_protection() {
        let temp_dir = tempfile::tempdir().unwrap();
        let base_dir = temp_dir.path();

        // Test parent directory traversal
        let malicious_path = base_dir.join("../passwd");
        assert!(validate_file_path(&malicious_path, base_dir).is_err());

        // Test valid path
        let valid_path = base_dir.join("valid.log");
        // Create file to make canonicalize work
        File::create(&valid_path).unwrap();
        assert!(validate_file_path(&valid_path, base_dir).is_ok());
    }

    #[test]
    fn test_validate_glob_pattern_valid() {
        assert!(validate_glob_pattern("*.enc").is_ok());
        assert!(validate_glob_pattern("logs/*.enc").is_ok());
        assert!(validate_glob_pattern("data/2024/*.log.enc").is_ok());
    }

    #[test]
    fn test_validate_glob_pattern_rejects_absolute_paths() {
        assert!(validate_glob_pattern("/var/log/*.enc").is_err());
        assert!(validate_glob_pattern("\\server\\share").is_err());
    }

    #[test]
    fn test_validate_glob_pattern_rejects_path_traversal() {
        assert!(validate_glob_pattern("../secret.enc").is_err());
        assert!(validate_glob_pattern("~/secret.enc").is_err());
        assert!(validate_glob_pattern("logs/../../etc/passwd").is_err());
    }

    #[test]
    fn test_validate_glob_pattern_rejects_suspicious_chars() {
        assert!(validate_glob_pattern("file\0.enc").is_err());
        assert!(validate_glob_pattern("file\u{2024}.enc").is_err());
        assert!(validate_glob_pattern("file\u{2025}.enc").is_err());
        assert!(validate_glob_pattern("file\u{FE52}.enc").is_err());
    }

    #[test]
    fn test_validate_file_path_rejects_suspicious_chars() {
        // 覆盖 L27-29:validate_file_path 的可疑字符错误路径(在 canonicalize 之前拦截)
        let temp_dir = tempfile::tempdir().unwrap();
        let base_dir = temp_dir.path();
        let malicious_path = base_dir.join("file\0.log");
        assert!(validate_file_path(&malicious_path, base_dir).is_err());

        // Unicode 变体点字符
        let unicode_path = base_dir.join("file\u{2024}.log");
        assert!(validate_file_path(&unicode_path, base_dir).is_err());
    }

    #[test]
    fn test_get_encryption_key_base64_wrong_length() {
        // 覆盖 L271-277: Base64 解码成功但长度不是 32
        let wrong_key = general_purpose::STANDARD.encode([0u8; 16]);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_WRONG_LEN_KEY", &wrong_key) };
        let result = get_encryption_key_cli("TEST_WRONG_LEN_KEY");
        assert!(result.is_err());
        let err = result.err().unwrap().to_string();
        assert!(err.contains("32 bytes"));
        unsafe { std::env::remove_var("TEST_WRONG_LEN_KEY") };
    }

    #[test]
    fn test_get_encryption_key_password_via_cli() {
        // 覆盖 L281-288: 通过 get_encryption_key_cli 调用 PBKDF2 派生
        // "my-short-password" 不是 32 字节,也不是有效 Base64(含 '-'),长度 < 128
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_PASSWORD_KEY_CLI", "my-short-password") };
        let result = get_encryption_key_cli("TEST_PASSWORD_KEY_CLI");
        assert!(result.is_ok());
        unsafe { std::env::remove_var("TEST_PASSWORD_KEY_CLI") };
    }

    #[test]
    fn test_get_encryption_key_too_long() {
        // 覆盖 L291-295: 密钥长度 >= 128 且非有效 Base64
        let long_key = "!".repeat(128);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("TEST_LONG_KEY", &long_key) };
        let result = get_encryption_key_cli("TEST_LONG_KEY");
        assert!(result.is_err());
        unsafe { std::env::remove_var("TEST_LONG_KEY") };
    }

    #[cfg(unix)]
    #[test]
    fn test_symlink_detected_before_canonicalize() {
        // symlink check must use symlink_metadata() to detect symlinks
        // on the original path before canonicalize resolves them.
        // 仅 unix 平台语义(Windows 无普通用户 symlink 权限)。
        let temp_dir = tempfile::tempdir().unwrap();
        let base_dir = temp_dir.path();

        // Create a real file and a symlink to it
        let real_file = base_dir.join("real.log");
        File::create(&real_file).unwrap();
        let symlink_path = base_dir.join("link.log");
        std::os::unix::fs::symlink(&real_file, &symlink_path).unwrap();

        // The symlink should be rejected
        let result = validate_file_path(&symlink_path, base_dir);
        assert!(result.is_err(), "symlinks should be rejected");
        let err_msg = result.unwrap_err().to_string();
        assert!(
            err_msg.contains("Symbolic links"),
            "error should mention symbolic links, got: {}",
            err_msg
        );
    }

    #[test]
    fn test_batch_decrypt_skips_paths_outside_base_dir() {
        // 相对 glob 模式以 CWD 为基准目录:经符号链接目录展开到基外的输入必须被跳过。
        // 该测试会切换进程 CWD,需要独占运行。
        static CWD_LOCK: std::sync::Mutex<()> = std::sync::Mutex::new(());
        let _lock = CWD_LOCK.lock().unwrap();

        let base_dir = tempfile::tempdir().unwrap();
        let outside_dir = tempfile::tempdir().unwrap();
        let output_dir = base_dir.path().join("decrypted");

        let test_key = generate_test_key();
        let key_base64 = general_purpose::STANDARD.encode(test_key);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("INKLOG_TEST_BATCH_BASE_KEY", &key_base64) };

        // 基内合法加密文件
        create_encrypted_file_v1(&base_dir.path().join("inside.enc"), b"inside", &test_key)
            .unwrap();
        // 基外文件,通过基内符号链接目录暴露给 glob(普通 glob 模式无法越过基准目录)
        std::fs::write(outside_dir.path().join("outside.enc"), b"junk").unwrap();

        let original_cwd = std::env::current_dir().unwrap();
        std::env::set_current_dir(base_dir.path()).unwrap();

        let ok_result = batch_decrypt("*.enc", &output_dir, "INKLOG_TEST_BATCH_BASE_KEY");

        #[cfg(unix)]
        let escape_result = {
            std::os::unix::fs::symlink(outside_dir.path(), base_dir.path().join("escape")).unwrap();
            batch_decrypt("escape/*.enc", &output_dir, "INKLOG_TEST_BATCH_BASE_KEY")
        };

        std::env::set_current_dir(original_cwd).unwrap();
        // SAFETY: test-only env var mutation
        unsafe { std::env::remove_var("INKLOG_TEST_BATCH_BASE_KEY") };

        assert!(
            ok_result.is_ok(),
            "inside-base file should decrypt: {ok_result:?}"
        );
        assert!(output_dir.join("inside.log").exists());

        #[cfg(unix)]
        {
            assert!(
                escape_result.is_err(),
                "out-of-base glob expansion should be skipped and reported"
            );
            assert!(!output_dir.join("outside.log").exists());
        }
    }

    #[cfg(unix)]
    #[test]
    fn test_directory_decrypt_validates_input_file_against_output_dir() {
        // 目录模式:每个待解密文件须通过相对输出目录的校验,
        // 符号链接输入文件必须被跳过,不影响其余文件解密
        let base_dir = tempfile::tempdir().unwrap();
        let input_dir = base_dir.path().to_path_buf();
        let outside_dir = tempfile::tempdir().unwrap();

        let test_key = generate_test_key();
        let key_base64 = general_purpose::STANDARD.encode(test_key);
        // SAFETY: test-only env var mutation
        unsafe { std::env::set_var("INKLOG_TEST_DIR_VALIDATE_KEY", &key_base64) };

        create_encrypted_file_v1(&input_dir.join("good.enc"), b"good", &test_key).unwrap();
        std::fs::write(outside_dir.path().join("secret.txt"), b"secret").unwrap();
        std::os::unix::fs::symlink(
            outside_dir.path().join("secret.txt"),
            input_dir.join("evil.enc"),
        )
        .unwrap();

        let result = decrypt_directory_compatible(
            &input_dir,
            &input_dir,
            "INKLOG_TEST_DIR_VALIDATE_KEY",
            false,
        );

        // SAFETY: test-only env var mutation
        unsafe { std::env::remove_var("INKLOG_TEST_DIR_VALIDATE_KEY") };

        assert!(result.is_err(), "symlinked input file should be skipped");
        assert!(
            input_dir.join("good.log").exists(),
            "regular file should decrypt"
        );
        assert!(
            !input_dir.join("evil.log").exists(),
            "symlinked input must not be decrypted"
        );
    }
}