IDOR in AI Code: Why Authentication Does Not Stop Data Leaks
I created two test accounts on an AI-built invoicing app, swapped an ID parameter, and downloaded another user's billing invoice in 35ms. Here is why auth checks fail without ownership checks.
01Run this check right now
Diagnostic TestThe ID Swapping Terminal Test
Log into two test accounts (User A and User B). Obtain User A's authentication token and attempt to fetch an invoice ID belonging to User B. If the response returns invoice data instead of an HTTP 403 or 404 status, your endpoint lacks ownership verification.
curl -s -H "Authorization: Bearer <USER_A_TOKEN>" "https://api.yourdomain.com/invoices/<USER_B_INVOICE_ID>"Findings from the Field
- /01I registered two test accounts, swapped the invoice ID in a curl request, and downloaded private billing records in 35ms.
- /02Authentication validates who a caller is; authorization verifies whether that specific caller owns the requested resource.
- /03AI models write middleware that checks valid JWT signatures, but generate queries like SELECT * FROM invoices WHERE id = $1 without tenant scoping.
- /04Sequential integer IDs allow an attacker to enumerate and scrape entire database tables with a 5-line bash loop.
- /05How compound WHERE clauses and Row Level Security enforce tenant boundaries at the database layer.
The 35-millisecond ID swap test
A team building a B2B billing portal asked me to look over their API routes before opening their beta. The code was generated with Cursor and Node.js. Every route had a clean `requireAuth` middleware attached to it, validating JSON Web Tokens on incoming requests.
To test their authorization boundary, I opened my browser and registered two test accounts: Account A and Account B. Under Account B, I created a mock invoice, which was assigned ID `1042`. Then I grabbed Account A's JWT token, opened my terminal, and sent a GET request to `/api/invoices/1042`.
In 35 milliseconds, the server returned Account B's complete invoice: customer company name, physical billing address, line items, and bank transfer routing details. The authentication middleware had passed because Account A had a valid token. But nobody had verified that Account A owned invoice 1042.
The hotel keycard analogy
Think of it like checking into a hotel. You walk up to the front desk, show your passport, and the clerk hands you a valid electronic keycard. That is authentication: the hotel confirmed who you are.
Now imagine you walk up to room 412 (your assigned room) and your keycard opens it. But then you walk down the hall to room 410, swipe your keycard, and that door opens too. That is an Insecure Direct Object Reference (IDOR). The lock verified that you are a registered hotel guest, but it never checked which room you rented.
Why AI models omit tenant isolation
When an AI coding model generates a REST endpoint, it breaks the task into two sequential steps. Step 1: add authentication middleware to verify the user session. Step 2: query the database for the resource requested in the URL parameter.
In the controller, the AI writes the most direct query possible:
If your database uses auto-incrementing integers (1001, 1002, 1003), anyone with a free registered account can write a simple five-line bash script to scrape every invoice, order, or patient record in your entire platform in under four minutes.
// VULNERABLE: checks if user is logged in, but queries by ID alone
app.get('/api/invoices/:id', requireAuth, async (req, res) => {
const invoice = await db.query(
'SELECT * FROM invoices WHERE id = $1',
[req.params.id]
);
if (!invoice.rows[0]) return res.status(404).send('Not found');
res.json(invoice.rows[0]);
});Fixing the query at the database layer
The fix is to enforce tenant ownership in every database query. You must never query by resource ID alone when retrieving or mutating customer data:
// SECURE: Enforces resource ID AND organization ownership
app.get('/api/invoices/:id', requireAuth, async (req: AuthRequest, res) => {
const invoiceId = req.params.id;
const orgId = req.user.organizationId;
const result = await db.query(
`SELECT id, total_amount, due_date, status, pdf_url
FROM invoices
WHERE id = $1 AND organization_id = $2`,
[invoiceId, orgId]
);
if (result.rows.length === 0) {
// Return 404 instead of 403 to avoid confirming record existence
return res.status(404).json({ error: "Invoice not found" });
}
res.json(result.rows[0]);
});Reflections: UUIDs do not replace authorization
A common suggestion in developer threads is: 'Just switch primary keys to UUIDs so IDs cannot be guessed.'
UUIDs are good practice because they stop simple enumeration scripts. But UUIDs are not authorization. UUIDs leak constantly: through referer headers, browser histories, share links, and webhook payloads. If an unauthorized user gets hold of a UUID through any channel, an endpoint without tenant scoping will still return private customer data.
Always scope your queries with the authenticated tenant ID, and you never have to worry about IDOR again. Now I am going to close this laptop and grab dinner, because yolo.
Production Hardening & Audits
Stuck on prompt regressions, leaked keys, or database scaling in an AI-built app? Explore our platform-specific teardowns:
Diagnostic & Rescue
1 business day replyThink your prototype is vulnerable or hitting scale limits?
Send us a note with your repository, Supabase link, or project details. A senior engineer will review your policies and reply within one business day.
