dotscope 0.6.0

A high-performance, cross-platform framework for analyzing and reverse engineering .NET PE executables
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
//! Individual security permissions in .NET Code Access Security.
//!
//! This module provides the [`Permission`] type, which represents individual security permissions
//! within .NET permission sets. Each permission corresponds to a specific .NET Framework security
//! class that defines access controls for system resources such as files, network, registry,
//! reflection capabilities, and other protected operations.
//!
//! # Architecture
//!
//! The .NET Code Access Security model uses strongly-typed permission classes to grant or restrict
//! access to system resources. The architecture follows a hierarchical structure:
//!
//! ```text
//! Permission Set
//! ├── Permission 1 (e.g., FileIOPermission)
//! │   ├── Class Name: System.Security.Permissions.FileIOPermission
//! │   ├── Assembly: mscorlib
//! │   └── Named Arguments: [Read="path", Write="path"]
//! ├── Permission 2 (e.g., SecurityPermission)
//! │   ├── Class Name: System.Security.Permissions.SecurityPermission
//! │   ├── Assembly: mscorlib
//! │   └── Named Arguments: [Flags=0x0002]
//! └── ...
//! ```
//!
//! Each permission encapsulates:
//! - **Class Identity**: Fully qualified type name and assembly
//! - **Configuration**: Named arguments defining specific access rules
//! - **Type Safety**: Strongly typed argument validation
//!
//! # Key Components
//!
//! ## Permission Classes
//! The .NET Framework provides numerous permission classes, each controlling specific resource access:
//!
//! ### File System Permissions
//! - **`FileIOPermission`**: Controls file system access (read, write, append, path discovery)
//! - **`IsolatedStoragePermission`**: Controls isolated storage access
//!
//! ### System Access Permissions
//! - **`SecurityPermission`**: Controls security-sensitive operations (unmanaged code, reflection)
//! - **`RegistryPermission`**: Controls Windows registry access
//! - **`EnvironmentPermission`**: Controls environment variable access
//!
//! ### Network and Communication
//! - **`SocketPermission`**: Controls network socket operations
//! - **`WebPermission`**: Controls HTTP web access
//! - **`DnsPermission`**: Controls DNS resolution
//!
//! ### Code Access Permissions
//! - **`ReflectionPermission`**: Controls reflection and code analysis capabilities
//! - **`FileDialogPermission`**: Controls file dialog operations
//! - **`UIPermission`**: Controls user interface operations
//!
//! ## Named Arguments Structure
//! Each permission can have multiple named arguments that configure its behavior:
//! - **Name**: Property or field identifier
//! - **Type**: Argument data type ([`crate::metadata::security::ArgumentType`])
//! - **Value**: Typed value ([`crate::metadata::security::ArgumentValue`])
//!
//! # Usage Examples
//!
//! ## File IO Permission Configuration
//!
//! ```rust
//! use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
//!
//! // Represents: [FileIOPermission(Read = "C:\\Data", Write = "C:\\Logs")]
//! let file_permission = Permission::new(
//!     "System.Security.Permissions.FileIOPermission".to_string(),
//!     "mscorlib".to_string(),
//!     vec![
//!         NamedArgument::new(
//!             "Read".to_string(),
//!             ArgumentType::String,
//!             ArgumentValue::String("C:\\Data".to_string())
//!         ),
//!         NamedArgument::new(
//!             "Write".to_string(),
//!             ArgumentType::String,
//!             ArgumentValue::String("C:\\Logs".to_string())
//!         ),
//!     ]
//! );
//!
//! assert!(file_permission.is_file_io());
//! println!("Permission: {}", file_permission);
//! ```
//!
//! ## Security Permission with Flags
//!
//! ```rust
//! use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
//!
//! // Represents: [SecurityPermission(UnmanagedCode = true)]
//! let security_permission = Permission::new(
//!     "System.Security.Permissions.SecurityPermission".to_string(),
//!     "mscorlib".to_string(),
//!     vec![
//!         NamedArgument::new(
//!             "Flags".to_string(),
//!             ArgumentType::Int32,
//!             ArgumentValue::Int32(0x0002) // UnmanagedCode flag
//!         ),
//!     ]
//! );
//!
//! assert!(security_permission.is_security());
//! ```
//!
//! ## Permission Analysis and Introspection
//!
//! ```rust
//! use dotscope::metadata::security::Permission;
//!
//! # fn get_permission() -> Permission {
//! #     Permission::new(
//! #         "System.Security.Permissions.FileIOPermission".to_string(),
//! #         "mscorlib".to_string(),
//! #         vec![]
//! #     )
//! # }
//! let permission = get_permission();
//!
//! // Check permission type
//! if permission.is_file_io() {
//!     println!("This permission controls file access");
//!     
//!     // Check for specific arguments
//!     if let Some(read_arg) = permission.get_argument("Read") {
//!         println!("Read access granted to: {:?}", read_arg.value());
//!     }
//! }
//!
//! // Display full permission details
//! println!("Permission class: {}", permission.class_name);
//! println!("From assembly: {}", permission.assembly_name);
//! println!("Argument count: {}", permission.named_arguments.len());
//! ```
//!
//! ## Extracting File Paths from `FileIOPermission`
//!
//! ```rust,no_run
//! use dotscope::metadata::security::Permission;
//!
//! # fn get_file_permission() -> Permission {
//! #     Permission::new(
//! #         "System.Security.Permissions.FileIOPermission".to_string(),
//! #         "mscorlib".to_string(),
//! #         vec![]
//! #     )
//! # }
//! let permission = get_file_permission();
//!
//! if permission.is_file_io() {
//!     // Extract specific file access paths
//!     let read_paths = permission.get_file_read_paths();
//!     let write_paths = permission.get_file_write_paths();
//!     let discovery_paths = permission.get_file_path_discovery();
//!     
//!     println!("Read access: {:?}", read_paths);
//!     println!("Write access: {:?}", write_paths);
//!     println!("Path discovery: {:?}", discovery_paths);
//! }
//! ```
//!
//! # Integration
//!
//! Permissions integrate with the broader .NET security infrastructure:
//!
//! ## With Permission Sets
//! - Individual permissions are grouped into [`crate::metadata::security::PermissionSet`]
//! - Each permission set can contain multiple permissions of different types
//! - Permission sets define complete security policies for assemblies, types, or methods
//!
//! ## With Security Attributes
//! - Permissions are created from declarative security attributes in .NET metadata
//! - Custom attribute blobs are parsed to extract permission configurations
//! - Support both property and field-based argument specification
//!
//! ## With Assembly Analysis
//! - Used for security policy analysis and compliance checking
//! - Enable detection of privileged operations in .NET assemblies
//! - Support both static analysis and runtime security enforcement
//!
//! ## With Security Actions
//! - Permissions work with security actions like Demand, Assert, Deny, `PermitOnly`
//! - Each action modifies how the permission is enforced at runtime
//! - Actions determine whether permissions grant or restrict access
//!
//! # Binary Format
//!
//! Permissions are stored in `DeclSecurity` metadata using a custom binary format:
//! ```text
//! - Permission class name (string)
//! - Assembly name (string)  
//! - Named argument count (compressed integer)
//! - Named arguments array (see NamedArgument format)
//! ```
//!
//! The format is defined by the .NET Framework security infrastructure and follows
//! the custom attribute serialization specification.
//!
//! # Error Handling
//!
//! The module handles various error conditions related to permission processing:
//! - **Invalid Class Names**: Malformed or unrecognized permission class names
//! - **Assembly Resolution**: Missing or incorrect assembly references
//! - **Argument Validation**: Type mismatches or invalid argument configurations
//! - **Serialization Errors**: Corrupted binary data in security metadata
//!
//! Common error scenarios include:
//! - Permissions referencing custom assemblies not available during analysis
//! - Malformed argument blobs due to metadata corruption
//! - Version mismatches between permission classes and runtime expectations
//!
//! # Legacy Support
//!
//! Code Access Security was deprecated in .NET Framework 4.0 and removed in .NET Core.
//! This implementation primarily supports analysis of legacy .NET Framework assemblies
//! that use declarative security attributes.
//!
//! # Thread Safety
//!
//! [`Permission`] instances are immutable after creation and safe to share across threads.

use crate::metadata::security::{
    security_classes, ArgumentValue, NamedArgument, SecurityPermissionFlags,
};
use std::fmt;

/// Represents a .NET security permission within a permission set.
///
/// A Permission represents a single security permission in the .NET Code Access Security (CAS) system.
/// Each permission corresponds to a specific .NET Framework security class that defines access
/// controls for system resources (like file I/O, network access, reflection capabilities, etc.).
///
/// # Structure
///
/// Each permission contains:
/// - **Class Name**: The fully qualified .NET type name (e.g., "System.Security.Permissions.FileIOPermission")
/// - **Assembly Name**: The assembly containing the permission class (typically "mscorlib" or "System")
/// - **Named Arguments**: Collection of property/field configurations specific to the permission type
///
/// # Examples
///
/// ## Creating a File I/O Permission
///
/// ```rust
/// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
///
/// let permission = Permission::new(
///     "System.Security.Permissions.FileIOPermission".to_string(),
///     "mscorlib".to_string(),
///     vec![
///         NamedArgument::new(
///             "Read".to_string(),
///             ArgumentType::String,
///             ArgumentValue::String("C:\\Data".to_string())
///         ),
///     ]
/// );
///
/// assert!(permission.is_file_io());
/// ```
///
/// ## Analyzing Permission Properties
///
/// ```rust
/// # use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
/// # let permission = Permission::new(
/// #     "System.Security.Permissions.FileIOPermission".to_string(),
/// #     "mscorlib".to_string(),
/// #     vec![NamedArgument::new("Read".to_string(), ArgumentType::String, ArgumentValue::String("C:\\Data".to_string()))]
/// # );
/// // Check permission type
/// if permission.is_file_io() {
///     if let Some(paths) = permission.get_file_read_paths() {
///         println!("Read access to: {:?}", paths);
///     }
/// }
///
/// // Get specific arguments
/// if let Some(arg) = permission.get_argument("Read") {
///     println!("Read argument: {}", arg);
/// }
/// ```
///
/// # Binary Format Support
///
/// Permissions are parsed from `DeclSecurity` metadata using the binary format defined
/// in ECMA-335. The format includes the permission class name, assembly name, and
/// a variable number of named arguments with their types and values.
///
/// # Thread Safety
///
/// [`Permission`] instances are immutable after creation and safe to share across threads.
/// All accessor methods are read-only and do not modify the internal state.
///
/// * `class_name` - The full name of the permission class (e.g., "System.Security.Permissions.FileIOPermission")
/// * `assembly_name` - The assembly containing the permission class (e.g., "mscorlib")
/// * `named_arguments` - Collection of named property or field settings for this permission
///
/// # Notes
///
/// In older .NET Framework versions, these permissions were extensively used to control security.
/// While less common in modern .NET, they may still be encountered in legacy assemblies.
#[derive(Debug, Clone)]
pub struct Permission {
    /// The fully qualified .NET type name of the permission class.
    ///
    /// Examples include:
    /// - `"System.Security.Permissions.FileIOPermission"`
    /// - `"System.Security.Permissions.SecurityPermission"`
    /// - `"System.Security.Permissions.ReflectionPermission"`
    /// - `"System.Security.Permissions.RegistryPermission"`
    pub class_name: String,

    /// The assembly containing the permission class.
    ///
    /// Typically "mscorlib" for core .NET Framework permissions, but may be
    /// "System" or other assemblies for specialized permission types.
    pub assembly_name: String,

    /// Collection of named property/field arguments that configure this permission.
    ///
    /// Each named argument represents a property or field setting on the permission
    /// instance, such as file paths for `FileIOPermission` or flags for `SecurityPermission`.
    /// The collection may be empty for permissions that grant unrestricted access.
    pub named_arguments: Vec<NamedArgument>,
}

impl Permission {
    /// Creates a new permission instance.
    ///
    /// # Arguments
    ///
    /// * `class_name` - The fully qualified .NET type name of the permission class
    /// * `assembly_name` - The assembly containing the permission class
    /// * `named_arguments` - Collection of named property/field settings for this permission
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
    ///
    /// let permission = Permission::new(
    ///     "System.Security.Permissions.FileIOPermission".to_string(),
    ///     "mscorlib".to_string(),
    ///     vec![
    ///         NamedArgument::new(
    ///             "Read".to_string(),
    ///             ArgumentType::String,
    ///             ArgumentValue::String("C:\\Data".to_string())
    ///         ),
    ///     ]
    /// );
    /// ```
    #[must_use]
    pub fn new(
        class_name: String,
        assembly_name: String,
        named_arguments: Vec<NamedArgument>,
    ) -> Self {
        Permission {
            class_name,
            assembly_name,
            named_arguments,
        }
    }

    /// Checks if this is a `FileIOPermission`.
    ///
    /// `FileIOPermissions` control access to file system resources including read, write,
    /// append, and path discovery operations.
    ///
    /// # Returns
    ///
    /// `true` if this permission's class name matches the `FileIOPermission` type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::Permission;
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.FileIOPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![]
    /// # );
    /// if permission.is_file_io() {
    ///     println!("This permission controls file system access");
    /// }
    /// ```
    #[must_use]
    pub fn is_file_io(&self) -> bool {
        self.class_name == security_classes::FILE_IO_PERMISSION
    }

    /// Checks if this is a `SecurityPermission`.
    ///
    /// `SecurityPermissions` control access to security-sensitive operations such as
    /// executing unmanaged code, skipping verification, controlling threads, and
    /// other runtime security features.
    ///
    /// # Returns
    ///
    /// `true` if this permission's class name matches the `SecurityPermission` type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::Permission;
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.SecurityPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![]
    /// # );
    /// if permission.is_security() {
    ///     if let Some(flags) = permission.get_security_flags() {
    ///         println!("Security flags: {:?}", flags);
    ///     }
    /// }
    /// ```
    #[must_use]
    pub fn is_security(&self) -> bool {
        self.class_name == security_classes::SECURITY_PERMISSION
    }

    /// Checks if this is a `ReflectionPermission`.
    ///
    /// `ReflectionPermissions` control access to reflection capabilities such as
    /// emitting IL code, invoking non-public members, and accessing type information.
    ///
    /// # Returns
    ///
    /// `true` if this permission's class name matches the `ReflectionPermission` type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::Permission;
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.ReflectionPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![]
    /// # );
    /// if permission.is_reflection() {
    ///     println!("This permission controls reflection operations");
    /// }
    /// ```
    #[must_use]
    pub fn is_reflection(&self) -> bool {
        self.class_name == security_classes::REFLECTION_PERMISSION
    }

    /// Checks if this is a `RegistryPermission`.
    ///
    /// `RegistryPermissions` control access to Windows registry operations including
    /// reading and writing registry keys and values.
    ///
    /// # Returns
    ///
    /// `true` if this permission's class name matches the `RegistryPermission` type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::Permission;
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.RegistryPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![]
    /// # );
    /// if permission.is_registry() {
    ///     println!("This permission controls registry access");
    /// }
    /// ```
    #[must_use]
    pub fn is_registry(&self) -> bool {
        self.class_name == security_classes::REGISTRY_PERMISSION
    }

    /// Checks if this is a `UIPermission`.
    ///
    /// `UIPermissions` control access to user interface operations such as
    /// clipboard access, safe printing, and window manipulation.
    ///
    /// # Returns
    ///
    /// `true` if this permission's class name matches the `UIPermission` type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::Permission;
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.UIPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![]
    /// # );
    /// if permission.is_ui() {
    ///     println!("This permission controls UI operations");
    /// }
    /// ```
    #[must_use]
    pub fn is_ui(&self) -> bool {
        self.class_name == security_classes::UI_PERMISSION
    }

    /// Checks if this is an `EnvironmentPermission`.
    ///
    /// `EnvironmentPermissions` control access to environment variable operations
    /// including reading and writing system and user environment variables.
    ///
    /// # Returns
    ///
    /// `true` if this permission's class name matches the `EnvironmentPermission` type.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::Permission;
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.EnvironmentPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![]
    /// # );
    /// if permission.is_environment() {
    ///     println!("This permission controls environment variable access");
    /// }
    /// ```
    #[must_use]
    pub fn is_environment(&self) -> bool {
        self.class_name == security_classes::ENVIRONMENT_PERMISSION
    }

    /// Retrieves a named argument by name.
    ///
    /// Named arguments represent property or field assignments on the permission instance.
    /// Common argument names include "Read", "Write", "Unrestricted", "Flags", etc.
    ///
    /// # Arguments
    ///
    /// * `name` - The name of the argument to search for (case-sensitive)
    ///
    /// # Returns
    ///
    /// `Some(&NamedArgument)` if an argument with the specified name exists,
    /// `None` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.FileIOPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![NamedArgument::new("Read".to_string(), ArgumentType::String, ArgumentValue::String("C:\\Data".to_string()))]
    /// # );
    /// if let Some(read_arg) = permission.get_argument("Read") {
    ///     println!("Read argument: {}", read_arg);
    /// }
    ///
    /// assert!(permission.get_argument("NonExistent").is_none());
    /// ```
    #[must_use]
    pub fn get_argument(&self, name: &str) -> Option<&NamedArgument> {
        self.named_arguments.iter().find(|arg| arg.name == name)
    }

    /// Extracts file paths granted read access from a `FileIOPermission`.
    ///
    /// This method specifically looks for the "Read" argument in `FileIOPermissions`
    /// and extracts the file paths specified for read access. The paths can be
    /// specified as a single string or an array of strings.
    ///
    /// # Returns
    ///
    /// - `Some(Vec<String>)` containing the read paths if this is a `FileIOPermission` with a "Read" argument
    /// - `None` if this is not a `FileIOPermission` or has no "Read" argument
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
    ///
    /// # let permission = Permission::new(
    /// #     "System.Security.Permissions.FileIOPermission".to_string(),
    /// #     "mscorlib".to_string(),
    /// #     vec![NamedArgument::new("Read".to_string(), ArgumentType::String, ArgumentValue::String("C:\\Data".to_string()))]
    /// # );
    /// if let Some(paths) = permission.get_file_read_paths() {
    ///     for path in paths {
    ///         println!("Read access to: {}", path);
    ///     }
    /// }
    /// ```
    ///
    /// # Path Format
    ///
    /// The returned paths are exactly as specified in the permission metadata,
    /// which may include wildcards, UNC paths, or relative paths depending on
    /// how the permission was originally configured.
    #[must_use]
    pub fn get_file_read_paths(&self) -> Option<Vec<String>> {
        self.extract_file_io_paths("Read")
    }

    /// Extracts file paths granted write access from a `FileIOPermission`.
    ///
    /// This method specifically looks for the "Write" argument in `FileIOPermissions`
    /// and extracts the file paths specified for write access. The paths can be
    /// specified as a single string or an array of strings.
    ///
    /// # Returns
    ///
    /// - `Some(Vec<String>)` containing the write paths if this is a `FileIOPermission` with a "Write" argument
    /// - `None` if this is not a `FileIOPermission` or has no "Write" argument
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
    ///
    /// let permission = Permission::new(
    ///     "System.Security.Permissions.FileIOPermission".to_string(),
    ///     "mscorlib".to_string(),
    ///     vec![NamedArgument::new(
    ///         "Write".to_string(),
    ///         ArgumentType::String,
    ///         ArgumentValue::String("C:\\Logs".to_string())
    ///     )]
    /// );
    ///
    /// if let Some(paths) = permission.get_file_write_paths() {
    ///     for path in paths {
    ///         println!("Write access to: {}", path);
    ///     }
    /// }
    /// ```
    ///
    /// # Security Implications
    ///
    /// Write permissions are more sensitive than read permissions as they allow
    /// modification of the file system. The paths should be carefully validated
    /// in security-sensitive contexts.
    #[must_use]
    pub fn get_file_write_paths(&self) -> Option<Vec<String>> {
        self.extract_file_io_paths("Write")
    }

    /// Extracts file paths granted path discovery access from a `FileIOPermission`.
    ///
    /// Path discovery permission allows code to determine if a file or directory exists
    /// and to retrieve path information, but not to read the actual contents.
    /// This method looks for the "`PathDiscovery`" argument in `FileIOPermissions`.
    ///
    /// # Returns
    ///
    /// - `Some(Vec<String>)` containing the path discovery paths if this is a `FileIOPermission` with a "`PathDiscovery`" argument
    /// - `None` if this is not a `FileIOPermission` or has no "`PathDiscovery`" argument
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
    ///
    /// let permission = Permission::new(
    ///     "System.Security.Permissions.FileIOPermission".to_string(),
    ///     "mscorlib".to_string(),
    ///     vec![NamedArgument::new(
    ///         "PathDiscovery".to_string(),
    ///         ArgumentType::String,
    ///         ArgumentValue::String("C:\\Program Files".to_string())
    ///     )]
    /// );
    ///
    /// if let Some(paths) = permission.get_file_path_discovery() {
    ///     for path in paths {
    ///         println!("Path discovery access to: {}", path);
    ///     }
    /// }
    /// ```
    ///
    /// # Use Cases
    ///
    /// Path discovery is often used by applications that need to check for the
    /// existence of files or directories without actually reading their contents,
    /// such as installers or configuration utilities.
    #[must_use]
    pub fn get_file_path_discovery(&self) -> Option<Vec<String>> {
        self.extract_file_io_paths("PathDiscovery")
    }

    /// Internal helper to extract file paths from a `FileIOPermission` argument.
    ///
    /// This method consolidates the common logic for extracting file paths from
    /// various `FileIOPermission` arguments (Read, Write, PathDiscovery, Append).
    /// It handles both single string values and arrays of strings.
    ///
    /// # Arguments
    ///
    /// * `arg_name` - The name of the argument to extract paths from
    ///
    /// # Returns
    ///
    /// - `Some(Vec<String>)` if this is a `FileIOPermission` with the specified argument
    /// - `None` if this is not a `FileIOPermission` or the argument is missing/invalid
    fn extract_file_io_paths(&self, arg_name: &str) -> Option<Vec<String>> {
        if !self.is_file_io() {
            return None;
        }

        self.get_argument(arg_name)
            .and_then(|arg| match &arg.value {
                ArgumentValue::String(s) => Some(vec![s.clone()]),
                ArgumentValue::Array(arr) => {
                    let paths: Vec<String> = arr
                        .iter()
                        .filter_map(|value| {
                            if let ArgumentValue::String(s) = value {
                                Some(s.clone())
                            } else {
                                None
                            }
                        })
                        .collect();
                    Some(paths)
                }
                _ => None,
            })
    }

    /// Determines if this permission grants unrestricted access.
    ///
    /// Many .NET permission classes support an "Unrestricted" property that, when set to `true`,
    /// grants full access to the protected resource without any limitations. This effectively
    /// bypasses all specific permission checks for that resource type.
    ///
    /// # Returns
    ///
    /// `true` if the permission has an "Unrestricted" argument set to `true`, `false` otherwise.
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue};
    ///
    /// let unrestricted_permission = Permission::new(
    ///     "System.Security.Permissions.FileIOPermission".to_string(),
    ///     "mscorlib".to_string(),
    ///     vec![NamedArgument::new(
    ///         "Unrestricted".to_string(),
    ///         ArgumentType::Boolean,
    ///         ArgumentValue::Boolean(true)
    ///     )]
    /// );
    ///
    /// if unrestricted_permission.is_unrestricted() {
    ///     println!("This permission grants unrestricted access");
    /// }
    /// ```
    ///
    /// # Security Implications
    ///
    /// Unrestricted permissions are very powerful and should be carefully monitored
    /// in security audits, as they effectively disable all access controls for
    /// the associated resource type.
    #[must_use]
    pub fn is_unrestricted(&self) -> bool {
        if let Some(arg) = self.get_argument("Unrestricted") {
            if let ArgumentValue::Boolean(b) = &arg.value {
                return *b;
            }
        }
        false
    }

    /// Extracts security permission flags from a `SecurityPermission`.
    ///
    /// `SecurityPermissions` use a flags enumeration to specify which security-sensitive
    /// operations are allowed. This method parses the "Flags" argument and returns
    /// the corresponding [`crate::metadata::security::SecurityPermissionFlags`].
    ///
    /// # Returns
    ///
    /// - `Some(SecurityPermissionFlags)` if this is a `SecurityPermission` with valid flags
    /// - `None` if this is not a `SecurityPermission` or has no flags argument
    ///
    /// # Supported Flag Formats
    ///
    /// The method supports multiple flag formats commonly found in .NET metadata:
    /// - **Integer values**: Direct bitwise flag values
    /// - **Enum values**: Typed enum representations
    /// - **String values**: Comma-separated flag names (e.g., "Execution,UnmanagedCode")
    ///
    /// # Examples
    ///
    /// ```rust
    /// use dotscope::metadata::security::{Permission, NamedArgument, ArgumentType, ArgumentValue, SecurityPermissionFlags};
    ///
    /// let permission = Permission::new(
    ///     "System.Security.Permissions.SecurityPermission".to_string(),
    ///     "mscorlib".to_string(),
    ///     vec![NamedArgument::new(
    ///         "Flags".to_string(),
    ///         ArgumentType::Int32,
    ///         ArgumentValue::Int32(0x0002) // UnmanagedCode flag
    ///     )]
    /// );
    ///
    /// if let Some(flags) = permission.get_security_flags() {
    ///     if flags.contains(SecurityPermissionFlags::SECURITY_FLAG_UNSAFE_CODE) {
    ///         println!("This permission allows unsafe code execution");
    ///     }
    /// }
    /// ```
    ///
    /// # Common Security Flags
    ///
    /// - **Execution**: Allows code execution
    /// - **`UnmanagedCode`**: Allows calling unmanaged code
    /// - **`SkipVerification`**: Allows skipping IL verification
    /// - **Assertion**: Allows asserting permissions
    /// - **`ControlThread`**: Allows thread manipulation
    /// - **`ControlPolicy`**: Allows security policy control
    #[must_use]
    pub fn get_security_flags(&self) -> Option<SecurityPermissionFlags> {
        if !self.is_security() {
            return None;
        }

        if let Some(arg) = self.get_argument("Flags") {
            if let ArgumentValue::Int32(flags) = &arg.value {
                return Some(SecurityPermissionFlags::from_bits_truncate(*flags));
            } else if let ArgumentValue::Enum(_, flags) = &arg.value {
                return Some(SecurityPermissionFlags::from_bits_truncate(*flags));
            } else if let ArgumentValue::String(flags_str) = &arg.value {
                // Handle string representations of security flags
                return Some(Self::parse_flags_from_string(flags_str));
            }
        }
        None
    }

    /// Parses security permission flags from a string representation.
    ///
    /// This internal method handles the conversion of string-based flag specifications
    /// to the corresponding [`crate::metadata::security::SecurityPermissionFlags`] bitfield.
    /// It supports both individual flag names and the special "`AllFlags`" value.
    ///
    /// # Arguments
    ///
    /// * `flags_str` - A string containing comma-separated flag names or "`AllFlags`"
    ///
    /// # Returns
    ///
    /// A [`crate::metadata::security::SecurityPermissionFlags`] value representing the parsed flags.
    ///
    /// # Supported Flag Names
    ///
    /// The following flag names are recognized (case-sensitive):
    ///
    /// | Flag Name | Description | Maps To |
    /// |-----------|-------------|---------|
    /// | `"NoFlags"` | No permissions | Empty flags |
    /// | `"Execution"` | Basic code execution rights | `SECURITY_FLAG_EXECUTION` |
    /// | `"SkipVerification"` | Ability to skip IL verification | `SECURITY_FLAG_SKIP_VERIFICATION` |
    /// | `"Assertion"` | Permission assertion capabilities | `SECURITY_FLAG_ASSERTION` |
    /// | `"UnmanagedCode"` | Unmanaged code execution | `SECURITY_FLAG_UNSAFE_CODE` + `SECURITY_FLAG_SKIP_VERIFICATION` |
    /// | `"UnsafeCode"` | Direct unsafe code execution | `SECURITY_FLAG_UNSAFE_CODE` |
    /// | `"ControlAppDomains"` | Application domain control | `SECURITY_FLAG_CONTROL_APPDOMAINS` |
    /// | `"ControlPolicy"` | Security policy manipulation | `SECURITY_FLAG_CONTROL_POLICY` |
    /// | `"Serialization"` | Object serialization rights | `SECURITY_FLAG_SERIALIZATION` |
    /// | `"ControlThread"` | Thread lifecycle control | `SECURITY_FLAG_CONTROL_THREAD` |
    /// | `"ControlEvidence"` | Evidence manipulation | `SECURITY_FLAG_CONTROL_EVIDENCE` |
    /// | `"ControlPrincipal"` | Principal object control | `SECURITY_FLAG_CONTROL_PRINCIPAL` |
    /// | `"Infrastructure"` | Infrastructure services access | `SECURITY_FLAG_INFRASTRUCTURE` |
    /// | `"BindingRedirects"` | Assembly binding redirects | `SECURITY_FLAG_BINDING` |
    /// | `"Binding"` | Assembly binding control (legacy) | `SECURITY_FLAG_BINDING` |
    /// | `"Remoting"` | Remoting infrastructure access | `SECURITY_FLAG_REMOTING` |
    /// | `"RemotingConfiguration"` | Remoting configuration | `SECURITY_FLAG_REMOTING` |
    /// | `"ControlDomainPolicy"` | Domain-level policy control | `SECURITY_FLAG_CONTROL_DOMAIN` |
    /// | `"ControlDomain"` | Domain-level control (legacy) | `SECURITY_FLAG_CONTROL_DOMAIN` |
    /// | `"Reflection"` | Reflection capabilities | `SECURITY_FLAG_REFLECTION` |
    /// | `"AllFlags"` | All available permissions | All flags set |
    ///
    /// # UnmanagedCode Flag Combination Rationale
    ///
    /// The `"UnmanagedCode"` flag maps to both `SECURITY_FLAG_UNSAFE_CODE` and
    /// `SECURITY_FLAG_SKIP_VERIFICATION` because in the .NET Framework security model,
    /// executing unmanaged code inherently requires the ability to bypass IL verification.
    /// Unmanaged code operates outside the CLR's type safety guarantees, so granting
    /// unmanaged code permission implicitly grants verification skip permission.
    /// This combination reflects the actual security implications in .NET Framework 1.0-4.x.
    ///
    /// # Format Examples
    ///
    /// - `"Execution"` - Single flag
    /// - `"Execution, UnmanagedCode"` - Multiple flags (whitespace around commas is trimmed)
    /// - `"AllFlags"` - All permissions
    /// - `"NoFlags"` - Empty permission set
    ///
    /// # Unknown Flag Handling
    ///
    /// Unknown flag names are silently ignored to maintain compatibility with
    /// future .NET Framework versions that may introduce new flags. This is intentional:
    /// when analyzing assemblies built with newer .NET versions, we want to parse
    /// what we can rather than fail entirely.
    fn parse_flags_from_string(flags_str: &str) -> SecurityPermissionFlags {
        /// Lookup table for flag name to SecurityPermissionFlags mapping.
        /// Using a static array for O(n) lookup is acceptable here since:
        /// 1. The table is small (20 entries)
        /// 2. This function is not called in hot paths
        /// 3. Linear search has good cache locality for small arrays
        const FLAG_MAPPINGS: &[(&str, SecurityPermissionFlags)] = &[
            ("NoFlags", SecurityPermissionFlags::empty()),
            (
                "Execution",
                SecurityPermissionFlags::SECURITY_FLAG_EXECUTION,
            ),
            (
                "SkipVerification",
                SecurityPermissionFlags::SECURITY_FLAG_SKIP_VERIFICATION,
            ),
            (
                "Assertion",
                SecurityPermissionFlags::SECURITY_FLAG_ASSERTION,
            ),
            (
                "UnsafeCode",
                SecurityPermissionFlags::SECURITY_FLAG_UNSAFE_CODE,
            ),
            (
                "ControlAppDomain",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_APPDOMAINS,
            ),
            (
                "ControlAppDomains",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_APPDOMAINS,
            ),
            (
                "ControlPolicy",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_POLICY,
            ),
            (
                "SerializationFormatter",
                SecurityPermissionFlags::SECURITY_FLAG_SERIALIZATION,
            ),
            (
                "Serialization",
                SecurityPermissionFlags::SECURITY_FLAG_SERIALIZATION,
            ),
            (
                "ControlThread",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_THREAD,
            ),
            (
                "ControlEvidence",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_EVIDENCE,
            ),
            (
                "ControlPrincipal",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_PRINCIPAL,
            ),
            (
                "Infrastructure",
                SecurityPermissionFlags::SECURITY_FLAG_INFRASTRUCTURE,
            ),
            (
                "BindingRedirects",
                SecurityPermissionFlags::SECURITY_FLAG_BINDING,
            ),
            ("Binding", SecurityPermissionFlags::SECURITY_FLAG_BINDING),
            (
                "RemotingConfiguration",
                SecurityPermissionFlags::SECURITY_FLAG_REMOTING,
            ),
            ("Remoting", SecurityPermissionFlags::SECURITY_FLAG_REMOTING),
            (
                "ControlDomainPolicy",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_DOMAIN,
            ),
            (
                "ControlDomain",
                SecurityPermissionFlags::SECURITY_FLAG_CONTROL_DOMAIN,
            ),
            (
                "Reflection",
                SecurityPermissionFlags::SECURITY_FLAG_REFLECTION,
            ),
        ];

        let mut flags = SecurityPermissionFlags::empty();

        // Handle special "AllFlags" case
        if flags_str == "AllFlags" {
            return SecurityPermissionFlags::all();
        }

        // Parse comma-separated flag names
        for flag_name in flags_str.split(',').map(str::trim) {
            // Skip empty segments (e.g., from "Flag1,,Flag2")
            if flag_name.is_empty() {
                continue;
            }

            // Special case: UnmanagedCode maps to multiple flags
            // See documentation above for rationale
            if flag_name == "UnmanagedCode" {
                flags |= SecurityPermissionFlags::SECURITY_FLAG_UNSAFE_CODE;
                flags |= SecurityPermissionFlags::SECURITY_FLAG_SKIP_VERIFICATION;
                continue;
            }

            // Look up flag in the mapping table
            if let Some((_, flag_value)) = FLAG_MAPPINGS.iter().find(|(name, _)| *name == flag_name)
            {
                flags |= *flag_value;
            }
            // Unknown flags are silently ignored for forward compatibility
        }

        flags
    }
}

impl fmt::Display for Permission {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        write!(f, "{}(", self.class_name)?;

        for (i, arg) in self.named_arguments.iter().enumerate() {
            if i > 0 {
                write!(f, ", ")?;
            }
            write!(f, "{arg}")?;
        }

        write!(f, ")")
    }
}

#[cfg(test)]
mod tests {
    use super::*;
    use crate::metadata::security::{ArgumentType, ArgumentValue};

    fn create_test_permission() -> Permission {
        let named_args = vec![
            NamedArgument::new(
                "Read".to_string(),
                ArgumentType::String,
                ArgumentValue::String("C:\\Data".to_string()),
            ),
            NamedArgument::new(
                "Unrestricted".to_string(),
                ArgumentType::Boolean,
                ArgumentValue::Boolean(false),
            ),
        ];

        Permission::new(
            security_classes::FILE_IO_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        )
    }

    #[test]
    fn test_permission_new() {
        let permission = create_test_permission();
        assert_eq!(permission.class_name, security_classes::FILE_IO_PERMISSION);
        assert_eq!(permission.assembly_name, "mscorlib");
        assert_eq!(permission.named_arguments.len(), 2);
    }

    #[test]
    fn test_is_file_io() {
        let file_io_perm = create_test_permission();
        assert!(file_io_perm.is_file_io());

        let security_perm = Permission::new(
            security_classes::SECURITY_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );
        assert!(!security_perm.is_file_io());
    }

    #[test]
    fn test_is_security() {
        let security_perm = Permission::new(
            security_classes::SECURITY_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );
        assert!(security_perm.is_security());

        let file_io_perm = create_test_permission();
        assert!(!file_io_perm.is_security());
    }

    #[test]
    fn test_is_reflection() {
        let reflection_perm = Permission::new(
            security_classes::REFLECTION_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );
        assert!(reflection_perm.is_reflection());

        let file_io_perm = create_test_permission();
        assert!(!file_io_perm.is_reflection());
    }

    #[test]
    fn test_is_registry() {
        let registry_perm = Permission::new(
            security_classes::REGISTRY_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );
        assert!(registry_perm.is_registry());

        let file_io_perm = create_test_permission();
        assert!(!file_io_perm.is_registry());
    }

    #[test]
    fn test_is_ui() {
        let ui_perm = Permission::new(
            security_classes::UI_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );
        assert!(ui_perm.is_ui());

        let file_io_perm = create_test_permission();
        assert!(!file_io_perm.is_ui());
    }

    #[test]
    fn test_is_environment() {
        let env_perm = Permission::new(
            security_classes::ENVIRONMENT_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );
        assert!(env_perm.is_environment());

        let file_io_perm = create_test_permission();
        assert!(!file_io_perm.is_environment());
    }

    #[test]
    fn test_get_argument() {
        let permission = create_test_permission();

        let read_arg = permission.get_argument("Read");
        assert!(read_arg.is_some());
        assert_eq!(read_arg.unwrap().name, "Read");

        let nonexistent = permission.get_argument("NonExistent");
        assert!(nonexistent.is_none());
    }

    #[test]
    fn test_get_file_read_paths_string() {
        let permission = create_test_permission();
        let paths = permission.get_file_read_paths();
        assert!(paths.is_some());

        let paths = paths.unwrap();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0], "C:\\Data");
    }

    #[test]
    fn test_get_file_read_paths_array() {
        let named_args = vec![NamedArgument::new(
            "Read".to_string(),
            ArgumentType::Array(Box::new(ArgumentType::String)),
            ArgumentValue::Array(vec![
                ArgumentValue::String("C:\\Data1".to_string()),
                ArgumentValue::String("C:\\Data2".to_string()),
            ]),
        )];

        let permission = Permission::new(
            security_classes::FILE_IO_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        );

        let paths = permission.get_file_read_paths();
        assert!(paths.is_some());

        let paths = paths.unwrap();
        assert_eq!(paths.len(), 2);
        assert_eq!(paths[0], "C:\\Data1");
        assert_eq!(paths[1], "C:\\Data2");
    }

    #[test]
    fn test_get_file_read_paths_non_file_io() {
        let security_perm = Permission::new(
            security_classes::SECURITY_PERMISSION.to_string(),
            "mscorlib".to_string(),
            vec![],
        );

        let paths = security_perm.get_file_read_paths();
        assert!(paths.is_none());
    }

    #[test]
    fn test_get_file_write_paths() {
        let named_args = vec![NamedArgument::new(
            "Write".to_string(),
            ArgumentType::String,
            ArgumentValue::String("C:\\Logs".to_string()),
        )];

        let permission = Permission::new(
            security_classes::FILE_IO_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        );

        let paths = permission.get_file_write_paths();
        assert!(paths.is_some());

        let paths = paths.unwrap();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0], "C:\\Logs");
    }

    #[test]
    fn test_get_file_path_discovery() {
        let named_args = vec![NamedArgument::new(
            "PathDiscovery".to_string(),
            ArgumentType::String,
            ArgumentValue::String("C:\\Discovery".to_string()),
        )];

        let permission = Permission::new(
            security_classes::FILE_IO_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        );

        let paths = permission.get_file_path_discovery();
        assert!(paths.is_some());

        let paths = paths.unwrap();
        assert_eq!(paths.len(), 1);
        assert_eq!(paths[0], "C:\\Discovery");
    }

    #[test]
    fn test_is_unrestricted_true() {
        let named_args = vec![NamedArgument::new(
            "Unrestricted".to_string(),
            ArgumentType::Boolean,
            ArgumentValue::Boolean(true),
        )];

        let permission = Permission::new(
            security_classes::FILE_IO_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        );

        assert!(permission.is_unrestricted());
    }

    #[test]
    fn test_is_unrestricted_false() {
        let permission = create_test_permission();
        assert!(!permission.is_unrestricted());
    }

    #[test]
    fn test_get_security_flags() {
        let named_args = vec![NamedArgument::new(
            "Flags".to_string(),
            ArgumentType::Int32,
            ArgumentValue::Int32(0x1), // ASSERTION flag
        )];

        let permission = Permission::new(
            security_classes::SECURITY_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        );

        let flags = permission.get_security_flags();
        assert!(flags.is_some());

        let flags = flags.unwrap();
        assert!(flags.contains(SecurityPermissionFlags::SECURITY_FLAG_ASSERTION));
    }

    #[test]
    fn test_get_security_flags_enum() {
        let named_args = vec![NamedArgument::new(
            "Flags".to_string(),
            ArgumentType::Enum("SecurityPermissionFlag".to_string()),
            ArgumentValue::Enum("SecurityPermissionFlag".to_string(), 0x20), // UNSAFE_CODE
        )];

        let permission = Permission::new(
            security_classes::SECURITY_PERMISSION.to_string(),
            "mscorlib".to_string(),
            named_args,
        );

        let flags = permission.get_security_flags();
        assert!(flags.is_some());

        let flags = flags.unwrap();
        assert!(flags.contains(SecurityPermissionFlags::SECURITY_FLAG_UNSAFE_CODE));
    }

    #[test]
    fn test_get_security_flags_non_security() {
        let permission = create_test_permission();
        let flags = permission.get_security_flags();
        assert!(flags.is_none());
    }

    #[test]
    fn test_display_formatting() {
        let permission = create_test_permission();
        let formatted = format!("{permission}");

        assert!(formatted.starts_with(security_classes::FILE_IO_PERMISSION));
        assert!(formatted.contains("Read = \"C:\\Data\""));
        assert!(formatted.contains("Unrestricted = false"));
        assert!(formatted.contains("("));
        assert!(formatted.contains(")"));
    }

    #[test]
    fn test_display_formatting_empty_args() {
        let permission =
            Permission::new("TestPermission".to_string(), "mscorlib".to_string(), vec![]);

        let formatted = format!("{permission}");
        assert_eq!(formatted, "TestPermission()");
    }

    #[test]
    fn test_clone() {
        let original = create_test_permission();
        let cloned = original.clone();

        assert_eq!(cloned.class_name, original.class_name);
        assert_eq!(cloned.assembly_name, original.assembly_name);
        assert_eq!(cloned.named_arguments.len(), original.named_arguments.len());
    }

    #[test]
    fn test_debug_formatting() {
        let permission = create_test_permission();
        let debug_str = format!("{permission:?}");

        assert!(debug_str.contains("Permission"));
        assert!(debug_str.contains(security_classes::FILE_IO_PERMISSION));
    }
}