Buckets:
AnonymousSpottedToad/candidate_bucket / codebase /python /SHAdd0WTAka_Zen-Ai-Pentest /github_app /handlers /pr_scan.py
| """Pull Request scan handler.""" | |
| import logging | |
| from datetime import datetime, timezone | |
| from typing import Any, Dict, List, Optional | |
| from ..models.config import PRScanConfig, SeverityLevel | |
| from ..models.events import PREvent | |
| from ..utils.github_api import GitHubAPI | |
| from ..utils.sarif import Finding, SARIFGenerator, Severity | |
| logger = logging.getLogger(__name__) | |
| class PRScanResult: | |
| """Result of a PR scan.""" | |
| def __init__(self): | |
| self.findings: List[Finding] = [] | |
| self.scanned_files: int = 0 | |
| self.errors: List[str] = [] | |
| self.duration_ms: int = 0 | |
| self.check_run_id: Optional[int] = None | |
| def has_critical(self) -> bool: | |
| """Check if there are critical findings.""" | |
| return any(f.severity == Severity.CRITICAL for f in self.findings) | |
| def has_high_or_above(self) -> bool: | |
| """Check if there are high or critical findings.""" | |
| return any(f.severity in [Severity.CRITICAL, Severity.HIGH] for f in self.findings) | |
| def count_by_severity(self) -> Dict[str, int]: | |
| """Count findings by severity.""" | |
| counts = {"critical": 0, "high": 0, "medium": 0, "low": 0, "info": 0} | |
| for finding in self.findings: | |
| if finding.severity == Severity.CRITICAL: | |
| counts["critical"] += 1 | |
| elif finding.severity == Severity.HIGH: | |
| counts["high"] += 1 | |
| elif finding.severity == Severity.MEDIUM: | |
| counts["medium"] += 1 | |
| elif finding.severity == Severity.LOW: | |
| counts["low"] += 1 | |
| else: | |
| counts["info"] += 1 | |
| return counts | |
| class PRScanHandler: | |
| """Handle pull request security scans.""" | |
| def __init__(self, github_api: GitHubAPI, config: PRScanConfig): | |
| self.github_api = github_api | |
| self.config = config | |
| self.sarif = SARIFGenerator() | |
| async def handle(self, event: PREvent) -> PRScanResult: | |
| """Handle PR scan event. | |
| Args: | |
| event: Pull request event | |
| Returns: | |
| Scan result | |
| """ | |
| result = PRScanResult() | |
| owner = event.repository.owner.login | |
| repo = event.repository.name | |
| pr_number = event.pull_request.number | |
| head_sha = event.pull_request.head["sha"] | |
| logger.info(f"Starting PR scan for {owner}/{repo}#{pr_number}") | |
| # Create check run if enabled | |
| check_run_id = None | |
| if self.config.check_run: | |
| check_run = await self.github_api.create_check_run( | |
| owner=owner, | |
| repo=repo, | |
| name="๐ Zen-AI Security Scan", | |
| head_sha=head_sha, | |
| status="in_progress", | |
| output={"title": "Security Scan in Progress", "summary": "Analyzing changed files for security issues..."}, | |
| ) | |
| check_run_id = check_run["id"] | |
| result.check_run_id = check_run_id | |
| try: | |
| # Get changed files | |
| files = await self.github_api.list_pr_files(owner, repo, pr_number) | |
| result.scanned_files = len(files) | |
| logger.info(f"Found {len(files)} changed files") | |
| # Filter relevant files | |
| relevant_files = self._filter_files(files) | |
| # Scan each file | |
| for file_info in relevant_files: | |
| findings = await self._scan_file(owner, repo, file_info, event) | |
| result.findings.extend(findings) | |
| self.sarif.add_findings(findings) | |
| # Post results | |
| await self._post_results(event, result, check_run_id) | |
| except Exception as e: | |
| logger.exception("PR scan failed") | |
| result.errors.append(str(e)) | |
| if check_run_id: | |
| await self.github_api.update_check_run( | |
| owner=owner, | |
| repo=repo, | |
| check_run_id=check_run_id, | |
| status="completed", | |
| conclusion="failure", | |
| output={"title": "Security Scan Failed", "summary": f"Scan failed with error: {e}"}, | |
| completed_at=datetime.now(timezone.utc).isoformat(), | |
| ) | |
| return result | |
| def _filter_files(self, files: List[Dict[str, Any]]) -> List[Dict[str, Any]]: | |
| """Filter files to scan based on configuration.""" | |
| filtered = [] | |
| for file in files: | |
| filename = file.get("filename", "") | |
| status = file.get("status", "") | |
| # Skip deleted files | |
| if status == "removed": | |
| continue | |
| # Skip ignored paths | |
| if any( | |
| filename.startswith(ignore) or filename.endswith(ignore.replace("*", "")) | |
| for ignore in self.config.ignore_paths | |
| ): | |
| continue | |
| # Only scan code files | |
| if any( | |
| filename.endswith(ext) | |
| for ext in [ | |
| ".py", | |
| ".js", | |
| ".ts", | |
| ".java", | |
| ".go", | |
| ".rb", | |
| ".php", | |
| ".c", | |
| ".cpp", | |
| ".h", | |
| ".cs", | |
| ".swift", | |
| ".kt", | |
| ".rs", | |
| ".yml", | |
| ".yaml", | |
| ".json", | |
| ".xml", | |
| ".tf", | |
| ".dockerfile", | |
| ] | |
| ): | |
| filtered.append(file) | |
| return filtered | |
| async def _scan_file(self, owner: str, repo: str, file_info: Dict[str, Any], event: PREvent) -> List[Finding]: | |
| """Scan a single file for security issues. | |
| Args: | |
| owner: Repository owner | |
| repo: Repository name | |
| file_info: File information from GitHub API | |
| event: PR event | |
| Returns: | |
| List of findings | |
| """ | |
| findings = [] | |
| filename = file_info["filename"] | |
| ref = event.pull_request.head["sha"] | |
| # Get file content | |
| content = await self.github_api.get_file_content(owner, repo, filename, ref) | |
| if not content: | |
| return findings | |
| # Run security checks based on tools config | |
| for tool in self.config.tools: | |
| tool_findings = await self._run_tool(tool, filename, content) | |
| findings.extend(tool_findings) | |
| return findings | |
| async def _run_tool(self, tool: str, filename: str, content: str) -> List[Finding]: | |
| """Run a security tool on file content. | |
| This is a simplified implementation. In production, this would | |
| integrate with the actual Zen-AI-Pentest tool suite. | |
| """ | |
| findings = [] | |
| # Simulated security checks (replace with actual tool integration) | |
| if tool == "semgrep": | |
| findings.extend(self._semgrep_checks(filename, content)) | |
| elif tool == "trufflehog": | |
| findings.extend(self._trufflehog_checks(filename, content)) | |
| elif tool == "bandit": | |
| findings.extend(self._bandit_checks(filename, content)) | |
| return findings | |
| def _semgrep_checks(self, filename: str, content: str) -> List[Finding]: | |
| """Simulated Semgrep checks.""" | |
| findings = [] | |
| lines = content.split("\n") | |
| patterns = [ | |
| (r"eval\s*\(", "eval-usage", "Dangerous eval() usage", Severity.HIGH, "CWE-95"), | |
| (r"exec\s*\(", "exec-usage", "Dangerous exec() usage", Severity.HIGH, "CWE-78"), | |
| (r"os\.system\s*\(", "os-system", "OS command injection risk", Severity.HIGH, "CWE-78"), | |
| (r"subprocess\.call.*shell\s*=\s*True", "shell-true", "Shell=True is dangerous", Severity.HIGH, "CWE-78"), | |
| ( | |
| r"\.format\s*\(.*\)|%\s*\(", | |
| "string-formatting", | |
| "Potential format string vulnerability", | |
| Severity.MEDIUM, | |
| "CWE-134", | |
| ), | |
| (r"pickle\.(loads|load)\s*\(", "pickle-usage", "Unsafe pickle deserialization", Severity.HIGH, "CWE-502"), | |
| (r"yaml\.load\s*\([^)]*\)", "yaml-unsafe", "Unsafe YAML loading", Severity.HIGH, "CWE-502"), | |
| ] | |
| import re | |
| for pattern, rule_id, message, severity, cwe in patterns: | |
| for i, line in enumerate(lines, 1): | |
| if re.search(pattern, line): | |
| findings.append( | |
| Finding( | |
| rule_id=f"semgrep.{rule_id}", | |
| message=message, | |
| file_path=filename, | |
| line_number=i, | |
| severity=severity, | |
| cwe=cwe, | |
| description=f"Potential security issue detected: {message}", | |
| recommendation="Review and fix this security issue", | |
| code_snippet=line.strip()[:200], | |
| ) | |
| ) | |
| return findings | |
| def _trufflehog_checks(self, filename: str, content: str) -> List[Finding]: | |
| """Simulated TruffleHog (secret detection) checks.""" | |
| findings = [] | |
| lines = content.split("\n") | |
| patterns = [ | |
| (r"(?i)api[_-]?key\s*[:=]\s*['\"][a-zA-Z0-9]{20,}['\"]", "api-key-exposed", "API Key exposed"), | |
| (r"(?i)password\s*[:=]\s*['\"][^'\"]{8,}['\"]", "password-hardcoded", "Hardcoded password"), | |
| (r"(?i)secret\s*[:=]\s*['\"][a-zA-Z0-9]{16,}['\"]", "secret-exposed", "Secret exposed"), | |
| (r"gh[pousr]_[a-zA-Z0-9]{36}", "github-token", "GitHub token exposed"), | |
| (r"sk-[a-zA-Z0-9]{48}", "openai-key", "OpenAI API key exposed"), | |
| (r"AKIA[0-9A-Z]{16}", "aws-key", "AWS Access Key ID exposed"), | |
| ] | |
| import re | |
| for pattern, rule_id, message in patterns: | |
| for i, line in enumerate(lines, 1): | |
| if re.search(pattern, line): | |
| # Mask the secret in output | |
| masked_line = re.sub(r"['\"][a-zA-Z0-9]{8,}['\"]", "'***REDACTED***'", line) | |
| findings.append( | |
| Finding( | |
| rule_id=f"trufflehog.{rule_id}", | |
| message=message, | |
| file_path=filename, | |
| line_number=i, | |
| severity=Severity.CRITICAL, | |
| cwe="CWE-798", | |
| description=f"Hardcoded credential detected: {message}", | |
| recommendation="Use environment variables or a secrets manager instead", | |
| code_snippet=masked_line.strip()[:200], | |
| ) | |
| ) | |
| return findings | |
| def _bandit_checks(self, filename: str, content: str) -> List[Finding]: | |
| """Simulated Bandit checks for Python files.""" | |
| findings = [] | |
| if not filename.endswith(".py"): | |
| return findings | |
| lines = content.split("\n") | |
| patterns = [ | |
| (r"assert\s+.*", "assert-used", "Assert statements are removed in optimized code", Severity.LOW), | |
| (r"hardcoded[_-]?password", "hardcoded-password", "Hardcoded password detected", Severity.HIGH), | |
| (r"MD5|md5", "weak-hash", "Weak hash algorithm detected", Severity.MEDIUM), | |
| (r"SHA1|sha1", "weak-hash-sha1", "SHA1 is considered weak", Severity.LOW), | |
| ] | |
| import re | |
| for pattern, rule_id, message, severity in patterns: | |
| for i, line in enumerate(lines, 1): | |
| if re.search(pattern, line): | |
| findings.append( | |
| Finding( | |
| rule_id=f"bandit.{rule_id}", | |
| message=message, | |
| file_path=filename, | |
| line_number=i, | |
| severity=severity, | |
| code_snippet=line.strip()[:200], | |
| ) | |
| ) | |
| return findings | |
| async def _post_results(self, event: PREvent, result: PRScanResult, check_run_id: Optional[int]) -> None: | |
| """Post scan results to PR.""" | |
| owner = event.repository.owner.login | |
| repo = event.repository.name | |
| pr_number = event.pull_request.number | |
| head_sha = event.pull_request.head["sha"] | |
| # Generate summary | |
| counts = result.count_by_severity() | |
| total = sum(counts.values()) | |
| # Build comment body | |
| body = self._build_comment_body(result, counts, total) | |
| # Post main comment | |
| if self.config.comment_summary and total > 0: | |
| await self.github_api.create_pr_comment(owner, repo, pr_number, body) | |
| # Post inline comments | |
| if self.config.inline_comments: | |
| posted = 0 | |
| for finding in result.findings[: self.config.max_comments]: | |
| try: | |
| await self.github_api.create_inline_comment( | |
| owner=owner, | |
| repo=repo, | |
| pr_number=pr_number, | |
| body=f"**{finding.rule_id}**: {finding.message}", | |
| commit_id=head_sha, | |
| path=finding.file_path, | |
| line=finding.line_number, | |
| ) | |
| posted += 1 | |
| except Exception as e: | |
| logger.warning(f"Failed to post inline comment: {e}") | |
| # Update check run | |
| if check_run_id: | |
| conclusion = self._determine_conclusion(result) | |
| await self.github_api.update_check_run( | |
| owner=owner, | |
| repo=repo, | |
| check_run_id=check_run_id, | |
| status="completed", | |
| conclusion=conclusion, | |
| output={ | |
| "title": f"Security Scan Complete - {total} issues found", | |
| "summary": body, | |
| "annotations": self._build_annotations(result.findings[:50]), | |
| }, | |
| completed_at=datetime.now(timezone.utc).isoformat(), | |
| ) | |
| def _build_comment_body(self, result: PRScanResult, counts: Dict[str, int], total: int) -> str: | |
| """Build PR comment body.""" | |
| if total == 0: | |
| return """## ๐ Zen-AI Security Scan Results | |
| โ **No security issues found!** | |
| All scanned files passed security checks. | |
| """ | |
| body = f"""## ๐ Zen-AI Security Scan Results | |
| **{total} security issues found** in {result.scanned_files} files | |
| | Severity | Count | | |
| |----------|-------| | |
| | ๐ด Critical | {counts["critical"]} | | |
| | ๐ High | {counts["high"]} | | |
| | ๐ก Medium | {counts["medium"]} | | |
| | ๐ข Low | {counts["low"]} | | |
| | โน๏ธ Info | {counts["info"]} | | |
| ### Details | |
| """ | |
| # Add top findings | |
| for finding in result.findings[:10]: | |
| emoji = ( | |
| "๐ด" | |
| if finding.severity == Severity.CRITICAL | |
| else "๐ " | |
| if finding.severity == Severity.HIGH | |
| else "๐ก" | |
| if finding.severity == Severity.MEDIUM | |
| else "๐ข" | |
| ) | |
| body += f"{emoji} **`{finding.file_path}:{finding.line_number}`** - {finding.message}\n" | |
| if len(result.findings) > 10: | |
| body += f"\n*... and {len(result.findings) - 10} more issues*\n" | |
| body += """ | |
| --- | |
| โ ๏ธ **Please review and fix these security issues before merging.** | |
| """ | |
| return body | |
| def _build_annotations(self, findings: List[Finding]) -> List[Dict[str, Any]]: | |
| """Build check run annotations from findings.""" | |
| annotations = [] | |
| for finding in findings: | |
| level = ( | |
| "failure" | |
| if finding.severity in [Severity.CRITICAL, Severity.HIGH] | |
| else "warning" | |
| if finding.severity == Severity.MEDIUM | |
| else "notice" | |
| ) | |
| annotations.append( | |
| { | |
| "path": finding.file_path, | |
| "start_line": finding.line_number, | |
| "end_line": finding.line_number, | |
| "annotation_level": level, | |
| "message": finding.message, | |
| "title": finding.rule_id, | |
| } | |
| ) | |
| return annotations | |
| def _determine_conclusion(self, result: PRScanResult) -> str: | |
| """Determine check run conclusion based on findings.""" | |
| if self.config.block_pr: | |
| if self.config.fail_on == SeverityLevel.CRITICAL and result.has_critical(): | |
| return "failure" | |
| elif self.config.fail_on == SeverityLevel.HIGH and result.has_high_or_above(): | |
| return "failure" | |
| elif self.config.fail_on == SeverityLevel.MEDIUM and result.findings: | |
| return "failure" | |
| return "success" if not result.errors else "failure" | |
Xet Storage Details
- Size:
- 17.2 kB
- Xet hash:
- f23b9d7b3623d579fe93b599bfc62b41ae618a16a11ca0fc40ca6c4257deac73
ยท
Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.