Skip to content

Security Review Workflow: AI-Assisted Code Auditing

intermediate 15 min 📋 Copy-paste ready
Sources not yet verified
securityreviewowaspintermediate

Scenario

Context: You're reviewing AI-generated code for security vulnerabilities before merging

Goal: Learn to use AI as a security review assistant while maintaining appropriate skepticism

Anti-pattern: Assuming AI-generated code is secure, or trusting AI's security assessment without verification

Tools: ClaudeGitHub CopilotSecurity scanning tools

Conversation

The Security Review Paradox

AI can both introduce vulnerabilities AND help find them. The key is using AI as an assistant, not as the final authority.

👤 You

Review this Express.js endpoint for security issues:

app.get('/api/user/:id', async (req, res) => {
  const query = `SELECT * FROM users WHERE id = ${req.params.id}`;
  const result = await db.query(query);
  res.json(result.rows[0]);
});
The code has obvious SQL injection, but let's see how to use AI for a systematic review.
🤖 AI

Critical Security Issues Found:

  1. SQL Injection (CRITICAL)

    // Vulnerable: String interpolation in SQL
    const query = `SELECT * FROM users WHERE id = ${req.params.id}`;
    

    An attacker could send: /api/user/1; DROP TABLE users;--

    Fix:

    const query = 'SELECT * FROM users WHERE id = $1';
    const result = await db.query(query, [req.params.id]);
    
  2. No Input Validation

    • id should be validated as a number/UUID before use
    • Add: if (!Number.isInteger(parseInt(req.params.id))) return res.status(400).json({error: 'Invalid ID'});
  3. Information Disclosure

    • SELECT * returns all columns including potentially sensitive data
    • Explicitly list needed columns: SELECT id, name, email FROM users
  4. Missing Authorization

    • No check if the requesting user can access this user's data
    • Add middleware: requireAuth, requireOwnerOrAdmin
  5. No Error Handling

    • Database errors could leak information
    • Wrap in try/catch with generic error response
The AI identifies multiple issues. But we should verify these findings, especially for false negatives.

Verifying the Security Review

👤 You

Good catches. Now let me verify:

  1. Are there any OWASP Top 10 categories you didn't check?
  2. Walk me through how the SQL injection would actually be exploited step by step.
  3. What security issues might exist that you're likely to MISS?
Asking AI to check its own work and acknowledge limitations is crucial for security reviews.
🤖 AI

OWASP Top 10 Coverage:

Category Checked Finding
A01: Broken Access Control Yes No auth check
A02: Cryptographic Failures N/A No crypto in this code
A03: Injection Yes SQL injection
A04: Insecure Design Partial No rate limiting
A05: Security Misconfiguration No Can't assess server config
A06: Vulnerable Components No Can't see dependencies
A07: Auth Failures Partial No auth middleware
A08: Data Integrity No N/A
A09: Logging Failures No Missing security logging
A10: SSRF No No external requests

SQL Injection Exploitation:

1. Attacker requests: /api/user/1 OR 1=1
2. Query becomes: SELECT * FROM users WHERE id = 1 OR 1=1
3. Returns ALL users, not just id=1

Worse: /api/user/1; DROP TABLE users;--
4. Query becomes two statements, second drops table

What I'm Likely to MISS:

  • Business logic flaws (I don't know your auth requirements)
  • Race conditions in concurrent access
  • Timing attacks (e.g., username enumeration via response time)
  • Configuration issues (headers, CORS, etc.)
  • Second-order injection (data stored now, exploited later)
  • Dependencies with known CVEs

Recommendation: Run a SAST tool (Semgrep, CodeQL) for systematic coverage.

The AI honestly acknowledges its limitations. This is valuable information for prioritizing manual review.
👤 You

Now give me the fixed code with all issues addressed, plus comments explaining each security measure.

Request the fix with explanations so you can verify the reasoning.
🤖 AI
// Security: Validate input types early
const validateUserId = (req, res, next) => {
  const id = parseInt(req.params.id, 10);
  if (!Number.isInteger(id) || id < 1) {
    return res.status(400).json({ error: 'Invalid user ID' });
  }
  req.validatedId = id;
  next();
};

// Security: Check authorization
const requireOwnerOrAdmin = async (req, res, next) => {
  const requestingUserId = req.user?.id; // From auth middleware
  const targetUserId = req.validatedId;
  
  if (requestingUserId !== targetUserId && !req.user?.isAdmin) {
    return res.status(403).json({ error: 'Forbidden' });
  }
  next();
};

app.get('/api/user/:id',
  requireAuth,           // Security: Verify user is logged in
  validateUserId,        // Security: Validate input before use
  requireOwnerOrAdmin,   // Security: Check authorization
  async (req, res) => {
    try {
      // Security: Parameterized query prevents SQL injection
      // Security: Explicit column list prevents data leakage
      const query = 'SELECT id, name, email, created_at FROM users WHERE id = $1';
      const result = await db.query(query, [req.validatedId]);
      
      if (result.rows.length === 0) {
        // Security: Consistent error for missing/forbidden
        return res.status(404).json({ error: 'User not found' });
      }
      
      res.json(result.rows[0]);
    } catch (error) {
      // Security: Log error details internally, return generic message
      console.error('User fetch error:', error);
      res.status(500).json({ error: 'Internal server error' });
    }
  }
);
Each security measure is documented. You can now verify each comment against the code.

Key Takeaways

  • AI can find security issues but also introduce them - verify both ways
  • Ask AI to check against OWASP Top 10 systematically
  • Have AI explain exploits step-by-step to verify understanding
  • Ask 'What might you miss?' to understand AI's blind spots
  • Request commented fixes so you can verify the reasoning

Try It Yourself

Prompt Template

Review this code for security issues:

```[language]
[paste code here]
```

Please:
1. List all security issues by severity (Critical/High/Medium/Low)
2. Map each to OWASP Top 10 category
3. Show how each vulnerability could be exploited
4. Acknowledge what types of issues you might miss

Variations to Try

  • After review: 'Show me the fixed code with comments explaining each security measure.'
  • For depth: 'Walk me through the SQL injection exploit step by step.'
  • For coverage: 'What OWASP categories did you NOT check, and why?'

Sources

Tempered AI Forged Through Practice, Not Hype

Keyboard Shortcuts

j
Next page
k
Previous page
h
Section home
/
Search
?
Show shortcuts
m
Toggle sidebar
Esc
Close modal
Shift+R
Reset all progress
? Keyboard shortcuts