瞭解適用於 Cloud Storage 語言的 Firebase 安全性規則核心語法

Firebase Security RulesCloud Storage,可讓您控管 Cloud Storage 值區中 儲存物件的存取權。彈性規則語法可讓您建立規則,控管任何作業,包括對 Cloud Storage bucket 的所有寫入作業,以及對特定檔案的作業。

本指南說明 Cloud Storage Security Rules 的基本語法和結構,可協助您建立完整的規則集。

服務和資料庫宣告

Firebase Security Rules Cloud Storage 一律以以下宣告開頭:

service firebase.storage {
    // ...
}

service firebase.storage 宣告會將規則範圍限定在 Cloud Storage,避免 Cloud Storage Security Rules 與其他產品 (例如 Cloud Firestore) 的規則發生衝突。

基本讀取/寫入規則

基本規則包含 match 陳述式 (用於識別 Cloud Storage 值區)、比對陳述式 (用於指定檔案名稱),以及 allow 運算式 (用於詳細說明何時允許讀取指定資料)。allow 運算式會指定涉及的存取方法 (例如讀取、寫入),以及允許或拒絕存取的條件

在預設規則集中,第一個 match 陳述式會使用 {bucket} 萬用字元運算式,指出規則適用於專案中的所有值區。我們會在下一節中進一步討論萬用字元比對的概念。

service firebase.storage {
  // The {bucket} wildcard indicates we match files in all Cloud Storage buckets
  match /b/{bucket}/o {
    // Match filename
    match /filename {
      allow read: if <condition>;
      allow write: if <condition>;
    }
  }
}

所有相符陳述式都指向檔案。比對陳述式可以指向特定檔案,例如 match /images/profilePhoto.png

比對萬用字元

除了指向單一檔案,Security Rules 也可以使用萬用字元指向名稱中含有特定字串前置字元的任何檔案,包括斜線,例如 match /images/{imageId}

在上述範例中,比對陳述式使用 {imageId} 萬用字元語法。也就是說,規則會套用至名稱開頭為 /images/ 的任何檔案,例如 /images/profilePhoto.png/images/croppedProfilePhoto.png。評估比對陳述式中的 allow 運算式時,imageId 變數會解析為圖片檔案名稱,例如 profilePhoto.pngcroppedProfilePhoto.png

可從 match 內參照萬用字元變數,提供檔案名稱或路徑授權:

// Another way to restrict the name of a file
match /images/{imageId} {
  allow read: if imageId == "profilePhoto.png";
}

階層式資料

如前所述,Cloud Storage bucket 內沒有階層結構。不過,只要使用檔案命名慣例 (通常是在檔案名稱中加入斜線),我們就能模擬出類似巢狀目錄和子目錄的結構。請務必瞭解 Firebase Security Rules 如何與這些檔案名稱互動。

假設有一組檔案,名稱開頭都是 /images/ 詞幹。Firebase Security Rules 只會套用至相符的檔案名稱,因此在 /images/ 詞幹上定義的存取權控管不會套用至 /mp3s/ 詞幹。請改為編寫符合不同檔案名稱模式的明確規則:

service firebase.storage {
  match /b/{bucket}/o {
    match /images/{imageId} {
      allow read, write: if <condition>;
    }

    // Explicitly define rules for the 'mp3s' pattern
    match /mp3s/{mp3Id} {
      allow read, write: if <condition>;
    }
  }
}

巢狀 match 陳述式內部的路徑 一律會附加至外部 match 陳述式的路徑。match因此,下列兩組規則集的作用相同:

service firebase.storage {
  match /b/{bucket}/o {
    match /images {
      // Exact match for "images/profilePhoto.png"
      match /profilePhoto.png {
        allow write: if <condition>;
      }
    }
  }
}
service firebase.storage {
  match /b/{bucket}/o {
    // Exact match for "images/profilePhoto.png"
    match /images/profilePhoto.png {
      allow write: if <condition>;
      }
  }
}

遞迴比對萬用字元

除了在檔案名稱結尾比對並傳回字串的萬用字元外,您也可以宣告多個區隔的萬用字元,在萬用字元名稱中加入 =**,例如 {path=**},進行更複雜的比對:

// Partial match for files that start with "images"
match /images {

  // Exact match for "images/**"
  // e.g. images/users/user:12345/profilePhoto.png is matched
  // images/profilePhoto.png is also matched!
  match /{allImages=**} {
    // This rule matches one or more path segments (**)
    // allImages is a path that contains all segments matched
    allow read: if <other_condition>;
  }
}

如果檔案符合多項規則,結果會是所有規則評估結果的 OR。也就是說,如果檔案符合的任何規則評估結果為 true,結果就是 true

在上述規則中,如果 conditionother_condition 評估結果為 true,即可讀取「images/profilePhoto.png」檔案,而「images/users/user:12345/profilePhoto.png」檔案只會受到 other_condition 的評估結果影響。

Cloud Storage Security Rules 不會層疊,只有在要求路徑與指定規則的路徑相符時,系統才會評估規則。

版本 1

Firebase Security Rules 預設會使用第 1 版。在第 1 版中,遞迴萬用字元會比對一或多個檔案名稱元素,而非零或多個元素。因此,match /images/{filenamePrefixWildcard}/{imageFilename=**} 會比對 /images/profilePics/profile.png 等檔案名稱,但不會比對 /images/badge.png。請改用 /images/{imagePrefixorFilename=**}

遞迴萬用字元必須放在比對陳述式的結尾。

建議使用第 2 版,因為功能更強大。

第 2 版

在第 2 版的 Firebase Security Rules 中,遞迴萬用字元會比對零或多個路徑項目。因此,/images/{filenamePrefixWildcard}/{imageFilename=**} 會比對檔案名稱 /images/profilePics/profile.png 和 /images/badge.png。

您必須在安全性規則頂端新增 rules_version = '2';,才能選擇使用第 2 版:

rules_version = '2';
service cloud.storage {
  match /b/{bucket}/o {
   ...
 }
}

每個比對陳述式最多可有一個遞迴萬用字元,但在第 2 版中,您可以在比對陳述式中的任何位置放置這個萬用字元。例如:

rules_version = '2';
service firebase.storage {
 match /b/{bucket}/o {
   // Matches any file in a songs "subdirectory" under the
   // top level of your Cloud Storage bucket.
   match /{prefixSegment=**}/songs/{mp3filenames} {
     allow read, write: if <condition>;
   }
  }
}

精細作業

在某些情況下,將 readwrite 分解為更精細的作業會很有用。舉例來說,您的應用程式可能想對檔案建立作業強制執行不同於檔案刪除作業的條件。

read 作業可分為 getlist

write 規則可分為 createupdatedelete

service firebase.storage {
  match /b/{bucket}/o {
    // A read rule can be divided into read and list rules
    match /images/{imageId} {
      // Applies to single file read requests
      allow get: if <condition>;
      // Applies to list and listAll requests (Security Rules Version 2)
      allow list: if <condition>;

    // A write rule can be divided into create, update, and delete rules
    match /images/{imageId} {
      // Applies to writes to file contents
      allow create: if <condition>;

      // Applies to updates to (pre-existing) file metadata
      allow update: if <condition>;

      // Applies to delete operations
      allow delete: if <condition>;
    }
  }
 }
}

重疊的相符陳述式

檔案名稱可能會符合多個 match 陳述式。如果多個 allow 運算式符合要求,只要任何條件為 true,系統就會允許存取:

service firebase.storage {
  match b/{bucket}/o {
    // Matches file names directly inside of '/images/'.
    match /images/{imageId} {
      allow read, write: if false;
    }

    // Matches file names anywhere under `/images/`
    match /images/{imageId=**} {
      allow read, write: if true;
    }
  }
}

在上述範例中,系統允許讀取及寫入名稱開頭為 /images/ 的檔案,因為第二條規則一律為 true,即使第一條規則為 false 也是如此。

規則不是篩選器

保護資料安全後,開始執行檔案作業時,請注意安全規則並非篩選器。您無法對符合檔案名稱模式的一組檔案執行作業,並期望 Cloud Storage 只存取目前用戶端有權存取的檔案。

舉例來說,請參考下列安全性規則:

service firebase.storage {
  match /b/{bucket}/o {
    // Allow the client to read files with contentType 'image/png'
    match /aFileNamePrefix/{aFileName} {
      allow read: if resource.contentType == 'image/png';
    }
  }
}

已拒絕:這項規則會拒絕下列要求,因為結果集可能包含 contentType 不是 image/png 的檔案:

網頁
filesRef = storage.ref().child("aFilenamePrefix");

filesRef.listAll()
    .then(function(result) {
      console.log("Success: ", result.items);
    })
});

Cloud Storage Security Rules 中的規則會根據每個查詢的潛在結果進行評估,如果查詢可能會傳回用戶端沒有讀取權限的檔案,就會導致要求失敗。存取要求必須遵守規則設定的限制。

後續步驟

如要深入瞭解Cloud StorageFirebase Security Rules,請參閱下列文章:

  • 瞭解規則語言的下一個主要概念:動態條件。動態條件可讓規則檢查使用者授權、比較現有和傳入的資料、驗證傳入的資料等。

  • 查看常見的安全性用途,以及解決這些用途的Firebase Security Rules定義

您可以探索 Firebase Security Rules 專屬的 Cloud Storage 用途: