Cloud Storage の Firebase セキュリティ ルールは、Cloud Storage に保存されているファイルへの読み取りおよび書き込みアクセス権を持つユーザー、およびファイルの構造とファイルに含まれるメタデータを決定するために使用されます。 Cloud Storage セキュリティ ルールは、ファイルのアップロードやファイル メタデータの取得など、目的のアクションを許可または拒否するrequest
とresource
を考慮するルールで構成されます。これらのリファレンス ドキュメントでは、ルールの種類、 request
とresource
のプロパティ、Cloud Storage セキュリティ ルールで使用されるデータ型、エラーの発生方法について説明します。
ルール
rule
、 request
目的のアクションを実行できるかどうかを判断するために評価される式です。
種類
許可する
allow
ルールは、 read
やwrite
などのメソッドとオプションの条件で構成されます。ルールが実行されると条件が評価され、条件がtrue
と評価された場合は、目的のメソッドが許可されます。それ以外の場合、メソッドは拒否されます。条件のないallow
ルールでは、常に目的のメソッドが許可されます。
// Always allow method allow <method>; // Allow method if condition is true allow <method>: if <condition>;
現在サポートされているルールの種類は、 allow
のみです。
リクエストメソッド
読む
read
メソッドは、ファイルのダウンロードやファイル メタデータの読み取りなど、ファイル データまたはメタデータが読み取られるすべてのリクエストをカバーします。
// Always allow reads allow read; // Allow reads if condition evaluates to true allow read: if <condition>;
書く
write
メソッドは、ファイルのアップロード、ファイルの削除、ファイルのメタデータの更新など、ファイル データまたはメタデータが書き込まれるすべてのリクエストをカバーします。
// Always allow writes allow write; // Allow writes if condition evaluates to true allow write: if <condition>;
マッチ
ルールは、ユーザーrequest
(ファイルのアップロードまたはダウンロードなど) がルールの対象となるファイル パスと一致する場合に実行されます。 match
パスと本文で構成され、少なくとも 1 つのallow
ルールが含まれている必要があります。一致するパスがない場合、リクエストは拒否されます。
完全な名前のパスmatch
も、ワイルドカードを挿入して特定のパターンに一致するすべてのパスを照合することもできます。
パスセグメント
single_segment
単一パス セグメントを使用して、Cloud Storage に保存されているファイルと一致するルールを作成できます。
// Allow read at "path" if condition evaluates to true match /path { allow read: if <condition>; }
複数のパス セグメントとネストされたパスも許可されます。
// Allow read at "path/to/object" if condition evaluates to true match /path { match /to { match /object { allow read: if <condition>; } } }
{single_segment_wildcard}
同じパスにある複数のファイルにルールを適用する場合は、ワイルドカード パス セグメントを使用して、特定のパスにあるすべてのファイルと一致させることができます。ワイルドカード変数は、変数を中括弧で囲むことによってパス内で宣言されます: {variable}
。この変数は、match ステートメント内でstring
としてアクセスできます。
// Allow read at any path "/*", if condition evaluates to true match /{single_path} { // Matches "path", "to", or "object" but not "path/to/object" allow read: if <condition>; }
複数のパス セグメントとネストされたパスにもワイルドカードを含めることができます。
// Allow read at any path "/path/*/newPath/*", if condition evaluates to true match /path/{first_wildcard} { match /newPath/{second_wildcard} { // Matches "path/to/newPath/newObject" or "path/from/newPath/oldObject" allow read: if <condition>; } }
{multi_segment_wildcard=**}
パス上またはその下の任意の数のパス セグメントを照合する場合は、マルチ セグメント ワイルドカードを使用できます。これにより、その場所以下のすべてのリクエストが照合されます。これは、ユーザーに独自の自由形式の記憶域を提供したり、さまざまなパス セグメントに一致するルールを作成したりする場合に役立ちます (公開で読み取り可能なファイル セットの作成や、すべての書き込みに認証を要求するなど)。
マルチセグメント ワイルドカード パスは、単一セグメント ワイルドカードと同様に、変数の末尾に=**
を追加して宣言されます: {variable=**}
。マルチセグメントのワイルドカード変数は、match ステートメント内でpath
オブジェクトとして使用できます。
// Allow read at any path "/**", if condition evaluates to true match /{multi_path=**} { // Matches anything at or below this, from "path", "path/to", "path/to/object", ... allow read: if <condition>; }
リクエスト
request
変数は、そのパスで行われるリクエストを表す条件内で提供されます。 request
変数には、受信リクエストを許可するかどうかを決定するために使用できる多数のプロパティがあります。
プロパティ
auth
認証されたユーザーが Cloud Storage に対してリクエストを実行すると、 auth
変数にはユーザーのuid
( request.auth.uid
) と Firebase Authentication JWT のクレーム ( request.auth.token
) が設定されます。
request.auth.token
は、次のキーの一部またはすべてが含まれています。
分野 | 説明 |
---|---|
email | アカウントに関連付けられている電子メール アドレス (存在する場合)。 |
email_verified | ユーザーがemail アドレスにアクセスできることを確認した場合はtrue 。一部のプロバイダーは、所有する電子メール アドレスを自動的に確認します。 |
phone_number | アカウントに関連付けられている電話番号 (存在する場合)。 |
name | ユーザーの表示名 (設定されている場合)。 |
sub | ユーザーの Firebase UID。これはプロジェクト内で一意です。 |
firebase.identities | このユーザーのアカウントに関連付けられているすべての ID の辞書。辞書のキーは、 email 、 phone 、 google.com 、 facebook.com 、 github.com 、 twitter.com のいずれかになります。ディクショナリの値は、アカウントに関連付けられた各 ID プロバイダーの一意の識別子の配列です。たとえば、 auth.token.firebase.identities["google.com"][0] アカウントに関連付けられた最初の Google ユーザー ID が含まれています。 |
firebase.sign_in_provider | このトークンを取得するために使用されるサインイン プロバイダー。次の文字列のいずれかを指定できます: custom 、 password 、 phone 、 anonymous 、 google.com 、 facebook.com 、 github.com 、 twitter.com 。 |
firebase.tenant | アカウントに関連付けられた tenantId (存在する場合)。例: tenant2-m6tyz |
カスタム認証を使用する場合、 request.auth.token
には開発者が指定したカスタム クレームも含まれます。
認証されていないユーザーがリクエストを実行すると、 request.auth
null
になります。
// Allow requests from authenticated users allow read, write: if request.auth != null;
path
path
変数には、 request
が実行されるパスが含まれます。
// Allow a request if the first path segment equals "images" allow read, write: if request.path[0] == 'images';
resource
resource
変数には、アップロードされるファイルのメタデータ、または既存のファイルの更新されたメタデータが含まれます。これは、新しいメタデータではなく、要求されたパスにある現在のファイル メタデータを含むresource
変数に関連しています。
// Allow a request if the new value is smaller than 5MB allow read, write: if request.resource.size < 5 * 1024 * 1024;
request.resource
には、 resource
からの次のプロパティが含まれます。
財産 |
---|
name |
bucket |
metadata |
size |
contentType |
time
time
変数には、リクエストが評価されている現在のサーバー時間を表すタイムスタンプが含まれます。これを使用すると、特定の日付までファイルのアップロードのみを許可したり、アップロード後 1 時間以内のファイルの読み取りのみを許可したりするなど、ファイルへの時間ベースのアクセスを提供できます。
// Allow a read if the file was created less than one hour ago allow read: if request.time < resource.timeCreated + duration.value(1, 'h');
タイムスタンプと期間を使用してルールを作成するための多くの関数が提供されています。
リソース
resource
変数には、ファイル名、サイズ、作成時間、カスタム メタデータなど、Cloud Storage 内のファイルのファイル メタデータが含まれています。
プロパティ
name
ファイルへのパスを含む、ファイルの完全名を含む文字列。
// Allow reads if the resource name is "path/to/object" allow read: if resource.name == 'path/to/object'
bucket
このファイルが保存されているGoogle Cloud Storageバケットを含む文字列。
// Allow reads of all resources in your bucket allow read: if resource.bucket == '<your-cloud-storage-bucket>'
generation
ファイルの Google Cloud Storageオブジェクト生成を含む int。オブジェクトのバージョン管理に使用されます。
// Allow reads if the resource matches a known object version allow read: if resource.generation == <known-generation>
metageneration
ファイルの Google Cloud Storageオブジェクトのメタ生成を含む int。オブジェクトのバージョン管理に使用されます。
// Allow reads if the resource matches a known object metadata version allow read: if resource.metageneration == <known-generation>
size
ファイルサイズをバイト単位で含む int 。
// Allow reads if the resource is less than 10 MB allow read: if resource.size < 10 * 1024 * 1024;
timeCreated
ファイルがいつ作成されたかを表すタイムスタンプ。
// Allow reads if the resource was created less than an hour ago allow read: if resource.timeCreated < request.time + duration.value(60, "m")
updated
ファイルが最後に更新された時間を表すタイムスタンプ。
// Allow reads if the resource was updated less than an hour ago allow read: if resource.updated < request.time + duration.value(60, "m")
md5Hash
ファイルのMD5 ハッシュを含む文字列。
// Allow writes if the hash of the uploaded file is the same as the existing file allow write: if request.resource.md5Hash == resource.md5Hash;
crc32c
ファイルのcrc32c ハッシュを含む文字列。
// Allow writes if the hash of the uploaded file is the same as the existing file allow write: if request.resource.crc32c == resource.crc32c;
etag
ファイルのetagを含む文字列。
// Allow writes if the etag matches a known object etag allow write: if resource.etag == <known-generation>
contentDisposition
ファイルのコンテンツの性質を含む文字列。
// Allow reads if the content disposition matches a certain value allow read: if resource.contentDisposition == 'inlined';
contentEncoding
ファイルのコンテンツエンコーディングを含む文字列。
// Allow reads if the content is encoded with gzip allow read: if resource.contentEncoding == 'gzip';
contentLanguage
ファイルのコンテンツ言語を含む文字列。
// Allow reads if the content language is Japanese allow read: if resource.contentLanguage == 'ja';
contentType
ファイルのコンテンツ タイプを含む文字列。
// Allow reads if the content type is PNG. allow read: if resource.contentType == 'image/png';
metadata
開発者が提供する追加のメタデータ フィールドを含むMap<String, String>
。
// Allow reads if a certain metadata field matches a desired value allow read: if resource.metadata.customProperty == 'customValue';
firestore.get と firestore.exists
firestore.get()
関数とfirestore.exists()
関数を使用すると、Cloud Firestore のドキュメントにアクセスして、複雑な承認基準を評価できます。
firestore.get()
とfirestore.exists()
関数はどちらも、完全に指定されたドキュメント パスを必要とします。変数を使用してfirestore.get()
およびfirestore.exists()
のパスを構築する場合は、 $(variable)
構文を使用して変数を明示的にエスケープする必要があります。
firestore.get
Cloud Firestore ドキュメントのコンテンツを取得します。
service firebase.storage { match /b/{bucket}/o { match /users/{club}/files/{fileId} { allow read: if club in firestore.get(/databases/(default)/documents/users/$(request.auth.uid)).data.memberships } } }
firestore.exists
Cloud Firestore ドキュメントが存在するかどうかを確認します。
service firebase.storage { match /b/{bucket}/o { match /users/{userId}/photos/{fileId} { allow read: if firestore.exists(/databases/(default)/documents/users/$(userId)/friends/$(request.auth.uid)) } } }
サービス
service
Cloud Storage セキュリティ ルール ファイルの最初の宣言であり、これらのルールがどのサービスに適用されるかを指定します。
名前
name
適用されるサービスルールの名前。現在の値はfirebase.storage
のみです。
// Specify the service name service firebase.storage { match /b/{bucket}/o { ... } }
データ型
Rules 言語では、 is
演算子を使用して型をチェックできます。
// For example
a is null
a is string
null
null
データ型は、存在しない値を表します。
allow read: if request.auth != null;
bool
bool
型はブール値のtrue
またはfalse
を表します。
allow read: if true; // always succeeds allow write: if false; // always fails
比較
ブール値は==
演算子!=
を使用して比較できます。
ブール演算
手術 | 表現 |
---|---|
AND | x && y |
OR | x || y |
NOT | !x |
操作は短絡しており、 true
、 false
、またはError のいずれかを返す可能性があります。
allow read: if true || false; // always succeeds, short circuits at true allow write: if false && true; // always fails, short circuits at false
int
とfloat
int
とfloat
型は数値を表します。整数は0
、 1
、 -2
など、浮動小数点は1.0
、 -2.0
、 3.33
などです。
int は符号付き 64 ビット値、float は 64 ビット IEEE 754 準拠の値です。 int
型の値は、 float
値を使用した比較や算術演算で使用される場合、 float
型に強制されます。
比較
int と float は、 ==
、 !=
、 >
、 <
、 >=
、および<=
演算子を使用して比較および順序付けできます。
算術
整数と浮動小数点数は、加算、減算、乗算、除算、剰余演算、および否定を行うことができます。
手術 | 表現 |
---|---|
追加 | x + y |
引き算 | x - y |
乗算 | x * y |
分割 | x / y |
モジュロ | x % y |
否定 | -x |
数学関数
Cloud Storage の Firebase セキュリティ ルールには、式を簡素化するための多数の数学ヘルパー関数も提供されています。
関数 | 説明 |
---|---|
math.ceil(x) | 数値の上限 |
math.floor(x) | 数値の下限 |
math.round(x) | 入力値を最も近い int に丸めます |
math.abs(x) | 入力の絶対値 |
math.isInfinite(x) | 値が±∞ であるかどうかをテストし、 bool を返します |
math.isNaN(x) | 値が数値NaN ではないかどうかをテストし、 bool を返します |
string
比較
==
、 !=
、 >
、 <
、 >=
、および<=
演算子を使用して、文字列を辞書編集的に比較および並べ替えることができます。
連結
+
演算子を使用して文字列を連結できます。
// Concatenate a file name and extension 'file' + '.txt'
インデックスと範囲
index
演算子string[]
は、文字列内の指定されたインデックスにある文字を含む文字列を返します。
// Allow reads of files that begin with 'a' match /{fileName} { allow read: if fileName[0] == 'a'; }
range
演算子string[i:j]
、指定されたインデックス ( i
を含む) からj
(これを含まない) までの文字を含む文字列を返します。 i
またはj
が指定されていない場合、デフォルトはそれぞれ 0 と文字列のサイズですが、範囲を有効にするには少なくともi
またはj
を指定する必要があります。
// Allow reads of files that begin with 'abcdef' match /{fileName} { allow read: if fileName[0:6] == 'abcdef'; }
指定されたインデックスが文字列の境界を超える場合、 index
演算子とrange
演算子はエラーを生成します。
size
文字列内の文字数を返します。
// Allow files with names less than 10 characters match /{fileName} { allow write: if fileName.size() < 10; }
matches
正規表現の一致を実行し、文字列が指定された正規表現と一致する場合にtrue
を返します。 Google RE2 構文を使用します。
// Allow writes to files which end in ".txt" match /{fileName} { allow write: if fileName.matches('.*\\.txt') }
split
指定された正規表現に従って文字列を分割し、文字列のlist
を返します。 Google RE2 構文を使用します。
// Allow files named "file.*" to be uploaded match /{fileName} { allow write: if fileName.split('.*\\..*')[0] == 'file' }
path
パスは、オプションのパターン マッチングを備えたディレクトリのような名前です。スラッシュ/
の存在は、パス セグメントの開始を示します。
path
string
引数をpath
に変換します。
// Allow reads on a specific file path match /{allFiles=**} { allow read: if allFiles == path('/path/to/file'); }
timestamp
タイムスタンプは UTC で、使用可能な値は 0001-01-01T00.00.00Z で始まり 9999-12-31T23.59.59Z で終わります。
比較
タイムスタンプは==
、 !=
、 >
、 <
、 >=
、および<=
演算子を使用して比較および順序付けできます。
算術
タイムスタンプは、次のようにタイムスタンプと期間の間の加算と減算をサポートします。
表現 | 結果 |
---|---|
timestamp + duration | timestamp |
duration + timestamp | timestamp |
timestamp - duration | timestamp |
timestamp - timestamp | duration |
duration + duration | duration |
duration - duration | duration |
date
year
、 month
、およびday
のみを含むtimestamp
値。
// Allow reads on the same day that the resource was created. allow read: if request.time.date() == resource.timeCreated.date()
year
1 ~ 9999 の int としての年の値。
// Allow reads on all requests made before 2017 allow read: if request.time.year() < 2017
month
1 ~ 12 の int としての月の値。
// Allow reads on all requests made during the month of January allow read: if request.time.month() == 1;
day
1 から 31 までの int としての現在の日付。
// Allow reads on all requests made during the first day of each month allow read: if request.time.day() == 1;
time
現在の時間を含むduration
値。
// Allow reads on all requests made before 12PM allow read: if request.time.time() < duration.time(12, 0, 0, 0);
hours
時間の値は 0 ~ 23 の int として表されます。
// Allow reads on all requests made before 12PM allow read: if request.time.hours() < 12;
minutes
分の値は 0 ~ 59 の int として表されます。
// Allow reads during even minutes of every hour allow read: if request.time.minutes() % 2 == 0;
seconds
0 ~ 59 の int としての秒の値。
// Allow reads during the second half of each minute allow read: if request.time.seconds() > 29;
nanos
int としてのナノ単位の小数秒。
// Allow reads during the first 0.1 seconds of each second allow read: if request.time.nanos() < 100000000;
dayOfWeek
1 (月曜日) から 7 (日曜日) までの曜日。
// Allow reads on weekdays (Monday to Friday) allow read: if request.time.dayOfWeek() < 6;
dayOfYear
現在の年の日 (1 から 366)。
// Allow reads every fourth day allow read: if request.time.dayOfYear() % 4 == 0;
toMillis
Unix エポックからの現在のミリ秒数を返します。
// Allow reads if the request is made before a specified time allow read: if request.time.toMillis() < <milliseconds>;
duration
期間の値は、秒にナノ秒の小数点以下を加えたものとして表されます。
比較
==
、 !=
、 >
、 <
、 >=
、および<=
演算子を使用して、期間を比較したり並べ替えたりできます。
算術
期間は、次のようにタイムスタンプと期間の間の加算と減算をサポートします。
表現 | 結果 |
---|---|
timestamp + duration | timestamp |
duration + timestamp | timestamp |
timestamp - duration | timestamp |
timestamp - timestamp | duration |
duration + duration | duration |
duration - duration | duration |
seconds
現在の継続時間の秒数。 -315,576,000,000 ~ +315,576,000,000 の範囲内である必要があります。
nanos
現在の継続時間の小数秒数 (ナノ秒単位)。 -999,999,999 ~ +999,999,999 の範囲内である必要があります。非ゼロ秒と非ゼロナノ秒の場合、両方の符号が一致する必要があります。
duration.value
期間は、指定された大きさと単位から期間を作成する、 duration.value(int magnitude, string units)
関数を使用して作成できます。
// All of these durations represent one hour: duration.value(1, "h") duration.value(60, "m") duration.value(3600, "s")
可能なunit
は次のとおりです。
間隔 | unit |
---|---|
週間 | w |
日々 | d |
時間 | h |
分 | m |
秒 | s |
ミリ秒 | ms |
ナノ秒 | ns |
duration.time
期間は、指定された時間、 duration.time(int hours, int minutes, int seconds, int nanoseconds)
関数を使用して作成できます。
// Create a four hour, three minute, two second, one nanosecond duration duration.time(4, 3, 2, 1)
list
リストには、順序付けされた値の配列が含まれます。値の型は、 null
、 bool
、 int
、 float
、 string
、 path
、 list
、 map
、 timestamp
、またはduration
。
list
型のx
とy
、およびint
型のi
とj
が与えられた場合
創造
リストを作成するには、括弧の間に値を追加します。
// Create a list of strings ['apples', 'grapes', 'bananas', 'cheese', 'goats']
比較
リストは==
演算子!=
を使用して比較できます。 2 つのリストが等しいには、すべての値が等しい必要があります。
インデックスと範囲
index
演算子list[]
、リスト内の指定されたインデックスにある項目を返します。
// Allow reads of all files that begin with 'a' match /{fileName} { allow read: if fileName[0] == 'a'; }
range
演算子list[i:j]
、指定されたインデックス ( i
(含む) からj
(含まない) まで) の間にあるリスト内のすべての項目を返します。 i
またはj
が指定されていない場合、デフォルトはそれぞれ 0 とリストのサイズですが、範囲を有効にするには少なくともi
またはj
を指定する必要があります。
// Allow reads of all files that begin with 'abcdef' match /{fileName} { allow read: if fileName[0:6] == 'abcdef'; }
in
目的の値がリストに存在する場合はtrue
を返し、存在しない場合はfalse
を返します。
// Allow read if a filename has the string 'txt' in it match /{fileName} { allow read: if 'txt' in fileName.split('\\.'); }
join
指定された文字列で区切られた文字列のリストを単一の文字列に結合します。
// Allow reads if the joined array is 'file.txt' allow read: if ['file', 'txt'].join('.') == 'file.txt';
size
リスト内の項目の数。
// Allow read if there are three items in our list allow read: if ['foo', 'bar', 'baz'].size() == 3;
hasAll
すべての値がリストに存在する場合はtrue
を返します。
// Allow read if one list has all items in the other list allow read: if ['file', 'txt'].hasAll(['file', 'txt']);
map
マップにはキーと値のペアが含まれます。キーは文字列で、値はnull
、 bool
、 int
、 float
、 string
、 path
、 list
、 map
、 timestamp
、またはduration
のいずれかになります。
創造
マップを作成するには、中かっこの間にキーと値のペアを追加します。
// Create a map of strings to strings { 'mercury': 'mars', 'rain': 'cloud', 'cats': 'dogs', }
比較
==
演算子!=
を使用してマップを比較できます。 2 つのマップが等しい場合は、すべてのキーが両方のマップに存在し、すべての値が等しい必要があります。
索引
マップ内の値には、括弧またはドット表記を使用してアクセスします。
// Access custom metadata properties allow read: if resource.metadata.property == 'property' allow write: if resource.metadata['otherProperty'] == 'otherProperty'
キーが存在しない場合は、 error
が返されます。
in
目的のキーがマップ内に存在する場合はtrue
を返し、存在しない場合はfalse
を返します。
// Allow reads if a property is present in the custom metadata allow read: if property in resource.metadata;
size
マップ内のキーの数。
// Allow reads if there's exactly one custom metadata key allow read: if resource.metadata.size() == 1;
keys
マップ内のすべてのキーのリスト。
// Allow reads if the first metadata key is 'myKey' allow read: if resource.metadata.keys()[0] == 'myKey';
values
マップ内のすべての値のキー順のリスト。
// Allow reads if the first metadata value is 'myValue' allow read: if resource.metadata.values()[0] == 'myValue';
エラー
エラー評価
Cloud Storage の Firebase セキュリティ ルールは、エラーが発生した場合でも評価を続行します。これは、条件付き&&
と||
があるため便利です。条件式がそれぞれfalse
またはtrue
に短絡する場合、式はエラーを吸収する可能性があります。例えば:
表現 | 結果 |
---|---|
error && true | error |
error && false | false |
error || true | true |
error || false | error |
エラーが発生する一般的な場所は、ゼロによる除算、リストまたはマップ内の存在しない値へのアクセス、および不正な型の値を関数に渡すことです。
// Error if resource.size is zero allow read: if 1000000 / resource.size; // Error, key doesn't exist allow read: if resource.metadata.nonExistentKey == 'value'; // Error, no unit 'y' exists allow read: if request.time < resource.timeCreated + duration.value(1, 'y');