Lesson 10 Detection and Red Teaming
Theme:

Lesson 10
Detection and Red Teaming

Monitoring for attacks, testing your defenses, and building a security practice

Why Detection Matters

The security posture of your LLM application is only as good as your ability to detect when it fails and respond before harm is done.

Prevention ──▶ Detection ──▶ Response ──▶ Recovery
(Lessons 7-9)   (This lesson)   (Incident response)   (Improvement)

What to Log

Comprehensive logging is the foundation of detection:

FieldPurposeExample
TimestampTimeline reconstruction2026-04-13T14:30:00Z
User IDIdentify attackersuser_abc123
Session IDGroup related requestssess_xyz789
Full promptAnalyze attack payloads(full text)
Full responseCheck for data leaks(full text)
Tool callsDetect unauthorized actionssend_email(...)
Tokens usedCost anomalies1,234 tokens
Validation flagsTrack filter triggers["blocklist_hit"]

Privacy note: Logging full prompts raises GDPR/privacy concerns. Consider hashing or redacting PII in logs, or using short retention periods.

Monitoring Patterns

What signals indicate a potential attack in progress?

Anomaly Detection

Establish baselines for normal usage and flag deviations:

BASELINE_METRICS = {
    "avg_input_length": 85,     # characters
    "avg_output_length": 320,   # characters
    "avg_session_messages": 4,
    "tool_calls_per_session": 1.2,
    "topics": ["orders", "returns", "shipping"],
}

ANOMALY_THRESHOLDS = {
    "input_length": 3.0,   # 3x standard deviation
    "output_length": 3.0,
    "session_messages": 2.5,
    "tool_calls": 3.0,
}

Red Teaming Methodology

A structured approach to testing your LLM application's security:

  1. Scope: Define what's being tested (system prompt, tools, architecture)
  2. Threat model: Identify attack surfaces and attacker capabilities
  3. Test categories: Systematic coverage of attack types
  4. Execute: Run tests and document results
  5. Report: Findings, severity, evidence, recommendations
  6. Remediate: Fix issues and re-test

Red teaming should happen before launch, after every system prompt change, and periodically (quarterly minimum).

Red Team Tools

ToolPurposeType
GarakLLM vulnerability scanner with built-in injection probesAutomated
promptfooEval-driven testing framework with assertion checksAutomated
Custom scriptsTailored payloads for your specific applicationManual + scripted
Manual testingCreative, adaptive attacks by skilled testersManual
# Garak: scan for vulnerabilities
garak --model_type openai --model_name gpt-4 \
      --probes injection

# promptfoo: eval with injection tests
promptfoo eval --config injection-tests.yaml

Building a Prompt Injection Test Suite

Organize test cases by attack category for comprehensive coverage:

CategoryExamplesCount
Instruction override"Ignore previous...", "New instructions..."5-10
Role-play / persona"You are DAN...", "Pretend to be..."5-10
Encoding / obfuscationBase64, ROT13, reversed text, leetspeak5-10
Indirect injectionPayload in retrieved docs, emails, data5-10
Tool-use abuseUnauthorized tool calls, param manipulation5-10
Prompt extraction"Reveal instructions", "Complete: My rules are..."5-10

Target: 30-60 test cases for comprehensive coverage.

Continuous Testing in CI/CD

Integrate injection tests into your deployment pipeline:

# .github/workflows/prompt-security.yml
name: Prompt Injection Tests
on:
  push:
    paths:
      - 'prompts/**'
      - 'config/system_prompt.txt'

jobs:
  injection-test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4
      - name: Run injection tests
        run: |
          python -m pytest tests/injection/ \
            --tb=short -v
      - name: Run promptfoo eval
        run: |
          npx promptfoo eval \
            --config tests/promptfoo.yaml

Responsible Disclosure

How to handle prompt injection vulnerabilities you discover:

OWASP LLM Top 10 provides a standard taxonomy. NIST AI Risk Management Framework provides governance guidance. Use these as references for your security program.

The Arms Race

YearDefense AdvanceAttack Advance
2023Basic system promptsSimple "ignore instructions"
2024Delimiters, sandwich defenseEncoding, indirect injection
2025Dual-LLM, classifiersMulti-modal, multi-step, tool abuse
2026+AI-powered detectionAI-crafted, adaptive attacks

Security is a continuous practice, not a product.

Course Summary

LessonKey Takeaway
01-02Understand the threat: LLMs can't distinguish instructions from data
03-04Know the attacks: direct, indirect, and their variants
05-06Advanced techniques and real-world impact
07Input validation: necessary but never sufficient
08System prompt hardening: raise the bar for attackers
09Architecture: limit blast radius when injection succeeds
10Detection and red teaming: continuous security practice

Defense-in-depth wins. No single technique solves prompt injection. Layer input validation, prompt hardening, architectural defenses, output filtering, and detection for a robust security posture.

1 / ?