# Vulnerability Analysis Example

AI-powered security vulnerability detection with structured findings.

## Files
- `input.json` - The prompt and code to analyze
- `schema.json` - JSON schema for structured security analysis
- `README.md` - This documentation

## Example:

When you use this example, here is what happens step by step:

**Input:**
```json
{
    "messages": [
        {
            "role": "system",
            "content": "You are a security expert."
                        "Analyze code changes for security vulnerabilities, focusing on OWASP Top 10, "
                        "common attack vectors, and secure coding practices."
        },
        {
            "role": "user",
            "content": "Analyze these code changes for security vulnerabilities:"
                        ""
                        "```diff"
                        "--- a/auth/login.py"
                        "+++ b/auth/login.py"
                        "@@ -10,7 +10,7 @@ def authenticate_user(username, password):"
                        "     if not username or not password:"
                        "         return False"
                        "     "
                        "-    query = f\"SELECT * FROM users WHERE username = '{username}'\""
                        "+    query = \"SELECT * FROM users WHERE username = %s\""
                        "     cursor.execute(query, (username,))"
                        "     user = cursor.fetchone()"
                        "     "
                        "@@ -25,6 +25,8 @@ def create_session(user_id):"
                        "     session_token = secrets.token_urlsafe(32)"
                        "     expiry = datetime.now() + timedelta(hours=24)"
                        "     "
                        "+    if not user_id or user_id <= 0:"
                        "+        raise ValueError(\"Invalid user_id\")"
                        "+    "
                        "     query = \"INSERT INTO sessions (user_id, token, expiry) VALUES (%s, %s, %s)\""
                        "     cursor.execute(query, (user_id, session_token, expiry))"
                        "     conn.commit()"
                        "```"
                        ""
                        "Provide detailed security assessment with specific vulnerabilities, "
                        "severity levels, and fix recommendations."
        }
    ],
    "context": {
        "session_id": "security-analysis-001",
        "metadata": {
            "task_type": "security_analysis",
            "domain": "authentication",
            "language": "python",
            "focus": "sql_injection_prevention"
        }
    }
}
```

**Schema:** The system enforces a JSON schema that defines the security analysis structure:
- `security_rating`: One of ["low_risk", "medium_risk", "high_risk", "critical_risk"]
- `vulnerabilities`: Array of vulnerability objects with type, severity, description, line_number, fix_suggestion, cwe_id, and owasp_category
- `recommendations`: Array of security recommendations
- `compliance_issues`: Array of compliance violations
- `risk_score`: Numeric score 0-10
- `summary`: Overall security assessment

**Command:**
```bash
llm-ci-runner \
  --input-file examples/03-security/vulnerability-analysis/input.json \
  --output-file security-analysis.json \
  --schema-file examples/03-security/vulnerability-analysis/schema.json \
  --log-level INFO
```

**Output:**
```json
{
  "success": true,
  "response": {
    "security_rating": "medium_risk",
    "vulnerabilities": [
      {
        "type": "sql_injection",
        "severity": "low",
        "description": "The original code concatenates user input directly into SQL query string,"
                       "which could lead to SQL Injection vulnerabilities if user input is crafted maliciously.",
        "line_number": 10,
        "fix_suggestion": "Use parameterized queries to prevent SQL injection,"
                          "as shown in the updated code. Instead of string interpolation,"
                          "pass parameters separately.",
        "cwe_id": "CWE-89",
        "owasp_category": "A01:Injection"
      },
      {
        "type": "other",
        "severity": "low",
        "description": "The create_session function includes a validation to check if user_id is valid;"
                        "this is good for data integrity but not directly a security vulnerability.",
        "line_number": 25,
        "fix_suggestion": "Ensure user_id validation is comprehensive to prevent logic errors. Additional validation might include checking if user_id exists in the database before creating a session.",
        "cwe_id": "",
        "owasp_category": ""
      }
    ],
    "recommendations": [
      "Ensure all database queries use parameterized statements to prevent SQL injection.",
      "Validate and sanitize all user inputs.",
      "Implement proper error handling to avoid leaking sensitive information.",
      "Use secure cookies and HTTPS to protect session tokens.",
      "Regularly review and update dependencies and libraries."
    ],
    "compliance_issues": [],
    "risk_score": 4.0,
    "summary": "Code has addressed the primary security concern of SQL injection with parameterized queries, significantly reducing risk. Additional input validation and security best practices are recommended."
  },
  "metadata": {
    "runner": "llm-ci-runner",
    "timestamp": "auto-generated"
  }
}
```

## What This Demonstrates
- Automated security vulnerability detection
- OWASP Top 10 compliance checking
- Risk scoring and severity assessment
- Specific vulnerability categorization
- Fix recommendations and CWE mapping
