Rate limiting for Google/Firebase cloud functions?

前端 未结 2 1814
刺人心
刺人心 2020-12-30 12:14

I am using Firebase to develop an app that uses Cloud Functions as a REST API internally. My question is, is there an easy way to implement per-IP/per-user rate-limiting sim

2条回答
  •  情书的邮戳
    2020-12-30 12:37

    Doing this on a per-user basis sounds fairly straightforward:

    1. Pass the ID token of the user to Cloud Functions with each request.
    2. Decode the ID token in your Cloud Function to determine the UID. For an example of these first two steps, see the functions-samples repo.
    3. Push the fact that user UID has called the function to a database, probably adding it to a list. E.g. admin.database().ref(`/userCalls/$uid`).push(ServerValue.TIMESTAMP).
    4. Query for the number of recent calls with something like admin.database().ref(`/userCalls/$uid`).orderByKey().startAt(Date.now()-60000).
    5. Count the results and reject if it is too high.

    I'm not sure if the IP address of the caller is passed to Cloud Functions. If it is, you can do the same logic for the IP address. If it isn't passed, it'll be hard to rate limit in a way that can't be easily spoofed.

提交回复
热议问题