Firestore 安全规则允许在没有更新规则的情况下进行更新

问题描述 投票:0回答:1

我可能不理解 firestore sdk set() 方法的正确使用。我的理解是,如果文档 ID 不存在,它将执行“创建”。如果确实如此,它将对现有文档执行“更新”并覆盖,除非包含

merge=True
。但这不是我所看到的。

我有以下 firestore 数据库结构:

Investment (collection)
  News (subcollection)

这些是我目前的规则:

rules_version = '2';
service cloud.firestore {
  
  function isUpdateToActivityField() {
    return request.resource.data.diff(resource.data).affectedKeys().hasOnly(['activity']);
  }

  match /databases/{database}/documents {
    match /Investment/{iid} {
      allow read: if request.auth != null;
      allow update: if request.auth != null && isUpdateToActivityField();
      allow create: if request.auth != null;
      
      match /News/{nid} {
        allow read: if request.auth != null;
        allow create: if request.auth != null;
      }
    }
  }
}

如果我手动修改新闻项目中的字段,然后执行更新,它将覆盖我的记录并恢复文本。

enter image description here

这就是我使用 set() 方法的方式。

        product_ref = client.collection("Investment").document(self.symbol)
        batch = client.batch()
        for n in news:
            ndict = n.to_dict()
            new_news_ref = product_ref.collection("News").document(ndict.pop("uuid"))
            batch.set(new_news_ref, ndict, merge=True)
        batch.commit()

我的目标只是让规则阻止创建或更新(如果记录已经存在)而无需签入代码。我什至尝试将创建规则更改为:

allow create: if request.auth != null && !exists(/databases/$(database)/documents/Investment/$(iid)/News/$(nid))

但是运气不佳。

我的做法是否错误?

python-3.x google-cloud-firestore firebase-security
1个回答
0
投票

Cloud Firestore 的 Python SDK 被视为服务器端 SDK,这意味着它会绕过您为项目设置的安全规则。来自文档:

服务器客户端库创建一个特权 Firebase 环境,可以完全访问您的数据库。在此环境中,不会根据您的 Firebase 安全规则评估请求。使用身份和访问管理 (IAM) 保护特权 Firebase 服务器的安全,请参阅服务器客户端库的安全性。

您应该仅在受信任的环境中使用服务器端 SDK,这样您可以确保访问项目的代码是您控制的代码。

要强制执行安全规则,请使用 Firestore 客户端 SDK,该 SDK 适用于 Web、Android、iOS、C++、Unity 和 Flutter。

© www.soinside.com 2019 - 2024. All rights reserved.