File size: 8,173 Bytes
ec37394
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
 
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
"""
πŸ“¦ Dependency Analyzer
Check for outdated packages, CVEs, and unused dependencies
"""
from typing import Dict, List, Any, Optional
import re
import json
import subprocess
import logging
from pathlib import Path

logger = logging.getLogger(__name__)


class DependencyAnalyzer:
    """Analyze project dependencies for security and optimization"""
    
    @staticmethod
    def parse_package_json(file_path: str) -> Optional[Dict[str, Any]]:
        """Parse package.json file"""
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                return json.load(f)
        except Exception as e:
            logger.error(f"Failed to parse package.json: {e}")
            return None
    
    @staticmethod
    def parse_requirements_txt(file_path: str) -> List[Dict[str, str]]:
        """Parse requirements.txt file"""
        dependencies = []
        try:
            with open(file_path, 'r', encoding='utf-8') as f:
                for line in f:
                    line = line.strip()
                    if line and not line.startswith('#'):
                        # Parse package==version or package>=version
                        match = re.match(r'([a-zA-Z0-9_-]+)([>=<]+)?([\d.]+)?', line)
                        if match:
                            dependencies.append({
                                "name": match.group(1),
                                "version": match.group(3) or "latest",
                                "operator": match.group(2) or "=="
                            })
        except Exception as e:
            logger.error(f"Failed to parse requirements.txt: {e}")
        return dependencies
    
    @staticmethod
    def check_known_vulnerabilities(package_name: str, version: str) -> List[Dict[str, Any]]:
        """Check for known CVEs (simplified - would integrate with OSV/Snyk API)"""
        # Simplified vulnerability database
        known_issues = {
            "lodash": {
                "versions": ["<4.17.21"],
                "cves": ["CVE-2021-23337", "CVE-2020-28500"],
                "severity": "high",
                "description": "Prototype pollution vulnerability"
            },
            "axios": {
                "versions": ["<0.21.1"],
                "cves": ["CVE-2020-28168"],
                "severity": "medium",
                "description": "SSRF vulnerability"
            },
            "requests": {
                "versions": ["<2.31.0"],
                "cves": ["CVE-2023-32681"],
                "severity": "medium",
                "description": "Proxy-Authorization header leak"
            }
        }
        
        issues = []
        if package_name in known_issues:
            vuln = known_issues[package_name]
            issues.append({
                "package": package_name,
                "current_version": version,
                "vulnerable_versions": vuln["versions"],
                "cves": vuln["cves"],
                "severity": vuln["severity"],
                "description": vuln["description"],
                "recommendation": "Update to latest version"
            })
        
        return issues
    
    @staticmethod
    def check_outdated_packages(dependencies: List[Dict[str, str]], 
                                ecosystem: str = "npm") -> List[Dict[str, Any]]:
        """Check which packages are outdated"""
        outdated = []
        
        # Simplified version checking (would integrate with npm/PyPI API)
        for dep in dependencies:
            name = dep.get("name")
            version = dep.get("version", "0.0.0")
            
            # Mock outdated check
            if version.startswith("0.") or version.startswith("1."):
                outdated.append({
                    "package": name,
                    "current": version,
                    "latest": "2.0.0",  # Mock latest version
                    "age": "Very old",
                    "recommendation": f"Update to 2.0.0"
                })
        
        return outdated
    
    @classmethod
    def analyze_dependencies(cls, project_path: str) -> Dict[str, Any]:
        """Full dependency analysis"""
        project_path = Path(project_path)
        results = {
            "dependencies": [],
            "vulnerabilities": [],
            "outdated": [],
            "unused": [],
            "stats": {}
        }
        
        # Check for package.json (Node.js)
        package_json_path = project_path / "package.json"
        if package_json_path.exists():
            pkg_data = cls.parse_package_json(str(package_json_path))
            if pkg_data:
                deps = pkg_data.get("dependencies", {})
                dev_deps = pkg_data.get("devDependencies", {})
                
                all_deps = []
                for name, version in {**deps, **dev_deps}.items():
                    all_deps.append({"name": name, "version": version.lstrip("^~")})
                
                results["dependencies"] = all_deps
                
                # Check vulnerabilities
                for dep in all_deps:
                    vulns = cls.check_known_vulnerabilities(dep["name"], dep["version"])
                    results["vulnerabilities"].extend(vulns)
                
                # Check outdated
                results["outdated"] = cls.check_outdated_packages(all_deps, "npm")
        
        # Check for requirements.txt (Python)
        requirements_path = project_path / "requirements.txt"
        if requirements_path.exists():
            deps = cls.parse_requirements_txt(str(requirements_path))
            results["dependencies"].extend(deps)
            
            # Check vulnerabilities
            for dep in deps:
                vulns = cls.check_known_vulnerabilities(dep["name"], dep["version"])
                results["vulnerabilities"].extend(vulns)
            
            # Check outdated
            outdated = cls.check_outdated_packages(deps, "pip")
            results["outdated"].extend(outdated)
        
        # Generate stats
        results["stats"] = {
            "total_dependencies": len(results["dependencies"]),
            "vulnerabilities_found": len(results["vulnerabilities"]),
            "outdated_count": len(results["outdated"]),
            "critical_vulns": sum(1 for v in results["vulnerabilities"] 
                                 if v.get("severity") == "critical"),
            "high_vulns": sum(1 for v in results["vulnerabilities"] 
                             if v.get("severity") == "high")
        }
        
        return results


def format_dependency_report(analysis: Dict[str, Any]) -> str:
    """Format dependency analysis into readable report"""
    stats = analysis.get("stats", {})
    vulns = analysis.get("vulnerabilities", [])
    outdated = analysis.get("outdated", [])
    
    report = f"""
# πŸ“¦ Dependency Analysis Report

## πŸ“Š Summary
- **Total Dependencies**: {stats.get('total_dependencies', 0)}
- **Vulnerabilities**: {stats.get('vulnerabilities_found', 0)}
  - πŸ”΄ Critical: {stats.get('critical_vulns', 0)}
  - 🟠 High: {stats.get('high_vulns', 0)}
- **Outdated Packages**: {stats.get('outdated_count', 0)}

"""
    
    if vulns:
        report += "## πŸ›‘οΈ Security Vulnerabilities\n\n"
        for vuln in vulns:
            severity = vuln.get("severity", "unknown").upper()
            emoji = "πŸ”΄" if severity == "CRITICAL" else "🟠" if severity == "HIGH" else "🟑"
            
            report += f"### {emoji} {vuln.get('package')} {vuln.get('current_version')}\n"
            report += f"**CVEs**: {', '.join(vuln.get('cves', []))}\n"
            report += f"**Description**: {vuln.get('description')}\n"
            report += f"**Fix**: {vuln.get('recommendation')}\n\n"
    
    if outdated:
        report += "## πŸ“… Outdated Packages\n\n"
        for pkg in outdated[:10]:  # Show top 10
            report += f"- **{pkg.get('package')}**: {pkg.get('current')} β†’ {pkg.get('latest')}\n"
    
    if not vulns and not outdated:
        report += "βœ… **All dependencies are up-to-date and secure!**\n"
    
    return report