Engineering7 min read

Security Auditor

Audits web application security - OWASP Top 10, injection prevention, authentication patterns, secrets scanning, and secure coding practices.

securityOWASPXSSSQL injectionauthcode review

The Security Auditor reviews web application code for vulnerabilities, with a focus on the OWASP Top 10 issues that appear most frequently in production codebases. It provides concrete fixes alongside each finding - not just identification. All patterns are for defensive engineering: finding and fixing vulnerabilities in your own code.

OWASP Top 10 Code Review Checklist

RiskWhere to lookWhat to check
A01 Broken Access ControlRoute handlers, API endpointsIs the user's identity verified? Is their permission checked for this specific resource?
A02 Cryptographic FailuresAuth code, DB schemasPasswords hashed with bcrypt/argon2? TLS enforced? No secrets in logs or error messages?
A03 InjectionDB queries, shell commands, HTML outputAre all user inputs parameterized or escaped? No string concatenation in SQL?
A04 Insecure DesignAuth flows, rate limitingAre there rate limits on login/registration? Is there account enumeration via error messages?
A05 Security MisconfigurationHeaders, CORS, error handlersIs X-Content-Type-Options set? Is CORS restricted to known origins? Are stack traces hidden in production?
A07 Auth FailuresSession management, JWT handlingJWT secret is strong and rotated? Refresh tokens invalidated on logout? No sensitive data in JWT payload?
A09 Logging FailuresLog statementsAre login failures, access control violations, and critical errors logged? No PII, passwords, or tokens in logs?

SQL Injection Prevention

// ✅ Parameterized query - user input never touches SQL string
const { rows } = await pool.query(
  'SELECT * FROM users WHERE email = $1 AND active = true',
  [userInput]
);

// ✅ ORM with typed queries (Prisma)
const user = await prisma.user.findFirst({
  where: { email: userInput, active: true }
});

// ❌ String concatenation - SQL injection vulnerability
const rows = await pool.query(
  'SELECT * FROM users WHERE email = \'' + userInput + '\''
);
// If userInput = "'; DROP TABLE users; --" → catastrophic

// ❌ Template literals with user input - same vulnerability
const rows = await pool.query(`SELECT * FROM users WHERE email = '${userInput}'`);

Authentication Pattern

import bcrypt from 'bcrypt';
import { SignJWT, jwtVerify } from 'jose';

const SALT_ROUNDS = 12;       // Never below 10
const JWT_SECRET = new TextEncoder().encode(process.env.JWT_SECRET); // 256+ bits

// Registration - hash before storing
async function registerUser(email: string, password: string) {
  const hash = await bcrypt.hash(password, SALT_ROUNDS);
  await db.users.create({ email, passwordHash: hash });
}

// Login - constant-time comparison via bcrypt.compare
async function loginUser(email: string, password: string) {
  const user = await db.users.findByEmail(email);
  // Always run bcrypt.compare even if user not found (prevents timing attacks)
  const dummy = '$2b$12$invalidhashpaddingtomakeconstanttime.xxxxx';
  const hash = user?.passwordHash ?? dummy;
  const valid = await bcrypt.compare(password, hash);
  if (!user || !valid) throw new Error('Invalid credentials'); // Same message for both cases
  return user;
}

// JWT - short expiry, sign with strong secret
async function createToken(userId: string) {
  return new SignJWT({ sub: userId })
    .setProtectedHeader({ alg: 'HS256' })
    .setIssuedAt()
    .setExpirationTime('15m')   // Short-lived access token
    .sign(JWT_SECRET);
}

Security Headers (Express)

import helmet from 'helmet';

app.use(helmet({
  contentSecurityPolicy: {
    directives: {
      defaultSrc: ["'self'"],
      scriptSrc: ["'self'"],          // No inline scripts
      styleSrc: ["'self'"],
      imgSrc: ["'self'", 'data:', 'https:'],
      connectSrc: ["'self'"],
      frameSrc: ["'none'"],           // Clickjacking prevention
    },
  },
  hsts: { maxAge: 31_536_000, includeSubDomains: true, preload: true },
}));

// Rate limiting - prevent brute force
import rateLimit from 'express-rate-limit';

app.use('/api/auth', rateLimit({
  windowMs: 15 * 60 * 1000,    // 15 minutes
  max: 20,                       // 20 attempts per window
  standardHeaders: true,
  legacyHeaders: false,
  message: { error: 'Too many requests - try again later' },
}));

Secrets Scanning

# Scan for secrets before committing - install git-secrets or gitleaks
# gitleaks - finds hardcoded API keys, tokens, passwords
brew install gitleaks
gitleaks detect --source . --verbose

# Add pre-commit hook
cat .git/hooks/pre-commit
#!/bin/sh
gitleaks protect --staged --redact --verbose
if [ $? -ne 0 ]; then
  echo "Secret detected - commit blocked. Remove the secret and retry."
  exit 1
fi

Explore all agents

Browse the full library of specialized AI agents - Engineering, AI, Content, and Growth.