安全地查詢資料

本頁面以結構安全性規則安全性規則的編寫條件中概念為基礎,說明 Cloud Firestore 安全性規則與查詢的互動方式。其中會進一步說明安全性規則如何影響您可以編寫的查詢,並說明如何讓查詢使用與安全性規則相同的限制。本頁面也會說明如何編寫安全性規則,以根據 limitorderBy 等查詢屬性允許或拒絕查詢。

規則不是篩選器

撰寫用來擷取文件的查詢時,請注意安全性規則並不是篩選,而是全部或沒有任何查詢。為節省您的時間和資源,Cloud Firestore 是根據查詢可能的結果集來評估查詢,而非所有文件的實際欄位值。如果查詢可能傳回用戶端無權讀取的文件,整個要求就會失敗。

查詢和安全性規則

如下列範例所示,您必須撰寫查詢以符合安全性規則的限制。

根據auth.uid保護文件並查詢文件

以下範例說明如何撰寫查詢,以擷取受安全性規則保護的文件。假設資料庫包含一組 story 文件:

/story/{storyid}

{
  title: "A Great Story",
  content: "Once upon a time...",
  author: "some_auth_id",
  published: false
}

除了 titlecontent 欄位以外,每份文件還會儲存用於存取權控管的 authorpublished 欄位。這些範例假設應用程式使用 Firebase 驗證,將 author 欄位設為建立文件的使用者 UID。Firebase 驗證也會填入安全性規則中的 request.auth 變數。

下列安全性規則使用 request.authresource.data 變數,限制個別 story 的讀取及寫入權限:

service cloud.firestore {
  match /databases/{database}/documents {
    match /stories/{storyid} {
      // Only the authenticated user who authored the document can read or write
      allow read, write: if request.auth != null && request.auth.uid == resource.data.author;
    }
  }
}

假設應用程式含有一個頁面,會顯示使用者所編寫的 story 文件清單。您可能會預期可以使用以下查詢來填入此頁面。但是,這項查詢將會失敗,因為其中沒有與安全性規則相同的限制:

無效:查詢限制與安全性規則限制不符

// This query will fail
db.collection("stories").get()

即使目前的使用者實際上是所有 story 文件的作者,查詢也會失敗。這個行為的原因是,當 Cloud Firestore 套用安全性規則時,會依據其「可能」結果集來評估查詢,而不是根據資料庫中文件的「實際」屬性來評估查詢。如果查詢可能包含違反安全性規則的文件,查詢就會失敗。

相反地,下列查詢因此成功,因為在 author 欄位加上與安全性規則相同的限制:

有效:查詢限制符合安全性規則限制

var user = firebase.auth().currentUser;

db.collection("stories").where("author", "==", user.uid).get()

依據欄位保護文件並查詢文件

為進一步示範查詢與規則之間的互動,以下安全性規則會展開 stories 集合的讀取權限,讓任何使用者讀取 published 欄位設為 truestory 文件。

service cloud.firestore {
  match /databases/{database}/documents {
    match /stories/{storyid} {
      // Anyone can read a published story; only story authors can read unpublished stories
      allow read: if resource.data.published == true || (request.auth != null && request.auth.uid == resource.data.author);
      // Only story authors can write
      allow write: if request.auth != null && request.auth.uid == resource.data.author;
    }
  }
}

已發布網頁的查詢必須包含與安全性規則相同的限制:

db.collection("stories").where("published", "==", true).get()

查詢限制 .where("published", "==", true) 可以保證任何結果的 resource.data.published 都是 true。因此,此查詢符合安全性規則,並允許讀取資料。

OR 項查詢

在根據規則集評估邏輯 OR 查詢 (orinarray-contains-any) 時,Cloud Firestore 會分別評估每個比較值。每個比較值都必須符合安全性規則限制。以下列規則為例:

match /mydocuments/{doc} {
  allow read: if resource.data.x > 5;
}

無效:查詢並不保證所有可能文件都使用 x > 5

// These queries will fail
query(db.collection("mydocuments"),
      or(where("x", "==", 1),
         where("x", "==", 6)
      )
    )

query(db.collection("mydocuments"),
      where("x", "in", [1, 3, 6, 42, 99])
    )

有效:查詢保證所有可能文件均以 x > 5 表示

query(db.collection("mydocuments"),
      or(where("x", "==", 6),
         where("x", "==", 42)
      )
    )

query(db.collection("mydocuments"),
      where("x", "in", [6, 42, 99, 105, 200])
    )

評估查詢限制

您的安全性規則也可以根據限制來接受或拒絕查詢。request.query 變數包含查詢的 limitoffsetorderBy 屬性。例如,您的安全性規則可以拒絕任何未將擷取的文件數量上限限制於特定範圍的查詢:

allow list: if request.query.limit <= 10;

下列規則集示範如何編寫用於評估查詢限制的安全性規則。本範例會擴充先前的 stories 規則,包含下列變更:

  • 規則集會將讀取規則拆分為 getlist 的規則。
  • get 規則會限制對單一文件的擷取作業,只能擷取使用者編寫的公開文件或文件。
  • list 規則套用與 get 相同的限制,但適用於查詢。也會檢查查詢限制,然後拒絕任何沒有限製或限制大於 10 的查詢。
  • 規則集定義 authorOrPublished() 函式,以避免程式碼重複。
service cloud.firestore {

  match /databases/{database}/documents {

    match /stories/{storyid} {

      // Returns `true` if the requested story is 'published'
      // or the user authored the story
      function authorOrPublished() {
        return resource.data.published == true || request.auth.uid == resource.data.author;
      }

      // Deny any query not limited to 10 or fewer documents
      // Anyone can query published stories
      // Authors can query their unpublished stories
      allow list: if request.query.limit <= 10 &&
                     authorOrPublished();

      // Anyone can retrieve a published story
      // Only a story's author can retrieve an unpublished story
      allow get: if authorOrPublished();

      // Only a story's author can write to a story
      allow write: if request.auth.uid == resource.data.author;
    }

  }
}

集合群組查詢和安全性規則

根據預設,查詢的範圍僅限於單一集合,且只會從該集合擷取結果。使用集合群組查詢,即可從包含相同 ID 的所有集合的集合群組中擷取結果。本節說明如何使用安全性規則保護集合群組查詢。

根據集合群組保護文件並查詢文件

在安全性規則中,您必須編寫集合群組的規則,明確允許集合群組查詢:

  1. 請確定 rules_version = '2'; 是規則集的第一行。集合群組查詢需要使用安全性規則 2 的新的遞迴萬用字元 {name=**} 行為。
  2. 使用 match /{path=**}/[COLLECTION_ID]/{doc} 為您的集合群組編寫規則。

舉例來說,假設某個論壇是整理成 forum 份文件,內含 posts 子集合:

/forums/{forumid}/posts/{postid}

{
  author: "some_auth_id",
  authorname: "some_username",
  content: "I just read a great story.",
}

在這個應用程式中,我們開放其擁有者編輯貼文,並供已驗證的使用者讀取:

service cloud.firestore {
  match /databases/{database}/documents {
    match /forums/{forumid}/posts/{post} {
      // Only authenticated users can read
      allow read: if request.auth != null;
      // Only the post author can write
      allow write: if request.auth != null && request.auth.uid == resource.data.author;
    }
  }
}

任何經過驗證的使用者都可以擷取任一論壇的貼文:

db.collection("forums/technology/posts").get()

不過,如果您想在所有論壇中顯示目前使用者張貼的訊息,該怎麼做? 您可以使用集合群組查詢,從所有 posts 集合擷取結果:

var user = firebase.auth().currentUser;

db.collectionGroup("posts").where("author", "==", user.uid).get()

在安全性規則中,您必須為 posts 集合群組編寫讀取或列出規則來允許這項查詢:

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {
    // Authenticated users can query the posts collection group
    // Applies to collection queries, collection group queries, and
    // single document retrievals
    match /{path=**}/posts/{post} {
      allow read: if request.auth != null;
    }
    match /forums/{forumid}/posts/{postid} {
      // Only a post's author can write to a post
      allow write: if request.auth != null && request.auth.uid == resource.data.author;

    }
  }
}

但請注意,無論階層為何,這些規則會套用至 ID 為 posts 的所有集合。例如,這些規則適用於下列所有 posts 集合:

  • /posts/{postid}
  • /forums/{forumid}/posts/{postid}
  • /forums/{forumid}/subforum/{subforumid}/posts/{postid}

基於欄位的安全集合群組查詢

如同單一集合查詢,集合群組查詢也必須符合安全性規則設定的限制。舉例來說,我們可以在每個論壇貼文中新增 published 欄位,方法如上方 stories 範例所示:

/forums/{forumid}/posts/{postid}

{
  author: "some_auth_id",
  authorname: "some_username",
  content: "I just read a great story.",
  published: false
}

然後,我們就能根據 published 狀態和貼文 authorposts 集合群組撰寫規則:

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {

    // Returns `true` if the requested post is 'published'
    // or the user authored the post
    function authorOrPublished() {
      return resource.data.published == true || request.auth.uid == resource.data.author;
    }

    match /{path=**}/posts/{post} {

      // Anyone can query published posts
      // Authors can query their unpublished posts
      allow list: if authorOrPublished();

      // Anyone can retrieve a published post
      // Authors can retrieve an unpublished post
      allow get: if authorOrPublished();
    }

    match /forums/{forumid}/posts/{postid} {
      // Only a post's author can write to a post
      allow write: if request.auth.uid == resource.data.author;
    }
  }
}

透過這些規則,網頁、Apple 和 Android 用戶端可以進行下列查詢:

  • 任何人都可以擷取論壇中的已發布貼文:

    db.collection("forums/technology/posts").where('published', '==', true).get()
    
  • 所有人都可擷取作者在所有論壇中發布的貼文:

    db.collectionGroup("posts").where("author", "==", "some_auth_id").where('published', '==', true).get()
    
  • 作者可擷取在所有論壇中,所有已發布和未發布的貼文:

    var user = firebase.auth().currentUser;
    
    db.collectionGroup("posts").where("author", "==", user.uid).get()
    

依集合群組和文件路徑保護文件並查詢文件

在某些情況下,您可能會想根據文件路徑限制集合群組查詢。如要建立這些限制,您可以使用相同的技巧,依據欄位保護及查詢文件。

假設有一個應用程式會在股票和加密貨幣交易平台中追蹤每位使用者的交易:

/users/{userid}/Exchange/{Exchangeid}/transactions/{transaction}

{
  amount: 100,
  exchange: 'some_exchange_name',
  timestamp: April 1, 2019 at 12:00:00 PM UTC-7,
  user: "some_auth_id",
}

請注意 user 欄位。即使我們知道哪位使用者擁有文件路徑中的 transaction 文件,我們仍會在每份 transaction 文件中複製這項資訊,因為我們可以執行以下兩項作業:

  • 撰寫僅限在文件路徑中包含特定 /users/{userid} 的文件的集合群組查詢。例如:

    var user = firebase.auth().currentUser;
    // Return current user's last five transactions across all exchanges
    db.collectionGroup("transactions").where("user", "==", user).orderBy('timestamp').limit(5)
    
  • transactions 集合群組中的所有查詢強制執行這項限制,如此一來,某個使用者就無法擷取其他使用者的 transaction 文件。

我們會在安全性規則中強制執行這項限制,並為 user 欄位加入資料驗證:

rules_version = '2';
service cloud.firestore {

  match /databases/{database}/documents {

    match /{path=**}/transactions/{transaction} {
      // Authenticated users can retrieve only their own transactions
      allow read: if resource.data.user == request.auth.uid;
    }

    match /users/{userid}/exchange/{exchangeid}/transactions/{transaction} {
      // Authenticated users can write to their own transactions subcollections
      // Writes must populate the user field with the correct auth id
      allow write: if userid == request.auth.uid && request.data.user == request.auth.uid
    }
  }
}

後續步驟