tensor
tensor

Reputation: 783

How to limit number of document reads from a humongous collection in firestore when some malicious user queries the data?

I have a firestore collection called letters which holds a public letter from users. In my app, I am using pagination to limit the results to 20 when they go to public letters screen. My concern is that this would work fine from within the app but if some malicious user query the database from let's say postman then I will be billed heavily for all those reads. I have all security rules in place like the user should be authenticated but this needs to be public collection so I can't think of anything else to restrict this. How can I restrict someone to read about 20 documents at time?

Upvotes: 4

Views: 2005

Answers (2)

Doug Stevenson
Doug Stevenson

Reputation: 317477

There is actually no way to restrict the consumption of a collection based on direct query volume. Renaud's answer proposes to use request.query.limit in security rules, but that does not stop a malicious user from simply making as many calls to the pagination API as they want. It just forces them to provide a limit() on each query. The caller can still consume the entire collection, and consume it as many times as they want.

Watch my video on the topic: https://youtu.be/9sOT5VOflvQ?t=330

If you want to enforce a hard limit on the total number of documents to read, you will need a backend to do that. Clients can request documents from the backend up to the limit it enforces. If the backend wants to allow pagination, it will have to somehow track the usage of the provided endpoint to prevent each caller from exhausting whatever limits or quotas you want to enforce.

Upvotes: 8

Renaud Tarnec
Renaud Tarnec

Reputation: 83103

As explained in the doc:

The request.query variable contains the limit, offset, and orderBy properties of a query.

So you can write a rule like:

allow list: if request.query.limit <= 20;

Note that we use list, instead of read. The doc says:

You can break read rules into get and list rules. Rules for get apply to requests for single documents, and rules for list apply to queries and requests for collections.

Upvotes: 6

Related Questions