DeepTeam is a framework to red team LLMs and AI agents.
feat: collect modules
tanayvaswani8d2a9805f076
diff --git a/deepteam/code_scanner/collect/__init__.py b/deepteam/code_scanner/collect/__init__.pynew file mode 100644index 00000000..ca793b83--- /dev/null+++ b/deepteam/code_scanner/collect/__init__.py@@ -0,0 +1,4 @@+from .files import collect_files+from .git import collect_changed_files++__all__ = ["collect_files", "collect_changed_files"]diff --git a/deepteam/code_scanner/collect.py b/deepteam/code_scanner/collect/base.pysimilarity index 54%rename from deepteam/code_scanner/collect.pyrename to deepteam/code_scanner/collect/base.pyindex de2f7c6f..3df74be1 100644--- a/deepteam/code_scanner/collect.py+++ b/deepteam/code_scanner/collect/base.py@@ -1,10 +1,8 @@import fnmatch-import os-import subprocessfrom pathlib import Pathfrom typing import List, Optional-from .schema import CodeChunk+from ..schema import CodeChunkDEFAULT_MAX_FILE_BYTES = 1_500_000DEFAULT_MAX_CHUNK_CHARS = 12_000@@ -172,90 +170,3 @@ def _chunk_path(if text is None:return []return _chunk_text(rel_path, text, language, max_chunk_chars)---def _iter_files(root: Path):- """Yield (absolute_path, posix_relative_path) for candidate files."""- if root.is_file():- yield root, root.name- return- for dirpath, dirnames, filenames in os.walk(root):- # Prune skipped directories in place so os.walk doesn't descend them.- dirnames[:] = [- directory for directory in dirnames if directory not in SKIP_DIRS- ]- for filename in filenames:- abs_path = Path(dirpath) / filename- rel_path = os.path.relpath(abs_path, root).replace(os.sep, "/")- yield abs_path, rel_path---def collect_files(- path: str,- include: Optional[List[str]] = None,- exclude: Optional[List[str]] = None,- max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,- max_chunk_chars: int = DEFAULT_MAX_CHUNK_CHARS,-) -> List[CodeChunk]:- """Collect scannable code chunks from a file or directory tree.-- Args:- path: A source file or a directory to walk.- include: Optional glob allow-list (matched against the relative path).- If given, a file must match at least one pattern.- exclude: Optional glob deny-list (matched against the relative path).- max_file_bytes: Skip files larger than this.- max_chunk_chars: Split files into chunks no larger than this.- """- root = Path(path)- chunks: List[CodeChunk] = []- for abs_path, rel_path in _iter_files(root):- if not _passes_filters(rel_path, include, exclude):- continue- chunks.extend(- _chunk_path(abs_path, rel_path, max_file_bytes, max_chunk_chars)- )- return chunks---def _git_changed_files(root: Path, base: str, head: Optional[str]) -> List[str]:- ref = f"{base}..{head}" if head else base- try:- out = subprocess.run(- ["git", "-C", str(root), "diff", "--name-only", ref],- capture_output=True,- text=True,- check=True,- ).stdout- except (subprocess.CalledProcessError, FileNotFoundError) as e:- raise RuntimeError(f"git diff --name-only {ref} failed: {e}") from e- return [line.strip() for line in out.splitlines() if line.strip()]---def collect_changed_files(- path: str,- base: str,- head: Optional[str] = None,- include: Optional[List[str]] = None,- exclude: Optional[List[str]] = None,- max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,- max_chunk_chars: int = DEFAULT_MAX_CHUNK_CHARS,-) -> List[CodeChunk]:- """Collect chunks for only the files changed between two git refs.-- Scans whole changed files (not line-level hunks), coarse but reliable for- PR/commit scanning. `path` should be the repository root. If `head` is- omitted, compares `base` against the working tree.- """- root = Path(path)- chunks: List[CodeChunk] = []- for rel_path in _git_changed_files(root, base, head):- abs_path = root / rel_path- if not abs_path.is_file():- continue # deleted or renamed away- if not _passes_filters(rel_path, include, exclude):- continue- chunks.extend(- _chunk_path(abs_path, rel_path, max_file_bytes, max_chunk_chars)- )- return chunksdiff --git a/deepteam/code_scanner/collect/files.py b/deepteam/code_scanner/collect/files.pynew file mode 100644index 00000000..8cf7b19f--- /dev/null+++ b/deepteam/code_scanner/collect/files.py@@ -0,0 +1,56 @@+import os+from pathlib import Path+from typing import List, Optional++from ..schema import CodeChunk+from .base import (+ DEFAULT_MAX_CHUNK_CHARS,+ DEFAULT_MAX_FILE_BYTES,+ SKIP_DIRS,+ _chunk_path,+ _passes_filters,+)+++def _iter_files(root: Path):+ """+ Yield (absolute_path, posix_relative_path) for candidate files.+ """+ if root.is_file():+ yield root, root.name+ return+ for dirpath, dirnames, filenames in os.walk(root):+ dirnames[:] = [+ directory for directory in dirnames if directory not in SKIP_DIRS+ ]+ for filename in filenames:+ abs_path = Path(dirpath) / filename+ rel_path = os.path.relpath(abs_path, root).replace(os.sep, "/")+ yield abs_path, rel_path+++def collect_files(+ path: str,+ include: Optional[List[str]] = None,+ exclude: Optional[List[str]] = None,+ max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,+ max_chunk_chars: int = DEFAULT_MAX_CHUNK_CHARS,+) -> List[CodeChunk]:+ """Collect scannable code chunks from a file or directory tree.++ Args:+ path: A source file or a directory to walk.+ include: Optional glob allow-list (matched against the relative path). If given, a file must match at least one pattern.+ exclude: Optional glob deny-list (matched against the relative path).+ max_file_bytes: Skip files larger than this.+ max_chunk_chars: Split files into chunks no larger than this.+ """+ root = Path(path)+ chunks: List[CodeChunk] = []+ for abs_path, rel_path in _iter_files(root):+ if not _passes_filters(rel_path, include, exclude):+ continue+ chunks.extend(+ _chunk_path(abs_path, rel_path, max_file_bytes, max_chunk_chars)+ )+ return chunksdiff --git a/deepteam/code_scanner/collect/git.py b/deepteam/code_scanner/collect/git.pynew file mode 100644index 00000000..227f513a--- /dev/null+++ b/deepteam/code_scanner/collect/git.py@@ -0,0 +1,54 @@+import subprocess+from pathlib import Path+from typing import List, Optional++from ..schema import CodeChunk+from .base import (+ DEFAULT_MAX_CHUNK_CHARS,+ DEFAULT_MAX_FILE_BYTES,+ _chunk_path,+ _passes_filters,+)+++def _git_changed_files(root: Path, base: str, head: Optional[str]) -> List[str]:+ ref = f"{base}..{head}" if head else base+ try:+ out = subprocess.run(+ ["git", "-C", str(root), "diff", "--name-only", ref],+ capture_output=True,+ text=True,+ check=True,+ ).stdout+ except (subprocess.CalledProcessError, FileNotFoundError) as e:+ raise RuntimeError(f"git diff --name-only {ref} failed: {e}") from e+ return [line.strip() for line in out.splitlines() if line.strip()]+++def collect_changed_files(+ path: str,+ base: str,+ head: Optional[str] = None,+ include: Optional[List[str]] = None,+ exclude: Optional[List[str]] = None,+ max_file_bytes: int = DEFAULT_MAX_FILE_BYTES,+ max_chunk_chars: int = DEFAULT_MAX_CHUNK_CHARS,+) -> List[CodeChunk]:+ """Collect chunks for only the files changed between two git refs.++ Scans whole changed files (not line-level hunks), coarse but reliable for+ PR/commit scanning. `path` should be the repository root. If `head` is+ omitted, compares `base` against the working tree.+ """+ root = Path(path)+ chunks: List[CodeChunk] = []+ for rel_path in _git_changed_files(root, base, head):+ abs_path = root / rel_path+ if not abs_path.is_file():+ continue # deleted or renamed away+ if not _passes_filters(rel_path, include, exclude):+ continue+ chunks.extend(+ _chunk_path(abs_path, rel_path, max_file_bytes, max_chunk_chars)+ )+ return chunksdiff --git a/deepteam/code_scanner/engines/__init__.py b/deepteam/code_scanner/engines/__init__.pyindex 63fa6f34..54b2b3c9 100644--- a/deepteam/code_scanner/engines/__init__.py+++ b/deepteam/code_scanner/engines/__init__.py@@ -1,9 +1,3 @@-"""-Code-scan engines: the built-in deepeval judge (a `None` engine) plus optional-agentic harnesses (Codex, Claude, Cursor). `resolve_provider` and `build_engine`-tie the modules together; the harness SDKs are imported lazily.-"""-import importlib.utilimport osfrom typing import Optionaldiff --git a/deepteam/code_scanner/github/__init__.py b/deepteam/code_scanner/github/__init__.pyindex ed8c52bc..ed0c3333 100644--- a/deepteam/code_scanner/github/__init__.py+++ b/deepteam/code_scanner/github/__init__.py@@ -1,5 +1,3 @@-"""GitHub integration for code scanning (PR comments via deepteam[bot])."""-from .report import post_pr_comments__all__ = ["post_pr_comments"]diff --git a/examples/code_scan_harness_example.py b/examples/code_scan_harness_example.pynew file mode 100644index 00000000..7fec6e10--- /dev/null+++ b/examples/code_scan_harness_example.py@@ -0,0 +1,75 @@+"""+Smoke-test the DeepTeam code scanner through an agentic harness, using that vendor's own API key.++Each harness SDK is an optional extra. Install the one you want and set its key:++ poetry add "deepteam[codex]" && export OPENAI_API_KEY=... # Codex+ poetry add "deepteam[claude]" && export ANTHROPIC_API_KEY=... # Claude Code+ poetry add "deepteam[cursor]" && export CURSOR_API_KEY=... # Cursor CLI++Then run this script, naming the provider (and optionally a model):++ poetry run python examples/code_scan_harness_example.py codex+ poetry run python examples/code_scan_harness_example.py claude <model>+ poetry run python examples/code_scan_harness_example.py cursor+ poetry run python examples/code_scan_harness_example.py+ poetry run python examples/code_scan_harness_example.py deepeval gpt-4o++The exact same selection works on the CLI:++ poetry run deepteam scan . --provider codex+ poetry run deepteam scan . --provider claude --model <model>+"""++import sys++from deepteam.code_scanner import (+ CodeChunk,+ CodeScanner,+ build_engine,+ resolve_provider,+)++VULNERABLE_CODE = '''\+import subprocess+++def handle(llm_output: str):+ eval(llm_output)+ subprocess.run(llm_output, shell=True)+ api_key = "sk-this-should-not-be-here-1234567890"+ return api_key+'''+++def main() -> None:+ provider = resolve_provider(sys.argv[1] if len(sys.argv) > 1 else None)+ model = sys.argv[2] if len(sys.argv) > 2 else None+ print(f"Provider: {provider} | Model: {model or '(provider default)'}\n")++ engine = build_engine(provider, model)+ scanner = CodeScanner(engine=engine)++ chunks = [+ CodeChunk(+ file_path="agent.py",+ content=VULNERABLE_CODE,+ language="python",+ )+ ]+ findings = scanner.scan(chunks)++ print(f"{len(findings)} finding(s):")+ for finding in findings:+ loc = f"{finding.filePath}:{finding.lineStart}"+ print(+ f" [{finding.severity.upper():8}] {loc} "+ f"{finding.vulnerability} / {finding.vulnerabilityType}"+ )+ print(f" {finding.reason}")+ if finding.recommendation:+ print(f" fix: {finding.recommendation}")+++if __name__ == "__main__":+ main()