1use crate::skills::cli_bridge::CliToolConfig;
11use crate::skills::manifest::parse_skill_file;
12use crate::utils::file_utils::read_file_with_context_sync;
13use anyhow::Result;
14use hashbrown::HashMap;
15use serde::{Deserialize, Serialize};
16use serde_json::Value;
17use std::path::{Path, PathBuf};
18use std::time::{Instant, SystemTime};
19use tracing::info;
20
21mod checks;
22
23#[derive(Debug, Clone, Serialize, Deserialize)]
25pub struct ValidationConfig {
26 pub enable_security_checks: bool,
28
29 pub enable_performance_checks: bool,
31
32 pub max_validation_time: u64,
34
35 pub max_script_size: usize,
37
38 pub allowed_script_extensions: Vec<String>,
40
41 pub blocked_commands: Vec<String>,
43
44 pub required_metadata_fields: Vec<String>,
46
47 pub enable_schema_validation: bool,
49
50 pub strict_mode: bool,
52}
53
54impl Default for ValidationConfig {
55 fn default() -> Self {
56 Self {
57 enable_security_checks: true,
58 enable_performance_checks: true,
59 max_validation_time: 30,
60 max_script_size: 1024 * 1024, allowed_script_extensions: vec![
62 "py".to_string(),
63 "sh".to_string(),
64 "bash".to_string(),
65 "js".to_string(),
66 "ts".to_string(),
67 "rb".to_string(),
68 "pl".to_string(),
69 "go".to_string(),
70 "rs".to_string(),
71 ],
72 blocked_commands: vec![
73 "rm -rf /".to_string(),
74 "sudo".to_string(),
75 "chmod 777".to_string(),
76 "curl.*|.*sh".to_string(),
77 "wget.*|.*sh".to_string(),
78 ],
79 required_metadata_fields: vec!["name".to_string(), "description".to_string()],
80 enable_schema_validation: true,
81 strict_mode: false,
82 }
83 }
84}
85
86#[derive(Debug, Clone, Serialize, Deserialize)]
88pub struct ValidationReport {
89 pub status: ValidationStatus,
91
92 pub skill_name: String,
94
95 pub timestamp: chrono::DateTime<chrono::Utc>,
97
98 pub checks: HashMap<String, CheckResult>,
100
101 pub performance: PerformanceMetrics,
103
104 pub security: SecurityAssessment,
106
107 pub recommendations: Vec<String>,
109}
110
111#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
113pub enum ValidationStatus {
114 Valid,
116 Warning,
118 Invalid,
120}
121
122#[derive(Debug, Clone, Serialize, Deserialize)]
124pub struct CheckResult {
125 pub name: String,
127
128 pub status: CheckStatus,
130
131 pub message: String,
133
134 pub details: Option<Value>,
136
137 pub execution_time_ms: u64,
139}
140
141#[derive(Debug, Clone, Serialize, Deserialize, PartialEq)]
143pub enum CheckStatus {
144 Passed,
146 Warning,
148 Failed,
150 Skipped,
152}
153
154#[derive(Debug, Clone, Default, Serialize, Deserialize)]
156pub struct PerformanceMetrics {
157 pub total_time_ms: u64,
159
160 pub loading_time_ms: u64,
162
163 pub schema_validation_time_ms: u64,
165
166 pub script_validation_time_ms: u64,
168
169 pub memory_usage_bytes: usize,
171
172 pub token_usage_estimate: usize,
174}
175
176#[derive(Debug, Clone, Default, Serialize, Deserialize)]
178pub struct SecurityAssessment {
179 pub security_level: SecurityLevel,
181
182 pub warnings: Vec<SecurityWarning>,
184
185 pub blocked_content: Vec<String>,
187
188 pub safe_to_execute: bool,
190}
191
192#[derive(Debug, Clone, Serialize, Deserialize, PartialEq, Default)]
194pub enum SecurityLevel {
195 #[default]
197 Safe,
198 LowRisk,
200 MediumRisk,
202 HighRisk,
204}
205
206#[derive(Debug, Clone, Serialize, Deserialize)]
208pub struct SecurityWarning {
209 pub warning_type: String,
211
212 pub message: String,
214
215 pub severity: SecurityLevel,
217
218 pub suggestion: Option<String>,
220}
221
222pub struct SkillValidator {
224 config: ValidationConfig,
225 schema_validation_cache: HashMap<PathBuf, (SystemTime, CheckResult)>,
228}
229
230impl SkillValidator {
231 pub fn new() -> Self {
233 Self::with_config(ValidationConfig::default())
234 }
235}
236
237impl Default for SkillValidator {
238 fn default() -> Self {
239 Self::new()
240 }
241}
242
243impl SkillValidator {
244 pub fn with_config(config: ValidationConfig) -> Self {
246 Self { config, schema_validation_cache: HashMap::new() }
247 }
248
249 pub async fn validate_skill_directory(&mut self, skill_path: &Path) -> Result<ValidationReport> {
251 let start_time = Instant::now();
252 let mut checks = HashMap::new();
253 info!("Validating skill directory: {}", skill_path.display());
256
257 let check_result = self.check_directory_exists(skill_path).await;
259 checks.insert("directory_exists".to_string(), check_result);
260
261 let skill_file = skill_path.join("SKILL.md");
263 let check_result = self.validate_skill_file(&skill_file).await;
264 checks.insert("skill_file_valid".to_string(), check_result.clone());
265
266 let skill_name = if let Some(manifest) = &check_result.details {
267 manifest.get("name").and_then(|v| v.as_str()).unwrap_or("unknown").to_string()
268 } else {
269 "unknown".to_string()
270 };
271
272 let scripts_dir = skill_path.join("scripts");
274 if scripts_dir.exists() {
275 let check_result = self.validate_scripts_directory(&scripts_dir).await;
276 checks.insert("scripts_valid".to_string(), check_result);
277 }
278
279 let resources_result = self.validate_resources(skill_path).await;
281 for (name, result) in resources_result {
282 checks.insert(format!("resource_{name}"), result);
283 }
284
285 let security = self.assess_security(&checks);
287
288 let recommendations = self.generate_recommendations(&checks, &security);
290
291 let status = self.determine_overall_status(&checks, &security);
293
294 let performance = PerformanceMetrics {
295 total_time_ms: start_time.elapsed().as_millis() as u64,
296 ..Default::default()
297 };
298
299 Ok(ValidationReport {
300 status,
301 skill_name,
302 timestamp: chrono::Utc::now(),
303 checks,
304 performance,
305 security,
306 recommendations,
307 })
308 }
309
310 pub async fn validate_cli_tool(&mut self, config: &CliToolConfig) -> Result<ValidationReport> {
312 let start_time = Instant::now();
313 let mut checks = HashMap::new();
314
315 info!("Validating CLI tool: {}", config.name);
316
317 let check_result = self.check_executable_exists(&config.executable_path).await;
319 checks.insert("executable_exists".to_string(), check_result);
320
321 let check_result = self.check_executable_permissions(&config.executable_path).await;
323 checks.insert("executable_permissions".to_string(), check_result);
324
325 if let Some(readme_path) = &config.readme_path {
327 let check_result = self.validate_readme_file(readme_path).await;
328 checks.insert("readme_valid".to_string(), check_result);
329 }
330
331 if let Some(schema_path) = &config.schema_path {
333 let check_result = self.validate_json_schema(schema_path).await;
334 checks.insert("schema_valid".to_string(), check_result);
335 }
336
337 let check_result = self.test_tool_execution(config).await;
339 checks.insert("tool_executable".to_string(), check_result);
340
341 let security = self.assess_security(&checks);
343
344 let recommendations = self.generate_recommendations(&checks, &security);
346
347 let status = self.determine_overall_status(&checks, &security);
349
350 let performance = PerformanceMetrics {
351 total_time_ms: start_time.elapsed().as_millis() as u64,
352 ..Default::default()
353 };
354
355 Ok(ValidationReport {
356 status,
357 skill_name: config.name.clone(),
358 timestamp: chrono::Utc::now(),
359 checks,
360 performance,
361 security,
362 recommendations,
363 })
364 }
365
366 async fn validate_json_schema(&mut self, schema_path: &Path) -> CheckResult {
368 let start_time = Instant::now();
369
370 if !schema_path.exists() {
371 return CheckResult {
372 name: "schema_valid".to_string(),
373 status: CheckStatus::Warning,
374 message: "Schema file not found".to_string(),
375 details: None,
376 execution_time_ms: start_time.elapsed().as_millis() as u64,
377 };
378 }
379
380 if let Ok(metadata) = tokio::fs::metadata(schema_path).await
382 && let Ok(mtime) = metadata.modified()
383 && let Some((cached_mtime, cached_result)) = self.schema_validation_cache.get(schema_path)
384 && *cached_mtime == mtime
385 {
386 let mut result = cached_result.clone();
387 result.execution_time_ms = start_time.elapsed().as_millis() as u64;
389 result.message = format!("{} (cached)", result.message);
390 return result;
391 }
392
393 let result = match read_file_with_context_sync(schema_path, "skill JSON schema") {
394 Ok(content) => {
395 match serde_json::from_str::<Value>(&content) {
396 Ok(schema_json) => {
397 match jsonschema::validator_for(&schema_json) {
399 Ok(_validator) => CheckResult {
400 name: "schema_valid".to_string(),
401 status: CheckStatus::Passed,
402 message: "JSON schema is valid and compilable".to_string(),
403 details: None,
404 execution_time_ms: start_time.elapsed().as_millis() as u64,
405 },
406 Err(e) => CheckResult {
407 name: "schema_valid".to_string(),
408 status: CheckStatus::Failed,
409 message: format!("Invalid JSON Schema: {e}"),
410 details: Some(
411 serde_json::json!({"error": format!("Schema compilation failed: {}", e)}),
412 ),
413 execution_time_ms: start_time.elapsed().as_millis() as u64,
414 },
415 }
416 }
417 Err(e) => CheckResult {
418 name: "schema_valid".to_string(),
419 status: CheckStatus::Failed,
420 message: format!("Invalid JSON in schema file: {e}"),
421 details: None,
422 execution_time_ms: start_time.elapsed().as_millis() as u64,
423 },
424 }
425 }
426 Err(e) => CheckResult {
427 name: "schema_valid".to_string(),
428 status: CheckStatus::Failed,
429 message: format!("Failed to read schema file: {e}"),
430 details: None,
431 execution_time_ms: start_time.elapsed().as_millis() as u64,
432 },
433 };
434
435 if let Ok(metadata) = tokio::fs::metadata(schema_path).await
437 && let Ok(mtime) = metadata.modified()
438 {
439 self.schema_validation_cache
440 .insert(schema_path.to_path_buf(), (mtime, result.clone()));
441 }
442
443 result
444 }
445
446 async fn test_tool_execution(&self, config: &CliToolConfig) -> CheckResult {
448 let start_time = Instant::now();
449
450 let exec_path = config.executable_path.clone();
454
455 let output =
457 tokio::task::spawn_blocking(move || std::process::Command::new(&exec_path).arg("--help").output()).await;
458
459 match output {
460 Ok(Ok(output)) if output.status.success() => CheckResult {
461 name: "tool_executable".to_string(),
462 status: CheckStatus::Passed,
463 message: "Tool executed successfully with --help".to_string(),
464 details: None,
465 execution_time_ms: start_time.elapsed().as_millis() as u64,
466 },
467 Ok(Ok(_)) => {
468 let exec_path = config.executable_path.clone();
470 match tokio::task::spawn_blocking(move || std::process::Command::new(&exec_path).arg("-h").output())
471 .await
472 {
473 Ok(Ok(output)) if output.status.success() => CheckResult {
474 name: "tool_executable".to_string(),
475 status: CheckStatus::Passed,
476 message: "Tool executed successfully with -h".to_string(),
477 details: None,
478 execution_time_ms: start_time.elapsed().as_millis() as u64,
479 },
480 Ok(Ok(_)) => CheckResult {
481 name: "tool_executable".to_string(),
482 status: CheckStatus::Warning,
483 message: "Tool executed but returned non-zero exit code".to_string(),
484 details: None,
485 execution_time_ms: start_time.elapsed().as_millis() as u64,
486 },
487 Ok(Err(e)) => CheckResult {
488 name: "tool_executable".to_string(),
489 status: CheckStatus::Failed,
490 message: format!("Failed to execute tool: {e}"),
491 details: None,
492 execution_time_ms: start_time.elapsed().as_millis() as u64,
493 },
494 Err(e) => CheckResult {
495 name: "tool_executable".to_string(),
496 status: CheckStatus::Failed,
497 message: format!("Validation task failed: {e}"),
498 details: None,
499 execution_time_ms: start_time.elapsed().as_millis() as u64,
500 },
501 }
502 }
503 Ok(Err(e)) => CheckResult {
504 name: "tool_executable".to_string(),
505 status: CheckStatus::Failed,
506 message: format!("Failed to execute tool: {e}"),
507 details: None,
508 execution_time_ms: start_time.elapsed().as_millis() as u64,
509 },
510 Err(e) => CheckResult {
511 name: "tool_executable".to_string(),
512 status: CheckStatus::Failed,
513 message: format!("Validation task failed: {e}"),
514 details: None,
515 execution_time_ms: start_time.elapsed().as_millis() as u64,
516 },
517 }
518 }
519
520 fn assess_security(&self, checks: &HashMap<String, CheckResult>) -> SecurityAssessment {
522 let mut warnings = vec![];
523 let blocked_content = vec![];
524 let mut security_level = SecurityLevel::Safe;
525
526 if let Some(scripts_check) = checks.get("scripts_valid")
528 && scripts_check.status == CheckStatus::Warning
529 && let Some(details) = &scripts_check.details
530 && let Some(issues) = details.as_array()
531 {
532 for issue in issues {
533 if let Some(issue_str) = issue.as_str()
534 && issue_str.contains("dangerous")
535 {
536 warnings.push(SecurityWarning {
537 warning_type: "dangerous_content".to_string(),
538 message: issue_str.to_string(),
539 severity: SecurityLevel::HighRisk,
540 suggestion: Some("Review script content for security issues".to_string()),
541 });
542 security_level = SecurityLevel::HighRisk;
543 }
544 }
545 }
546
547 let safe_to_execute = security_level != SecurityLevel::HighRisk;
548
549 SecurityAssessment {
550 security_level,
551 warnings,
552 blocked_content,
553 safe_to_execute,
554 }
555 }
556
557 fn generate_recommendations(
559 &self,
560 checks: &HashMap<String, CheckResult>,
561 security: &SecurityAssessment,
562 ) -> Vec<String> {
563 let mut recommendations = vec![];
564
565 for check in checks.values() {
567 match check.status {
568 CheckStatus::Warning => {
569 recommendations.push(format!("Address warning in {}: {}", check.name, check.message));
570 }
571 CheckStatus::Failed => {
572 recommendations.push(format!("Fix failed check {}: {}", check.name, check.message));
573 }
574 _ => {}
575 }
576 }
577
578 if security.security_level == SecurityLevel::HighRisk {
580 recommendations.push("Review and fix security issues before using this skill".to_string());
581 }
582
583 if let Some(loading_check) = checks.get("skill_file_valid")
585 && loading_check.execution_time_ms > 1000
586 {
587 recommendations.push("Consider optimizing skill file parsing performance".to_string());
588 }
589
590 recommendations
591 }
592
593 fn determine_overall_status(
595 &self,
596 checks: &HashMap<String, CheckResult>,
597 security: &SecurityAssessment,
598 ) -> ValidationStatus {
599 let has_failures = checks.values().any(|check| check.status == CheckStatus::Failed);
600 let has_warnings = checks.values().any(|check| check.status == CheckStatus::Warning);
601 let has_high_risk = security.security_level == SecurityLevel::HighRisk;
602
603 if has_failures || has_high_risk {
604 ValidationStatus::Invalid
605 } else if has_warnings {
606 ValidationStatus::Warning
607 } else {
608 ValidationStatus::Valid
609 }
610 }
611
612 pub async fn validate_batch(&mut self, skill_paths: Vec<&Path>) -> Vec<Result<ValidationReport>> {
614 let mut results = vec![];
615
616 for path in skill_paths {
617 let result = self.validate_skill_directory(path).await;
618 results.push(result);
619 }
620
621 results
622 }
623}
624
625#[derive(Debug, Clone, Serialize, Deserialize)]
627pub struct BatchValidationResult {
628 pub total_skills: usize,
630
631 pub valid_skills: Vec<String>,
633
634 pub warning_skills: Vec<String>,
636
637 pub invalid_skills: Vec<String>,
639
640 pub average_validation_time_ms: u64,
642
643 pub reports: Vec<ValidationReport>,
645}
646
647pub async fn validate_skill_batch(skill_paths: Vec<&Path>) -> Result<BatchValidationResult> {
649 let mut validator = SkillValidator::new();
650 let mut reports = vec![];
651 let mut total_time = 0u64;
652
653 for path in skill_paths {
654 match validator.validate_skill_directory(path).await {
655 Ok(report) => {
656 total_time += report.performance.total_time_ms;
657 reports.push(report);
658 }
659 Err(e) => {
660 let error_report = ValidationReport {
662 status: ValidationStatus::Invalid,
663 skill_name: path.to_string_lossy().to_string(),
664 timestamp: chrono::Utc::now(),
665 checks: HashMap::new(),
666 performance: PerformanceMetrics::default(),
667 security: SecurityAssessment::default(),
668 recommendations: vec![format!("Validation failed: {}", e)],
669 };
670 reports.push(error_report);
671 }
672 }
673 }
674
675 let valid_skills: Vec<String> = reports
676 .iter()
677 .filter(|r| r.status == ValidationStatus::Valid)
678 .map(|r| r.skill_name.clone())
679 .collect();
680
681 let warning_skills: Vec<String> = reports
682 .iter()
683 .filter(|r| r.status == ValidationStatus::Warning)
684 .map(|r| r.skill_name.clone())
685 .collect();
686
687 let invalid_skills: Vec<String> = reports
688 .iter()
689 .filter(|r| r.status == ValidationStatus::Invalid)
690 .map(|r| r.skill_name.clone())
691 .collect();
692
693 let average_time = if !reports.is_empty() {
694 total_time / reports.len() as u64
695 } else {
696 0
697 };
698
699 Ok(BatchValidationResult {
700 total_skills: reports.len(),
701 valid_skills,
702 warning_skills,
703 invalid_skills,
704 average_validation_time_ms: average_time,
705 reports,
706 })
707}
708
709#[cfg(test)]
710mod tests;