Skip to content

DeepTeam is a framework to red team LLMs and AI agents.

feat: address reviews, add collect.py

tanayvaswanid402a53ee277
diff --git a/deepteam/code_scanner/__init__.py b/deepteam/code_scanner/__init__.py
index 80d5310c..c5a61055 100644
--- a/deepteam/code_scanner/__init__.py
+++ b/deepteam/code_scanner/__init__.py
@@ -16,6 +16,7 @@ from .constants import (
)
from .template import CodeScanTemplate
from .code_scanner import CodeScanner
+from .collect import collect_files, collect_changed_files
__all__ = [
"CodeChunk",
@@ -30,4 +31,6 @@ __all__ = [
"CODE_CONTEXT_LIMIT",
"CodeScanTemplate",
"CodeScanner",
+ "collect_files",
+ "collect_changed_files",
]
diff --git a/deepteam/code_scanner/code_scanner.py b/deepteam/code_scanner/code_scanner.py
index 56708d7b..3f4ecfa2 100644
--- a/deepteam/code_scanner/code_scanner.py
+++ b/deepteam/code_scanner/code_scanner.py
@@ -10,6 +10,7 @@ from deepteam.attacks.attack_simulator.utils import generate, a_generate
from .constants import CODE_CONTEXT_LIMIT
from .schema import CodeChunk, CodeFinding, CodeFindingsList
+from .taxonomy import VulnerabilityRef
from .template import CodeScanTemplate
logger = logging.getLogger(__name__)
@@ -24,7 +25,7 @@ class CodeScanner:
self,
model: DeepEvalBaseLLM,
template=CodeScanTemplate,
- vulnerabilities: Optional[List[str]] = None,
+ vulnerabilities: Optional[List[VulnerabilityRef]] = None,
guidance: Optional[str] = None,
limit: int = CODE_CONTEXT_LIMIT,
max_concurrent: int = 10,
@@ -61,8 +62,7 @@ class CodeScanner:
def _build_prompt(self, batch: List[CodeChunk]) -> str:
batch_string = json.dumps(
- [chunk.model_dump(exclude_none=True) for chunk in batch],
- indent=2
+ [chunk.model_dump(exclude_none=True) for chunk in batch], indent=2
)
return self.template.generate_code_batch_evaluation(
batch_data=batch_string,
@@ -74,17 +74,18 @@ class CodeScanner:
findings: List[CodeFinding] = []
for batch in self._make_batches(chunks):
try:
- prompt = self._build_prompt(batch)
- res: CodeFindingsList = generate(
- prompt, CodeFindingsList, self.model
- )
- findings.extend(res.findings)
+ findings.extend(self._scan_batch(batch))
except Exception as e:
logger.warning(
"code_scan batch failed (%d chunks): %s", len(batch), e
)
return self._dedupe(findings)
+ def _scan_batch(self, batch: List[CodeChunk]) -> List[CodeFinding]:
+ prompt = self._build_prompt(batch)
+ res: CodeFindingsList = generate(prompt, CodeFindingsList, self.model)
+ return res.findings
+
async def a_scan(self, chunks: List[CodeChunk]) -> List[CodeFinding]:
semaphore = asyncio.Semaphore(self.max_concurrent)
batches = self._make_batches(chunks)
diff --git a/deepteam/code_scanner/collect.py b/deepteam/code_scanner/collect.py
new file mode 100644
index 00000000..de2f7c6f
--- /dev/null
+++ b/deepteam/code_scanner/collect.py
@@ -0,0 +1,261 @@
+import fnmatch
+import os
+import subprocess
+from pathlib import Path
+from typing import List, Optional
+
+from .schema import CodeChunk
+
+DEFAULT_MAX_FILE_BYTES = 1_500_000
+DEFAULT_MAX_CHUNK_CHARS = 12_000
+
+LANGUAGE_BY_EXT = {
+ ".py": "python",
+ ".pyi": "python",
+ ".js": "javascript",
+ ".jsx": "javascript",
+ ".mjs": "javascript",
+ ".cjs": "javascript",
+ ".ts": "typescript",
+ ".tsx": "typescript",
+ ".java": "java",
+ ".kt": "kotlin",
+ ".kts": "kotlin",
+ ".go": "go",
+ ".rb": "ruby",
+ ".php": "php",
+ ".rs": "rust",
+ ".c": "c",
+ ".h": "c",
+ ".cc": "cpp",
+ ".cpp": "cpp",
+ ".cxx": "cpp",
+ ".hpp": "cpp",
+ ".hh": "cpp",
+ ".cs": "csharp",
+ ".scala": "scala",
+ ".swift": "swift",
+ ".sh": "shell",
+ ".bash": "shell",
+ ".zsh": "shell",
+ ".sql": "sql",
+ ".tf": "terraform",
+ ".yaml": "yaml",
+ ".yml": "yaml",
+}
+
+SKIP_DIRS = {
+ ".git",
+ ".hg",
+ ".svn",
+ "node_modules",
+ "bower_components",
+ ".venv",
+ "venv",
+ "env",
+ "__pycache__",
+ ".mypy_cache",
+ ".pytest_cache",
+ ".ruff_cache",
+ "site-packages",
+ "dist",
+ "build",
+ "out",
+ ".next",
+ ".nuxt",
+ "target",
+ "vendor",
+ ".terraform",
+ "coverage",
+ ".turbo",
+ ".cache",
+ ".idea",
+ ".vscode",
+}
+
+SKIP_FILE_GLOBS = [
+ "*.min.js",
+ "*.min.css",
+ "*.map",
+ "*.lock",
+ "package-lock.json",
+ "yarn.lock",
+ "pnpm-lock.yaml",
+ "go.sum",
+]
+
+
+def _matches_any(value: str, patterns: List[str]) -> bool:
+ return any(fnmatch.fnmatch(value, pat) for pat in patterns)
+
+
+def _language_for(path: Path) -> Optional[str]:
+ return LANGUAGE_BY_EXT.get(path.suffix.lower())
+
+
+def _read_text(path: Path, max_file_bytes: int) -> Optional[str]:
+ """Return file text, or None if it's too large, unreadable, or binary."""
+ try:
+ if path.stat().st_size > max_file_bytes:
+ return None
+ data = path.read_bytes()
+ except OSError:
+ return None
+ if b"\x00" in data:
+ return None # binary
+ return data.decode("utf-8", errors="replace")
+
+
+def _chunk_text(
+ rel_path: str, text: str, language: Optional[str], max_chunk_chars: int
+) -> List[CodeChunk]:
+ """Split a file into line-aligned chunks, tracking absolute start lines."""
+ lines = text.splitlines(keepends=True)
+ chunks: List[CodeChunk] = []
+ buf: List[str] = []
+ buf_len = 0
+ start_line = 1
+
+ for line_no, line in enumerate(lines, start=1):
+ if buf and buf_len + len(line) > max_chunk_chars:
+ chunks.append(
+ CodeChunk(
+ file_path=rel_path,
+ content="".join(buf),
+ language=language,
+ start_line=start_line,
+ )
+ )
+ buf = []
+ buf_len = 0
+ start_line = line_no
+ buf.append(line)
+ buf_len += len(line)
+
+ if buf:
+ chunks.append(
+ CodeChunk(
+ file_path=rel_path,
+ content="".join(buf),
+ language=language,
+ start_line=start_line,
+ )
+ )
+ return chunks
+
+
+def _passes_filters(
+ rel_path: str,
+ include: Optional[List[str]],
+ exclude: Optional[List[str]],
+) -> bool:
+ name = rel_path.rsplit("/", 1)[-1]
+ if _matches_any(name, SKIP_FILE_GLOBS):
+ return False
+ if include and not _matches_any(rel_path, include):
+ return False
+ if exclude and _matches_any(rel_path, exclude):
+ return False
+ return True
+
+
+def _chunk_path(
+ abs_path: Path,
+ rel_path: str,
+ max_file_bytes: int,
+ max_chunk_chars: int,
+) -> List[CodeChunk]:
+ language = _language_for(abs_path)
+ if language is None:
+ return []
+ text = _read_text(abs_path, max_file_bytes)
+ 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 chunks
diff --git a/deepteam/code_scanner/constants.py b/deepteam/code_scanner/constants.py
index 5ac2c510..6e1cd7d9 100644
--- a/deepteam/code_scanner/constants.py
+++ b/deepteam/code_scanner/constants.py
@@ -1,21 +1,41 @@
import os
-from typing import List
+from typing import List, Type
+
+from deepteam.vulnerabilities import (
+ BFLA,
+ BOLA,
+ RBAC,
+ SSRF,
+ DebugAccess,
+ ExcessiveAgency,
+ IndirectInstruction,
+ PIILeakage,
+ PromptLeakage,
+ SQLInjection,
+ ShellInjection,
+ ToolMetadataPoisoning,
+ ToolOrchestrationAbuse,
+ UnexpectedCodeExecution,
+)
+from deepteam.vulnerabilities.base_vulnerability import BaseVulnerability
CODE_CONTEXT_LIMIT = int(os.getenv("CODE_CONTEXT_LIMIT", "40000"))
-DEFAULT_CODE_SCAN_VULNERABILITIES: List[str] = [
- "Unexpected Code Execution",
- "Shell Injection",
- "SQL Injection",
- "SSRF",
- "Excessive Agency",
- "Indirect Instruction",
- "Tool Metadata Poisoning",
- "Tool Orchestration Abuse",
- "BFLA",
- "BOLA",
- "RBAC",
- "Debug Access",
- "Prompt Leakage",
- "PII Leakage",
+# Default categories the code scanner looks for: a curated subset of deepteam's
+# taxonomy whose risk is visible in source code.
+DEFAULT_CODE_SCAN_VULNERABILITIES: List[Type[BaseVulnerability]] = [
+ UnexpectedCodeExecution,
+ ShellInjection,
+ SQLInjection,
+ SSRF,
+ ExcessiveAgency,
+ IndirectInstruction,
+ ToolMetadataPoisoning,
+ ToolOrchestrationAbuse,
+ BFLA,
+ BOLA,
+ RBAC,
+ DebugAccess,
+ PromptLeakage,
+ PIILeakage,
]
diff --git a/deepteam/code_scanner/taxonomy.py b/deepteam/code_scanner/taxonomy.py
index 9b677e34..cb5879aa 100644
--- a/deepteam/code_scanner/taxonomy.py
+++ b/deepteam/code_scanner/taxonomy.py
@@ -1,13 +1,23 @@
-from typing import Dict, List, Optional
+from typing import Dict, List, Optional, Type, Union
+from deepteam.vulnerabilities.base_vulnerability import BaseVulnerability
from deepteam.vulnerabilities.constants import VULNERABILITY_INFO_MAP
+VulnerabilityRef = Union[str, Type[BaseVulnerability]]
+
KNOWN_VULNERABILITIES: Dict[str, List[str]] = {
name: list(info.allowed_types)
for name, info in VULNERABILITY_INFO_MAP.items()
}
+def to_name(vulnerability: VulnerabilityRef) -> str:
+ """Normalize a vulnerability class/instance or name string to its name."""
+ if isinstance(vulnerability, str):
+ return vulnerability
+ return vulnerability.name
+
+
def vulnerability_names() -> List[str]:
"""All known deepteam vulnerability category names."""
return list(KNOWN_VULNERABILITIES.keys())
diff --git a/deepteam/code_scanner/template.py b/deepteam/code_scanner/template.py
index f19e3434..a70af6b7 100644
--- a/deepteam/code_scanner/template.py
+++ b/deepteam/code_scanner/template.py
@@ -3,7 +3,11 @@ from typing import List, Optional
from deepteam.code_scanner.constants import (
DEFAULT_CODE_SCAN_VULNERABILITIES,
)
-from deepteam.code_scanner.taxonomy import allowed_types
+from deepteam.code_scanner.taxonomy import (
+ VulnerabilityRef,
+ allowed_types,
+ to_name,
+)
class CodeScanTemplate:
@@ -12,13 +16,15 @@ class CodeScanTemplate:
"""
@staticmethod
- def _render_catalog(vulnerabilities: List[str]) -> str:
+ def _render_catalog(vulnerabilities: List[VulnerabilityRef]) -> str:
"""
Render `- Name: type1, type2` lines, pulling the allowed subtypes
straight from the taxonomy so the judge can only use known labels.
+ Entries may be vulnerability classes or name strings.
"""
lines = []
- for name in vulnerabilities:
+ for vulnerability in vulnerabilities:
+ name = to_name(vulnerability)
types = allowed_types(name)
if not types:
continue
@@ -28,14 +34,14 @@ class CodeScanTemplate:
@staticmethod
def generate_code_batch_evaluation(
batch_data: str,
- vulnerabilities: Optional[List[str]] = None,
+ vulnerabilities: Optional[List[VulnerabilityRef]] = None,
guidance: Optional[str] = None,
) -> str:
"""Build the evaluation prompt for one batch of code chunks.
Args:
batch_data: JSON array of code chunks. Each has `file_path`, `content`, optional `language`, and `start_line` (the absolute line number `content`'s first line maps to).
- vulnerabilities: Category names to scan for. Defaults to `DEFAULT_CODE_SCAN_VULNERABILITIES`. Pass a subset to scope.
+ vulnerabilities: Vulnerability classes or name strings to scan for. Defaults to `DEFAULT_CODE_SCAN_VULNERABILITIES`. Pass a subset to scope.
guidance: Optional free-text project guidance (e.g. "treat any PII exposure as high severity").
"""
vulnerabilities = vulnerabilities or DEFAULT_CODE_SCAN_VULNERABILITIES