|
| 1 | +"""Record a real agent CLI transcript as a redacted JSON fixture. |
| 2 | +
|
| 3 | +Usage (from the repo root): |
| 4 | +
|
| 5 | + python scripts/record_agent.py --agent claude --scenario success \ |
| 6 | + --skill secret-scanning --workdir examples --timeout 240 |
| 7 | +
|
| 8 | +The script runs the *real* secfoo adapter (same argv, same stdin/stdout |
| 9 | +contract), then stores stdout, stderr, exit code, status and usage under |
| 10 | +``tests/fixtures/agents/<id>/<cli-version>/<scenario>.json``. Before writing |
| 11 | +anything it redacts known credential shapes and refuses to save if a key |
| 12 | +pattern is still present. JSONL transcripts also have opaque provider IDs |
| 13 | +and encrypted reasoning blobs replaced, and bulky tool output truncated, |
| 14 | +while every event and the final report are kept. Environment variable values |
| 15 | +are never recorded -- only their names, for scenarios that isolate credentials. |
| 16 | +""" |
| 17 | + |
| 18 | +from __future__ import annotations |
| 19 | + |
| 20 | +import argparse |
| 21 | +import hashlib |
| 22 | +import json |
| 23 | +import os |
| 24 | +import platform |
| 25 | +import re |
| 26 | +import shutil |
| 27 | +import subprocess |
| 28 | +import sys |
| 29 | +import tempfile |
| 30 | +from datetime import datetime, timezone |
| 31 | +from pathlib import Path |
| 32 | + |
| 33 | +ROOT = Path(__file__).resolve().parents[1] |
| 34 | +sys.path.insert(0, str(ROOT / "src")) |
| 35 | + |
| 36 | +from secfoo.agents.registry import get_adapter |
| 37 | +from secfoo.skills.loader import load_skill |
| 38 | +from secfoo.skills.renderer import TargetContext, render_prompt |
| 39 | + |
| 40 | +REDACTED = "[REDACTED]" |
| 41 | + |
| 42 | +# Provider-generated identifiers and encrypted reasoning are neither useful |
| 43 | +# evidence nor safe to publish; replacing them keeps the transcript small and |
| 44 | +# reviewable without changing the event sequence secfoo parses. |
| 45 | +OPAQUE_KEYS = { |
| 46 | + "id", |
| 47 | + "parentId", |
| 48 | + "sessionId", |
| 49 | + "messageId", |
| 50 | + "apiCallId", |
| 51 | + "reasoningId", |
| 52 | + "reasoningOpaque", |
| 53 | + "toolCallId", |
| 54 | + "interactionId", |
| 55 | + "ownerNativeSessionId", |
| 56 | + "encrypted_content", |
| 57 | + "timestamp", |
| 58 | + "occurredAt", |
| 59 | + "startTime", |
| 60 | + "endTime", |
| 61 | + "cacheExpiresAt", |
| 62 | +} |
| 63 | +MAX_TEXT = 1200 |
| 64 | + |
| 65 | +# Patterns are deliberately broad: a false positive aborts the recording and |
| 66 | +# the operator can inspect it locally, while a false negative would commit a |
| 67 | +# credential to a public repository. |
| 68 | +KEY_PATTERNS = { |
| 69 | + "openai": re.compile(r"\bsk-(?:proj-)?[A-Za-z0-9_-]{16,}\b"), |
| 70 | + "anthropic": re.compile(r"\bsk-ant-[A-Za-z0-9_-]{16,}\b"), |
| 71 | + "github": re.compile(r"\b(?:gh[pousr]_[A-Za-z0-9]{20,}|github_pat_[A-Za-z0-9_]{30,})\b"), |
| 72 | + "aws": re.compile(r"\b(?:AKIA|ASIA)[0-9A-Z]{16}\b"), |
| 73 | + "slack": re.compile(r"\bxox[baprs]-[A-Za-z0-9-]{10,}\b"), |
| 74 | + "private_key": re.compile(r"-----BEGIN [A-Z ]*PRIVATE KEY-----"), |
| 75 | + "assignment": re.compile( |
| 76 | + r"(?i)\b(api[_-]?key|access[_-]?token|auth[_-]?token|password|secret)\b" |
| 77 | + r"\s*[:=]\s*[\"']?(?!" + re.escape(REDACTED) + r")([^\s,;\"']{8,})" |
| 78 | + ), |
| 79 | +} |
| 80 | + |
| 81 | + |
| 82 | +class KeyFound(RuntimeError): |
| 83 | + """A credential-shaped string survived redaction; do not write the file.""" |
| 84 | + |
| 85 | + |
| 86 | +def redact(text: str) -> str: |
| 87 | + for name, pattern in KEY_PATTERNS.items(): |
| 88 | + replacement = r"\1=" + REDACTED if name == "assignment" else REDACTED |
| 89 | + text = pattern.sub(replacement, text) |
| 90 | + return text |
| 91 | + |
| 92 | + |
| 93 | +def assert_no_keys(text: str, *, where: str) -> None: |
| 94 | + for name, pattern in KEY_PATTERNS.items(): |
| 95 | + if pattern.search(text): |
| 96 | + raise KeyFound(f"{name} pattern found in {where}; refusing to save") |
| 97 | + |
| 98 | + |
| 99 | +def scrub_event(event: object, *, keep_full: bool = False) -> object: |
| 100 | + """Keep a real CLI event, minus opaque IDs and oversized non-report text.""" |
| 101 | + if not isinstance(event, dict): |
| 102 | + return event |
| 103 | + # The final main-agent answer is the evidence extract_report() consumes, |
| 104 | + # so it is kept in full; all other long strings (subagent answers, tool |
| 105 | + # output, reasoning deltas, echoed prompt) are truncated with a marker. |
| 106 | + keep = {".data.content"} if keep_full else set() |
| 107 | + |
| 108 | + def scrub(value: object, *, key: str | None = None, path: str = "") -> object: |
| 109 | + if key in OPAQUE_KEYS: |
| 110 | + return REDACTED |
| 111 | + if isinstance(value, dict): |
| 112 | + return {name: scrub(item, key=name, path=f"{path}.{name}") for name, item in value.items()} |
| 113 | + if isinstance(value, list): |
| 114 | + return [scrub(item, key=key, path=f"{path}[]") for item in value] |
| 115 | + if isinstance(value, str): |
| 116 | + value = redact(value) |
| 117 | + if path in keep or len(value) <= MAX_TEXT: |
| 118 | + return value |
| 119 | + return f"{value[:MAX_TEXT]}\n[{REDACTED} {len(value) - MAX_TEXT} chars]" |
| 120 | + return value |
| 121 | + |
| 122 | + return scrub(event) |
| 123 | + |
| 124 | + |
| 125 | +def redact_transcript(text: str) -> str: |
| 126 | + """Redact JSONL stdin/stdout while preserving one line per CLI event.""" |
| 127 | + parsed: list[object] = [] |
| 128 | + for line in text.splitlines(): |
| 129 | + try: |
| 130 | + parsed.append(json.loads(line)) |
| 131 | + except json.JSONDecodeError: |
| 132 | + parsed.append(line) |
| 133 | + |
| 134 | + keep_index = -1 |
| 135 | + for index, event in enumerate(parsed): |
| 136 | + if isinstance(event, dict) and event.get("type") == "assistant.message" and "agentId" not in event: |
| 137 | + keep_index = index |
| 138 | + |
| 139 | + lines = [ |
| 140 | + json.dumps( |
| 141 | + scrub_event(event, keep_full=(index == keep_index)), |
| 142 | + ensure_ascii=False, |
| 143 | + separators=(",", ":"), |
| 144 | + ) |
| 145 | + if isinstance(event, dict) |
| 146 | + else redact(event) |
| 147 | + for index, event in enumerate(parsed) |
| 148 | + ] |
| 149 | + return "\n".join(lines) + ("\n" if text.endswith("\n") else "") |
| 150 | + |
| 151 | + |
| 152 | +def version_slug(version: str) -> str: |
| 153 | + match = re.search(r"\d+\.\d+(?:\.\d+)?", version) |
| 154 | + slug = match.group(0) if match else re.sub(r"[^A-Za-z0-9._-]+", "-", version).strip("-") |
| 155 | + return slug or "unknown" |
| 156 | + |
| 157 | + |
| 158 | +def cli_version(binary: str) -> str: |
| 159 | + try: |
| 160 | + found = shutil.which(binary) or binary |
| 161 | + out = subprocess.run([found, "--version"], capture_output=True, text=True, timeout=15, check=False) |
| 162 | + text = (out.stdout or out.stderr).strip() |
| 163 | + # copilot 1.0.117 prints a package-extraction banner before its |
| 164 | + # version; take the first line that actually looks like a version. |
| 165 | + match = re.search(r"\b\d+\.\d+\.\d+\b", text) |
| 166 | + return match.group(0) if match else (text.splitlines() or ["unknown"])[0] |
| 167 | + except (OSError, subprocess.SubprocessError): |
| 168 | + return "unknown" |
| 169 | + |
| 170 | + |
| 171 | +def render(skill_id: str, workdir: Path, depth: str) -> str: |
| 172 | + return render_prompt( |
| 173 | + load_skill(skill_id), |
| 174 | + TargetContext(kind="local", local_path=workdir, display_source=str(workdir)), |
| 175 | + depth=depth, |
| 176 | + ) |
| 177 | + |
| 178 | + |
| 179 | +def main() -> int: |
| 180 | + parser = argparse.ArgumentParser(description=__doc__) |
| 181 | + parser.add_argument("--agent", default="claude", help="Adapter id (default: claude)") |
| 182 | + parser.add_argument( |
| 183 | + "--scenario", |
| 184 | + required=True, |
| 185 | + choices=["success", "auth_failure", "timeout", "binary_not_found"], |
| 186 | + help="Which real execution to record", |
| 187 | + ) |
| 188 | + parser.add_argument("--skill", default="secret-scanning") |
| 189 | + parser.add_argument("--workdir", type=Path, default=Path("examples")) |
| 190 | + parser.add_argument("--depth", default="quick", choices=["quick", "standard"]) |
| 191 | + parser.add_argument("--timeout", type=int, default=240, help="Seconds passed to adapter.run()") |
| 192 | + parser.add_argument("--expect", help="Assert the resulting status (e.g. timeout)") |
| 193 | + args = parser.parse_args() |
| 194 | + |
| 195 | + workdir = (ROOT / args.workdir).resolve() if not args.workdir.is_absolute() else args.workdir.resolve() |
| 196 | + if not workdir.is_dir(): |
| 197 | + parser.error(f"workdir does not exist: {workdir}") |
| 198 | + |
| 199 | + adapter = get_adapter(args.agent) |
| 200 | + version = cli_version(adapter.binary) |
| 201 | + prompt = render(args.skill, workdir, args.depth) |
| 202 | + env_changes: dict[str, str | None] = {} |
| 203 | + saved_env: dict[str, str | None] = {} |
| 204 | + restore_which = None |
| 205 | + try: |
| 206 | + if args.scenario == "auth_failure": |
| 207 | + isolated = tempfile.mkdtemp(prefix=f"secfoo-no-auth-{args.agent}-") |
| 208 | + if args.agent == "claude": |
| 209 | + # An isolated config dir has no /login session; removing the |
| 210 | + # key env vars leaves the real CLI with no credentials. |
| 211 | + env_changes = { |
| 212 | + "CLAUDE_CONFIG_DIR": isolated, |
| 213 | + "ANTHROPIC_API_KEY": None, |
| 214 | + "CLAUDE_CODE_OAUTH_TOKEN": None, |
| 215 | + } |
| 216 | + elif args.agent == "copilot": |
| 217 | + # An isolated COPILOT_HOME plus a deliberately invalid token |
| 218 | + # makes the real CLI reject auth with a 401 (no real key is |
| 219 | + # written to the fixture -- stdout/stderr are redacted). |
| 220 | + env_changes = { |
| 221 | + "COPILOT_HOME": isolated, |
| 222 | + "COPILOT_GITHUB_TOKEN": None, |
| 223 | + "GITHUB_TOKEN": None, |
| 224 | + "GH_TOKEN": "invalid-token-for-test", |
| 225 | + } |
| 226 | + else: |
| 227 | + parser.error(f"auth_failure scenario not implemented for {args.agent!r}") |
| 228 | + for name, value in env_changes.items(): |
| 229 | + saved_env[name] = os.environ.get(name) |
| 230 | + if value is None: |
| 231 | + os.environ.pop(name, None) |
| 232 | + else: |
| 233 | + os.environ[name] = value |
| 234 | + if args.scenario == "binary_not_found": |
| 235 | + from secfoo.agents import base |
| 236 | + |
| 237 | + restore_which = base.shutil.which |
| 238 | + base.shutil.which = lambda _name: None # type: ignore[assignment] |
| 239 | + |
| 240 | + # build_command is called separately only to record the exact argv; |
| 241 | + # run() still builds and executes it itself, unmodified. |
| 242 | + argv = [str(part) for part in adapter.build_command(prompt, workdir=workdir)] |
| 243 | + result = adapter.run(prompt, workdir=workdir, timeout=args.timeout) |
| 244 | + finally: |
| 245 | + for name, value in saved_env.items(): |
| 246 | + if value is None: |
| 247 | + os.environ.pop(name, None) |
| 248 | + else: |
| 249 | + os.environ[name] = value |
| 250 | + if restore_which is not None: |
| 251 | + from secfoo.agents import base |
| 252 | + |
| 253 | + base.shutil.which = restore_which # type: ignore[assignment] |
| 254 | + |
| 255 | + if args.expect and result.status != args.expect: |
| 256 | + raise SystemExit(f"expected status {args.expect!r}, got {result.status!r}: {result.stderr[:500]}") |
| 257 | + |
| 258 | + payload = { |
| 259 | + "schema_version": 1, |
| 260 | + "agent": args.agent, |
| 261 | + "scenario": args.scenario, |
| 262 | + "cli_version": version, |
| 263 | + "recorded_at": datetime.now(timezone.utc).isoformat(), |
| 264 | + "platform": platform.platform(), |
| 265 | + "python": platform.python_version(), |
| 266 | + "skill": args.skill, |
| 267 | + "depth": args.depth, |
| 268 | + "workdir": str(workdir.relative_to(ROOT)) if workdir.is_relative_to(ROOT) else "<external>", |
| 269 | + "argv": [redact(part) for part in argv], |
| 270 | + "env_names_isolated": sorted(env_changes), |
| 271 | + "prompt_sha256": hashlib.sha256(prompt.encode("utf-8")).hexdigest(), |
| 272 | + "exit_code": result.exit_code, |
| 273 | + "status": result.status, |
| 274 | + "duration_seconds": round(result.duration_seconds, 3), |
| 275 | + "stdout": redact_transcript(result.stdout), |
| 276 | + "stderr": redact_transcript(result.stderr), |
| 277 | + "raw_report": redact(result.raw_report), |
| 278 | + "usage": { |
| 279 | + "input_tokens": result.input_tokens, |
| 280 | + "output_tokens": result.output_tokens, |
| 281 | + "cost_usd": result.cost_usd, |
| 282 | + }, |
| 283 | + # CopilotAdapter keeps the exact JSON the CLI wrote so the test can |
| 284 | + # check secfoo's numbers against the CLI's printed numbers. |
| 285 | + "usage_file": getattr(adapter, "last_usage_payload", None), |
| 286 | + } |
| 287 | + text = json.dumps(payload, indent=2, ensure_ascii=False) + "\n" |
| 288 | + assert_no_keys(text, where="the complete fixture") |
| 289 | + |
| 290 | + fixture = ROOT / "tests" / "fixtures" / "agents" / args.agent / version_slug(version) / f"{args.scenario}.json" |
| 291 | + fixture.parent.mkdir(parents=True, exist_ok=True) |
| 292 | + fixture.write_text(text, encoding="utf-8") |
| 293 | + print( |
| 294 | + f"{args.agent}/{version_slug(version)}/{args.scenario}: status={result.status} " |
| 295 | + f"exit={result.exit_code} bytes={len(result.stdout)} saved={fixture.relative_to(ROOT)}" |
| 296 | + ) |
| 297 | + return 0 |
| 298 | + |
| 299 | + |
| 300 | +if __name__ == "__main__": |
| 301 | + raise SystemExit(main()) |
0 commit comments