bamboo-tools 2026.5.3

Tool execution and integrations for the Bamboo agent framework
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
1001
1002
1003
1004
1005
1006
1007
1008
1009
1010
1011
1012
1013
1014
1015
1016
1017
1018
1019
1020
1021
1022
1023
1024
1025
1026
1027
1028
1029
1030
1031
1032
1033
1034
1035
1036
1037
1038
1039
1040
1041
1042
1043
1044
1045
1046
1047
1048
1049
1050
1051
1052
1053
1054
1055
1056
1057
1058
1059
1060
1061
1062
1063
1064
1065
1066
1067
1068
1069
1070
1071
1072
1073
1074
1075
1076
1077
1078
1079
1080
1081
1082
1083
1084
1085
1086
1087
1088
1089
1090
1091
1092
1093
1094
1095
1096
1097
1098
1099
1100
1101
1102
1103
1104
1105
1106
1107
1108
1109
1110
1111
1112
1113
1114
1115
1116
1117
1118
1119
1120
1121
1122
1123
1124
1125
1126
1127
1128
1129
1130
1131
1132
1133
1134
1135
1136
1137
1138
1139
1140
1141
1142
1143
1144
1145
1146
1147
1148
1149
1150
1151
1152
1153
1154
1155
1156
1157
1158
1159
1160
1161
1162
1163
1164
1165
1166
1167
1168
1169
1170
1171
1172
1173
1174
1175
1176
1177
1178
1179
1180
1181
1182
1183
1184
1185
1186
1187
1188
1189
1190
1191
1192
1193
1194
1195
1196
1197
1198
1199
1200
1201
1202
1203
1204
1205
1206
1207
1208
1209
1210
1211
1212
1213
1214
1215
1216
1217
1218
1219
1220
1221
1222
1223
1224
1225
1226
1227
1228
1229
1230
1231
1232
1233
1234
1235
1236
1237
1238
1239
1240
1241
1242
1243
1244
1245
1246
1247
1248
1249
1250
1251
1252
1253
1254
1255
1256
1257
1258
1259
1260
1261
1262
1263
1264
1265
1266
1267
1268
1269
1270
1271
1272
1273
1274
1275
1276
1277
1278
1279
1280
1281
1282
1283
1284
1285
1286
1287
1288
1289
1290
1291
1292
1293
1294
1295
1296
1297
1298
1299
1300
1301
1302
1303
1304
1305
1306
1307
1308
1309
1310
1311
1312
1313
1314
1315
1316
1317
1318
1319
1320
1321
1322
1323
1324
1325
1326
1327
1328
1329
1330
1331
1332
1333
1334
1335
1336
1337
1338
1339
1340
1341
1342
1343
1344
1345
1346
1347
1348
1349
1350
1351
1352
1353
1354
1355
1356
1357
1358
1359
1360
1361
1362
1363
1364
1365
1366
1367
1368
1369
1370
1371
1372
1373
1374
1375
1376
1377
1378
1379
1380
1381
1382
1383
1384
1385
1386
1387
1388
1389
1390
1391
1392
1393
1394
1395
1396
1397
1398
1399
1400
1401
1402
1403
1404
1405
1406
1407
1408
1409
1410
1411
1412
1413
1414
1415
1416
1417
1418
1419
1420
1421
1422
1423
1424
1425
1426
1427
1428
1429
1430
1431
1432
1433
1434
1435
1436
1437
1438
1439
1440
1441
1442
1443
1444
1445
1446
1447
1448
1449
1450
1451
1452
1453
1454
1455
1456
1457
1458
1459
1460
1461
1462
1463
1464
1465
1466
1467
1468
1469
1470
1471
1472
1473
1474
1475
//! Permission configuration for tool execution.
//!
//! This module provides a flexible permission system for controlling access to
//! potentially dangerous operations like file writes, command execution, and HTTP requests.

use std::path::{Component, Path};
use std::sync::atomic::{AtomicBool, Ordering};
use std::sync::RwLock;
use std::time::{Duration, Instant};

use tracing::warn;

use dashmap::DashMap;
use serde::{Deserialize, Serialize};

// Re-export PermissionMode from the shared location in bamboo-infrastructure
pub use bamboo_infrastructure::config::settings::PermissionMode;

/// Types of permissions that can be granted
#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Serialize, Deserialize)]
#[serde(rename_all = "snake_case")]
pub enum PermissionType {
    /// Permission to write files
    WriteFile,
    /// Permission to execute shell commands
    ExecuteCommand,
    /// Permission to perform Git write operations (commit, push, etc.)
    GitWrite,
    /// Permission to make HTTP requests
    HttpRequest,
    /// Permission to perform delete operations
    DeleteOperation,
    /// Permission for terminal sessions (long-running interactive commands)
    TerminalSession,
}

impl PermissionType {
    /// Get a human-readable description of this permission type
    pub fn description(&self) -> &'static str {
        match self {
            PermissionType::WriteFile => "Write files to disk",
            PermissionType::ExecuteCommand => "Execute shell commands",
            PermissionType::GitWrite => "Perform Git write operations (commit, push, etc.)",
            PermissionType::HttpRequest => "Make HTTP requests to external services",
            PermissionType::DeleteOperation => "Delete files or directories",
            PermissionType::TerminalSession => "Run interactive terminal sessions",
        }
    }

    /// Get the risk level of this permission type
    pub fn risk_level(&self) -> RiskLevel {
        match self {
            PermissionType::WriteFile => RiskLevel::Medium,
            PermissionType::ExecuteCommand => RiskLevel::High,
            PermissionType::GitWrite => RiskLevel::High,
            PermissionType::HttpRequest => RiskLevel::Medium,
            PermissionType::DeleteOperation => RiskLevel::High,
            PermissionType::TerminalSession => RiskLevel::High,
        }
    }
}

/// Risk level for permission types
#[derive(Debug, Clone, Copy, PartialEq, Eq)]
pub enum RiskLevel {
    Low,
    Medium,
    High,
}

impl RiskLevel {
    /// Get a human-readable label for this risk level
    pub fn label(&self) -> &'static str {
        match self {
            RiskLevel::Low => "Low Risk",
            RiskLevel::Medium => "Medium Risk",
            RiskLevel::High => "High Risk",
        }
    }
}

/// A rule in the permission whitelist
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct PermissionRule {
    /// The type of permission this rule applies to
    pub tool_type: PermissionType,
    /// Pattern to match resources (e.g., "/Users/bigduu/project/*" or "*.rs")
    pub resource_pattern: String,
    /// Whether this rule allows or denies access
    pub allowed: bool,
    /// Optional expiration time for this rule
    #[serde(skip_serializing_if = "Option::is_none")]
    pub expires_at: Option<chrono::DateTime<chrono::Utc>>,
}

impl PermissionRule {
    /// Create a new permission rule
    pub fn new(
        tool_type: PermissionType,
        resource_pattern: impl Into<String>,
        allowed: bool,
    ) -> Self {
        Self {
            tool_type,
            resource_pattern: resource_pattern.into(),
            allowed,
            expires_at: None,
        }
    }

    /// Set an expiration time for this rule
    pub fn with_expiration(mut self, expires_at: chrono::DateTime<chrono::Utc>) -> Self {
        self.expires_at = Some(expires_at);
        self
    }

    /// Check if this rule has expired
    pub fn is_expired(&self) -> bool {
        self.expires_at
            .map(|exp| chrono::Utc::now() > exp)
            .unwrap_or(false)
    }

    /// Check if this rule matches the given permission type and resource
    pub fn matches(&self, perm_type: PermissionType, resource: &str) -> bool {
        if self.tool_type != perm_type {
            return false;
        }
        if self.is_expired() {
            return false;
        }

        // For file-related permissions, normalize the path
        // For other permissions (HTTP, commands, etc.), match directly
        let normalized_resource = match perm_type {
            PermissionType::WriteFile => canonicalize_path_for_matching(resource),
            _ => Some(resource.to_string()),
        };

        let normalized_resource = match normalized_resource {
            Some(r) => r,
            None => return false,
        };

        // Use globset for proper glob matching
        match_glob_pattern(&self.resource_pattern, &normalized_resource)
    }
}

/// Session-granted permission entry with expiration
#[derive(Debug, Clone)]
pub struct SessionGrant {
    /// When this grant was created
    pub granted_at: Instant,
    /// When this grant expires
    pub expires_at: Instant,
    /// The resource pattern this grant applies to
    pub resource_pattern: String,
}

impl SessionGrant {
    /// Create a new session grant with the given duration
    pub fn new(resource_pattern: impl Into<String>, duration: Duration) -> Self {
        let now = Instant::now();
        Self {
            granted_at: now,
            expires_at: now + duration,
            resource_pattern: resource_pattern.into(),
        }
    }

    /// Check if this grant has expired
    pub fn is_expired(&self) -> bool {
        Instant::now() > self.expires_at
    }

    /// Check if this grant matches the given resource
    ///
    /// # Arguments
    ///
    /// * `perm_type` - The type of permission being checked
    /// * `resource` - The resource to match against (path, URL, command, etc.)
    ///
    /// # Returns
    ///
    /// `true` if the grant matches and has not expired, `false` otherwise.
    pub fn matches(&self, perm_type: PermissionType, resource: &str) -> bool {
        if self.is_expired() {
            return false;
        }

        // For file-related permissions, normalize the path
        // For other permissions (HTTP, commands, etc.), match directly
        let normalized_resource = match perm_type {
            PermissionType::WriteFile => canonicalize_path_for_matching(resource),
            _ => Some(resource.to_string()),
        };

        let normalized_resource = match normalized_resource {
            Some(r) => r,
            None => return false,
        };

        match_glob_pattern(&self.resource_pattern, &normalized_resource)
    }
}

/// Canonicalize a resource path before permission matching.
///
/// This function:
/// 1. Resolves symlinks using `std::fs::canonicalize()` to prevent symlink bypass attacks
/// 2. Normalizes path separators and removes `.` and `..` components
/// 3. Supports both Unix and Windows paths
/// 4. For non-existent paths, resolves the parent directory and appends the filename
/// 5. Falls back to basic normalization if filesystem operations fail
///
/// Returns `None` when:
/// - The path is not absolute
/// - The path contains parent directory traversal (`..`) in the original string
///
/// # Security
///
/// Always use this function to resolve paths before permission checking to prevent
/// symlink-based bypass attacks where an attacker creates a symlink in an allowed
/// directory pointing to a sensitive file.
///
/// The function attempts to resolve symlinks for maximum security, but falls back
/// to basic normalization if the path doesn't exist or cannot be accessed.
pub fn canonicalize_path_for_matching(path: &str) -> Option<String> {
    let path_obj = Path::new(path);

    // Require absolute paths
    if !path_obj.is_absolute() {
        warn!("Permission check rejected non-absolute path: {}", path);
        return None;
    }

    // Quick rejection: if the original path contains "..", reject it immediately
    // This prevents basic traversal attempts even if filesystem operations fail
    if has_path_traversal(path) {
        warn!("Permission check rejected path with traversal: {}", path);
        return None;
    }

    // Try to canonicalize the full path first (resolves symlinks for existing paths)
    if let Ok(canonical) = std::fs::canonicalize(path_obj) {
        // On Windows, canonicalize may return UNC paths like \\?\C:\foo\bar
        // We need to normalize this for pattern matching
        let canonical_str = canonical.to_str()?.to_string();

        #[cfg(windows)]
        {
            // Remove the \\?\ prefix if present (UNC path prefix)
            let normalized = if canonical_str.starts_with(r"\\?\") {
                &canonical_str[4..]
            } else {
                &canonical_str
            };
            // Convert backslashes to forward slashes for consistent pattern matching
            return Some(normalized.replace('\\', "/"));
        }

        #[cfg(not(windows))]
        {
            return Some(canonical_str);
        }
    }

    // Path doesn't exist - try to canonicalize parent directory
    if let Some(parent) = path_obj.parent() {
        if let Some(file_name) = path_obj.file_name() {
            // Canonicalize the parent directory (resolves symlinks)
            if let Ok(canonical_parent) = std::fs::canonicalize(parent) {
                // Reconstruct the path: canonical_parent + file_name
                let mut result = canonical_parent;
                result.push(file_name);

                // On Windows, normalize UNC paths for pattern matching
                #[cfg(windows)]
                {
                    let result_str = result.to_str()?.to_string();
                    let normalized = if result_str.starts_with(r"\\?\") {
                        &result_str[4..]
                    } else {
                        &result_str
                    };
                    return Some(normalized.replace('\\', "/"));
                }

                #[cfg(not(windows))]
                {
                    return Some(result.to_str()?.to_string());
                }
            }
        }
    }

    // Fallback: basic normalization without filesystem access
    // This handles test environments and unusual error conditions
    let normalized = normalize_path_basic(path);
    Some(normalized)
}

/// Basic path normalization without filesystem access.
///
/// This function:
/// - Removes redundant slashes
/// - Removes `.` components
/// - Rejects `..` components (already checked by caller)
/// - Normalizes to forward slashes for cross-platform pattern matching
///
/// This is a fallback when `canonicalize_path_for_matching` cannot access
/// the filesystem. It does NOT resolve symlinks, so it's less secure than
/// the full canonicalization.
///
/// # Platform-specific behavior
///
/// On Windows, backslashes are converted to forward slashes for consistent
/// pattern matching. On Unix, the path is left as-is.
fn normalize_path_basic(path: &str) -> String {
    // Always replace backslashes with forward slashes for cross-platform consistency
    // This allows Windows paths to be tested on Unix systems
    let path = path.replace('\\', "/");

    let components: Vec<&str> = path
        .split('/')
        .filter(|s| !s.is_empty() && *s != ".")
        .collect();

    // Handle Windows paths with drive letters (e.g., "C:/Users/foo")
    // The drive letter will be the first component after splitting
    if !components.is_empty() && components[0].ends_with(':') {
        // Windows path with drive letter: C: is already in components
        // Just join them with forward slashes
        return components.join("/");
    }

    "/".to_string() + &components.join("/")
}

/// Check if a path contains parent directory traversal components.
///
/// This is a lightweight check for paths that haven't been canonicalized yet.
/// It rejects paths containing `..` components which could be used for directory traversal.
///
/// # Security Note
///
/// This check alone is NOT sufficient for security - always use `canonicalize_path_for_matching`
/// before permission checks to fully resolve symlinks and normalize paths.
pub fn has_path_traversal(path: &str) -> bool {
    Path::new(path)
        .components()
        .any(|c| matches!(c, Component::ParentDir))
}

/// Open a file safely with O_NOFOLLOW to prevent TOCTOU symlink attacks.
///
/// This function opens a file while ensuring that:
/// 1. If the file exists, it's opened with O_NOFOLLOW (fails if it's a symlink)
/// 2. If the file doesn't exist, we verify the parent directory exists and is not a symlink
///
/// This prevents the TOCTOU (Time-of-Check to Time-of-Use) race condition where:
/// - Attacker creates a file in allowed location
/// - We check permissions on the file
/// - Attacker replaces the file with a symlink to a sensitive location
/// - We open the symlink (now pointing to sensitive location)
///
/// # Platform Notes
///
/// - Unix: Uses `O_NOFOLLOW` flag directly
/// - Windows: Uses `FILE_FLAG_OPEN_REPARSE_POINT` to avoid following symlinks
pub fn open_file_no_follow(path: &Path) -> Result<std::fs::File, std::io::Error> {
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(false)
            .custom_flags(libc::O_NOFOLLOW)
            .open(path)
    }

    #[cfg(windows)]
    {
        use std::os::windows::fs::OpenOptionsExt;

        // On Windows, use FILE_FLAG_OPEN_REPARSE_POINT to avoid following reparse points
        // This is similar to O_NOFOLLOW on Unix
        const FILE_FLAG_OPEN_REPARSE_POINT: u32 = 0x00200000;

        std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(false)
            .attributes(FILE_FLAG_OPEN_REPARSE_POINT)
            .open(path)
    }

    #[cfg(not(any(unix, windows)))]
    {
        // Fallback for other platforms - still try to avoid following symlinks
        // by checking the file type before opening
        if let Ok(metadata) = std::fs::symlink_metadata(path) {
            if metadata.file_type().is_symlink() {
                return Err(std::io::Error::new(
                    std::io::ErrorKind::PermissionDenied,
                    "Path is a symbolic link",
                ));
            }
        }
        std::fs::OpenOptions::new()
            .read(true)
            .write(true)
            .create(false)
            .open(path)
    }
}

/// Open a file for writing safely, handling both new and existing files securely.
///
/// This function handles the case where we need to create a new file:
/// 1. Verifies the parent directory exists and is canonical (not a symlink)
/// 2. Creates the file with restrictive permissions
///
/// For existing files, uses `open_file_no_follow` to ensure it's not a symlink.
pub fn open_file_for_write_secure(path: &Path) -> Result<std::fs::File, std::io::Error> {
    // First, check if the file exists
    if path.exists() {
        // File exists - use O_NOFOLLOW to prevent symlink attacks
        return open_file_no_follow(path);
    }

    // File doesn't exist - we need to check the parent directory
    let parent = path.parent().ok_or_else(|| {
        std::io::Error::new(
            std::io::ErrorKind::InvalidInput,
            "Path has no parent directory",
        )
    })?;

    // Canonicalize parent to resolve any symlinks in the path
    // This ensures we're creating the file in the intended location
    let canonical_parent = std::fs::canonicalize(parent).map_err(|e| {
        std::io::Error::new(
            std::io::ErrorKind::NotFound,
            format!("Parent directory cannot be resolved: {}", e),
        )
    })?;

    // Verify the parent is actually a directory
    let parent_metadata = std::fs::metadata(&canonical_parent)?;
    if !parent_metadata.is_dir() {
        return Err(std::io::Error::new(
            std::io::ErrorKind::PermissionDenied,
            "Parent path is not a directory",
        ));
    }

    // Reconstruct the full path with canonical parent
    let file_name = path.file_name().ok_or_else(|| {
        std::io::Error::new(std::io::ErrorKind::InvalidInput, "Path has no file name")
    })?;

    let canonical_path = canonical_parent.join(file_name);

    // Check again if the file exists now (possible race condition)
    if canonical_path.exists() {
        return open_file_no_follow(&canonical_path);
    }

    // Create the new file
    #[cfg(unix)]
    {
        use std::os::unix::fs::OpenOptionsExt;
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .mode(0o644) // Restrictive permissions for new files
            .open(&canonical_path)
    }

    #[cfg(not(unix))]
    {
        std::fs::OpenOptions::new()
            .write(true)
            .create(true)
            .truncate(true)
            .open(&canonical_path)
    }
}

/// Normalize a path for pattern matching by converting backslashes to forward slashes.
/// This allows patterns to use forward slashes and match against Windows paths.
fn normalize_path_separators(path: &str) -> String {
    path.replace('\\', "/")
}

/// Match a glob pattern against a resource path
///
/// Supports:
/// - `*` - matches everything
/// - `**/*` - matches everything (recursive)
/// - `*.ext` - matches files with extension
/// - `/path/*` - matches direct children of /path
/// - `/path/**` - matches all descendants of /path
/// - Exact string matches
///
/// # Platform-specific behavior
///
/// On macOS, `/tmp` is a symlink to `/private/tmp`. This function handles
/// both the original and canonicalized paths for common symlinks like `/tmp`.
///
/// On Windows, backslashes are normalized to forward slashes for pattern matching,
/// allowing patterns like `C:/Users/*` to match `C:\Users\file.txt`.
pub(crate) fn match_glob_pattern(pattern: &str, resource: &str) -> bool {
    // Normalize path separators for cross-platform matching
    let resource = normalize_path_separators(resource);

    // Universal wildcards
    if pattern == "*" || pattern == "**/*" {
        return true;
    }

    // File extension pattern: *.rs
    if pattern.starts_with("*.") && !pattern.contains('/') {
        let suffix = &pattern[1..]; // .rs
        return resource.ends_with(suffix);
    }

    // Try matching with the resource as-is first
    if match_pattern_internal(pattern, &resource) {
        return true;
    }

    // On macOS and some systems, /tmp is a symlink to /private/tmp
    // Handle common symlink patterns by checking both directions
    if resource.starts_with("/private/tmp/") && pattern.starts_with("/tmp/") {
        let alt_resource = resource.replacen("/private/tmp/", "/tmp/", 1);
        if match_pattern_internal(pattern, &alt_resource) {
            return true;
        }
    }

    if resource.starts_with("/tmp/") && pattern.starts_with("/private/tmp/") {
        let alt_resource = resource.replacen("/tmp/", "/private/tmp/", 1);
        if match_pattern_internal(pattern, &alt_resource) {
            return true;
        }
    }

    false
}

/// Internal pattern matching logic
fn match_pattern_internal(pattern: &str, resource: &str) -> bool {
    // Directory prefix patterns need careful handling
    // /tmp/* should match /tmp/file.txt but NOT /tmpx/file.txt
    if pattern.ends_with("/*") && !pattern.contains("**") {
        let prefix = &pattern[..pattern.len() - 1]; // /tmp/
        return resource.starts_with(prefix) && !resource[prefix.len()..].contains('/');
    }

    // Recursive directory pattern: /tmp/**
    if let Some(prefix) = pattern.strip_suffix("/**") {
        // pattern is like "/tmp/**", remove the "/**" to get "/tmp"
        // Remove "**" and the preceding "/"
        return resource.starts_with(prefix)
            && (resource.len() == prefix.len() || resource[prefix.len()..].starts_with('/'));
    }

    // Exact match
    resource == pattern
}

/// Global permission configuration
///
/// This struct manages both persistent whitelist rules and session-level grants.
/// It is designed to be shared across threads using Arc.
#[derive(Debug)]
pub struct PermissionConfig {
    /// Persistent whitelist rules (loaded from/saved to config file)
    whitelist: DashMap<String, PermissionRule>,
    /// Session-granted permissions that expire after a timeout
    session_grants: DashMap<PermissionType, Vec<SessionGrant>>,
    /// Default session grant duration (default: 30 minutes)
    session_grant_duration: Duration,
    /// Whether permission checks are enabled
    enabled: AtomicBool,
    /// Active permission mode controlling auto-approval behavior
    mode: RwLock<PermissionMode>,
}

impl Default for PermissionConfig {
    fn default() -> Self {
        Self::new()
    }
}

impl PermissionConfig {
    /// Create a new permission config with default settings
    pub fn new() -> Self {
        Self {
            whitelist: DashMap::new(),
            session_grants: DashMap::new(),
            session_grant_duration: Duration::from_secs(30 * 60), // 30 minutes
            enabled: AtomicBool::new(true),
            mode: RwLock::new(PermissionMode::Default),
        }
    }

    /// Create a new permission config with specific settings
    pub fn with_settings(enabled: bool, session_duration: Duration) -> Self {
        Self {
            whitelist: DashMap::new(),
            session_grants: DashMap::new(),
            session_grant_duration: session_duration,
            enabled: AtomicBool::new(enabled),
            mode: RwLock::new(PermissionMode::Default),
        }
    }

    /// Check if permission checks are enabled
    pub fn is_enabled(&self) -> bool {
        self.enabled.load(Ordering::Relaxed)
    }

    /// Enable or disable permission checks
    pub fn set_enabled(&self, enabled: bool) {
        self.enabled.store(enabled, Ordering::Relaxed);
    }

    /// Get the current permission mode
    pub fn mode(&self) -> PermissionMode {
        *self.mode.read().expect("mode lock poisoned")
    }

    /// Set the permission mode
    pub fn set_mode(&self, mode: PermissionMode) {
        *self.mode.write().expect("mode lock poisoned") = mode;
    }

    /// Get the session grant duration
    pub fn session_grant_duration(&self) -> Duration {
        self.session_grant_duration
    }

    /// Set the session grant duration
    pub fn set_session_grant_duration(&mut self, duration: Duration) {
        self.session_grant_duration = duration;
    }

    /// Add a rule to the whitelist
    pub fn add_rule(&self, rule: PermissionRule) {
        let key = format!("{:?}:{}", rule.tool_type, rule.resource_pattern);
        self.whitelist.insert(key, rule);
    }

    /// Remove a rule from the whitelist
    pub fn remove_rule(&self, tool_type: PermissionType, resource_pattern: &str) -> bool {
        let key = format!("{:?}:{}", tool_type, resource_pattern);
        self.whitelist.remove(&key).is_some()
    }

    /// Get all whitelist rules
    pub fn get_rules(&self) -> Vec<PermissionRule> {
        self.whitelist
            .iter()
            .map(|entry| entry.value().clone())
            .filter(|rule| !rule.is_expired())
            .collect()
    }

    /// Clear all whitelist rules
    pub fn clear_rules(&self) {
        self.whitelist.clear();
    }

    /// Grant a permission for the current session
    pub fn grant_session_permission(
        &self,
        perm_type: PermissionType,
        resource_pattern: impl Into<String>,
    ) {
        let grant = SessionGrant::new(resource_pattern, self.session_grant_duration);

        self.session_grants
            .entry(perm_type)
            .and_modify(|grants| {
                grants.push(grant.clone());
            })
            .or_insert_with(|| vec![grant]);
    }

    /// Check if a permission is granted for the current session
    pub fn is_session_granted(&self, perm_type: PermissionType, resource: &str) -> bool {
        if let Some(grants) = self.session_grants.get(&perm_type) {
            // Clean up expired grants and check for matches
            let has_match = grants.iter().any(|grant| {
                if grant.is_expired() {
                    return false;
                }
                grant.matches(perm_type, resource)
            });

            if has_match {
                return true;
            }
        }
        false
    }

    /// Clear all session grants
    pub fn clear_session_grants(&self) {
        self.session_grants.clear();
    }

    /// Clean up expired session grants
    pub fn cleanup_expired_grants(&self) {
        for mut entry in self.session_grants.iter_mut() {
            entry.value_mut().retain(|grant| !grant.is_expired());
        }
    }

    /// Check if a permission is allowed by the whitelist
    pub fn is_whitelist_allowed(&self, perm_type: PermissionType, resource: &str) -> Option<bool> {
        // Check for explicit denies first, then explicit allows
        let mut allowed = None;

        for entry in self.whitelist.iter() {
            let rule = entry.value();
            if rule.matches(perm_type, resource) {
                if rule.allowed {
                    allowed = Some(true);
                } else {
                    // Explicit deny takes precedence
                    return Some(false);
                }
            }
        }

        allowed
    }

    /// Check if permission is required for an operation
    ///
    /// Returns true if the operation requires user confirmation
    pub fn needs_confirmation(&self, perm_type: PermissionType, resource: &str) -> bool {
        if !self.is_enabled() {
            return false;
        }

        // Check session grants first (fast path)
        if self.is_session_granted(perm_type, resource) {
            return false;
        }

        // Check whitelist
        match self.is_whitelist_allowed(perm_type, resource) {
            Some(true) => false, // Explicitly allowed
            Some(false) => true, // Explicitly denied (requires override)
            None => true,        // No rule found, require confirmation
        }
    }

    /// Convert to serializable format for persistence
    pub fn to_serializable(&self) -> SerializablePermissionConfig {
        SerializablePermissionConfig {
            whitelist: self.get_rules(),
            enabled: self.is_enabled(),
            session_grant_duration_secs: self.session_grant_duration.as_secs(),
            mode: Some(self.mode()),
        }
    }

    /// Load from serializable format
    pub fn from_serializable(config: SerializablePermissionConfig) -> Self {
        let whitelist = DashMap::new();
        for rule in config.whitelist {
            let key = format!("{:?}:{}", rule.tool_type, rule.resource_pattern);
            whitelist.insert(key, rule);
        }

        let mode = config.mode.unwrap_or_default();

        Self {
            whitelist,
            session_grants: DashMap::new(),
            session_grant_duration: Duration::from_secs(config.session_grant_duration_secs),
            enabled: AtomicBool::new(config.enabled),
            mode: RwLock::new(mode),
        }
    }

    /// Merge `other` into this config, returning a new `PermissionConfig`.
    ///
    /// `other` has higher priority: its whitelist rules replace conflicting ones from `self`,
    /// its mode overrides `self`'s, and its enabled flag takes precedence.
    /// Both allow and deny rules from both configs are preserved (deduplicated).
    pub fn merge(&self, other: &PermissionConfig) -> Self {
        let merged = Self::new();

        // Copy all rules from self (lower priority)
        for rule in self.get_rules() {
            let key = format!("{:?}:{}", rule.tool_type, rule.resource_pattern);
            merged.whitelist.insert(key, rule);
        }

        // Override/add rules from other (higher priority)
        for rule in other.get_rules() {
            let key = format!("{:?}:{}", rule.tool_type, rule.resource_pattern);
            merged.whitelist.insert(key, rule);
        }

        // Session grants from other (higher priority source)
        for entry in other.session_grants.iter() {
            let perm_type = entry.key();
            let grants = entry.value();
            merged.session_grants.insert(*perm_type, grants.clone());
        }

        // Mode from other takes precedence
        merged.set_mode(other.mode());

        // Enabled flag from other takes precedence
        merged.set_enabled(other.is_enabled());

        merged
    }
}
#[derive(Debug, Clone, Serialize, Deserialize)]
pub struct SerializablePermissionConfig {
    pub whitelist: Vec<PermissionRule>,
    pub enabled: bool,
    pub session_grant_duration_secs: u64,
    #[serde(default, skip_serializing_if = "Option::is_none")]
    pub mode: Option<PermissionMode>,
}

impl Default for SerializablePermissionConfig {
    fn default() -> Self {
        Self {
            whitelist: Vec::new(),
            enabled: true,
            session_grant_duration_secs: 30 * 60, // 30 minutes
            mode: None,
        }
    }
}

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_permission_type_description() {
        assert!(PermissionType::WriteFile
            .description()
            .contains("Write files"));
        assert!(PermissionType::ExecuteCommand
            .description()
            .contains("Execute"));
    }

    #[test]
    fn test_risk_level() {
        assert_eq!(PermissionType::WriteFile.risk_level(), RiskLevel::Medium);
        assert_eq!(PermissionType::ExecuteCommand.risk_level(), RiskLevel::High);
    }

    #[test]
    fn test_session_grant_with_real_paths() {
        let grant = SessionGrant::new("/tmp/*", Duration::from_secs(3600));
        // Use /tmp which exists on most systems
        assert!(grant.matches(PermissionType::WriteFile, "/tmp/test.txt"));
        assert!(!grant.matches(PermissionType::WriteFile, "/var/test.txt"));
    }

    #[test]
    fn test_permission_rule_matches() {
        // Test with paths that should exist
        let rule = PermissionRule::new(PermissionType::WriteFile, "*.rs", true);
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/test.rs"));
        assert!(!rule.matches(PermissionType::WriteFile, "/tmp/test.txt"));
        assert!(!rule.matches(PermissionType::ExecuteCommand, "/tmp/test.rs"));
    }

    #[test]
    fn test_permission_rule_directory_pattern() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "/tmp/*", true);
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/test.txt"));
        assert!(!rule.matches(PermissionType::WriteFile, "/var/test.txt"));
    }

    #[test]
    fn test_session_grant_matches() {
        let grant = SessionGrant::new("/tmp/*", Duration::from_secs(3600));
        // Test with /tmp which should exist
        assert!(grant.matches(PermissionType::WriteFile, "/tmp/test.txt"));
        assert!(!grant.matches(PermissionType::WriteFile, "/var/test.txt"));
    }

    #[test]
    fn test_permission_rule_rejects_traversal() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "/safe/**", true);
        assert!(!rule.matches(PermissionType::WriteFile, "/safe/../etc/passwd"));
    }

    #[test]
    fn test_session_grant_rejects_traversal() {
        let grant = SessionGrant::new("/safe/**", Duration::from_secs(3600));
        assert!(!grant.matches(PermissionType::WriteFile, "/safe/../etc/passwd"));
    }

    #[test]
    fn test_permission_rule_normalizes_slashes() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "/tmp/*", true);
        assert!(rule.matches(PermissionType::WriteFile, "/tmp//file.txt"));
    }

    #[test]
    fn test_permission_rule_rejects_relative_resource() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "*.rs", true);
        assert!(!rule.matches(PermissionType::WriteFile, "test.rs"));
    }

    #[test]
    fn test_config_needs_confirmation() {
        let config = PermissionConfig::new();

        // By default, should require confirmation
        assert!(config.needs_confirmation(PermissionType::WriteFile, "/tmp/test.txt"));

        // After granting session permission, should not require confirmation
        config.grant_session_permission(PermissionType::WriteFile, "/tmp/*");
        assert!(!config.needs_confirmation(PermissionType::WriteFile, "/tmp/test.txt"));
        assert!(config.needs_confirmation(PermissionType::WriteFile, "/var/test.txt"));
    }

    #[test]
    fn test_whitelist_allowed() {
        let config = PermissionConfig::new();
        config.add_rule(PermissionRule::new(PermissionType::WriteFile, "*.rs", true));

        assert_eq!(
            config.is_whitelist_allowed(PermissionType::WriteFile, "/tmp/test.rs"),
            Some(true)
        );
        assert_eq!(
            config.is_whitelist_allowed(PermissionType::WriteFile, "/tmp/test.txt"),
            None
        );
    }

    #[test]
    fn test_whitelist_denial() {
        let config = PermissionConfig::new();
        config.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "*.txt",
            false,
        ));

        assert_eq!(
            config.is_whitelist_allowed(PermissionType::WriteFile, "/tmp/test.txt"),
            Some(false)
        );
    }

    #[test]
    fn test_glob_pattern_exact_match() {
        assert!(match_glob_pattern("/tmp/test.txt", "/tmp/test.txt"));
        assert!(!match_glob_pattern("/tmp/test.txt", "/tmp/other.txt"));
    }

    #[test]
    fn test_glob_pattern_wildcard() {
        assert!(match_glob_pattern("*", "/any/path"));
        assert!(match_glob_pattern("**/*", "/any/path"));
    }

    #[test]
    fn test_glob_pattern_extension() {
        assert!(match_glob_pattern("*.rs", "test.rs"));
        assert!(match_glob_pattern("*.rs", "/path/to/test.rs"));
        assert!(!match_glob_pattern("*.rs", "test.txt"));
        assert!(!match_glob_pattern("*.rs", "/path/to/test.rs.txt"));
    }

    #[test]
    fn test_glob_pattern_directory_children() {
        // /tmp/* should match /tmp/file.txt but NOT /tmp/subdir/file.txt
        let rule = PermissionRule::new(PermissionType::WriteFile, "/tmp/*", true);
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/test.txt"));
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/file.rs"));
        assert!(!rule.matches(PermissionType::WriteFile, "/tmp/subdir/file.txt"));
        assert!(!rule.matches(PermissionType::WriteFile, "/tmpx/file.txt"));
    }

    #[test]
    fn test_glob_pattern_recursive() {
        // /tmp/** should match all descendants
        assert!(match_glob_pattern("/tmp/**", "/tmp/file.txt"));
        assert!(match_glob_pattern("/tmp/**", "/tmp/subdir/file.txt"));
        assert!(match_glob_pattern("/tmp/**", "/tmp/a/b/c/d.txt"));
        assert!(!match_glob_pattern("/tmp/**", "/tmpx/file.txt"));
    }

    #[test]
    fn test_glob_pattern_edge_cases() {
        // Ensure /tmp/* does NOT match /tmpx/ (boundary check)
        assert!(!match_glob_pattern("/tmp/*", "/tmpx/file.txt"));

        // Ensure directory patterns work correctly
        assert!(match_glob_pattern("/home/user/*", "/home/user/file.txt"));
        assert!(!match_glob_pattern("/home/user/*", "/home/user2/file.txt"));
    }

    #[test]
    fn test_non_path_resources_http_domains() {
        // HTTP domain permissions should match domains in URLs
        let rule = PermissionRule::new(PermissionType::HttpRequest, "api.example.com", true);
        // Exact match should work
        assert!(rule.matches(PermissionType::HttpRequest, "api.example.com"));
        // Different domain should not match
        assert!(!rule.matches(PermissionType::HttpRequest, "other.example.com"));
        // Note: Subdomain matching and full URL extraction are handled at the call site
        // in tool_permissions.rs using extract_domain_from_url
    }

    #[test]
    fn test_non_path_resources_commands() {
        // Command permissions should match command prefix
        let rule = PermissionRule::new(PermissionType::ExecuteCommand, "npm", true);
        assert!(rule.matches(PermissionType::ExecuteCommand, "npm"));
        // Different command should not match
        assert!(!rule.matches(PermissionType::ExecuteCommand, "yarn"));
        // Note: "npm install" matching would need prefix matching, which is current behavior
        // but the test expectation was wrong
    }

    #[test]
    fn test_non_path_resources_session_ids() {
        // Session ID permissions should match exactly
        let grant = SessionGrant::new("session_abc123", Duration::from_secs(3600));
        assert!(grant.matches(PermissionType::TerminalSession, "session_abc123"));
        assert!(!grant.matches(PermissionType::TerminalSession, "session_xyz789"));
    }

    #[test]
    fn test_permission_rule_expiration() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "/tmp/*", true)
            .with_expiration(chrono::Utc::now() - chrono::Duration::seconds(1)); // Expired

        assert!(!rule.matches(PermissionType::WriteFile, "/tmp/test.txt"));
    }

    #[test]
    fn test_session_grant_expiration() {
        let grant = SessionGrant::new("/tmp/*", Duration::from_secs(0)); // Immediately expired

        // Wait a bit to ensure expiration
        std::thread::sleep(std::time::Duration::from_millis(10));

        assert!(!grant.matches(PermissionType::WriteFile, "/tmp/test.txt"));
    }

    #[test]
    fn test_empty_strings() {
        // Empty pattern should not match anything
        let rule = PermissionRule::new(PermissionType::WriteFile, "", true);
        assert!(!rule.matches(PermissionType::WriteFile, "/tmp/test.txt"));

        // Non-empty pattern should not match empty resource
        assert!(!rule.matches(PermissionType::WriteFile, ""));
    }

    #[test]
    fn test_special_characters_in_paths() {
        // Paths with special characters should be handled correctly
        let rule = PermissionRule::new(PermissionType::WriteFile, "/tmp/*", true);
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/file-with-dash.txt"));
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/file_with_underscore.txt"));
        assert!(rule.matches(PermissionType::WriteFile, "/tmp/file.with.dots.txt"));
    }

    #[test]
    fn test_traversal_variants() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "/safe/*", true);

        // All these should be rejected
        assert!(!rule.matches(PermissionType::WriteFile, "/safe/../etc/passwd"));
        assert!(!rule.matches(PermissionType::WriteFile, "/safe/./etc/passwd"));
        assert!(!rule.matches(PermissionType::WriteFile, "/safe/subdir/../../etc/passwd"));
        assert!(!rule.matches(PermissionType::WriteFile, "/safe//etc/passwd")); // Double slash
    }

    #[test]
    fn test_has_path_traversal() {
        // Test the helper function directly
        assert!(has_path_traversal("../etc/passwd"));
        assert!(has_path_traversal("/safe/../etc/passwd"));
        // Note: "./" is CurrentDir, not ParentDir, so it's not considered traversal
        assert!(!has_path_traversal("/safe/./etc/passwd"));
        assert!(!has_path_traversal("/safe/etc/passwd"));
    }

    #[test]
    fn test_wildcard_matches_anything() {
        // Wildcard patterns should match any resource
        assert!(match_glob_pattern("*", "anything"));
        assert!(match_glob_pattern("*", "/any/path"));
        assert!(match_glob_pattern("**/*", "/any/deep/path"));
        assert!(match_glob_pattern("*", "api.example.com"));
        assert!(match_glob_pattern("*", "C:/Windows/file.txt"));
    }

    #[test]
    fn test_windows_paths() {
        // Windows-style paths should work with basic normalization
        // On Unix, we test the normalization logic directly
        let normalized = normalize_path_basic("C:/Users/file.txt");
        assert_eq!(normalized, "C:/Users/file.txt");

        let normalized = normalize_path_basic("C:\\Users\\file.txt");
        assert_eq!(normalized, "C:/Users/file.txt");

        // Test that drive letter is preserved
        assert!(normalized.contains(':'));
        assert!(normalized.starts_with("C:/"));
    }

    #[test]
    fn test_permission_type_mismatch() {
        let rule = PermissionRule::new(PermissionType::WriteFile, "/tmp/*", true);

        // Should not match if permission types don't match
        assert!(!rule.matches(PermissionType::ExecuteCommand, "/tmp/test.txt"));
        assert!(!rule.matches(PermissionType::HttpRequest, "/tmp/test.txt"));
    }

    #[test]
    fn test_config_enabled_disabled() {
        let config = PermissionConfig::new();

        // By default, enabled
        assert!(config.is_enabled());

        // Should require confirmation when enabled
        assert!(config.needs_confirmation(PermissionType::WriteFile, "/tmp/test.txt"));

        // Disable checks
        config.set_enabled(false);
        assert!(!config.is_enabled());

        // Should not require confirmation when disabled
        assert!(!config.needs_confirmation(PermissionType::WriteFile, "/tmp/test.txt"));
    }

    // TOCTOU Protection Tests
    #[test]
    fn test_path_symlink_switch_blocked() {
        use std::io::Write;

        // Create a temporary directory for testing
        let temp_dir = std::env::temp_dir().join(format!("toctou_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        // Create allowed directory
        let allowed_dir = temp_dir.join("allowed");
        std::fs::create_dir_all(&allowed_dir).unwrap();

        // Create a file in the allowed directory
        let test_file = allowed_dir.join("test.txt");
        {
            let mut file = std::fs::File::create(&test_file).unwrap();
            file.write_all(b"original content").unwrap();
        }

        // Verify we can open the real file
        assert!(open_file_no_follow(&test_file).is_ok());

        // Create a symlink pointing outside the allowed directory
        let symlink_file = allowed_dir.join("symlink.txt");
        let outside_file = temp_dir.join("outside.txt");
        {
            let mut file = std::fs::File::create(&outside_file).unwrap();
            file.write_all(b"sensitive content").unwrap();
        }

        #[cfg(unix)]
        {
            use std::os::unix::fs::symlink;
            symlink(&outside_file, &symlink_file).unwrap();

            // Attempting to open the symlink should fail
            let result = open_file_no_follow(&symlink_file);
            assert!(result.is_err(), "Should block opening symlink");

            // Verify we can't read the symlink target's content
            if let Err(e) = result {
                // On macOS (errno 62: Too many levels of symbolic links)
                // On Linux (errno 40: Too many symbolic links)
                // Both indicate the symlink was blocked
                let is_blocked = e.kind() == std::io::ErrorKind::PermissionDenied
                    || e.kind() == std::io::ErrorKind::InvalidInput
                    || e.kind() == std::io::ErrorKind::Other
                    || e.raw_os_error() == Some(62)  // macOS ELOOP
                    || e.raw_os_error() == Some(40); // Linux ELOOP
                assert!(is_blocked, "Expected symlink to be blocked, got: {:?}", e);
            }
        }

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }

    #[test]
    fn test_path_traversal_blocked() {
        // Test path traversal in various forms
        let test_cases = vec![
            "/safe/../etc/passwd",
            "/safe/subdir/../../etc/passwd",
            "/safe/./../etc/passwd",
        ];

        for path in test_cases {
            let config = PermissionConfig::new();
            config.add_rule(PermissionRule::new(
                PermissionType::WriteFile,
                "/safe/*",
                true,
            ));

            // All traversal attempts should be rejected
            assert!(
                config.needs_confirmation(PermissionType::WriteFile, path),
                "Path traversal should require confirmation (be blocked by default): {}",
                path
            );
        }
    }

    #[test]
    fn test_path_within_allowed_directory() {
        let config = PermissionConfig::new();
        // Use ** for recursive matching to include subdirectories
        config.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/allowed/**",
            true,
        ));

        // Files within allowed directory should be allowed
        assert!(!config.needs_confirmation(PermissionType::WriteFile, "/tmp/allowed/file.txt"));
        assert!(
            !config.needs_confirmation(PermissionType::WriteFile, "/tmp/allowed/subdir/file.txt")
        );

        // Files outside should require confirmation
        assert!(config.needs_confirmation(PermissionType::WriteFile, "/tmp/other/file.txt"));
        assert!(config.needs_confirmation(PermissionType::WriteFile, "/etc/passwd"));
    }

    #[test]
    fn test_secure_file_create_parent_validation() {
        use std::io::Write;

        let temp_dir =
            std::env::temp_dir().join(format!("secure_create_test_{}", std::process::id()));
        let _ = std::fs::remove_dir_all(&temp_dir);
        std::fs::create_dir_all(&temp_dir).unwrap();

        let allowed_dir = temp_dir.join("allowed");
        std::fs::create_dir_all(&allowed_dir).unwrap();

        // Creating a file in an allowed directory should work
        let new_file = allowed_dir.join("new_file.txt");
        let result = open_file_for_write_secure(&new_file);
        assert!(
            result.is_ok(),
            "Should be able to create file in allowed directory"
        );

        if let Ok(mut file) = result {
            file.write_all(b"test content").unwrap();
            drop(file);

            // Verify file was created
            assert!(new_file.exists());
            let content = std::fs::read_to_string(&new_file).unwrap();
            assert_eq!(content, "test content");
        }

        // Creating in non-existent directory should fail
        let bad_path = temp_dir.join("nonexistent_dir").join("file.txt");
        let result = open_file_for_write_secure(&bad_path);
        assert!(result.is_err(), "Should fail when parent doesn't exist");

        // Cleanup
        let _ = std::fs::remove_dir_all(&temp_dir);
    }
}

#[cfg(test)]
mod integration_tests {
    use super::*;

    #[test]
    fn test_whitelist_with_session_grants() {
        let config = PermissionConfig::new();

        // Add whitelist rule
        config.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/*",
            true,
        ));

        // Whitelist allows, should not require confirmation
        assert!(!config.needs_confirmation(PermissionType::WriteFile, "/tmp/test.txt"));

        // Outside whitelist, requires confirmation
        assert!(config.needs_confirmation(PermissionType::WriteFile, "/home/test.txt"));

        // Grant session permission for different path
        config.grant_session_permission(PermissionType::WriteFile, "/home/*");

        // Now /home should not require confirmation (if /home exists)
        // Note: This depends on whether /home exists on the system
    }

    #[test]
    fn test_multiple_session_grants() {
        let config = PermissionConfig::new();

        // Grant multiple session permissions
        config.grant_session_permission(PermissionType::WriteFile, "/tmp/*");
        config.grant_session_permission(PermissionType::WriteFile, "/home/*");

        // Both should work if paths exist
        assert!(!config.needs_confirmation(PermissionType::WriteFile, "/tmp/test.txt"));
        // Note: /home may not exist on all systems
    }

    #[test]
    fn test_deny_overrides_allow() {
        let config = PermissionConfig::new();

        // Add allow rule
        config.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/*",
            true,
        ));

        // Add deny rule (should override allow)
        config.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/sensitive.txt",
            false,
        ));

        // Normal files in /tmp should be allowed
        assert_eq!(
            config.is_whitelist_allowed(PermissionType::WriteFile, "/tmp/test.txt"),
            Some(true)
        );

        // Sensitive file should be denied
        assert_eq!(
            config.is_whitelist_allowed(PermissionType::WriteFile, "/tmp/sensitive.txt"),
            Some(false)
        );
    }

    #[test]
    fn test_non_path_permissions_integration() {
        let config = PermissionConfig::new();

        // HTTP domain permission
        config.grant_session_permission(PermissionType::HttpRequest, "api.example.com");
        assert!(!config.needs_confirmation(PermissionType::HttpRequest, "api.example.com"));

        // Command permission
        config.grant_session_permission(PermissionType::ExecuteCommand, "npm");
        assert!(!config.needs_confirmation(PermissionType::ExecuteCommand, "npm"));
    }

    #[test]
    fn test_permission_mode_default_is_default() {
        let config = PermissionConfig::new();
        assert_eq!(config.mode(), PermissionMode::Default);
    }

    #[test]
    fn test_permission_mode_set_and_get() {
        let config = PermissionConfig::new();
        config.set_mode(PermissionMode::Plan);
        assert_eq!(config.mode(), PermissionMode::Plan);
        config.set_mode(PermissionMode::BypassPermissions);
        assert_eq!(config.mode(), PermissionMode::BypassPermissions);
    }

    #[test]
    fn test_permission_mode_serialize_roundtrip() {
        let mut serializable = SerializablePermissionConfig::default();
        assert!(serializable.mode.is_none());

        serializable.mode = Some(PermissionMode::Plan);
        let json = serde_json::to_string(&serializable).unwrap();
        assert!(json.contains("plan"));

        let deserialized: SerializablePermissionConfig = serde_json::from_str(&json).unwrap();
        assert_eq!(deserialized.mode, Some(PermissionMode::Plan));
    }

    #[test]
    fn test_permission_mode_backward_compat_no_mode() {
        // Old serialized format without mode field should deserialize to Default
        let json = r#"{"whitelist":[],"enabled":true,"session_grant_duration_secs":1800}"#;
        let deserialized: SerializablePermissionConfig = serde_json::from_str(json).unwrap();
        assert!(deserialized.mode.is_none());

        let config = PermissionConfig::from_serializable(deserialized);
        assert_eq!(config.mode(), PermissionMode::Default);
    }

    #[test]
    fn test_permission_config_merge() {
        let user = PermissionConfig::new();
        user.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/user/*",
            true,
        ));
        user.set_mode(PermissionMode::Default);

        let project = PermissionConfig::new();
        project.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/project/*",
            true,
        ));
        project.add_rule(PermissionRule::new(
            PermissionType::WriteFile,
            "/tmp/project/secret",
            false,
        ));
        project.set_mode(PermissionMode::AcceptEdits);

        let merged = user.merge(&project);

        // Project mode takes precedence
        assert_eq!(merged.mode(), PermissionMode::AcceptEdits);

        // Both user and project allow rules are present
        assert!(!merged.needs_confirmation(PermissionType::WriteFile, "/tmp/user/code.rs"));
        assert!(!merged.needs_confirmation(PermissionType::WriteFile, "/tmp/project/code.rs"));

        // Project deny rule overrides user allow
        assert!(merged.needs_confirmation(PermissionType::WriteFile, "/tmp/project/secret"));
    }

    #[test]
    fn test_permission_mode_description() {
        assert!(!PermissionMode::Default.description().is_empty());
        assert!(!PermissionMode::Plan.description().is_empty());
        assert!(!PermissionMode::AcceptEdits.description().is_empty());
        assert!(!PermissionMode::DontAsk.description().is_empty());
        assert!(!PermissionMode::BypassPermissions.description().is_empty());
    }
}