问题
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?
回答1:
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.
回答2:
As explained in the doc:
The request.query variable contains the limit,
offset
, andorderBy
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
andlist
rules. Rules forget
apply to requests for single documents, and rules forlist
apply to queries and requests for collections.
来源:https://stackoverflow.com/questions/62228970/how-to-limit-number-of-document-reads-from-a-humongous-collection-in-firestore-w