Skip to content

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

feat: add server posts for pr comments

tanayvaswani09e578e1f59b
diff --git a/deepteam/cli/main.py b/deepteam/cli/main.py
index 3cb2f754..4b141842 100644
--- a/deepteam/cli/main.py
+++ b/deepteam/cli/main.py
@@ -438,6 +438,11 @@ def scan(
"--fail-on-findings/--no-fail-on-findings",
help="Exit with code 1 if any findings remain (useful in CI).",
),
+ comment: bool = typer.Option(
+ False,
+ "--comment",
+ help="Post findings to Confident AI so deepteam[bot] comments on the PR (GitHub Actions only).",
+ ),
):
"""Scan source code for AI-security vulnerabilities."""
from deepteam.code_scanner import (
@@ -446,6 +451,7 @@ def scan(
collect_files,
filter_by_severity,
load_config,
+ post_pr_comments,
to_json,
to_markdown,
to_sarif,
@@ -498,6 +504,9 @@ def scan(
else:
typer.echo(rendered)
+ if comment:
+ post_pr_comments(findings)
+
if fail_on_findings and findings:
raise typer.Exit(code=1)
diff --git a/deepteam/code_scanner/__init__.py b/deepteam/code_scanner/__init__.py
index 2bfd0fcb..efde6696 100644
--- a/deepteam/code_scanner/__init__.py
+++ b/deepteam/code_scanner/__init__.py
@@ -17,6 +17,7 @@ from .constants import (
from .template import CodeScanTemplate
from .code_scanner import CodeScanner
from .collect import collect_files, collect_changed_files
+from .github_report import post_pr_comments
from .config import (
CONFIG_FILENAMES,
CodeScanConfig,
@@ -46,6 +47,7 @@ __all__ = [
"CodeScanner",
"collect_files",
"collect_changed_files",
+ "post_pr_comments",
"CONFIG_FILENAMES",
"CodeScanConfig",
"find_config_file",
diff --git a/deepteam/code_scanner/github_report.py b/deepteam/code_scanner/github_report.py
new file mode 100644
index 00000000..4371d80d
--- /dev/null
+++ b/deepteam/code_scanner/github_report.py
@@ -0,0 +1,93 @@
+import json
+import os
+from typing import List, Optional
+
+import requests
+from deepeval.confident.api import get_base_api_url
+
+from .schema import CodeFinding
+
+PR_COMMENTS_ENDPOINT = "/v1/deepteam/code-scan/comments"
+_OIDC_AUDIENCE = "confident-code-scan"
+
+
+def _github_oidc_token() -> Optional[str]:
+ """
+ Fetch the GitHub Actions OIDC token.
+ """
+ req_token = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_TOKEN")
+ req_url = os.environ.get("ACTIONS_ID_TOKEN_REQUEST_URL")
+ if not req_token or not req_url:
+ return None
+ resp = requests.get(
+ f"{req_url}&audience={_OIDC_AUDIENCE}",
+ headers={
+ "Authorization": f"bearer {req_token}"
+ },
+ timeout=15,
+ )
+ resp.raise_for_status()
+ return resp.json().get("value")
+
+
+def _pr_number() -> Optional[int]:
+ """
+ Resolve the PR number from the Actions environment.
+ """
+ event_path = os.environ.get("GITHUB_EVENT_PATH")
+ if event_path and os.path.exists(event_path):
+ try:
+ with open(event_path) as f:
+ event = json.load(f)
+ num = (event.get("pull_request") or {}).get("number")
+ if num is None:
+ num = (event.get("inputs") or {}).get("pr_number")
+ if num is not None:
+ return int(num)
+ except (OSError, ValueError, json.JSONDecodeError):
+ pass
+ parts = os.environ.get("GITHUB_REF", "").split("/")
+ if len(parts) >= 3 and parts[1] == "pull":
+ try:
+ return int(parts[2])
+ except ValueError:
+ return None
+ return None
+
+
+def post_pr_comments(
+ findings: List[CodeFinding],
+ repo: Optional[str] = None,
+ pr_number: Optional[int] = None,
+ api_url: Optional[str] = None,
+) -> None:
+ """
+ Send findings to Confident AI, the platform posts them as deepteam[bot].
+ """
+ repo = repo or os.environ.get("GITHUB_REPOSITORY")
+ if pr_number is None:
+ pr_number = _pr_number()
+ oidc = _github_oidc_token()
+
+ if not repo or pr_number is None:
+ raise RuntimeError(
+ "`deepteam scan --comment` must run in a GitHub Actions "
+ "pull_request job (could not resolve repository or PR number)."
+ )
+ if not oidc:
+ raise RuntimeError(
+ "Could not obtain a GitHub OIDC token. Grant the workflow "
+ "`permissions: id-token: write`."
+ )
+
+ base = api_url or get_base_api_url()
+ payload = {
+ "repo": repo,
+ "pr": pr_number,
+ "oidc": oidc,
+ "findings": [f.model_dump(exclude_none=True) for f in findings],
+ }
+ resp = requests.post(
+ f"{base}{PR_COMMENTS_ENDPOINT}", json=payload, timeout=30
+ )
+ resp.raise_for_status()
diff --git a/tests/test_core/test_code_scanner/test_cli.py b/tests/test_core/test_code_scanner/test_cli.py
index 29ab06ab..75bc6893 100644
--- a/tests/test_core/test_code_scanner/test_cli.py
+++ b/tests/test_core/test_code_scanner/test_cli.py
@@ -85,3 +85,17 @@ class TestScanCli:
def test_bad_format(self, runner, scan_dir):
r = runner.invoke(climain.app, ["scan", scan_dir, "--format", "xml"])
assert r.exit_code != 0
+
+ def test_comment_flag_posts_findings(self, runner, scan_dir, monkeypatch):
+ import deepteam.code_scanner as pkg
+
+ calls = []
+ monkeypatch.setattr(
+ pkg, "post_pr_comments", lambda findings: calls.append(findings)
+ )
+ r = runner.invoke(
+ climain.app,
+ ["scan", scan_dir, "--comment", "--no-fail-on-findings"],
+ )
+ assert r.exit_code == 0
+ assert len(calls) == 1 and len(calls[0]) == 1
diff --git a/tests/test_core/test_code_scanner/test_github_report.py b/tests/test_core/test_code_scanner/test_github_report.py
new file mode 100644
index 00000000..3bef0d3d
--- /dev/null
+++ b/tests/test_core/test_code_scanner/test_github_report.py
@@ -0,0 +1,89 @@
+import json
+
+import pytest
+
+import deepteam.code_scanner.github_report as gr
+from deepteam.code_scanner import CodeFinding
+
+
+class _Resp:
+ def __init__(self, data=None):
+ self._data = data or {}
+
+ def json(self):
+ return self._data
+
+ def raise_for_status(self):
+ pass
+
+
+def _finding():
+ return CodeFinding(
+ filePath="a.py",
+ lineStart=1,
+ vulnerability="SSRF",
+ vulnerabilityType="port_scanning",
+ severity="high",
+ reason="x",
+ )
+
+
+def _setup_env(monkeypatch, tmp_path):
+ monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", "req-tok")
+ monkeypatch.setenv("ACTIONS_ID_TOKEN_REQUEST_URL", "https://oidc/req")
+ monkeypatch.setenv("GITHUB_REPOSITORY", "octo/repo")
+ event = tmp_path / "event.json"
+ event.write_text(json.dumps({"pull_request": {"number": 42}}))
+ monkeypatch.setenv("GITHUB_EVENT_PATH", str(event))
+ monkeypatch.setattr(gr, "get_base_api_url", lambda: "https://api.test")
+
+
+class TestGithubReport:
+ def test_posts_payload_with_oidc(self, monkeypatch, tmp_path):
+ _setup_env(monkeypatch, tmp_path)
+ monkeypatch.setattr(
+ gr.requests,
+ "get",
+ lambda url, headers=None, timeout=None: _Resp({"value": "jwt"}),
+ )
+ captured = {}
+
+ def fake_post(url, json=None, timeout=None):
+ captured["url"] = url
+ captured["json"] = json
+ return _Resp()
+
+ monkeypatch.setattr(gr.requests, "post", fake_post)
+
+ gr.post_pr_comments([_finding()])
+
+ assert (
+ captured["url"] == "https://api.test/v1/deepteam/code-scan/comments"
+ )
+ body = captured["json"]
+ assert body["repo"] == "octo/repo"
+ assert body["pr"] == 42
+ assert body["oidc"] == "jwt"
+ assert body["findings"][0]["vulnerability"] == "SSRF"
+
+ def test_pr_number_from_ref(self, monkeypatch):
+ monkeypatch.delenv("GITHUB_EVENT_PATH", raising=False)
+ monkeypatch.setenv("GITHUB_REF", "refs/pull/77/merge")
+ assert gr._pr_number() == 77
+
+ def test_raises_without_oidc(self, monkeypatch, tmp_path):
+ _setup_env(monkeypatch, tmp_path)
+ monkeypatch.delenv("ACTIONS_ID_TOKEN_REQUEST_TOKEN", raising=False)
+ with pytest.raises(RuntimeError):
+ gr.post_pr_comments([_finding()])
+
+ def test_raises_without_repo(self, monkeypatch, tmp_path):
+ _setup_env(monkeypatch, tmp_path)
+ monkeypatch.delenv("GITHUB_REPOSITORY", raising=False)
+ monkeypatch.setattr(
+ gr.requests,
+ "get",
+ lambda url, headers=None, timeout=None: _Resp({"value": "jwt"}),
+ )
+ with pytest.raises(RuntimeError):
+ gr.post_pr_comments([_finding()])