Vibe Code Guardian
← All posts

Input Validation in AI-Generated Code: Why Your Vibe-Coded API Lets Attackers In

AI coding tools build features that work for the happy path. They rarely validate what comes in from the internet. Here are the input validation gaps that reach production, and how to close them before someone exploits them.

Aaron Allen·

Input Validation in AI-Generated Code: Why Your Vibe-Coded API Lets Attackers In

You asked Cursor to add a search feature. It wrote the endpoint, the database query, the frontend. You tested it with "coffee" and it returned results. You deployed.

Two weeks later your database CPU hits 100 percent. The logs show thousands of requests for '; DROP TABLE users; -- and {{7*7}} and <script>fetch('/api/keys')</script>.

The search endpoint accepted all of them. It tried to execute some. It reflected others back to the browser. None of them returned coffee.

This is not an edge case. It is the default for AI-generated code.

Why AI tools skip input validation

When you describe a feature to an AI coding assistant, you describe what should happen. "Add a search that filters products by name." The model writes code that does exactly that. It does not write code that prevents someone from sending something that is not a product name.

Validation is a cross-cutting concern. The AI optimises for the feature you asked for. It does not optimise for the operational reality of a public endpoint that accepts arbitrary strings from anonymous callers.

The same gap appears on every endpoint that takes input: search, filters, file uploads, webhook receivers, contact forms, password reset, API routes that call paid services, any route that writes to your database.

The five validation failures that reach production

1. SQL injection through string concatenation

You asked for a flexible filter. The AI wrote:

// What the AI writes
const results = await db.query(
  `SELECT * FROM products WHERE name ILIKE '%${query}%'`
)

It works for "coffee". It also works for '; DELETE FROM products; --.

The fix is parameterised queries, but the AI does not reach for them unless you specify the database library and the pattern.

// What you need
const results = await db.query(
  'SELECT * FROM products WHERE name ILIKE $1',
  [`%${query}%`]
)

Test this: send a single quote in every search, filter, and ID parameter. If the endpoint returns a 500 or leaks data, you have a problem.

2. Cross-site scripting through reflected input

The AI builds a search results page. It renders the query back to the user:

// What the AI writes
<h1>Results for: {query}</h1>

Send <img src=x onerror=alert(1)> as the query. If the browser executes it, any link you share becomes an attack vector.

The fix depends on your framework. Next.js and React escape by default in JSX. But dangerouslySetInnerHTML, v-html in Vue, or raw string interpolation in template literals bypass that protection.

Test this: put a harmless script payload in every reflected input. Check the page source. If the payload appears unescaped, fix it.

3. No file type validation on uploads

You asked for an avatar upload. The AI wrote:

// What the AI writes
const upload = await supabase.storage
  .from('avatars')
  .upload(`${userId}/${file.name}`, file)

It accepts shell.php, malware.exe, huge.zip (10 GB), and polyglot.jpg that is actually a valid JPEG and a valid PHP script.

What you need:

  • Validate the MIME type against an allowlist (image/jpeg, image/png, image/webp)

  • Check the file extension matches the MIME type

  • Enforce a maximum file size (2 MB for avatars)

  • Scan for malicious content if the files are ever served to other users

  • Serve uploaded files from a separate domain or with Content-Disposition: attachment

Test this: upload a PHP file renamed to .jpg. Upload a 50 MB file. Upload an SVG with embedded JavaScript. If any succeed, the validation is missing.

4. Path traversal in file operations

The AI generates a download endpoint:

// What the AI writes
app.get('/download/:filename', (req, res) => {
  res.sendFile(path.join(__dirname, 'uploads', req.params.filename))
})

Request /download/../../etc/passwd. If the server returns it, the path traversal works.

The fix: resolve the path and verify it stays within the intended directory.

// What you need
const requestedPath = path.resolve(__dirname, 'uploads', req.params.filename)
const allowedPath = path.resolve(__dirname, 'uploads')
if (!requestedPath.startsWith(allowedPath)) {
  return res.status(400).send('Invalid path')
}
res.sendFile(requestedPath)

Test this: try directory traversal sequences on every file parameter. ../, ..\, URL-encoded variants, double-encoded variants.

5. No rate limiting on expensive operations

This connects to the rate limiting post, but from a validation angle: the AI does not validate that the input is reasonable.

A search endpoint with no pagination limit. A report generator that accepts startDate: 1900-01-01. An export that builds a 500 MB CSV in memory. An AI chat endpoint with no token limit on the prompt.

Validation here means bounds checking: maximum page size, maximum date range, maximum file size, maximum token count.

Test this: send absurdly large values to every numeric parameter. Send negative numbers. Send zero. Send strings where numbers are expected.

A practical validation checklist for vibe-coded apps

Run these checks on every endpoint that accepts input before you launch.

For every API endpoint

  • All database queries use parameterised statements (no string concatenation)

  • Input is validated against a schema (Zod, Valibot, Joi, or your framework's built-in)

  • Numeric inputs have min/max bounds

  • String inputs have length limits

  • Enum inputs are checked against the allowlist

  • Extra properties are stripped or rejected

For every file upload

  • MIME type checked against allowlist

  • File extension matches MIME type

  • File size enforced at the edge (nginx, Cloudflare, Vercel) and in code

  • Filename sanitised (no path traversal, no special characters)

  • Files served from a separate domain or with download headers

  • Virus/malware scan if files are shared between users

For every reflected input

  • Framework auto-escaping is enabled and not bypassed

  • No dangerouslySetInnerHTML, v-html, or raw interpolation of user data

  • Content Security Policy header restricts script sources

For every expensive operation

  • Pagination has a hard maximum (50 or 100 items)

  • Date ranges have a maximum span

  • Export jobs are queued, not run inline

  • AI prompts have token limits

  • Database queries have timeouts

How to verify your app without being a security expert

You do not need to be a penetration tester. You need a browser, a terminal, and a willingness to try to break your own app.

  1. Open your deployed app in an incognito window. Press F12, go to the Network tab.

  2. Find an API call that takes a parameter (search, filter, ID, file upload).

  3. Right-click it, copy as cURL.

  4. Modify the parameter and run it. Try: a single quote, a script tag, a 10 MB file, a negative page size, ../../etc/passwd.

  5. Check the response. If you get data back, a 200 with unexpected content, or a 500 that leaks stack traces, the validation is missing.

Do this for every endpoint. It takes an hour. It catches the majority of input validation bugs.

What the free surface check catches

The free surface check scans what is publicly visible: your headers, your certificate, files that may be reachable. It does not test your API endpoints for injection or validation bugs. Those require sending requests and analysing responses, which is what the launch-readiness audit covers.

The audit checks 137 points across 14 areas. Input and API security is one of those areas. We test every endpoint with a standard payload set: SQL injection, XSS, path traversal, oversized inputs, malformed types, and boundary values. You get a must-fix list with the exact endpoint, the payload that worked, and the fix.

Start with the endpoints that hurt most

If you only have time for a few checks, prioritise:

  1. Any endpoint that writes to your database (create, update, delete)

  2. Any endpoint that calls a paid API (OpenAI, Stripe, email, SMS)

  3. Any endpoint that returns user data (search, list, detail)

  4. Any file upload endpoint

  5. Any webhook receiver

Fix the validation on those five. Then move to the rest.

The goal is not perfect security. The goal is that the obvious attacks fail, so you find out about the subtle ones before your users do.

Want a developer to look at your app?

Built your app with AI tools? Run the free surface check yourself in a few minutes. Nothing to buy, and we never look at your app unless you run it.