tencent cloud

CloudBase

Product Introduction
Product Overview
Features and Strengths
Use Cases
System Limits
Purchase Guide
Product Pricing
Description Of Billing Capability Items
Yearly/Monthly Subscription Package Description
Alarm and Notification
Overdue Payment Instructions
Development Guide
Cloud Storage
Database
Identity Verification
Cloud function
Static website management
SDK Documentation
Client SDK
Server SDKs
Management-side SDK
Product Agreement
Cloud Development Service Level Agreement

Security Rules

PDF
Modo Foco
Tamanho da Fonte
Última atualização: 2025-12-31 11:48:17
To protect users' data security, CloudBase offers more flexible, scalable, and fine-grained security rule capabilities. Developers can customize security rules in the cloud backend or Mini Program development tools to restrict database access permissions on the consumer side.
Similar to previous database permission settings, security rules provide document-level access control for databases. Currently, access control for document attributes is not supported.
Security rules only restrict access requests on the consumer side and do not impose any restrictions on requests from developers (such as access requests via cloud functions).

Configurations

Each collection can be individually configured with security rules. Use json to describe security rules. Here is a configuration example:
{
"read": "auth.uid==doc.uid",
"write": "doc.name=='zzz'"
}
The key of the json configuration indicates the user's operation type, while the value is an expression. When the result of executing the expression is true, the user's operation is allowed; otherwise, the operation is not allowed.
Operation Type
Description
Default Value
read
Read a document
false
write
Write a document, subdivided into create, update, and delete.
false
create
Create a document
N/A
update
Update a document.
N/A
delete
Delete a document.
N/A

Description

If the developer does not specify the rule for the write operation type, the write rule is read by default. For example, the developer's security rule configuration is as follows:
{
"read": ".....",
"write": "....",
"create": "...."
}
The user's operation to create a document will read the corresponding rule under create, while an update operation will read the rule under write.

Expressions

An expression is a pseudocode statement. It cannot be too long when configured. A single expression is limited to 1,024 characters.

Variables

Global Variables

Variable Name
Type
Description
request
The root object mounted by the request
auth
User login information. For attribute descriptions, see the following section.
now
number
Current time.
doc
any
Document data or query conditions

Request

Field Name
Type
Description
data
object
Request data exists during create and update operations, representing a request for data.

Auth

Field Name
Type
Description
loginType
string
Login method. Requests from WeChat Mini Programs do not have this value. It is only available for web logins.
uid
string
User unique ID. Requests from WeChat Mini Programs do not have this value.
openid
string
User openid. This value only exists in WeChat login mode.

LoginType Enum

Enumeration Value
Login Method Description
WECHAT_PUBLIC
WeChat official account
WECHAT_OPEN
Weixin Open Platform
ANONYMOUS
Anonymous Login
EMAIL
Email Login
CUSTOM
Custom Login

Operators

Operators
Description
Example
Example Explanation (Collection Query)
==
Equal to
auth.uid == 'zzz'
The user's uid is zzz.
!=
Not equal to
auth.uid != 'zzz'
The user's uid is not zzz.
>
Greater than
doc.age>10
The age attribute of the query condition is greater than 10.
>=
Greater than or equal to
doc.age>=10
The age attribute of the query condition is greater than or equal to 10.
<
Less than
doc.age>10
The age attribute of the query condition is less than 10.
<=
Less than or equal to
doc.age>=10
The age attribute of the query condition is less than or equal to 10.
in
Exists in the collection
auth.uid in ['zzz','aaa']
The user's uid is one of ['zzz','aaa'].
!(xx in [])
Not exists in collection, described using in method !(a in [1,2,3])
!(auth.uid in ['zzz','aaa'])
The user's uid is not any of ['zzz','aaa'].
&&
And
auth.uid == 'zzz' && doc.age>10
The user's uid is zzz, and the age attribute of the query condition is greater than 10.
||
Or
auth.uid == 'zzz' || doc.age>10
The user's uid is zzz, or the age attribute of the query condition is greater than 10.
.
Object element accessor
auth.uid
User's uid.
[]
Array accessor attribute
get('database.collection_a.user')[auth.uid] == 'zzz'
In collection_a, document with id as user, where the attribute value whose key is user uid is zzz.

Functions

Currently, only the get function is supported. The unique parameter should be database.collection name.document id. Determine whether user operations conform to security rules by accessing data from other documents.

get

get(path: string): Document | null | undefined
Get the specified doc content based on parameters. If undefined or null is returned, the document does not exist. Otherwise, it is a Document object, representing the queried data.
Input Parameter
Type
Description
path
string
Non-empty, a string formatted as database.collection name.document id. Its value can be obtained through multiple calculation methods, such as using a string template for concatenation: (database.${doc.collction}.${doc._id}).

Example

1. User permissions are written in a separate document, with a numeric value indicating the user's permission scope.
{
"read": "get('database.test.123')[auth.uid] in [1,2,3]",
"delete": "get('xxxx')[auth.uid] == 1 && doc.user in ['ersed','sfsdf'] "
}
2. Collection A contains the association between shopId and orderId. Collection B contains the association between the owner and shopId. If you want to query collection A and limit the query to only orders from shops the current user has permission to access:
{
"read:": "auth.openid in get(`database.B.${doc.shopId}`).owner"
}

Limitations

1. The variable doc in the get parameter should appear in the query condition as == or in the method. If the in method is used, only allow in a unique value, that is, doc.shopId in array, array.length == 1.
2. An expression can have up to 3 get functions and can access up to 10 different documents.
3. The nesting depth of a get function cannot exceed 2, that is, get(get(path)).

Description

Without using variables, each get produces one read operation. When using variables, each get and each variable value produces one read operation. For example: If the rule is get(database.collection.${doc._id}).test and the query is _.or([{_id:1},{_id:2},{_id:3},{_id:4},{_id:5}])}, 5 reads will be produced. The system will cache reads for the same doc and the same field.

Queries

Valid Queries

In actual usage, queries are mainly divided into two kinds: queries by specifying document ID and collection queries.
A query by document ID specifies a single document ID via the doc condition.
A collection query is a query with where conditions or a query restricted by aggregated search match. If there is an aggregated search, only the first match restriction is matched.
In query conditions, if key is _openid and value is {openid}, or key is uid and value is {uid}, the server will automatically replace the value with the actual one.

Collection Queries

For collection queries, query conditions should be a subset of the security rules. In such cases, doc refers to query conditions. This subset means all possible subsets of the rules, rather than subsets of actual data.
The operation types include read, update, and delete.

Example

// Security rule configuration for colleciton_a.
{
"read":"doc.age>10"
}

// Complies with security rules.
let queryRes = db.collection('colleciton_a').where({
age:_.gt(10)
}).get()

// Not complies with security rules.
let queryRes = db.collection('colleciton_a').where({
age:_.gt(8)
}).get

// Complies with security rules.
let res = await db.collection('collection_a').aggregate().match({
age: _.gt(10)
}).project({
age: 1
}).end()

// Not complies with security rules.
let res = await db.collection('collection_a').aggregate().match({
age: _.gt(8)
}).project({
age: 1
}).end()


Queries by Specifying Document ID (Migration Modification Required)

The operation types include read, update, delete, and create.
If the operation type is create, the system will verify whether the data written conforms to the security rule restrictions.
If the operation type is read, update, or delete, and the security rule contains doc restrictions, the system will first read the document data from the db once, then determine whether it complies with the security rule.
For update operations, the system only verifies the existing document data in the database and does not validate written data. It does not guarantee the atomicity of this operation.
Since security rules require the query condition to be a subset of the security rules (all restrictions on doc should appear in the query condition, and the query condition's limit range should be a subset of the rule's restrictions; for example, query a>20 is a subset of rule a>10) and the implicit default behaviors of legacy permission configurations are removed, developers should note the following upgrade/compatibility considerations when enabling security rules.
Since doc operations (such as doc.get and doc.set) are performed only by specifying _id and their query conditions only include {_id:"xxx"}, therefore, in most cases, they do not meet the subset requirement of security rules (unless performing a read operation under "read": true or a write operation under "write": true). Hence, they need to be converted into equivalent forms where the query conditions include the security rules or their subsets.

Example

// Security rule configuration for colleciton_a.
{
"read":"doc._openid == auth.openid"
}

// Data for document id='ccc' is
{
age:12
}

// The security rule is not met, and subset requirements are not satisfied.
let queryRes = db.collection('colleciton_a').doc('ccc').get()

// The security rule is met and rewritten as where query.
let queryRes = db.collection('colleciton_a').where({_id: "ccc", _openid: "{openid}"}).get()

Note:
Under basic permission control, the query condition can omit _openid, while security rule permissions require explicitly passing openid to ensure the query condition complies with security rules. Therefore, openid needs to be passed for all query conditions. You can use the template "{openid}" or "{uid}" to represent the currently logged in user's openid or uid.

Supported Databases Commands

logic command

command
description
or
|| Logical OR
and
&& Logical AND

query command

command
description
eq
==
ne/neq
!=
gt
>
gte
>=
lt
<
lte
<=
in
in
nin
!(in [])

update command

command
description
set
Overwrite, {key: set(object)}
remove
Delete field, {key: remove()}

Billing

Security rules themselves are not charged, but additional data access from security rules will be counted in billing.
The get function will produce additional data access.
All write operations for queries by specifying document id will produce one data access.

Permission Settings Comparison

Readable for All Users and Writable for the Creator and Administrator Only

{
"read": true,
"write": "doc._openid == auth.openid" // Login method is WeChat.
"write": "doc._openid == auth.uid" // Login method is not WeChat.
}

Read-Write for the Creator and Administrator Only

{
"read": "doc._openid == auth.openid" //Login method is WeChat.
"read": "doc._openid == auth.uid" // Login method is not WeChat.
"write": "doc._openid == auth.openid" //Login method is WeChat.
"write": "doc._openid == auth.uid" // Login method is not WeChat.
}

Readable for All Users and Writable for the Administrator Only

{
"read": true,
"write": false
}

Read-Write for the Administrator Only

{
"read": false,
"write": false
}

Implementing Role-Based Access Control

You can use CloudBase's data model and custom security rules to implement role-based access control in your application.
Assuming you are building a collaborative writing application, where users can write "stories" and "comments" according to the following security requirements:
Each story has an owner and can be shared with the writer.
The writer has all access permissions that a commenter has and can edit the story content as well.
The owner can edit any part of the story and control other users' access permission.
Regular users can only view stories and comments, and write their own comments. They cannot edit stories.

Data Struct

Assuming your application has a collection of stories where each document represents a story, a collection of comments where each document represents a comment on that story, and a collection of roles where each document contains a user's role for a story. To keep track of access roles, you need to add a roles field to map user IDs to roles:

A Collection of Stories

Each story document data is as follows:
{
"id": `storyid`,
"title": "A Great Story",
"content": "Once upon a time ..."
}

A Collection of Roles

Each role document data is as follows:
{
"id": `storyid`,
"roles": {
"alice": "owner",
"bob": "writer",
"david": "writer"
// ...
}
}

A Collection of Comments

Each comment document data is as follows. The comment contains only three fields: the commenter's user ID, content, and storyid.
{
"id": `commentId`,
"storyid": `storyid`,
"user": "alice",
"content": "I think this is a great story!"
}

Rules

Since the user role is recorded in the database, security rules should be written for role verification. The following rules assume the application uses TCB Authentication, so the auth.uid variable is the user ID.

Roles Adding Rules

The administrator can change roles and allow story writers to read roles.
{
"write": "doc.roles[auth.uid] === 'owner' ",
"read": "doc.roles[auth.uid] in ['owner', 'writer']"
}

Stories Adding Rules

The administrator and story writers can modify stories, while others can read stories.
{
"read": true,
"write": "get(`database.roles.${doc.id}`).roles[auth.uid] in ['owner', 'writer'] "
}

Comments Rules

All are allowed to post comments.
Only the comment owner can update and delete comments.
{
"read": true,
"create": true,
"update": "doc.user == auth.uid",
"delete": "doc.user == auth.uid "
}


Ajuda e Suporte

Esta página foi útil?

comentários