Vibe Coding Securely, Ch. 4: The Database Is the App
Part of Vibe Coding Securely, a short, hands-on book about shipping the app an AI built without getting owned.
In the last chapter we taught the server to know who you really are. That felt like the finish line. It is only the start line. Knowing you are bob answers one question, who is asking, and leaves a second one wide open: of all the things in this app, which ones is bob allowed to touch? Those are two different jobs. The first is authentication, proving who you are. The second is authorization, deciding what you may do. An AI tool is good at the first and tends to forget the second, because the prompt that builds a “show me a note” feature says nothing about whose note it is.
So this chapter is about the gap between them. The app will know you are bob, check your login carefully, and then hand you alice’s private note anyway, because you asked for it by its number and nobody checked whose it was.
Put the app at the start of this chapter:
git checkout ch4-start
Vibe Notes now stores a note’s owner. Each note belongs to a user, alice or bob, and each note has its own page at /notes/1, /notes/2, and so on. Log in as bob from the bar at the top and you see bob’s notes, each linking to its own page.
The feature, and the question it forgets to ask
When you open a note, the page asks the server for it through an API route, app/api/notes/[id]/route.ts. The [id] in the folder name is a placeholder: a request for /api/notes/3 arrives here with id set to 3. Here is the code the tool wrote:
export async function GET(
_req: Request,
{ params }: { params: Promise<{ id: string }> }
) {
const user = await getUser();
if (!user) {
return NextResponse.json({ error: "log in first" }, { status: 401 });
}
const { id } = await params;
const note = getDb()
.prepare("SELECT id, user_id, title, body, created_at FROM notes WHERE id = ?")
.get(id);
if (!note) {
return NextResponse.json({ error: "not found" }, { status: 404 });
}
return NextResponse.json(note);
}
Read it slowly, because almost all of it is right. It calls getUser, the function we fixed in chapter 3, and turns away anyone who is not logged in. That is a real authentication check, and it works. Then it looks up the note: SELECT ... FROM notes WHERE id = ?. The ? is a placeholder the database fills in with the id from the URL, which is the safe way to build a query, and we will come back to why in the next chapter.
The whole bug is one clause that is not there. The query asks for the note WHERE id = ?. It never asks AND whose note is it. The code checks that you are someone. It never checks that the note is yours. So once you are logged in as anyone at all, you can ask for any note by its number, and the server will fetch it and hand it over.
Seeing it
You would probably find this one by accident. You are bob, you are looking at your note at /notes/3, and you wonder what note number 1 is. You change the 3 to a 1 in the address bar. That is the whole attack. There is no tool, no trick, just a smaller number.
Let me do the same thing precisely, on the API the page uses, so this chapter’s check can watch it happen. First log in as bob. This saves the session cookie from chapter 3 into a file called a cookie jar, so the next command is making requests as a logged-in bob, exactly like the browser does:
curl -s -c jar.txt -X POST http://localhost:3000/api/login \
-H 'Content-Type: application/json' -d '{"username":"bob"}'
{"id":2,"username":"bob","role":"user"}
Now bob asks for his own note, number 3. The -b jar.txt sends the cookie back, so the server sees a logged-in bob:
curl -s -b jar.txt http://localhost:3000/api/notes/3
{"id":3,"user_id":2,"title":"Bob's todo","body":"Return the library book. Email the landlord about the sink.","created_at":"..."}
That is fine. Note 3 belongs to bob (user_id 2), and bob is reading it. Now change one character. Ask for note 1 instead:
curl -s -b jar.txt http://localhost:3000/api/notes/1
{"id":1,"user_id":1,"title":"Alice's diary","body":"Private. The spare key is under the third flowerpot.","created_at":"..."}
There it is. That note’s user_id is 1, which is alice, not bob. bob is logged in as himself, honestly, and he is reading alice’s diary, including the line about where the spare key is. He did not break anything. He asked for note 1, and the server, having confirmed he was logged in, never thought to ask whether note 1 was his.
This chapter’s check does the same walk and reports it:
npm run check:ch4
FOUND: logged in as bob, GET /api/notes/1 returned "Alice's diary"
(owned by user 1, not bob). Change the id, read anyone's note. See chapter 4.
This bug is common enough to have a name: IDOR, an insecure direct object reference. The direct object reference is that plain 1 sitting in the URL, a straight pointer to a row in your database. It becomes insecure the moment the server will hand you the row just because you named it, without checking it is yours to see. And because the ids count up, 1, 2, 3, an attacker does not even have to guess. They start at 1 and keep going, reading every note from every user in order. On a real app those rows are messages, invoices, medical forms, whatever the app holds. This single missing clause is behind a long list of real breaches, and it is the most common serious flaw in the kind of app we are building, precisely because the happy-path code looks finished.
The fix: let the database enforce ownership
The fix is one clause, in the same query. Stop asking the database for “the note with this id” and start asking for “the note with this id that also belongs to this user.” The current user’s id is already in hand from getUser, so we have everything we need:
const note = getDb()
.prepare(
"SELECT id, user_id, title, body, created_at FROM notes WHERE id = ? AND user_id = ?"
)
.get(id, user.id);
That is the whole change: AND user_id = ?, with user.id filled into the new placeholder. Now when bob asks for note 1, the database looks for a note that is both number 1 and owned by bob, finds none, and returns nothing. The route’s existing “not found” branch catches that and replies 404.
It matters that the fix lives in the query and not in an if after it. A tempting near-miss is to fetch the note the old way and then check: if (note.user_id !== user.id) return 403. That mostly works, but it tells the visitor something it should not. A 403 Forbidden on note 1 and a 404 Not Found on note 999 together confirm that note 1 exists and belongs to someone else, which is a small leak of its own. By folding ownership into the query, a note that is not yours is indistinguishable from a note that does not exist. bob learns nothing about alice’s notes, not even that they are there.
Jump to the fixed app if you like:
git checkout ch4-done
Proving it
Log in as bob again and run the same two requests. His own note still works:
curl -s -c jar.txt -X POST http://localhost:3000/api/login \
-H 'Content-Type: application/json' -d '{"username":"bob"}'
curl -s -b jar.txt http://localhost:3000/api/notes/3
{"id":3,"user_id":2,"title":"Bob's todo","body":"Return the library book. Email the landlord about the sink.","created_at":"..."}
And alice’s note is now a closed door:
curl -s -w "\n[http %{http_code}]\n" -b jar.txt http://localhost:3000/api/notes/1
{"error":"not found"}
[http 404]
The check agrees:
npm run check:ch4
BLOCKED: bob cannot read note 1; the server checks ownership (status 404).
bob can still read everything that is his, and nothing that is not. The feature did not get smaller. It got correct.
The part that generalizes
Here is the rule this chapter leaves you with, and it is worth saying plainly because it is so easy to skip: every time your app reads or writes data that belongs to a user, the ownership check is part of the query, not an afterthought. “Get the note” is never the real request. The real request is always “get the note, if it is theirs.” That applies to reading a note, editing it, deleting it, and to every other row your app will ever hold.
The uncomfortable part is that in our stack this is on you, in every single query, forever. SQLite, the small file-based database Vibe Notes uses, does exactly what you tell it, so one query that forgets AND user_id = ? is one hole, and it is the kind of line an AI tool leaves out without a flicker. There is no net under you.
Straight talk. Bigger apps often buy themselves a net, and it is worth knowing it exists. Hosted databases like Supabase, which is managed PostgreSQL, support a feature called row-level security, or RLS. You write the ownership rule once, in the database itself, as a policy: a row in
notesis visible only when itsuser_idmatches the currently logged-in user. After that the database refuses to return rows the policy forbids, no matter what the query says. A query that forgets the filter still cannot leak someone else’s row, because the rule does not live in the query. That is a genuinely stronger place to put the check, since it holds even when you make a mistake. We are using SQLite in this book because it needs no account and no setup, which is the right call for learning, and the price of that simplicity is exactly this: the ownership check is your job, on every query. If you move to a hosted database later, turning on RLS and writing one policy per table is one of the highest-value afternoons you can spend.
One more trap to name, because vibe-coded apps fall into it constantly. It is tempting to “fix” IDOR by making the ids impossible to guess, swapping the counting 1, 2, 3 for long random strings. That does raise the bar, and random ids are a fine idea for other reasons. But it does not fix this. The note’s id travels in links, in browser history, in server logs, in the URL you paste to a friend. An id that leaks once is an id forever, and an unguessable id that is still handed over to anyone who presents it is still a hole. Guessing was never the vulnerability. Handing over the row without checking ownership was. Fix the check, and the ids can be whatever you like.
Try it. Log in as bob and walk the numbers by hand:
curl -s -b jar.txt http://localhost:3000/api/notes/1, then/2, then/3, then/4. Onch4-startyou can read every note that exists. Onch4-doneonly bob’s own notes come back, and everything else is a404. Watching the same four commands change their answers after a one-clause fix is the whole lesson in miniature.
Where this leaves us
The app now checks not just who you are but what is yours, and it lets the database do the checking so a wrong answer comes back as “not found” rather than a leak. That closes the door on reading other people’s rows.
The next hole is a different kind of trust. So far the danger has been in what the app believes about you. Next it is in what the app does with what you type. Vibe Notes has a search box that builds a database query by pasting your words straight into it, and a note page that renders your text straight into the page as HTML. Both look like features. Both are doors. That is chapter 5.