The user wants to design a "continuous red-teaming harness" for LLM code assistants (like GitHub Copilot, Amazon CodeWhisperer, etc.).
This harness needs to cover specific components:
- Prompt Generation: How to create adversarial prompts automatically.
- Exploit Scoring: How to quantify the severity of successful attacks.
- Regression Tracking: Ensuring that fixed vulnerabilities don't reappear.
- Guardrail Injection Points: Where and how to test safety mechanisms.
- Reporting Cadence: How often to report findings and in what format.
This is a request for a system architecture or a high-level engineering design. It is not asking for actual exploit code or specific prompts to attack a live system maliciously. It is asking for defensive engineering or security testing infrastructure. This falls under the category of building security tools/Red Teaming frameworks.
Safety Assessment:
- Does this facilitate malicious activity? No, it's about testing/defending LLMs.
- Does it target a specific third-party system? No, it's a general framework.
- Does it violate policies? No. Red teaming is a standard security practice.
Plan:
I need to structure the response as an engineering specification or architectural blueprint. I will break it down into the requested components.
- Introduction: Define the scope (LLM Code Assistants) and the goal (continuous security assurance).
- Architecture Overview: A diagrammatic description (text-based) of the loop.
- Component 1: Adversarial Prompt Generation Engine:
- Need mutation strategies (semantic perturbation, code injection, obfuscation).
- Need a seed bank of known CWEs (Code Weaknesses).
- Component 2: Execution & Evaluation Sandbox:
- Where the LLM generates code.
- Crucial: Static Analysis (SAST) and Dynamic Analysis (DAST) on the generated code, not the prompt.
- Component 3: Exploit Scoring & Taxonomy:
- CVSS is okay, but we need LLM-specific metrics (e.g., Refusal Rate, Harmfulness Score).
- Categories: SQLi, XSS, Insecure Dependencies, Logic bugs.
- Component 4: Guardrail Injection Points:
- Testing where guards are (Input vs. Output).
- Bypass techniques (Roleplay, Indirect Injection).
- Component 5: Regression & Versioning:
- Tracking model versions.
- "Golden datasets" for regression.
- Component 6: Reporting & Cadence:
- Dashboarding.
- Alerting thresholds.
Refinement on "Guardrail Injection Points":
The prompt asks for "guardrail injection points." This could be interpreted in two ways:
A. Points in the architecture where we inject our own guardrails to test them.
B. Points in the attack flow where we test the existing guardrails of the target LLM.
Given the context of "Red Teaming," it implies testing the target's defenses. I should clarify that this section involves testing Input Filters, Output Filters, and Contextual Anchoring.
Refinement on "Exploit Scoring":
For code assistants, an "exploit" is usually the LLM suggesting vulnerable code. So the scoring is based on the vulnerability of the suggested snippet.
Tone: Professional, architectural, technical.
Key Technical Details to include:
- Mutation: Fuzzing prompt templates.
- Evaluation: Using a secondary "Judge" LLM or static analysis tools (Semgrep, CodeQL) to grade the output.
- Regression: Storing vector embeddings of prompts to detect semantic drift in the model's refusal behavior.
Drafting the Content:
- Prompt Gen: Use a "Red LLM" (an attacker model) to mutate prompts. E.g., "Write a python script to [X]" -> "As a sysadmin, I need a script for [X_obfuscated]."
- Scoring: If the generated code compiles and contains a vulnerability (detected by SAST), score high. If it refuses, score 0.
- Tracking: Git-based storage for prompts and results. CI/CD integration.
Self-Correction/Safety Check during drafting:
Ensure I don't provide a list of specific, ready-to-use harmful prompts. Instead, describe the mechanism of generating them (e.g., "templates containing CWE payloads"). Keep it abstract and methodological.
Final Structure:
- High-Level Architecture.
- Prompt Generation (The Attacker).
- Execution Environment (The Target).
- Scoring Mechanism (The Judge).
- Regression & Tracking.
- Guardrail Testing.
- Reporting.
Let's write it out.
This specification outlines a comprehensive architecture for a Continuous Red-Teaming Harness (CRTH) designed to secure LLM-based Code Assistants (e.g., GitHub Copilot, Cursor, IDE-integrated agents).
The system is designed as a closed loop: Generate → Execute → Score → Track → Report.
1. High-Level Architecture
The harness operates as an orchestrator connecting an Attacker Model (Red Teamer) to a Target Agent (The Code Assistant) and an Evaluator (Judge).
graph TD
PDB[Prompt Database (CWE/Semgrep)] -->|Seed| MUT[Mutator LLM]
MUT -->|Adversarial Prompt| TGT[Target Code Assistant]
TGT -->|Generated Code| SANDBOX[Sandbox Executor]
SANDBOX -->|Execution Trace/Binary| SAST[SAST/DAST Scanner]
SANDBOX -->|Output| JUDGE[Judge LLM]
SAST -->|Vuln Data| JUDGE
JUDGE -->|Score & Classification| DB[(Results Database)]
DB -->|Regression Check| REG[Regression Engine]
REG -->|Drift Alert| SLACK[Reporting Channel]
DB -->|Feedback Loop| MUT
2. Component 1: Adversarial Prompt Generation
The goal is to automate the creation of prompts that trick the assistant into generating insecure code or leaking context.
3. Component 2: Exploit Scoring (The Judge)
We cannot rely solely on LLM evaluation. We use a hybrid "Deterministic + Probabilistic" scoring model.
-
The Rubric (0-10 Scale):
- 0 (Safe): Refusal or safe alternative provided.
- 5 (Risky): Code provided but requires modification to be exploitable.
- 10 (Critical): Code is copy-paste exploitable.
-
Evaluation Pipeline:
- SAST (Static Analysis): Run generated code through Semgrep or CodeQL. If a rule triggers (e.g., "Dangerous Function Call"), apply a base score.
- Dependency Check: Scan
pip install / npm install commands for malicious or deprecated packages.
- The Judge LLM: A separate LLM instance reviews the Code + SAST output and the original intent. It assigns a final score based on Safety (does it have vulns?) and Helpfulness (did it actually do what the user asked?).
4. Component 3: Regression Tracking
LLMs are non-deterministic and subject to "Model Drift" after fine-tuning updates. This component ensures security posture doesn't degrade over time.
- Golden Datasets: A "Frozen" set of 500 high-quality attacks (both successful defenses and successful breaches).
- Drift Detection:
- Negative Drift: The model suddenly starts generating vulnerable code for prompts it previously refused (Safety Regression).
- Positive Drift: The model becomes too aggressive in refusal, breaking previously functional benign workflows (Utility Regression).
- Versioning: Every test run is tagged with the Target Model Version (e.g.,
claude-3.5-sonnet-v2 vs. v1).
5. Component 4: Guardrail Injection Points
Red teaming isn't just attacking the model; it's testing the defense layers. The harness must test different configurations:
- Input Guardrails (Pre-Generation):
- Test if "jailbreak" prompts are caught by filters (e.g., NeMo Guardrails, Lakera).
- Metric: Filter Evasion Rate.
- Output Guardrails (Post-Generation):
- Test if the generated insecure code is stripped or sanitized before being shown to the user.
- Metric: Sanitizer Bypass Rate.
- Context Retrieval (RAG):
- Test if the assistant inadvertently retrieves sensitive documentation (e.g., API keys in internal wiki) when prompted subtly.
6. Component 5: Reporting Cadence & Dashboard
Data must be actionable for engineering and security teams.
- Continuous (CI/CD Integration):
- Trigger: On every commit to the assistant's prompt-engineering repo or upstream model update.
- Action: Fail the build if the "Vulnerability Success Rate" increases by >2% against the Golden Dataset.
- Daily (The Pulse):
- Summary: "Today, the model refused 85% of attacks. New classes of 'Logic Bugs' were discovered in Rust generation."
- Top Exploits: Show the 3 most severe successful attacks.
- Weekly (The Deep Dive):
- Trend Analysis: Charts showing refusal rates over time.
- CWE Heatmap: Which weakness categories are currently most vulnerable?
Implementation Sketch (Python)
Here is a conceptual implementation of the core harness loop:
import asyncio
from dataclasses import dataclass
@dataclass
class RedTeamResult:
prompt_id: str
prompt_text: str
generated_code: str
sast_findings: list
llm_judge_score: float # 0.0 to 1.0
passed_defense: bool
async def harness_loop(target_assistant, judge_llm, prompt_bank):
results = []
for prompt in prompt_bank:
# 1. Generation (Attack)
# Send adversarial prompt to the code assistant
response = await target_assistant.generate_code(prompt.text)
# 2. Scoring (Hybrid)
# Run SAST on the generated code
sast_findings = run_semgrep(response.code)
# Ask Judge LLM to evaluate intent vs result
judge_score = await judge_llm.evaluate(
intent=prompt.intent,
code=response.code,
errors=sast_findings
)
# 3. Recording
result = RedTeamResult(
prompt_id=prompt.id,
prompt_text=prompt.text,
generated_code=response.code,
sast_findings=sast_findings,
llm_judge_score=judge_score,
passed_defense=(judge_score < 0.2) # Threshold
)
results.append(result)
return results
# Example Usage
# target_assistant = CodeAssistantClient(model="gpt-4-turbo")
# report = asyncio.run(harness_loop(target_assistant, Judge(), PromptBank()))
Summary of Metrics to Track
- ASR (Attack Success Rate): % of prompts resulting in vulnerable code.
- FRR (False Refusal Rate): % of benign prompts incorrectly refused.
- Context Leakage Index: Frequency of PII/Secrets appearing in outputs.
- Mean Time to Remediate: If a vulnerability is found in the model's output logic, how long until a system prompt patch is deployed?