diff --git a/src/agents/codesec/agent.py b/src/agents/codesec/agent.py index 2a233c4..95b7e6c 100644 --- a/src/agents/codesec/agent.py +++ b/src/agents/codesec/agent.py @@ -260,7 +260,8 @@ def _clone_repo(self, repo_url: str, job_id: str, commit_sha: str | None = None) def _get_repo_metadata(self, repo_path: Path, repo_url: str) -> RepoMetadata: """Extract repository metadata from cloned directory.""" repo_name = repo_url.rstrip("/").split("/")[-1] - total_files = sum(1 for _ in repo_path.rglob("*") if _.is_file()) + SKIP_DIRS = {".venv", "node_modules", ".git", "__pycache__", ".pytest_cache", "dist", "build"} + total_files = sum(1 for f in repo_path.rglob("*") if f.is_file() and not any(part in SKIP_DIRS for part in f.relative_to(repo_path).parts)) lang_breakdown = get_language_breakdown(repo_path) total_loc = sum(lang_breakdown.values()) @@ -385,6 +386,15 @@ def _add_phase(name: str, status: PhaseStatus, started: datetime | None = None, if repo_path is None: repo_path = self._clone_repo(validated_url or "", job_id, commit_sha=commit_sha) else: + # Local path: apply same size/file limits as cloned repos + total_size = sum(f.stat().st_size for f in repo_path.rglob("*") if f.is_file()) + total_size_mb = total_size / (1024 * 1024) + if total_size_mb > MAX_REPO_SIZE_MB: + raise RuntimeError(f"Local folder exceeds {MAX_REPO_SIZE_MB} MB limit ({total_size_mb:.1f} MB)") + total_files = sum(1 for _ in repo_path.rglob("*") if _.is_file()) + if total_files > MAX_FILES_PER_REPO: + raise RuntimeError(f"Local folder exceeds {MAX_FILES_PER_REPO} file limit ({total_files} files)") + # Local path: run RAG ingestion if available try: from lib.rag.ingestion import ingest_repo diff --git a/src/agents/codesec/scanners/dependencies.py b/src/agents/codesec/scanners/dependencies.py index cd1c8ef..5d056eb 100644 --- a/src/agents/codesec/scanners/dependencies.py +++ b/src/agents/codesec/scanners/dependencies.py @@ -148,6 +148,7 @@ def _run_trivy_fs(repo_path: Path) -> list[VulnerablePackage]: report_path = repo_path / ".codesec_trivy_deps.json" cmd = [ tool.executable, + "--skip-dirs", ".venv,node_modules,__pycache__,.pytest_cache,dist,build", "fs", "--scanners=vuln", "--format=json", diff --git a/src/agents/codesec/scanners/sast.py b/src/agents/codesec/scanners/sast.py index 9725083..173b2c9 100644 --- a/src/agents/codesec/scanners/sast.py +++ b/src/agents/codesec/scanners/sast.py @@ -78,7 +78,6 @@ def _run_semgrep(repo_path: Path) -> list[SASTFinding]: logger.info("No source files found for Semgrep scan.") return [] - # FIX #4: --include takes glob patterns, not a file list path cmd = [ tool.executable, "--config=auto", @@ -164,7 +163,7 @@ def _run_bandit(repo_path: Path) -> list[SASTFinding]: "-f", "json", "-x", - "tests,test,venv,.venv", + "tests,test,venv,.venv,node_modules", ] try: diff --git a/src/agents/codesec/scanners/secrets.py b/src/agents/codesec/scanners/secrets.py index 0b64945..fe3cbf3 100644 --- a/src/agents/codesec/scanners/secrets.py +++ b/src/agents/codesec/scanners/secrets.py @@ -136,7 +136,10 @@ def run_secrets_scan(repo_path: Path) -> list[Secret]: try: result = run_subprocess( - ["gitleaks", "detect", "--no-git", "--report-format=json", "--path=."], + [ + "gitleaks", "detect", "--no-git", "--report-format=json", "--path=.", + "--exclude-folders=.venv,node_modules,__pycache__,.pytest_cache,dist,build", + ], cwd=repo_path, timeout=60, ) diff --git a/src/backend/api/jobs.py b/src/backend/api/jobs.py index a8bc4a0..57f5288 100644 --- a/src/backend/api/jobs.py +++ b/src/backend/api/jobs.py @@ -107,12 +107,17 @@ def _create_run( def _store_uploaded_files(files: list[UploadFile], job_id: str) -> Path: base_dir = Path(tempfile.mkdtemp(prefix=f"devguard_upload_{job_id}_")) + # Dossiers à ignorer complètement + SKIP_DIRS = {".venv", "node_modules", ".git", "__pycache__", ".pytest_cache", "dist", "build"} for uploaded in files: if not uploaded.filename: continue relative = PurePosixPath(uploaded.filename) if relative.is_absolute() or any(part in ("..", "") for part in relative.parts): continue + # Ignore si le fichier est dans un dossier exclu + if any(part in SKIP_DIRS for part in relative.parts): + continue target = base_dir.joinpath(*relative.parts) target.parent.mkdir(parents=True, exist_ok=True) content = uploaded.file.read() @@ -234,7 +239,7 @@ def create_job( @router.post("/upload", status_code=201) -def upload_job( +async def upload_job( files: list[UploadFile] = File(...), commit_sha: str = Form("HEAD"), commit_message: str | None = Form(default=None), diff --git a/src/frontend/src/api/jobs.ts b/src/frontend/src/api/jobs.ts index 5f2aaab..8ee3188 100644 --- a/src/frontend/src/api/jobs.ts +++ b/src/frontend/src/api/jobs.ts @@ -1,4 +1,5 @@ import { client } from "./client" +import { tokenStore } from "./tokenStore" import type { ApproveRequest, JobCreate, @@ -7,7 +8,6 @@ import type { JobResponse, } from "../types/jobs" import type { JobResults, TerraformArtifact } from "../types/results" - export interface RollbackRequest { reason?: string target_revision?: number | null @@ -114,8 +114,25 @@ export interface MonitoringResponse { } export const jobsApi = { create: (body: JobCreate) => client.post("/jobs/", body), - remove: (jobId: string) => client.del<{ job_id: string; deleted: boolean }>(`/jobs/${jobId}`), -upload: (formData: FormData) => client.upload("/jobs/upload", formData), + upload: (formData: FormData) => fetch(`/api/jobs/upload`, { + method: "POST", + headers: { + Authorization: `Bearer ${tokenStore.access ?? ""}`, + }, + body: formData, + }).then(async (res) => { + if (!res.ok) { + let detail = res.statusText + try { + const body = (await res.json()) as { detail?: string } + if (typeof body.detail === "string") detail = body.detail + } catch { + // non-JSON body is fine + } + throw new Error(detail) + } + return res.json() as Promise + }), list: () => client.get("/jobs/"), get: (jobId: string) => client.get(`/jobs/${jobId}`), approve: (jobId: string, body: ApproveRequest) => client.post(`/jobs/${jobId}/approve`, body), diff --git a/src/frontend/src/pages/NewRunPage.tsx b/src/frontend/src/pages/NewRunPage.tsx index f803c35..645aa54 100644 --- a/src/frontend/src/pages/NewRunPage.tsx +++ b/src/frontend/src/pages/NewRunPage.tsx @@ -31,11 +31,106 @@ export function NewRunPage() { formData.append("commit_sha", commitSha || "HEAD") formData.append("default_branch", defaultBranch) formData.append("source_type", "local_folder") + + // 1. Dossiers à exclure (inclut les variants de venv + dossiers internes venv) + const SKIP_DIRS = new Set([ + ".venv", "venv", "env", ".env", "virtualenv", ".virtualenvs", "envs", + "node_modules", ".git", "__pycache__", ".pytest_cache", + "dist", "build", ".mypy_cache", ".ruff_cache", "coverage", ".tox", + ".next", ".nuxt", ".output", ".vercel", ".netlify", "out", + ".idea", ".vscode", ".vs", ".github", ".gitlab", + ".cache", "tmp", "temp", "logs", "log", + ".venv_old_broken", ".venv_old", "venv_old", "venv_bak", "env_bak", + // Dossiers internes d'un venv Python (souvent en majuscule sur Windows) + "lib", "lib64", "include", "scripts", "bin", "share", "man", + "site-packages", "dist-packages", "libs", + ]) + + // 2. Extensions à garder (whitelist) + const KEEP_EXTS = new Set([ + ".py", ".ts", ".tsx", ".js", ".jsx", ".mjs", ".cjs", + ".yml", ".yaml", ".json", ".tf", ".hcl", ".tpl", + ".md", ".txt", ".toml", ".ini", ".cfg", ".conf", + ".html", ".htm", ".css", ".scss", ".sass", ".less", ".styl", + ".j2", ".jinja", ".jinja2", + ".sh", ".bash", ".zsh", ".ps1", ".bat", ".cmd", + ".sql", ".graphql", ".proto", ".thrift", + ".rs", ".go", ".java", ".kt", ".scala", ".rb", ".php", ".cs", ".cpp", ".c", ".h", ".hpp", ".swift", ".r", + ".dockerfile" + ]) + + // 3. Fichiers sans extension à garder + const KEEP_NAMES = new Set([ + "dockerfile", "dockerfile.dev", "dockerfile.prod", "dockerfile.test", + "makefile", "makefile.win", "gnumakefile", + "requirements.txt", "requirements-dev.txt", "requirements-test.txt", + "package.json", "package-lock.json", "yarn.lock", "pnpm-lock.yaml", + "pyproject.toml", "setup.py", "setup.cfg", "poetry.lock", "pipfile", "pipfile.lock", + "tsconfig.json", "jsconfig.json", + "vite.config.ts", "vite.config.js", "vite.config.mjs", + "tailwind.config.js", "tailwind.config.ts", + "next.config.js", "next.config.ts", + "jest.config.js", "jest.config.ts", + "babel.config.js", ".babelrc", ".babelrc.json", + ".eslintrc", ".eslintrc.json", ".eslintrc.js", ".eslintrc.yaml", + ".prettierrc", ".prettierrc.json", ".prettierrc.js", + ".gitignore", ".gitattributes", ".editorconfig", ".dockerignore", ".npmignore", + "manifest.json", "robots.txt", "sitemap.xml", + ".env", ".env.example", ".env.local", ".env.development", ".env.production", + "docker-compose.yml", "docker-compose.yaml", "compose.yml", "compose.yaml", + "nginx.conf", "apache.conf", "httpd.conf" + ]) + + let fileCount = 0 + const dirCounts: Record = {} + const passedFiles: string[] = [] + Array.from(uploadedFiles).forEach((file) => { const relPath = (file as File & { webkitRelativePath?: string }).webkitRelativePath || file.name - formData.append("files", file, relPath) + const parts = relPath.split(/[/\\]/) + + // Skip excluded directories + if (parts.some(part => SKIP_DIRS.has(part.toLowerCase()))) return + + const nameLower = file.name.toLowerCase() + const ext = nameLower.includes(".") ? nameLower.slice(nameLower.lastIndexOf(".")) : "" + + // Keep by extension + if (KEEP_EXTS.has(ext)) { + formData.append("files", file, relPath) + fileCount++ + const topDir = parts[0] || "root" + dirCounts[topDir] = (dirCounts[topDir] || 0) + 1 + if (passedFiles.length < 20) passedFiles.push(relPath) + return + } + + // Keep by exact filename + if (KEEP_NAMES.has(nameLower)) { + formData.append("files", file, relPath) + fileCount++ + const topDir = parts[0] || "root" + dirCounts[topDir] = (dirCounts[topDir] || 0) + 1 + if (passedFiles.length < 20) passedFiles.push(relPath) + return + } + + // Skip everything else }) + console.log("=== UPLOAD DIAGNOSTIC ===") + console.log("Files per top directory:", dirCounts) + console.log("First 20 files passing filter:", passedFiles) + console.log("=========================") + + alert(`Uploading ${fileCount} files (skipped ${uploadedFiles.length - fileCount})\n\nTop dirs: ${JSON.stringify(dirCounts, null, 2).slice(0, 500)}`) + if (fileCount === 0) { + throw new Error("No valid files to upload after filtering.") + } + if (fileCount > 2000) { + throw new Error(`Too many files (${fileCount}). Check console (F12) for diagnostic.`) + } + return jobsApi.upload(formData) }