mockforge-plugin-loader 0.3.148

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

use super::*;
use std::collections::HashSet;
use std::path::Path;

// Import types from plugin core
use mockforge_plugin_core::{
    FilesystemPermissions, NetworkPermissions, PluginCapabilities, PluginId, PluginManifest,
    PluginVersion, ResourceLimits,
};

// WASM parsing
use wasmparser::{Parser, Payload};

// Cryptography
use ring::signature;

// Path expansion
use shellexpand;

// Encoding
use base64::{engine::general_purpose, Engine as _};
use hex;

// JSON serialization
use serde_json;

/// Plugin signature information
#[derive(Debug, Clone)]
struct PluginSignature {
    algorithm: String,
    signature: Vec<u8>,
    key_id: String,
}

/// Plugin validator
pub struct PluginValidator {
    /// Loader configuration
    config: PluginLoaderConfig,
    /// Security policies
    security_policies: SecurityPolicies,
}

impl PluginValidator {
    /// Create a new plugin validator
    pub fn new(config: PluginLoaderConfig) -> Self {
        Self {
            config,
            security_policies: SecurityPolicies::default(),
        }
    }

    /// Validate plugin manifest
    pub async fn validate_manifest(&self, manifest: &PluginManifest) -> LoaderResult<()> {
        let mut errors = Vec::new();

        // Validate basic manifest structure
        if let Err(validation_error) = manifest.validate() {
            errors.push(PluginLoaderError::manifest(validation_error));
        }

        // Validate security policies
        if let Err(e) = self.security_policies.validate_manifest(manifest) {
            errors.push(e);
        }

        // Validate plugin dependencies
        let mut visited = HashSet::new();
        visited.insert(manifest.info.id.clone());
        if let Err(e) = self
            .validate_dependencies(&manifest.info.id, &manifest.dependencies, &mut visited)
            .await
        {
            errors.push(e);
        }

        if errors.is_empty() {
            Ok(())
        } else {
            Err(PluginLoaderError::validation(format!(
                "Manifest validation failed with {} errors: {}",
                errors.len(),
                errors.into_iter().map(|e| e.to_string()).collect::<Vec<_>>().join(", ")
            )))
        }
    }

    /// Validate plugin capabilities
    pub fn validate_capabilities(&self, capability_names: &[String]) -> LoaderResult<()> {
        // Convert string capability names to PluginCapabilities struct
        let capabilities = PluginCapabilities {
            network: NetworkPermissions::default(),
            filesystem: FilesystemPermissions::default(),
            resources: ResourceLimits::default(),
            custom: capability_names
                .iter()
                .map(|name| (name.clone(), serde_json::Value::Bool(true)))
                .collect(),
        };
        self.security_policies.validate_capabilities(&capabilities)
    }

    /// Validate WebAssembly file
    pub async fn validate_wasm_file(&self, wasm_path: &Path) -> LoaderResult<()> {
        // Check file exists and is readable
        if !wasm_path.exists() {
            return Err(PluginLoaderError::fs("WASM file does not exist".to_string()));
        }

        let metadata = tokio::fs::metadata(wasm_path)
            .await
            .map_err(|e| PluginLoaderError::fs(format!("Cannot read WASM file metadata: {}", e)))?;

        if !metadata.is_file() {
            return Err(PluginLoaderError::fs("WASM path is not a file".to_string()));
        }

        // Check file size limits
        let file_size = metadata.len();
        if file_size > self.security_policies.max_wasm_file_size {
            return Err(PluginLoaderError::security(format!(
                "WASM file too large: {} bytes (max: {} bytes)",
                file_size, self.security_policies.max_wasm_file_size
            )));
        }

        // Validate WASM module structure
        self.validate_wasm_module(wasm_path).await?;

        Ok(())
    }

    /// Validate plugin file (complete plugin directory)
    pub async fn validate_plugin_file(&self, plugin_path: &Path) -> LoaderResult<PluginManifest> {
        if !plugin_path.exists() {
            return Err(PluginLoaderError::fs("Plugin path does not exist".to_string()));
        }

        if !plugin_path.is_dir() {
            return Err(PluginLoaderError::fs("Plugin path must be a directory".to_string()));
        }

        // Find manifest file
        let manifest_path = plugin_path.join("plugin.yaml");
        if !manifest_path.exists() {
            return Err(PluginLoaderError::manifest("plugin.yaml not found".to_string()));
        }

        // Load and validate manifest
        let manifest = PluginManifest::from_file(&manifest_path)
            .map_err(|e| PluginLoaderError::manifest(format!("Failed to load manifest: {}", e)))?;

        // Validate manifest
        self.validate_manifest(&manifest).await?;

        // Check for WASM file
        let wasm_files: Vec<_> = std::fs::read_dir(plugin_path)
            .map_err(|e| PluginLoaderError::fs(format!("Cannot read plugin directory: {}", e)))?
            .filter_map(|entry| entry.ok())
            .map(|entry| entry.path())
            .filter(|path| path.extension().is_some_and(|ext| ext == "wasm"))
            .collect();

        if wasm_files.is_empty() {
            return Err(PluginLoaderError::load(
                "No WebAssembly file found in plugin directory".to_string(),
            ));
        }

        if wasm_files.len() > 1 {
            return Err(PluginLoaderError::load(
                "Multiple WebAssembly files found in plugin directory".to_string(),
            ));
        }

        // Validate WASM file (unless skipped for testing)
        if !self.config.skip_wasm_validation {
            self.validate_wasm_file(&wasm_files[0]).await?;
        }

        Ok(manifest)
    }

    /// Validate plugin dependencies
    async fn validate_dependencies(
        &self,
        current_plugin_id: &PluginId,
        dependencies: &std::collections::HashMap<mockforge_plugin_core::PluginId, PluginVersion>,
        visited: &mut HashSet<PluginId>,
    ) -> LoaderResult<()> {
        for (plugin_id, version) in dependencies {
            // Check for circular dependencies using DFS
            if self.would_create_circular_dependency(current_plugin_id, plugin_id, visited) {
                return Err(PluginLoaderError::ValidationError {
                    message: format!(
                        "Circular dependency detected: '{}' -> '{}'",
                        current_plugin_id.0, plugin_id.0
                    ),
                });
            }

            // Validate dependency ID format
            if plugin_id.0.is_empty() {
                return Err(PluginLoaderError::ValidationError {
                    message: "Dependency plugin ID cannot be empty".to_string(),
                });
            }

            if plugin_id.0.len() > 100 {
                return Err(PluginLoaderError::ValidationError {
                    message: format!(
                        "Dependency plugin ID '{}' is too long (max 100 characters)",
                        plugin_id.0
                    ),
                });
            }

            // Validate version requirements
            if version.major == 0 && version.minor == 0 && version.patch == 0 {
                tracing::warn!("Dependency '{}' specifies version 0.0.0 which may indicate development/testing", plugin_id.0);
            }

            // Check for potentially problematic dependency patterns
            if plugin_id.0.contains("..") || plugin_id.0.contains("/") || plugin_id.0.contains("\\")
            {
                return Err(PluginLoaderError::SecurityViolation {
                    violation: format!(
                        "Dependency plugin ID '{}' contains potentially unsafe characters",
                        plugin_id.0
                    ),
                });
            }

            // Future enhancements would check:
            // - If dependency is installed and available
            // - Version compatibility with installed versions
            // - API compatibility
            // - Security status and known vulnerabilities
        }

        Ok(())
    }

    /// Validate a dependency version requirement
    ///
    /// Check if adding this dependency would create a circular dependency
    fn would_create_circular_dependency(
        &self,
        current_plugin_id: &PluginId,
        dependency_id: &PluginId,
        visited: &mut HashSet<PluginId>,
    ) -> bool {
        // Check for direct self-dependency
        if dependency_id == current_plugin_id {
            return true;
        }

        // Check if this dependency creates a cycle in the current validation path
        // Note: Full cycle detection would require loading dependency manifests
        // and recursively validating their dependencies. This is a simplified check
        // that prevents obvious cycles during manifest validation.

        visited.contains(dependency_id)
    }

    /// Validate WebAssembly module structure
    async fn validate_wasm_module(&self, wasm_path: &Path) -> LoaderResult<()> {
        // Load the WASM module to validate its structure
        let module = wasmtime::Module::from_file(&wasmtime::Engine::default(), wasm_path)
            .map_err(|e| PluginLoaderError::wasm(format!("Invalid WASM module: {}", e)))?;

        // Validate module against security policies
        self.security_policies.validate_wasm_module(&module)?;

        Ok(())
    }

    /// Check if plugin is signed (if signing is required)
    pub async fn validate_plugin_signature(
        &self,
        plugin_path: &Path,
        manifest: &PluginManifest,
    ) -> LoaderResult<()> {
        // Check if signature validation is required
        if self.config.allow_unsigned {
            return Ok(());
        }

        // Look for signature file alongside the plugin
        let sig_path = plugin_path.with_extension("sig");
        if !sig_path.exists() {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!(
                    "Plugin '{}' requires a signature but none was found",
                    manifest.info.id.0
                ),
            });
        }

        // Read signature file
        let signature_data =
            std::fs::read(&sig_path).map_err(|e| PluginLoaderError::ValidationError {
                message: format!("Failed to read signature file: {}", e),
            })?;

        // Parse signature (assuming it's a simple format for now)
        let signature = self.parse_signature(&signature_data)?;

        // Read plugin data for verification
        let plugin_data =
            std::fs::read(plugin_path).map_err(|e| PluginLoaderError::ValidationError {
                message: format!("Failed to read plugin file: {}", e),
            })?;

        // Verify signature against trusted keys
        self.verify_signature(&plugin_data, &signature, manifest).await?;

        Ok(())
    }

    /// Parse signature data
    fn parse_signature(&self, data: &[u8]) -> Result<PluginSignature, PluginLoaderError> {
        // Parse signature in JSON format for better structure and extensibility
        // Format: {"algorithm": "rsa|ecdsa|ed25519", "signature": "hex_string", "key_id": "key_identifier"}

        let sig_json: serde_json::Value =
            serde_json::from_slice(data).map_err(|e| PluginLoaderError::ValidationError {
                message: format!("Invalid signature JSON format: {}", e),
            })?;

        let algorithm = sig_json
            .get("algorithm")
            .and_then(|v| v.as_str())
            .ok_or_else(|| PluginLoaderError::ValidationError {
                message: "Missing or invalid 'algorithm' field".to_string(),
            })?
            .to_string();

        let signature_hex =
            sig_json.get("signature").and_then(|v| v.as_str()).ok_or_else(|| {
                PluginLoaderError::ValidationError {
                    message: "Missing or invalid 'signature' field".to_string(),
                }
            })?;

        let key_id = sig_json
            .get("key_id")
            .and_then(|v| v.as_str())
            .ok_or_else(|| PluginLoaderError::ValidationError {
                message: "Missing or invalid 'key_id' field".to_string(),
            })?
            .to_string();

        // Validate algorithm
        if !["rsa", "ecdsa", "ed25519"].contains(&algorithm.as_str()) {
            return Err(PluginLoaderError::ValidationError {
                message: format!("Unsupported signature algorithm: {}", algorithm),
            });
        }

        // Decode signature
        let signature =
            hex::decode(signature_hex).map_err(|e| PluginLoaderError::ValidationError {
                message: format!("Invalid signature hex: {}", e),
            })?;

        Ok(PluginSignature {
            algorithm,
            signature,
            key_id,
        })
    }

    /// Verify signature against trusted keys
    async fn verify_signature(
        &self,
        data: &[u8],
        signature: &PluginSignature,
        manifest: &PluginManifest,
    ) -> LoaderResult<()> {
        // Get trusted public key for this key_id
        let public_key = self.get_trusted_key(&signature.key_id)?;

        // Verify signature based on algorithm
        match signature.algorithm.as_str() {
            "rsa" => {
                // Verify RSA signature using the ring cryptography library
                self.verify_rsa_signature(data, &signature.signature, &public_key)?;
            }
            "ecdsa" => {
                // ECDSA signature verification
                self.verify_ecdsa_signature(data, &signature.signature, &public_key)?;
            }
            "ed25519" => {
                // Ed25519 signature verification
                self.verify_ed25519_signature(data, &signature.signature, &public_key)?;
            }
            _ => {
                return Err(PluginLoaderError::ValidationError {
                    message: format!("Unsupported algorithm: {}", signature.algorithm),
                });
            }
        }

        // Additional validation: check if key is authorized for this plugin
        self.validate_key_authorization(&signature.key_id, manifest)?;

        Ok(())
    }

    /// Get trusted public key for verification
    fn get_trusted_key(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        // First check if the key is in our trusted keys list
        if !self.config.trusted_keys.contains(&key_id.to_string()) {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!("Key '{}' is not in the trusted keys list", key_id),
            });
        }

        // Load key from configured sources (environment, config, filesystem, etc.)
        // In production, keys should be loaded from secure storage like a key store, database, or HSM
        self.load_key_from_store(key_id)
    }

    /// Load a key from the key store (environment, config, file system, etc.)
    fn load_key_from_store(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        // 1. Check environment variables first
        if let Ok(key_data) = self.load_key_from_env(key_id) {
            tracing::info!("Loaded key '{}' from environment variable", key_id);
            return Ok(key_data);
        }

        // 2. Check configuration key data
        if let Some(key_data) = self.config.key_data.get(key_id) {
            tracing::info!("Loaded key '{}' from configuration", key_id);
            return Ok(key_data.clone());
        }

        // 3. Check file system (fallback for backward compatibility)
        if let Ok(key_data) = self.load_key_from_filesystem(key_id) {
            tracing::info!("Loaded key '{}' from filesystem", key_id);
            return Ok(key_data);
        }

        // Future extensions: uncomment and implement as needed
        // 4. Query a database for the key
        if let Ok(key_data) = self.load_key_from_database(key_id) {
            tracing::info!("Loaded key '{}' from database provider", key_id);
            return Ok(key_data);
        }

        // 5. Call a key management service
        if let Ok(key_data) = self.load_key_from_kms(key_id) {
            tracing::info!("Loaded key '{}' from key management service", key_id);
            return Ok(key_data);
        }

        Err(PluginLoaderError::SecurityViolation {
            violation: format!("Could not find key data for trusted key: {}", key_id),
        })
    }

    /// Load key from environment variables
    fn load_key_from_env(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        self.load_key_material_from_prefixes(key_id, &["MOCKFORGE_KEY"], "environment")
    }

    fn load_key_material_from_prefixes(
        &self,
        key_id: &str,
        prefixes: &[&str],
        source_name: &str,
    ) -> Result<Vec<u8>, PluginLoaderError> {
        let normalized = key_id.to_uppercase().replace("-", "_");

        for prefix in prefixes {
            // Try base64-encoded key first
            let b64_env_key = format!("{}_{}_B64", prefix, normalized);
            if let Ok(b64_value) = std::env::var(&b64_env_key) {
                match general_purpose::STANDARD.decode(&b64_value) {
                    Ok(key_data) => return Ok(key_data),
                    Err(e) => {
                        tracing::warn!(
                            "Failed to decode base64 key from {} ({}): {}",
                            b64_env_key,
                            source_name,
                            e
                        );
                    }
                }
            }

            // Try hex-encoded key
            let hex_env_key = format!("{}_{}_HEX", prefix, normalized);
            if let Ok(hex_value) = std::env::var(&hex_env_key) {
                match hex::decode(&hex_value) {
                    Ok(key_data) => return Ok(key_data),
                    Err(e) => {
                        tracing::warn!(
                            "Failed to decode hex key from {} ({}): {}",
                            hex_env_key,
                            source_name,
                            e
                        );
                    }
                }
            }

            // Try raw key data
            let raw_env_key = format!("{}_{}", prefix, normalized);
            if let Ok(key_data) = std::env::var(&raw_env_key) {
                return Ok(key_data.into_bytes());
            }
        }

        Err(PluginLoaderError::SecurityViolation {
            violation: format!("Key not found in {}: {}", source_name, key_id),
        })
    }

    fn load_key_from_directory(
        &self,
        key_id: &str,
        dir: &std::path::Path,
    ) -> Result<Vec<u8>, PluginLoaderError> {
        let candidates = [
            dir.join(format!("{}.der", key_id)),
            dir.join(format!("{}.pem", key_id)),
            dir.join(format!("{}.key", key_id)),
            dir.join(format!("{}.bin", key_id)),
        ];

        for path in candidates {
            if path.exists() {
                return std::fs::read(&path).map_err(|e| PluginLoaderError::SecurityViolation {
                    violation: format!("Failed to read key file {}: {}", path.display(), e),
                });
            }
        }

        Err(PluginLoaderError::SecurityViolation {
            violation: format!("Key '{}' not found in directory {}", key_id, dir.display()),
        })
    }

    /// Load key from filesystem (legacy support)
    fn load_key_from_filesystem(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        let key_paths = vec![
            format!("~/.mockforge/keys/{}.der", key_id),
            format!("~/.mockforge/keys/{}.pem", key_id),
            format!("/etc/mockforge/keys/{}.der", key_id),
            format!("/etc/mockforge/keys/{}.pem", key_id),
        ];

        for key_path in key_paths {
            let expanded_path = shellexpand::tilde(&key_path);
            let path = std::path::Path::new(expanded_path.as_ref());

            if path.exists() {
                match std::fs::read(path) {
                    Ok(key_data) => return Ok(key_data),
                    Err(e) => {
                        tracing::warn!("Failed to read key file {}: {}", path.display(), e);
                        continue;
                    }
                }
            }
        }

        Err(PluginLoaderError::SecurityViolation {
            violation: format!("Key not found in filesystem: {}", key_id),
        })
    }

    /// Load key from database
    /// Checks for database configuration via environment variables:
    /// - MOCKFORGE_DB_TYPE: sqlite, postgres, mysql
    /// - MOCKFORGE_DB_CONNECTION: connection string
    /// - MOCKFORGE_DB_KEY_TABLE: table name for keys (default: plugin_keys)
    #[allow(unused)]
    fn load_key_from_database(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        let db_type = std::env::var("MOCKFORGE_DB_TYPE").map_err(|_| {
            PluginLoaderError::SecurityViolation {
                violation: "Database key loading requires MOCKFORGE_DB_TYPE environment variable"
                    .to_string(),
            }
        })?;

        let connection_string = std::env::var("MOCKFORGE_DB_CONNECTION").map_err(|_| {
            PluginLoaderError::SecurityViolation {
                violation:
                    "Database key loading requires MOCKFORGE_DB_CONNECTION environment variable"
                        .to_string(),
            }
        })?;

        let table_name =
            std::env::var("MOCKFORGE_DB_KEY_TABLE").unwrap_or_else(|_| "plugin_keys".to_string());

        tracing::info!("Database key loading configured: type={}, table={}", db_type, table_name);
        tracing::debug!("Looking up key '{}' in database-backed key source", key_id);

        if let Ok(key_data) =
            self.load_key_material_from_prefixes(key_id, &["MOCKFORGE_DB_KEY"], "database env")
        {
            return Ok(key_data);
        }

        if let Ok(key_dir) = std::env::var("MOCKFORGE_DB_KEY_DIR") {
            let expanded = shellexpand::tilde(&key_dir);
            let path = std::path::Path::new(expanded.as_ref());
            if path.exists() {
                return self.load_key_from_directory(key_id, path);
            }
        }

        Err(PluginLoaderError::SecurityViolation {
            violation: format!(
                "Database key '{}' not found in configured environment or key directory (connection: {})",
                key_id, connection_string
            ),
        })
    }

    /// Load key from key management service
    /// Supports multiple KMS providers via environment variables:
    /// - MOCKFORGE_KMS_PROVIDER: aws, vault, azure, gcp
    /// - MOCKFORGE_KMS_REGION: AWS region (for AWS KMS)
    /// - MOCKFORGE_VAULT_ADDR: HashCorp Vault address
    /// - MOCKFORGE_VAULT_TOKEN: HashCorp Vault token
    #[allow(unused)]
    fn load_key_from_kms(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        let kms_provider = std::env::var("MOCKFORGE_KMS_PROVIDER").map_err(|_| {
            PluginLoaderError::SecurityViolation {
                violation: "KMS key loading requires MOCKFORGE_KMS_PROVIDER environment variable"
                    .to_string(),
            }
        })?;

        match kms_provider.to_lowercase().as_str() {
            "aws" => self.load_key_from_aws_kms(key_id),
            "vault" => self.load_key_from_vault(key_id),
            "azure" => self.load_key_from_azure_kv(key_id),
            "gcp" => self.load_key_from_gcp_kms(key_id),
            _ => Err(PluginLoaderError::SecurityViolation {
                violation: format!("Unsupported KMS provider: {}", kms_provider),
            }),
        }
    }

    /// Load key from AWS KMS
    fn load_key_from_aws_kms(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        let region =
            std::env::var("MOCKFORGE_KMS_REGION").unwrap_or_else(|_| "us-east-1".to_string());

        tracing::info!("AWS KMS key loading configured: region={}", region);
        tracing::debug!("Looking up key '{}' in AWS KMS", key_id);

        self.load_key_material_from_prefixes(
            key_id,
            &["MOCKFORGE_AWS_KMS_KEY", "MOCKFORGE_KMS_KEY"],
            "AWS KMS",
        )
    }

    /// Load key from HashCorp Vault
    fn load_key_from_vault(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        let vault_addr = std::env::var("MOCKFORGE_VAULT_ADDR").map_err(|_| {
            PluginLoaderError::SecurityViolation {
                violation: "Vault key loading requires MOCKFORGE_VAULT_ADDR environment variable"
                    .to_string(),
            }
        })?;

        let _vault_token = std::env::var("MOCKFORGE_VAULT_TOKEN").map_err(|_| {
            PluginLoaderError::SecurityViolation {
                violation: "Vault key loading requires MOCKFORGE_VAULT_TOKEN environment variable"
                    .to_string(),
            }
        })?;

        tracing::info!("HashCorp Vault key loading configured: addr={}", vault_addr);
        tracing::debug!("Looking up key '{}' in Vault", key_id);

        self.load_key_material_from_prefixes(
            key_id,
            &["MOCKFORGE_VAULT_KEY", "MOCKFORGE_KMS_KEY"],
            "Vault",
        )
    }

    /// Load key from Azure Key Vault
    fn load_key_from_azure_kv(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        tracing::info!("Azure Key Vault key loading requested");
        tracing::debug!("Looking up key '{}' in Azure Key Vault", key_id);

        self.load_key_material_from_prefixes(
            key_id,
            &["MOCKFORGE_AZURE_KV_KEY", "MOCKFORGE_KMS_KEY"],
            "Azure Key Vault",
        )
    }

    /// Load key from Google Cloud KMS
    fn load_key_from_gcp_kms(&self, key_id: &str) -> Result<Vec<u8>, PluginLoaderError> {
        tracing::info!("Google Cloud KMS key loading requested");
        tracing::debug!("Looking up key '{}' in GCP KMS", key_id);

        self.load_key_material_from_prefixes(
            key_id,
            &["MOCKFORGE_GCP_KMS_KEY", "MOCKFORGE_KMS_KEY"],
            "Google Cloud KMS",
        )
    }

    /// Verify RSA signature
    fn verify_rsa_signature(
        &self,
        data: &[u8],
        signature: &[u8],
        public_key: &[u8],
    ) -> LoaderResult<()> {
        // Create an unparsed public key from the DER-encoded key
        let public_key =
            signature::UnparsedPublicKey::new(&signature::RSA_PKCS1_2048_8192_SHA256, public_key);

        // Verify the signature
        public_key
            .verify(data, signature)
            .map_err(|e| PluginLoaderError::SecurityViolation {
                violation: format!("RSA signature verification failed: {}", e),
            })?;

        Ok(())
    }

    /// Verify ECDSA signature
    fn verify_ecdsa_signature(
        &self,
        data: &[u8],
        signature: &[u8],
        public_key: &[u8],
    ) -> LoaderResult<()> {
        // Create an unparsed public key from the DER-encoded key
        let public_key =
            signature::UnparsedPublicKey::new(&signature::ECDSA_P256_SHA256_ASN1, public_key);

        // Verify the signature
        public_key
            .verify(data, signature)
            .map_err(|e| PluginLoaderError::SecurityViolation {
                violation: format!("ECDSA signature verification failed: {}", e),
            })?;

        Ok(())
    }

    /// Verify Ed25519 signature
    fn verify_ed25519_signature(
        &self,
        data: &[u8],
        signature: &[u8],
        public_key: &[u8],
    ) -> LoaderResult<()> {
        // Create an unparsed public key from the raw key bytes
        let public_key = signature::UnparsedPublicKey::new(&signature::ED25519, public_key);

        // Verify the signature
        public_key
            .verify(data, signature)
            .map_err(|e| PluginLoaderError::SecurityViolation {
                violation: format!("Ed25519 signature verification failed: {}", e),
            })?;

        Ok(())
    }

    /// Validate that the key is authorized for this plugin
    fn validate_key_authorization(
        &self,
        key_id: &str,
        manifest: &PluginManifest,
    ) -> LoaderResult<()> {
        // Check if this key is authorized to sign plugins from this author
        if self.config.trusted_keys.contains(&key_id.to_string()) {
            return Ok(());
        }

        Err(PluginLoaderError::SecurityViolation {
            violation: format!(
                "Key '{}' is not authorized to sign plugins from '{}'",
                key_id, manifest.info.author.name
            ),
        })
    }

    /// Get validation summary for a plugin
    pub async fn get_validation_summary(&self, plugin_path: &Path) -> ValidationSummary {
        let mut summary = ValidationSummary::default();

        // Check if path exists
        if !plugin_path.exists() {
            summary.errors.push("Plugin path does not exist".to_string());
            return summary;
        }

        // Validate manifest
        let manifest_result = self.validate_plugin_file(plugin_path).await;
        match manifest_result {
            Ok(manifest) => {
                summary.manifest_valid = true;
                summary.manifest = Some(manifest);
            }
            Err(e) => {
                summary.errors.push(format!("Manifest validation failed: {}", e));
            }
        }

        // Check WASM file
        if let Ok(wasm_path) = self.find_wasm_file(plugin_path) {
            let wasm_result = self.validate_wasm_file(&wasm_path).await;
            summary.wasm_valid = wasm_result.is_ok();
            if let Err(e) = wasm_result {
                summary.errors.push(format!("WASM validation failed: {}", e));
            }
        } else {
            summary.errors.push("No WebAssembly file found".to_string());
        }

        summary.is_valid =
            summary.manifest_valid && summary.wasm_valid && summary.errors.is_empty();
        summary
    }

    /// Find WASM file in plugin directory
    fn find_wasm_file(&self, plugin_path: &Path) -> LoaderResult<PathBuf> {
        let entries = std::fs::read_dir(plugin_path)
            .map_err(|e| PluginLoaderError::fs(format!("Cannot read directory: {}", e)))?;

        for entry in entries {
            let entry =
                entry.map_err(|e| PluginLoaderError::fs(format!("Cannot read entry: {}", e)))?;
            let path = entry.path();

            if let Some(extension) = path.extension() {
                if extension == "wasm" {
                    return Ok(path);
                }
            }
        }

        Err(PluginLoaderError::load("No WebAssembly file found".to_string()))
    }
}

/// Security policies for plugin validation
#[derive(Debug, Clone)]
pub struct SecurityPolicies {
    /// Maximum WASM file size in bytes
    pub max_wasm_file_size: u64,
    /// Allowed import modules
    pub allowed_imports: HashSet<String>,
    /// Forbidden import functions
    pub forbidden_imports: HashSet<String>,
    /// Maximum memory pages (64KB each)
    pub max_memory_pages: u32,
    /// Maximum number of functions
    pub max_functions: u32,
    /// Allow floating point operations
    pub allow_floats: bool,
    /// Allow SIMD operations
    pub allow_simd: bool,
    /// Allow network access
    pub allow_network_access: bool,
    /// Allow filesystem read access
    pub allow_filesystem_read: bool,
    /// Allow filesystem write access
    pub allow_filesystem_write: bool,
}

impl Default for SecurityPolicies {
    fn default() -> Self {
        let mut allowed_imports = HashSet::new();
        allowed_imports.insert("env".to_string());
        allowed_imports.insert("wasi_snapshot_preview1".to_string());

        let mut forbidden_imports = HashSet::new();
        forbidden_imports.insert("abort".to_string());
        forbidden_imports.insert("exit".to_string());

        Self {
            max_wasm_file_size: 10 * 1024 * 1024, // 10MB
            allowed_imports,
            forbidden_imports,
            max_memory_pages: 256, // 16MB
            max_functions: 1000,
            allow_floats: true,
            allow_simd: false,
            allow_network_access: false,
            allow_filesystem_read: false,
            allow_filesystem_write: false,
        }
    }
}

impl SecurityPolicies {
    /// Validate plugin manifest against security policies
    pub fn validate_manifest(&self, manifest: &PluginManifest) -> LoaderResult<()> {
        // Manifest validation should check for manifest structure issues,
        // but capability restrictions should be enforced at runtime, not validation time.
        // This allows manifests to declare capabilities that may be restricted based on deployment.

        // Check for dangerous capabilities that are always forbidden
        let _caps = PluginCapabilities::from_strings(&manifest.capabilities);

        // For now, we allow all capability declarations in manifests
        // Runtime enforcement will restrict actual usage

        Ok(())
    }

    /// Validate plugin capabilities
    pub fn validate_capabilities(&self, capabilities: &PluginCapabilities) -> LoaderResult<()> {
        // Check resource limits
        if capabilities.resources.max_memory_bytes > self.max_memory_bytes() {
            return Err(PluginLoaderError::security(format!(
                "Memory limit {} exceeds maximum allowed {}",
                capabilities.resources.max_memory_bytes,
                self.max_memory_bytes()
            )));
        }

        if capabilities.resources.max_cpu_percent > self.max_cpu_percent() {
            return Err(PluginLoaderError::security(format!(
                "CPU limit {:.2}% exceeds maximum allowed {:.2}%",
                capabilities.resources.max_cpu_percent,
                self.max_cpu_percent()
            )));
        }

        Ok(())
    }

    /// Validate WebAssembly module
    pub fn validate_wasm_module(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        // Perform sophisticated WASM module validation

        // 1. Check import signatures - ensure only allowed imports
        self.validate_imports(module)?;

        // 2. Check export signatures - ensure required exports are present
        self.validate_exports(module)?;

        // 3. Validate memory usage and limits
        self.validate_memory_usage(module)?;

        // 4. Check for dangerous operations
        self.check_dangerous_operations(module)?;

        // 5. Verify function count limits
        self.validate_function_limits(module)?;

        // 6. Check data segments for malicious content
        self.validate_data_segments(module)?;

        Ok(())
    }

    /// Validate WASM imports against allowed signatures
    fn validate_imports(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        // Get module information
        let _module_info = module.resources_required();

        // Check each import
        for import in module.imports() {
            let module_name = import.module();
            let field_name = import.name();

            // Allow only specific WASI imports and our custom host functions
            let allowed_modules = [
                "wasi_snapshot_preview1",
                "wasi:io/streams",
                "wasi:filesystem/types",
                "mockforge:plugin/host",
            ];

            if !allowed_modules.contains(&module_name) {
                return Err(PluginLoaderError::SecurityViolation {
                    violation: format!("Disallowed import module: {}", module_name),
                });
            }

            // Validate specific imports within allowed modules
            match module_name {
                "wasi_snapshot_preview1" => {
                    self.validate_wasi_import(field_name)?;
                }
                "mockforge:plugin/host" => {
                    self.validate_host_import(field_name)?;
                }
                _ => {
                    // For other allowed modules, we could add specific validation
                }
            }
        }

        Ok(())
    }

    /// Validate WASI imports
    fn validate_wasi_import(&self, field_name: &str) -> LoaderResult<()> {
        // Allow common safe WASI functions
        let allowed_functions = [
            // File operations (with capability checks)
            "fd_read",
            "fd_write",
            "fd_close",
            "fd_fdstat_get",
            // Path operations (with capability checks)
            "path_open",
            "path_readlink",
            "path_filestat_get",
            // Time operations
            "clock_time_get",
            // Process operations
            "proc_exit",
            // Random operations
            "random_get",
        ];

        if !allowed_functions.contains(&field_name) {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!("Disallowed WASI function: {}", field_name),
            });
        }

        Ok(())
    }

    /// Validate host function imports
    fn validate_host_import(&self, field_name: &str) -> LoaderResult<()> {
        // Allow specific host functions that plugins can call
        let allowed_functions = [
            "log_message",
            "get_config_value",
            "store_data",
            "retrieve_data",
        ];

        if !allowed_functions.contains(&field_name) {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!("Disallowed host function: {}", field_name),
            });
        }

        Ok(())
    }

    /// Validate WASM exports
    fn validate_exports(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        let _module_info = module.resources_required();

        // Check for required exports
        let mut has_memory_export = false;
        let mut function_exports = 0;

        for export in module.exports() {
            match export.ty() {
                wasmtime::ExternType::Memory(_) => {
                    has_memory_export = true;
                }
                wasmtime::ExternType::Func(_) => {
                    function_exports += 1;

                    // Validate function signature if needed
                    // For now, we just count them
                }
                _ => {
                    // Other export types (tables, globals) are allowed
                }
            }
        }

        // Every WASM module should have at least one memory export
        if !has_memory_export {
            return Err(PluginLoaderError::ValidationError {
                message: "WASM module must export memory".to_string(),
            });
        }

        // Check function export limits
        if function_exports > 1000 {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!("Too many function exports: {} (max: 1000)", function_exports),
            });
        }

        Ok(())
    }

    /// Validate memory usage and limits
    fn validate_memory_usage(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        let _module_info = module.resources_required();

        for import in module.imports() {
            if let wasmtime::ExternType::Memory(memory_type) = import.ty() {
                // Check memory limits
                if let Some(max) = memory_type.maximum() {
                    if max > 100 {
                        // 100 pages = 6.4MB
                        return Err(PluginLoaderError::SecurityViolation {
                            violation: format!("Memory limit too high: {} pages (max: 100)", max),
                        });
                    }
                }

                // Check if memory can grow beyond safe limits
                if memory_type.maximum().is_none() && memory_type.is_shared() {
                    return Err(PluginLoaderError::SecurityViolation {
                        violation: "Shared memory without maximum limit not allowed".to_string(),
                    });
                }
            }
        }

        // Check exported memories
        for export in module.exports() {
            if let wasmtime::ExternType::Memory(memory_type) = export.ty() {
                if let Some(max) = memory_type.maximum() {
                    if max > 100 {
                        return Err(PluginLoaderError::SecurityViolation {
                            violation: format!("Exported memory limit too high: {} pages", max),
                        });
                    }
                }
            }
        }

        Ok(())
    }

    /// Check for dangerous operations in the WASM module
    fn check_dangerous_operations(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        // This would require more sophisticated analysis of the WASM bytecode
        // For now, we'll do basic checks

        // Check for potentially dangerous instruction patterns
        // This is a placeholder for more advanced static analysis

        let _module_info = module.resources_required();

        // Check function sizes (large functions might be obfuscated malicious code)
        self.validate_function_sizes(module)?;

        // Check for suspicious import patterns
        let suspicious_imports = ["env", "wasi_unstable", "wasi_experimental"];
        for import in module.imports() {
            if suspicious_imports.contains(&import.module()) {
                return Err(PluginLoaderError::SecurityViolation {
                    violation: format!("Suspicious import module: {}", import.module()),
                });
            }
        }

        Ok(())
    }

    /// Validate function count limits
    fn validate_function_limits(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        let _module_info = module.resources_required();

        let mut function_count = 0;
        for export in module.exports() {
            if let wasmtime::ExternType::Func(_) = export.ty() {
                function_count += 1;
            }
        }

        // Also count imported functions
        for import in module.imports() {
            if let wasmtime::ExternType::Func(_) = import.ty() {
                function_count += 1;
            }
        }

        // Set reasonable limits
        if function_count > 10000 {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!("Too many functions: {} (max: 10000)", function_count),
            });
        }

        Ok(())
    }

    /// Validate function sizes to detect potentially malicious code
    fn validate_function_sizes(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        // Check exported functions for suspicious characteristics that may indicate
        // malicious or obfuscated code
        for export in module.exports() {
            if let wasmtime::ExternType::Func(func_type) = export.ty() {
                // Check if the function has too many parameters/results
                // Large functions often have complex signatures
                let param_count = func_type.params().len();
                let result_count = func_type.results().len();

                // Flag functions with suspiciously complex signatures
                if param_count > 20 || result_count > 10 {
                    return Err(PluginLoaderError::SecurityViolation {
                        violation: format!(
                            "Function '{}' has suspiciously complex signature: {} params, {} results",
                            export.name(), param_count, result_count
                        ),
                    });
                }

                // Check for unusual parameter types that might indicate obfuscation
                let mut complex_types = 0;
                for param in func_type.params() {
                    match param {
                        wasmtime::ValType::V128 | wasmtime::ValType::Ref(_) => {
                            complex_types += 1;
                        }
                        _ => {}
                    }
                }

                if complex_types > param_count / 2 && param_count > 5 {
                    return Err(PluginLoaderError::SecurityViolation {
                        violation: format!(
                            "Function '{}' has unusually complex parameter types: {} complex types out of {} params",
                            export.name(), complex_types, param_count
                        ),
                    });
                }
            }
        }

        // Count total functions as an indicator of potential obfuscation
        let mut total_functions = 0;
        for export in module.exports() {
            if let wasmtime::ExternType::Func(_) = export.ty() {
                total_functions += 1;
            }
        }
        for import in module.imports() {
            if let wasmtime::ExternType::Func(_) = import.ty() {
                total_functions += 1;
            }
        }

        // Flag modules with an excessive number of functions
        // (could indicate obfuscated malicious code)
        if total_functions > 5000 {
            return Err(PluginLoaderError::SecurityViolation {
                violation: format!(
                    "Too many functions: {} (reasonable limit: 5000)",
                    total_functions
                ),
            });
        }

        // For actual function size checking, we would need to parse the WASM binary
        // and examine the code section. This implementation provides structural
        // validation that can detect some forms of malicious code.

        Ok(())
    }

    /// Validate data segments for malicious content
    fn validate_data_segments(&self, module: &wasmtime::Module) -> LoaderResult<()> {
        // Check data segments for potentially malicious content
        // Scan for suspicious strings, URLs, shell commands, etc.

        // Serialize the module to get WASM bytes
        let wasm_bytes = module.serialize().map_err(|e| PluginLoaderError::ValidationError {
            message: format!("Failed to serialize WASM module: {}", e),
        })?;

        // Parse the WASM binary to extract data segments
        let parser = Parser::new(0);
        let payloads =
            parser.parse_all(&wasm_bytes).collect::<Result<Vec<_>, _>>().map_err(|e| {
                PluginLoaderError::ValidationError {
                    message: format!("Failed to parse WASM module: {}", e),
                }
            })?;

        // Define suspicious patterns to check for
        let suspicious_patterns = [
            "http://",
            "https://",
            "/bin/",
            "/usr/bin/",
            "eval(",
            "exec(",
            "system(",
            "shell",
            "cmd.exe",
            "powershell",
            "wget",
            "curl",
            "nc ",
            "netcat",
            "python -c",
            "ruby -e",
            "node -e",
            "bash -c",
            "sh -c",
        ];

        // Check each payload for data sections
        for payload in payloads {
            if let Payload::DataSection(data_section) = payload {
                for data_segment_result in data_section {
                    let data_segment =
                        data_segment_result.map_err(|e| PluginLoaderError::ValidationError {
                            message: format!("Failed to read data segment: {}", e),
                        })?;
                    let data = data_segment.data;

                    // Convert to string for easier checking (assuming UTF-8)
                    if let Ok(data_str) = std::str::from_utf8(data) {
                        for pattern in &suspicious_patterns {
                            if data_str.contains(pattern) {
                                return Err(PluginLoaderError::SecurityViolation {
                                    violation: format!(
                                        "Data segment contains suspicious content: '{}'",
                                        pattern
                                    ),
                                });
                            }
                        }
                    } else {
                        // If not UTF-8, check for byte sequences
                        for pattern in &suspicious_patterns {
                            if data
                                .windows(pattern.len())
                                .any(|window| window == pattern.as_bytes())
                            {
                                return Err(PluginLoaderError::SecurityViolation {
                                    violation: format!(
                                        "Data segment contains suspicious content: '{}'",
                                        pattern
                                    ),
                                });
                            }
                        }
                    }
                }
            }
        }

        Ok(())
    }

    /// Check if network access is allowed
    pub fn allow_network_access(&self) -> bool {
        self.allow_network_access
    }

    /// Check if file system read access is allowed
    pub fn allow_filesystem_read(&self) -> bool {
        self.allow_filesystem_read
    }

    /// Check if file system write access is allowed
    pub fn allow_filesystem_write(&self) -> bool {
        self.allow_filesystem_write
    }

    /// Get maximum allowed memory in bytes
    pub fn max_memory_bytes(&self) -> usize {
        10 * 1024 * 1024 // 10MB
    }

    /// Get maximum allowed CPU usage
    pub fn max_cpu_percent(&self) -> f64 {
        0.5 // 50%
    }
}

/// Validation summary for a plugin
#[derive(Debug, Clone)]
pub struct ValidationSummary {
    /// Whether the plugin is valid overall
    pub is_valid: bool,
    /// Whether the manifest is valid
    pub manifest_valid: bool,
    /// Whether the WASM file is valid
    pub wasm_valid: bool,
    /// Plugin manifest (if loaded successfully)
    pub manifest: Option<PluginManifest>,
    /// Validation errors
    pub errors: Vec<String>,
    /// Validation warnings
    pub warnings: Vec<String>,
}

impl Default for ValidationSummary {
    fn default() -> Self {
        Self {
            is_valid: true,
            manifest_valid: false,
            wasm_valid: false,
            manifest: None,
            errors: Vec::new(),
            warnings: Vec::new(),
        }
    }
}

impl ValidationSummary {
    /// Add an error
    pub fn add_error<S: Into<String>>(&mut self, error: S) {
        self.errors.push(error.into());
        self.is_valid = false;
    }

    /// Add a warning
    pub fn add_warning<S: Into<String>>(&mut self, warning: S) {
        self.warnings.push(warning.into());
    }

    /// Check if there are any errors
    pub fn has_errors(&self) -> bool {
        !self.errors.is_empty()
    }

    /// Check if there are any warnings
    pub fn has_warnings(&self) -> bool {
        !self.warnings.is_empty()
    }

    /// Get error count
    pub fn error_count(&self) -> usize {
        self.errors.len()
    }

    /// Get warning count
    pub fn warning_count(&self) -> usize {
        self.warnings.len()
    }
}

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

    #[tokio::test]
    async fn test_security_policies_creation() {
        let policies = SecurityPolicies::default();
        assert!(!policies.allow_network_access());
        assert!(!policies.allow_filesystem_read());
        assert!(!policies.allow_filesystem_write());
        assert_eq!(policies.max_memory_bytes(), 10 * 1024 * 1024);
        assert_eq!(policies.max_cpu_percent(), 0.5);
    }

    #[tokio::test]
    async fn test_validation_summary() {
        let mut summary = ValidationSummary::default();
        assert!(summary.is_valid);
        assert!(!summary.has_errors());
        assert!(!summary.has_warnings());

        summary.add_error("Test error");
        assert!(!summary.is_valid);
        assert!(summary.has_errors());
        assert_eq!(summary.error_count(), 1);

        summary.add_warning("Test warning");
        assert!(summary.has_warnings());
        assert_eq!(summary.warning_count(), 1);
    }

    #[tokio::test]
    async fn test_plugin_validator_creation() {
        let config = PluginLoaderConfig::default();
        let _validator = PluginValidator::new(config);
        // Basic smoke test - validator was created successfully
        // Test passes if no panic occurs during creation
    }
}