Skip to main content

threatflux_package_security/core/
package.rs

1//! Core package traits and structures
2
3use anyhow::Result;
4use async_trait::async_trait;
5use serde::{Deserialize, Serialize};
6use std::collections::BTreeMap;
7use std::path::Path;
8
9use super::{DependencyAnalysis, MaliciousPattern, RiskAssessment, Vulnerability};
10
11/// Basic package information common to all package types
12#[derive(Debug, Clone, Serialize, Deserialize)]
13pub struct PackageMetadata {
14    pub name: String,
15    pub version: String,
16    pub description: Option<String>,
17    pub author: Option<String>,
18    pub license: Option<String>,
19    pub homepage: Option<String>,
20    pub repository: Option<String>,
21    pub keywords: Vec<String>,
22    pub publish_date: Option<String>,
23}
24
25/// Package quality metrics
26#[derive(Debug, Clone, Serialize, Deserialize)]
27pub struct QualityMetrics {
28    pub documentation_score: f32,
29    pub has_tests: bool,
30    pub has_ci_cd: bool,
31    pub maintenance_score: f32,
32}
33
34impl Default for QualityMetrics {
35    fn default() -> Self {
36        Self {
37            documentation_score: 0.5,
38            has_tests: false,
39            has_ci_cd: false,
40            maintenance_score: 0.5,
41        }
42    }
43}
44
45impl QualityMetrics {
46    pub fn documentation_score(&self) -> f32 {
47        self.documentation_score
48    }
49
50    pub fn has_tests(&self) -> bool {
51        self.has_tests
52    }
53
54    pub fn has_ci_cd(&self) -> bool {
55        self.has_ci_cd
56    }
57}
58
59/// Typosquatting risk assessment
60#[derive(Debug, Clone, Serialize, Deserialize)]
61pub struct TyposquattingRisk {
62    pub is_potential_typosquatting: bool,
63    pub similar_packages: Vec<String>,
64    pub confidence_score: f32,
65}
66
67impl TyposquattingRisk {
68    pub fn is_potential_typosquatting(&self) -> bool {
69        self.is_potential_typosquatting
70    }
71
72    pub fn similar_packages(&self) -> &[String] {
73        &self.similar_packages
74    }
75}
76
77/// Package-specific information trait
78pub trait PackageInfo: Send + Sync {
79    /// Get basic metadata
80    fn metadata(&self) -> &PackageMetadata;
81
82    /// Get package type identifier
83    fn package_type(&self) -> &str;
84
85    /// Get custom attributes specific to this package type
86    fn custom_attributes(&self) -> BTreeMap<String, serde_json::Value>;
87
88    /// Get package name (convenience method)
89    fn name(&self) -> &str {
90        &self.metadata().name
91    }
92}
93
94/// Analysis result trait
95pub trait AnalysisResult: Send + Sync {
96    /// Get the package info
97    fn package_info(&self) -> &dyn PackageInfo;
98
99    /// Get risk assessment
100    fn risk_assessment(&self) -> &RiskAssessment;
101
102    /// Get dependency analysis
103    fn dependency_analysis(&self) -> &DependencyAnalysis;
104
105    /// Get the deterministic, deduplicated union of advisory matches for the
106    /// analyzed subject package and its dependencies.
107    fn vulnerabilities(&self) -> &[Vulnerability];
108
109    /// Get advisory matches for the analyzed subject package itself. An empty
110    /// slice means none were matched or the analyzer has no subject advisory
111    /// capability.
112    fn subject_vulnerabilities(&self) -> &[Vulnerability] {
113        &[]
114    }
115
116    /// Get heuristic pattern matches (the method name is retained for compatibility).
117    fn malicious_patterns(&self) -> &[MaliciousPattern];
118
119    /// Advisory database coverage/provenance for this analysis, when one was
120    /// consulted.
121    fn vulnerability_database_metadata(&self) -> Option<&super::DatabaseMetadata>;
122
123    /// Convert to JSON representation
124    fn to_json(&self) -> Result<serde_json::Value>;
125
126    /// Get overall risk level (convenience method)
127    fn overall_risk_level(&self) -> super::RiskLevel {
128        self.risk_assessment().risk_score.risk_level
129    }
130
131    /// Get malicious indicators (convenience method)
132    fn malicious_indicators(&self) -> &[super::MaliciousPattern] {
133        self.malicious_patterns()
134    }
135
136    /// Get supply chain risk score (convenience method)
137    fn supply_chain_risk_score(&self) -> f32 {
138        self.risk_assessment()
139            .risk_score
140            .components
141            .get("supply_chain")
142            .copied()
143            .unwrap_or(0.0)
144    }
145
146    /// Get computed quality metrics, when an analyzer supports them.
147    fn quality_metrics(&self) -> Option<super::QualityMetrics> {
148        None
149    }
150
151    /// Get typosquatting risk (default implementation)
152    fn typosquatting_risk(&self) -> Option<TyposquattingRisk> {
153        None
154    }
155}
156
157/// Package analyzer trait
158#[async_trait]
159pub trait PackageAnalyzer: Send + Sync {
160    /// The specific package type this analyzer handles
161    type Package: PackageInfo;
162
163    /// The analysis result type
164    type Analysis: AnalysisResult;
165
166    /// Analyze a package from the given path.
167    ///
168    /// The returned future must be polled from an active Tokio runtime. The
169    /// implementation returns an error instead of panicking when no runtime is
170    /// active.
171    async fn analyze(&self, path: &Path) -> Result<Self::Analysis>;
172
173    /// Check if this analyzer can handle the given path
174    fn can_analyze(&self, path: &Path) -> bool;
175
176    /// Get analyzer name
177    fn name(&self) -> &str;
178
179    /// Get supported file extensions
180    fn supported_extensions(&self) -> Vec<&str>;
181}