Buckets:

download
raw
12 kB
"""Push event scan handler."""
import logging
from typing import List
from ..models.config import PushScanConfig
from ..models.events import PushEvent
from ..utils.github_api import GitHubAPI
from ..utils.sarif import Finding, SARIFGenerator, Severity
logger = logging.getLogger(__name__)
class PushScanResult:
"""Result of a push scan."""
def __init__(self):
self.findings: List[Finding] = []
self.scanned_files: int = 0
self.errors: List[str] = []
self.new_findings: List[Finding] = []
self.branch: str = ""
self.commit_sha: str = ""
class PushScanHandler:
"""Handle push event security scans."""
def __init__(self, github_api: GitHubAPI, config: PushScanConfig):
self.github_api = github_api
self.config = config
self.sarif = SARIFGenerator()
async def handle(self, event: PushEvent) -> PushScanResult:
"""Handle push scan event.
Args:
event: Push event
Returns:
Scan result
"""
result = PushScanResult()
owner = event.repository.owner.login
repo = event.repository.name
# Extract branch name
branch = event.ref.replace("refs/heads/", "")
result.branch = branch
result.commit_sha = event.after
logger.info(f"Starting push scan for {owner}/{repo}@{branch}")
# Check if branch should be scanned
if not self._should_scan_branch(branch):
logger.info(f"Skipping scan for branch {branch}")
return result
try:
# Get changed files from commits
changed_files = self._get_changed_files(event)
result.scanned_files = len(changed_files)
logger.info(f"Scanning {len(changed_files)} changed files")
# Scan each file
for file_path in changed_files:
findings = await self._scan_file(owner, repo, file_path, event.after)
result.findings.extend(findings)
self.sarif.add_findings(findings)
# Identify new findings (compare with previous commit)
result.new_findings = await self._identify_new_findings(owner, repo, event.before, result.findings)
# Upload SARIF to GitHub Security tab
if self.config.sarif_upload:
await self._upload_sarif(owner, repo, event)
# Create issues for new critical findings
if self.config.create_issues and result.new_findings:
await self._create_issues(owner, repo, result.new_findings, event)
logger.info(f"Push scan complete: {len(result.findings)} findings")
except Exception as e:
logger.exception("Push scan failed")
result.errors.append(str(e))
return result
def _should_scan_branch(self, branch: str) -> bool:
"""Check if branch should be scanned."""
return branch in self.config.branches or "*" in self.config.branches
def _get_changed_files(self, event: PushEvent) -> List[str]:
"""Extract changed file paths from push event."""
files = set()
for commit in event.commits:
files.update(commit.added)
files.update(commit.modified)
# Filter out ignored paths
filtered = []
for f in files:
if not any(f.startswith(ignore) or f.endswith(ignore.replace("*", "")) for ignore in self.config.ignore_paths):
filtered.append(f)
return filtered
async def _scan_file(self, owner: str, repo: str, file_path: str, ref: str) -> List[Finding]:
"""Scan a single file."""
findings = []
# Get file content
content = await self.github_api.get_file_content(owner, repo, file_path, ref)
if not content:
return findings
# Run configured tools
for tool in self.config.tools:
tool_findings = await self._run_tool(tool, file_path, content)
findings.extend(tool_findings)
return findings
async def _run_tool(self, tool: str, filename: str, content: str) -> List[Finding]:
"""Run security tool on file."""
findings = []
# Simulated security checks
if tool == "semgrep":
findings.extend(self._run_semgrep(filename, content))
elif tool == "trufflehog":
findings.extend(self._run_trufflehog(filename, content))
elif tool == "trivy":
findings.extend(self._run_trivy(filename, content))
elif tool == "bandit":
findings.extend(self._run_bandit(filename, content))
return findings
def _run_semgrep(self, filename: str, content: str) -> List[Finding]:
"""Run Semgrep checks."""
findings = []
lines = content.split("\n")
import re
patterns = [
(r"eval\s*\(", "eval-usage", "Dangerous eval() usage", Severity.HIGH),
(r"exec\s*\(", "exec-usage", "Dangerous exec() usage", Severity.HIGH),
(r"pickle\.(loads|load)", "pickle-deserialization", "Unsafe deserialization", Severity.HIGH),
(r"yaml\.load\s*\(", "yaml-unsafe-load", "Unsafe YAML loading", Severity.HIGH),
]
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"semgrep.{rule_id}",
message=message,
file_path=filename,
line_number=i,
severity=severity,
code_snippet=line.strip()[:200],
)
)
return findings
def _run_trufflehog(self, filename: str, content: str) -> List[Finding]:
"""Run TruffleHog (secret detection)."""
findings = []
lines = content.split("\n")
import re
patterns = [
(r"(?i)api[_-]?key\s*[:=]\s*['\"][a-zA-Z0-9]{20,}['\"]", "api-key", "API Key exposed"),
(r"(?i)password\s*[:=]\s*['\"][^'\"]{8,}['\"]", "password", "Hardcoded password"),
(r"sk-[a-zA-Z0-9]{48}", "openai-key", "OpenAI API key"),
(r"gh[pousr]_[a-zA-Z0-9]{36}", "github-token", "GitHub token"),
]
for pattern, rule_id, message in patterns:
for i, line in enumerate(lines, 1):
if re.search(pattern, line):
findings.append(
Finding(
rule_id=f"trufflehog.{rule_id}",
message=message,
file_path=filename,
line_number=i,
severity=Severity.CRITICAL,
cwe="CWE-798",
code_snippet=line.strip()[:200],
)
)
return findings
def _run_trivy(self, filename: str, content: str) -> List[Finding]:
"""Run Trivy (dependency scanning)."""
findings = []
# Check for vulnerable dependencies in requirements.txt
if filename.endswith("requirements.txt"):
vulnerable_packages = {
"requests": ("2.20.0", "CVE-2018-18074"),
"urllib3": ("1.23", "CVE-2019-11324"),
"django": ("2.1.0", "CVE-2019-19844"),
}
lines = content.split("\n")
import re
for i, line in enumerate(lines, 1):
for pkg, (min_ver, cve) in vulnerable_packages.items():
if re.search(rf"^{pkg}[=<>]", line, re.IGNORECASE):
findings.append(
Finding(
rule_id=f"trivy.{pkg}-vuln",
message=f"Potentially vulnerable {pkg} version",
file_path=filename,
line_number=i,
severity=Severity.HIGH,
description=f"Package {pkg} may be vulnerable ({cve})",
recommendation=f"Update to {pkg}>={min_ver}",
)
)
# Check Dockerfile
if "Dockerfile" in filename:
lines = content.split("\n")
for i, line in enumerate(lines, 1):
if line.strip().startswith("FROM") and ":latest" in line:
findings.append(
Finding(
rule_id="trivy.latest-tag",
message="Avoid using 'latest' tag in FROM",
file_path=filename,
line_number=i,
severity=Severity.MEDIUM,
code_snippet=line.strip()[:200],
)
)
return findings
def _run_bandit(self, filename: str, content: str) -> List[Finding]:
"""Run Bandit (Python security)."""
findings = []
if not filename.endswith(".py"):
return findings
lines = content.split("\n")
import re
patterns = [
(r"assert\s+", "assert-used", "Assert removed in optimized code", Severity.LOW),
(r"except\s*:", "bare-except", "Bare except clause", Severity.MEDIUM),
]
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
)
)
return findings
async def _identify_new_findings(
self, owner: str, repo: str, before_sha: str, current_findings: List[Finding]
) -> List[Finding]:
"""Identify findings that are new in this push."""
# In production, this would compare with previous scan results
# For now, return all findings as new
return current_findings
async def _upload_sarif(self, owner: str, repo: str, event: PushEvent) -> None:
"""Upload SARIF results to GitHub Security tab."""
try:
sarif_data = self.sarif.generate_json()
await self.github_api.upload_sarif(
owner=owner, repo=repo, sarif_data=sarif_data, commit_sha=event.after, ref=event.ref
)
logger.info(f"SARIF uploaded to {owner}/{repo}")
except Exception as e:
logger.error(f"Failed to upload SARIF: {e}")
async def _create_issues(self, owner: str, repo: str, findings: List[Finding], event: PushEvent) -> None:
"""Create GitHub issues for new critical findings."""
# Only create issues for critical/high findings
critical_findings = [f for f in findings if f.severity in [Severity.CRITICAL, Severity.HIGH]]
for finding in critical_findings[:5]: # Limit to 5 issues per push
title = f"[Security] {finding.rule_id} in {finding.file_path}"
f"""## Security Alert
**Rule:** {finding.rule_id}
**Severity:** {finding.severity.value.upper()}
**File:** `{finding.file_path}:{finding.line_number}`
### Description
{finding.description}
### Recommendation
{finding.recommendation or "Please review and fix this security issue."}
---
*This issue was automatically created by Zen-AI Security Scan*
*Commit: {event.after[:7]}*
"""
try:
# Note: Would need to implement create_issue in GitHubAPI
logger.info(f"Would create issue: {title}")
except Exception as e:
logger.error(f"Failed to create issue: {e}")

Xet Storage Details

Size:
12 kB
·
Xet hash:
ddf96a168f618070ae5570f40ed18a70a59ce1e9d85d264034554bcfa76119e5

Xet efficiently stores files, intelligently splitting them into unique chunks and accelerating uploads and downloads. More info.