NoSQL Injection: When Input Becomes a Query
See how a MongoDB query can accept an instruction where it expects an access code, then fix it with a runtime type check.
You’re reading a preview. Premium includes the full lesson and specialist practice. View the full curriculum.
A document you can find, but cannot open
Imagine a team app called SharedDesk. You belong to the Green workspace, and a colleague sends you a link to a private handbook. The link contains the document's ID, but you still need its secret access code to read it. Being in the same workspace is not enough.
The app should check two things before returning the document:
- Does it belong to your workspace?
- Did you supply the correct access code?
In this exercise, you'll see how a small mistake lets someone get past the second check. Then you'll fix it. You only need to follow a few lines of JavaScript; we'll explain the MongoDB syntax as we go.
Start with a normal request
Suppose the handbook's ID is doc-handbook and its code is river-stone. These are fictional example values. A request with the correct code looks like this:
{
"documentId": "doc-handbook",
"accessCode": "river-stone"
}
The server reads that JSON and builds a MongoDB query:
const document = await documents.findOne({
tenantId: membership.tenantId,
documentId: body.documentId,
accessCode: body.accessCode,
});
Read this as: find a document in my workspace, with this ID, and with this access code. All three conditions must match. findOne returns a matching document, or null if there isn't one.
Here, tenantId is just the database's name for the workspace ID. The server gets it from the signed-in user's verified membership. The other two values come from the request.
With "river-stone", the handbook is returned. With "wrong-code", it isn't. So far, so good.