Learn Security Rules
Security Rules Language
Security Rules are based on a flexible and powerful custom language, capable of supporting permission controls of varying complexity and granularity. Developers can set specific or general rules according to the specific needs of their applications. Security Rules use a JSON structure, in which:
keyrefers to the operation type (such as read, write, etc.)valueis the condition for allowing operations, which can be:- A simple
booleanvalue (true/false) - An expression string similar to JavaScript
- A simple
An expression can be a single logical expression or multiple expressions combined with AND/OR logic. The system determines whether to allow the operation based on the evaluation result of the expression.
Since Security Rules are a specially designed language, they may require some learning time. This guide will help you understand the basics of the rules language, laying the foundation for writing more complex rules later.
Basic Structure and Syntax
- Database
- Cloud Storage
- Cloud Function
Security Rules are based on a JSON structure, where value can be a boolean or a JavaScript-like expression:
{
"read": true,
"write": <<condition>>,
"create": true,
"update": false,
"delete": <<condition>>
}
Which contains several key concepts
- Operation Type: The JSON
keyrepresents the operation type supporting permission control.create,delete,read, andupdatecorrespond to the create, delete, read, and update operations on a collection.writeis a simplified configuration for controlling write permissions on a collection. Ifcreate,delete, andupdateoperations are not configured, the system will follow thewriteconfiguration. - Rule: The JSON
valueserves as the rule condition, which can be abooleanvalue or a logical expression (group). When the condition evaluates to true, it indicates that the operation is permitted.
By default, encountering an undefined operation type results in denial of access to that operation.
Security Rules are based on a JSON structure, where value can be a boolean or a JavaScript-like expression:
{
"read": true,
"write": <<condition>>,
}
Which contains several key concepts
- Operation Type: The JSON
keyrepresents the operation type supporting permission control.readandwritecorrespond to the read and write operations on Cloud Storage files. - Condition: The JSON
valueserves as the rule condition, which can be abooleanvalue or a logical expression (group). When the condition evaluates to true, it indicates that the operation is permitted.
By default, encountering an undefined operation type results in denial of access to that operation.
Cloud Function Security Rules are based on a JSON structure with a unique hierarchy. The top-level key represents the function name, and its value corresponds to the permission configuration for that function, also in JSON format. The sub-configuration key is the operation name (invoke), and the value can be a boolean or a JavaScript-like expression:
{
"*": {
"invoke": "auth!==null"
},
"function1": {
"invoke": false
},
"function3": {
"invoke": true
}
}
Which contains several key concepts
- Function name: The top-level JSON
keyrepresents the function name, used to match and obtain the configuration for a specific function. The special character*is allowed as a wildcard for function names. When no specific function is matched, the configuration for*will be applied. Cloud Function Security Rules must include the*configuration. - Operation Type: The
keyin the sub-configuration JSON under the function name represents the operation type. Currently, onlyinvokeis supported and must be used. - Condition: The sub-configuration JSON
valueserves as the rule condition, which can be abooleanvalue or a logical expression (group). When the condition evaluates to true, it indicates that the operation is permitted. The expression only supportsauth!=null.
Condition Construction
Conditions can be either boolean values or expression strings. The expression string syntax resembles Javascript, which may be a single logical expression or multiple logical expressions combined using AND/OR operators. The evaluation result of the expression determines whether the operation is permitted.
- Database
- Cloud Storage
- Cloud Function
Predefined Variables
| Variable | Type | Description |
|---|---|---|
| now | number | Current timestamp, indicating the number of milliseconds since the Linux epoch |
| auth | Auth | User login information, containing uid (unique user ID) and loginType (login type); becomes null when not logged in |
| doc | Object | The record object for the current operation. When referenced, it will be read once from the service, and this query will be counted against relevant resource quotas. |
| request | Request | The request object, containing various request-related information |
Auth
| Field Name | Type | Description |
|---|---|---|
| loginType | string | login method, such as public platform login, open platform login, custom login, anonymous login, etc. |
| uid | string | User unique identifier ID. Note: This value is not included in WeChat Mini Program requests. |
| openid | string | User's WeChat openid, only exists in WeChat-related login methods |
LoginType Enum Values
| Enum Value | Sign-in Method |
|---|---|
| WECHAT_PUBLIC | WeChat Official Account |
| WECHAT_OPEN | WeChat Open Platform |
| doc | Object |
| Email Login | |
| CUSTOM | Custom Login |
Request
| Field Name | Type | Description |
|---|---|---|
| data | object | Data object passed in the request, present only for create and update operation types. |
Variables can be used in rule expressions. Through doc and request.data, the current value of the data and the value passed in the request can be obtained. For example, in an order collection, to prevent order amounts from being tampered with, the following rule can be used:
{
// ... other rules ... //
"update": "doc.price == request.data.price || request.data.price == undefined"
// ... other rules ... //
}
This rule ensures that either the request does not modify the price field, or the modified price remains the same as the original price.
Built-in Methods
Currently, only the get function is supported. This function accepts one parameter, and the format must be database.collection_name.document_id. Through this function, you can access data from other documents to determine whether the current operation complies with security rules.
For example, check whether the user has permission to modify specific documents:
{
"update": "get(`database.users.${auth.uid}`).role == 'admin'"
}
Predefined Variables
| Variable | Type | Description |
|---|---|---|
| now | number | Current timestamp, indicating the number of milliseconds since the Linux epoch |
| auth | Auth | User login information, containing uid (unique user ID) and loginType (login type); becomes null when not logged in |
| resource | Resource | Metadata of the request file, read once from the service when referenced |
Auth
| Field Name | Type | Description |
|---|---|---|
| loginType | string | login method, such as public platform login, open platform login, custom login, anonymous login, etc. |
| uid | string | User unique id. This value is not present in WeChat Mini Program requests. |
| openid | string | User openid, present only in WeChat login method |
LoginType Enum
| Enum Value | Sign-in Method Description |
|---|---|
| WECHAT_PUBLIC | WeChat Official Account |
| WECHAT_OPEN | WeChat Open Platform |
| doc | Object |
| Email Login | |
| CUSTOM | Custom Login |
Resource
| Field Name | Type | Description |
|---|---|---|
| openid | string | Private ownership identifier of the file, used to identify the file owner's ID |
| path | string | The relative path of the file in cloud storage (excluding bucket name), in the format path/image.jpg. Note: The path must not start with path indicators such as ./, /, or . |
Variables can be used in rule expressions. For example: set files in the public directory to be readable by all users, but restrict users to only modify files that belong to them.
{
"read": "/^public\\//.test(resource.path) == true",
"write": "resource.openid == auth.uid"
}
This rule ensures:
- All files in paths starting with "public/" are readable by all users.
- Users can only modify files they created (the file owner ID matches the user ID).
Special Methods
Cloud Storage Security Rules support special regular expression syntax. You can introduce regular expression objects via literal notation (e.g., /^reg\$/) and use the test method of the regular expression object to verify whether parameters match the regular expression.
When using the
testmethod in rule expressions, it must be explicitly compared withtrueorfalse. For example:- Correct usage:
read: "/^public/.test(resource.path) == true" - Incorrect usage:
read: "/^public/.test(resource.path)"
- Correct usage:
Since security rule expressions are stored in strings, special characters in regular expressions require multiple escaping:
- For example, to match the string
test/image:- The regular expression object itself is:
/^test\/image/ - In rule expressions, it should be written as:
"/^test\\/image/.test(resource.path)"
- The regular expression object itself is:
- For example, to match the string
Escaping rules: When representing regular expressions in JSON strings, the backslash
\must be written as\\
Predefined Variables
| Variable | Type | Description |
|---|---|---|
| auth | - | In Cloud Function Security Rules, auth has only two states: null and non-null. Accessing member properties of auth is not supported. |
Operators
| Operator | Description | Example | Meaning Description |
|---|---|---|---|
| == | Equal to | auth.uid == 'zzz' | User's uid equals 'zzz' |
| != | Not equal to | auth.uid != 'zzz' | User's uid is not equal to 'zzz' |
| > | Greater than | a>10 | The value of variable a is greater than 10 |
| >= | Greater than or equal to | a>=10 | The value of variable a is greater than or equal to 10 |
| < | Less than | a<10 | The value of variable a is less than 10 |
| <= | Less than or equal to | a<=10 | The value of variable a is less than or equal to 10 |
| in | In set | auth.uid in ['zzz','aaa'] | User's uid is one of the values in ['zzz','aaa'] |
| !(xx in []) | Not in set | !(auth.uid in ['zzz','aaa']) | User's uid is not in the set ['zzz','aaa'] |
| && | Logical AND | auth.uid == 'zzz' && a>10 | User's uid equals 'zzz' and the value of a is greater than 10 |
| || | Logical OR | auth.uid == 'zzz' || a>10 | User's uid is 'zzz' or the value of a is greater than 10 |
| . | Object property accessor | auth.uid | Access the uid property of the auth object |
| [] | Object property or array element access | a[auth.uid] == 'zzz' | The value of the property in object a with the key being the user's uid equals 'zzz'. |