Skip to main content

Data Access Control Management

CloudBase provides a multi-level data access control management mechanism, ensuring data security while meeting the access control requirements of different business scenarios.

Access Control Management System

CloudBase data access control management comprises two levels:

Permission TypeGranularityApplicable ScenariosConfiguration Complexity
Basic Access ControlCollection LevelSimple Permission RequirementsLow
Security Rule PermissionsDocument LevelComplex Business LogicHigh

Basic Access Control

Configuration Method

On the collection management page of the Tencent Cloud Development Platform, set corresponding permissions for each collection:

Permission Options

Basic Access Control provides four predefined permission types for selection based on user identity and data characteristics:

Permission TypeApplicable ScenariosUsage Recommendations
Read all data, modify own dataPublic content, such as articles, productsSuitable for content display applications
Read and modify own dataPrivate data, such as user profilesSuitable for personal information management
Read all data, cannot modify dataConfiguration data, such as system settingsSuitable for read-only configurations and reference data
No accessSensitive data, such as financial informationSuitable for sensitive data requiring server-side processing

Security Rule Permissions

Feature Overview

Security rule permissions provide more flexible, scalable, and fine-grained access control capabilities, supporting dynamic permission judgments based on document content.

Core Features:

  • Document-level Control: Access permissions can be determined based on the specific content of the document.
  • Expression-driven: Define permission logic using programming language-like expressions.
  • Dynamic Permissions: Support dynamic permission determination based on user identity, time, and data content.
  • Client-side Only: Only restricts client-side user access without affecting server-side (Cloud Functions) operations.

Configuration Entry

On the Collection Management page of Cloud Development Platform/Database, configure more granular security rules through Security Rule Permissions settings:

Security Rules Configuration

Rule Configuration Format

Security Rules are configured using JSON format, with the basic structure as follows:

{
"read": "expression",
"write": "expression",
"create": "expression",
"update": "expression",
"delete": "expression"
}

Operation Types Description

Operation TypeDescriptionDefault ValueExample Scenario
readRead documentsfalseQuery and obtain documents
writeWrite documents (generic)falseDefault rule when no specific write operation is specified
createCreate documentsInherit writeAdd new data
updateUpdate documentsInherit writeModify existing data
deleteDelete documentsInherit writeDelete data

💡 Note: If no specific write operation rules (create/update/delete) are specified, the write rule will be applied automatically.

Expression Syntax

Global Variables

Security rule expressions can use the following global variables:

Variable NameTypeDescriptionExample
authObjectUser login informationauth.openid, auth.uid
docObjectDocument data or query conditionsdoc.userId, doc.status
requestObjectRequest informationrequest.data
nowNumberCurrent timestampnow > doc.expireTime

User Identity Information (auth)

FieldTypeDescriptionApplicable Scenarios
openidStringWeChat user OpenIDWeChat Mini Program login
uidStringUser Unique IDWeb login
loginTypeStringLogin methodDistinguishes different login channels

Operator Support

Security rule expressions support the following operators:

OperatorDescriptionExampleUse Cases
==Equal toauth.uid == doc.userIdVerify data owner
!=Not equal todoc.status != 'deleted'Exclude specific status
>, >=, <, <=comparison operationsdoc.age >= 18range validation
inInauth.uid in doc.editorsCheck if a user is in a list
&&Logical ANDauth.uid == doc.userId && doc.publishedMultiple condition combination
||Logical ORauth.uid == doc.userId \|\| doc.publicMultiple access methods

Practical Application Example

1. Basic Permission Mapping

Readable by all users, writable only by the creator:

{
"read": true,
"write": "doc._openid == auth.openid"
}

Readable and writable only by the creator:

{
"read": "doc._openid == auth.openid",
"write": "doc._openid == auth.openid"
}

2. Complex Business Logic

Article Publishing System:

{
"read": "doc.published == true || doc.author == auth.uid",
"create": true,
"update": "doc.author == auth.uid",
"delete": "doc.author == auth.uid && doc.published == false"
}

Collaborative Document System:

{
"read": "auth.uid in doc.readers || auth.uid in doc.editors || doc.owner == auth.uid",
"write": "auth.uid in doc.editors || doc.owner == auth.uid"
}

3. Time Control

Time-limited Activity Data:

{
"read": "now >= doc.startTime && now <= doc.endTime",
"write": "doc.owner == auth.uid && now <= doc.endTime"
}

get Function: Cross-Document Permission Verification

Feature Description

The get() function allows accessing data from other documents during permission verification to implement complex cross-document permission control.

Syntax: get('database.collection_name.document_id')

Usage Example

Role-Based Access Control:

{
"read": "get('database.user_roles.' + auth.uid).role in ['admin', 'editor']",
"write": "get('database.user_roles.' + auth.uid).role == 'admin'"
}

Related Data Permissions:

{
"read": "auth.uid == get('database.projects.' + doc.projectId).owner"
}

Usage Restrictions

⚠️ Note: When using the get() function, be aware of the following limitations:

  • A single expression supports up to 3 get functions.
  • Up to 10 different documents can be accessed.
  • Up to 2 levels of nesting
  • Additional database read operations are generated (billed).

Query Limitations and Optimization

Requirements for Query Conditions

Security rules require that query conditions must be a subset of the rule:

// Security Rules
{
"read": "doc.age > 10"
}

// ✅ Complies with rules (Query conditions are a subset of the rule)
db.collection('users').where({
age: _.gt(15)
}).get()

// ❌ Non-compliant with rules (Query condition scope is broader)
db.collection('users').where({
age: _.gt(5)
}).get()

Document ID Query Optimization

The traditional doc().get() query needs to be rewritten as a where() query:

// ❌ Traditional approach (Non-compliant with security rules)
db.collection('posts').doc('postId').get();

// ✅ After rewriting (Compliant with security rules)
db.collection('posts')
.where({
_id: 'postId',
_openid: _openid: '{openid}', // Using template variables
})
.get();

Best Practices

1. Rule Design Principles

  • Principle of Least Privilege: Grant only necessary permissions
  • Principle of Clarity: Rule expressions should be clear and easy to understand
  • Performance Considerations: Avoid excessive get() function calls

2. Common Patterns

Data Owner Pattern:

{
"read": "doc._openid == auth.openid",
"write": "doc._openid == auth.openid"
}

Public Read, Restricted Write:

{
"read": true,
"write": "doc.author == auth.uid"
}

State-Based Permission:

{
"read": "doc.status == 'published' || doc.author == auth.uid",
"update": "doc.author == auth.uid && doc.status != 'locked'"
}

3. Debugging Tips

  • Start with simple rules and gradually increase complexity
  • Test various scenarios thoroughly in the development environment
  • Check the permission error messages in the console
  • Properly use logging to record the permission verification process

Permission Selection Guide

Choose Based on Business Complexity

Business ScenarioRecommended SolutionReason
Simple ApplicationBasic Access ControlSimple configuration, meets basic requirements
Complex Business LogicSecurity Rule PermissionsFlexible expressions that support complex judgments
Enterprise ApplicationRole-Based Permissions + Basic PermissionsOrganizational structure support, clear permission hierarchy
High Security RequirementsSecurity Rules + Role-Based PermissionsMulti-layer protection, fine-grained control

Permission Configuration Best Practices

  1. Start simple: Begin with basic permissions and upgrade gradually as needed.
  2. Layered design: Basic permissions handle common logic, security rules handle specific logic.
  3. Test and verify: Thoroughly test various permission scenarios in the development environment
  4. Documentation: Document the permission design rationale and configuration instructions in detail

Through reasonable permission configuration, you can build a secure yet flexible data access control system that meets various complex business requirements.