security rules for cloud function

Viewed 72

Just like how we write security rules before accessing firestore database, can we write security rules before requesting to cloud functions firebase to protect it from abuse and another linked question is does appcheck work work before calling or I have explicitly write context.app.

1 Answers

can we write security rules before requesting to cloud functions firebase to protect it from abuse

There aren't any security rules for Cloud functions. You would have to explicitly validate the incoming request and check if the caller is authorized to perform the actions. This is necessary as Cloud functions use Admin SDK which has privileged accessed to your Firebase project and has doesn't obey security rules either.

exports.yourCallableFunction = functions.https.onCall((data, context) => {
  // verify context.app
  if (!context.app) return null;
  
  const {uid, token} = context.auth
  // check if this user is authorized to perform requested action
  // you can access custom claims from the token object
})

Do note that this does cost you invocations and CPU usage time. You should try to terminate spam requests as early as possible.

does appcheck work before calling or I have explicitly write context.app.

You need to explicitly check for context.app. It will be undefined if the request doesn't include a valid App Check token as mentioned in the documentation.

if (context.app == undefined) {
  throw new functions.https.HttpsError(
      'failed-precondition',
      'The function must be called from an App Check verified app.')
}
Related