5

I would like to know if, by itself, callables functions with Firebase Cloud Functions, for example :

exports.myCallableFunction = functions.https.onCall((data, context) => { 
  //... 
});

are safe by themselves or if I need to implement some code inside of them to make sure only authenticated users that calls them gets something out of it. From my understanding, it's called via an API end point, so I'm kind of concerned about everybody being able to call it.

If some logic needs to be implemented, what logic would make sure it's safe?

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
UmbrellaCorpAgent
  • 548
  • 1
  • 5
  • 17

2 Answers2

4

If you want only authenticated users to be able to invoke your function, a callable function by itself is not "safe" in that respect. You will need to add code to make sure the user is authenticated, then decide what you want to send if they are not.

exports.myCallableFunction = functions.https.onCall((data, context) => {
    if (!context.auth) {
        throw new functions.https.HttpsError("unauthenticated", "You must be authenticated");
    }

    // continue here if they are auth'd
});
Doug Stevenson
  • 297,357
  • 32
  • 422
  • 441
  • 3
    Any chance/timeline of supporting built-in auth enforcement (rather than having to write custom code)? Since in this case, the function has **actually been invoked** with an unauthenticated request; which kind of defies the point of having authentication set up in the first place (unlike, say, in case of AWS Cognito based Lambda authentication) – Janaka Bandara Mar 02 '21 at 01:10
  • 1
    I do feel like making sure the user has the right to call a function before the function is actually invoked would make total sens instead of verifying everytime inside the function itself – UmbrellaCorpAgent Jul 10 '22 at 18:45
  • 1
    You also need to check `context.auth.uid`. If someone sends an invalid Bearer token, the `auth` object is still present, but is just `undefined` – simonthumper Sep 17 '22 at 08:09
1

Anyone can call a callable cloud function, but you can easily check whether the user is signed in (and who they are) by checking context.auth.

I recommend reading the documentation on [callable cloud functions], which contains a section on authentication.

Frank van Puffelen
  • 565,676
  • 79
  • 828
  • 807
  • Is it enough to just check if `context.auth` exists as in [this example from documentation](https://firebase.google.com/docs/functions/callable#handle_errors), or do we need to do some further checking like verifying that `context.auth.token` is valid and how? This is not specified in documentation, and I'm worried that someone could just add any `context.auth` information in their request and the check from documentation looks like it would pass, any comment on that? – ado387 Sep 01 '22 at 07:50