Firebase cloud function: how to deal with continuous request

前端 未结 4 809
北恋
北恋 2020-12-23 10:47

When working with Firebase (Firebase cloud function in this case), we have to pay for every byte of bandwidth.

So, i wonder how can we deal with case that someone wh

4条回答
  •  粉色の甜心
    2020-12-23 10:52

    Since you didn't specify which type of request, I'm going to assume that you mean http(s)-triggers on firebase cloud functions.

    There are multiple limiters you can put in place to 'reduce' the bandwidth consumed by the request. I'll write a few that comes to my mind

    1) Limit the type of requests

    If all you need is GET and say for example you don't need PUT you can start off by returning a 403 for those, before you go any further in your cloud function.

    if (req.method === 'PUT') { res.status(403).send('Forbidden!'); }
    

    2) Authenticate if you can

    Follow Google's example here and allow only authorized users to use your https endpoints. You can simply achieve this by verifying tokens like this SOF answer to this question.

    3) Check for origin

    You can try checking for the origin of the request before going any further in your cloud function. If I recall correctly, cloud functions give you full access to the HTTP Request/Response objects so you can set the appropriate CORS headers and respond to pre-flight OPTIONS requests.

    Experimental Idea 1

    You can hypothetically put your functions behind a load balancer / firewall, and relay-trigger them. It would more or less defeat the purpose of cloud functions' scalable nature, but if a form of DoS is a bigger concern for you than scalability, then you could try creating an app engine relay, put it behind a load balancer / firewall and handle the security at that layer.

    Experimental Idea 2

    You can try using DNS level attack-prevention solutions to your problem by putting something like cloudflare in between. Use a CNAME, and Cloudflare Page Rules to map URLs to your cloud functions. This could hypothetically absorb the impact. Like this :

    *function1.mydomain.com/* -> https://us-central1-etc-etc-etc.cloudfunctions.net/function1/$2

    Now if you go to

    http://function1.mydomain.com/?something=awesome

    you can even pass the URL params to your functions. A tactic which I've read about in this medium article during the summer when I needed something similar.

    Finally

    In an attempt to make the questions on SOF more linked, and help everyone find answers, here's another question I found that's similar in nature. Linking here so that others can find it as well.

提交回复
热议问题