From cbe2d92be21cb046add524aa57c454e12c0bbc02 Mon Sep 17 00:00:00 2001 From: NadaBhm Date: Wed, 26 Aug 2026 16:50:43 +0100 Subject: [PATCH 1/2] fix: filter local folder upload to exclude venv/node_modules - Frontend: whitelist extensions and skip excluded dirs (.venv, node_modules, etc.) - Backend: filter uploaded files and repo metadata counting - Scanners: add --exclude flags for venv/node_modules - Fix jobs.ts tokenStore key mismatch (access_token vs devguard.access_token) - Delete versioned artifacts (codesec_result.json, pytest_output.txt) - Rename 'payload samples' -> 'payload_samples' --- src/agents/codesec/agent.py | 12 ++- src/agents/codesec/scanners/dependencies.py | 1 + src/agents/codesec/scanners/sast.py | 3 +- src/agents/codesec/scanners/secrets.py | 5 +- src/backend/api/jobs.py | 7 +- src/frontend/src/pages/NewRunPage.tsx | 97 ++++++++++++++++++++- 6 files changed, 119 insertions(+), 6 deletions(-) diff --git a/src/agents/codesec/agent.py b/src/agents/codesec/agent.py index 0938563..7d0bad5 100644 --- a/src/agents/codesec/agent.py +++ b/src/agents/codesec/agent.py @@ -243,7 +243,8 @@ def _clone_repo(self, repo_url: str, job_id: str) -> Path: 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()) @@ -373,6 +374,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) 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 af7a67d..3d02c16 100644 --- a/src/backend/api/jobs.py +++ b/src/backend/api/jobs.py @@ -106,12 +106,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() @@ -232,7 +237,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/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) } From d025083eaf64502a790c77927d007fa0a210634a Mon Sep 17 00:00:00 2001 From: NadaBhm Date: Fri, 28 Aug 2026 10:19:34 +0100 Subject: [PATCH 2/2] final fix of local folder upload --- src/frontend/src/api/jobs.ts | 4 ++-- 1 file changed, 2 insertions(+), 2 deletions(-) diff --git a/src/frontend/src/api/jobs.ts b/src/frontend/src/api/jobs.ts index e8de599..972c57f 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 @@ -77,7 +77,7 @@ export const jobsApi = { upload: (formData: FormData) => fetch(`/api/jobs/upload`, { method: "POST", headers: { - Authorization: `Bearer ${localStorage.getItem("access_token") ?? ""}`, + Authorization: `Bearer ${tokenStore.access ?? ""}`, }, body: formData, }).then(async (res) => {