云功能的安全规则

security rules for cloud function

就像我们在访问 firestore 数据库之前编写安全规则一样,我们能否在请求云功能 firebase 之前编写安全规则以保护它免受滥用,另一个相关的问题是 appcheck 在调用之前是否工作或者我已经明确写 context.app.

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

云函数没有任何安全规则。您必须显式验证传入请求并检查调用者是否有权执行这些操作。这是必要的,因为云功能使用 Admin SDK,它具有访问您的 Firebase 项目的特权并且也不遵守安全规则。

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
})

请注意,这确实会花费您的调用次数和 CPU 使用时间。您应该尽早终止垃圾邮件请求。

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

您需要明确检查 context.app。如果请求不包含 documentation.

中提到的有效 App Check 令牌,则它将是未定义的
if (context.app == undefined) {
  throw new functions.https.HttpsError(
      'failed-precondition',
      'The function must be called from an App Check verified app.')
}