I. Why Data Isolation, Privacy Protection, and Permission Management Matter So Much
With the spread of large models, RAG, Agents, and enterprise knowledge bases, AI systems have begun to come into contact with large amounts of sensitive information:
- Internal corporate documents, contracts, and financial data.
- Users' personal information, contact details, and identity records.
- Business databases, orders, transactions, and customer records.
- API Keys, access tokens, and system keys.
- Internal corporate code, design documents, and trade secrets.
Traditional applications usually protect data through database permissions, API authentication, and network boundaries. But AI systems introduce new data access paths:
- A user asks a question in natural language.
- The system retrieves relevant content from the knowledge base.
- The model generates an answer based on the context.
- The Agent may further call databases, file systems, and external APIs.
- Tool execution results may re-enter the model's context.
- The model ultimately outputs the information to the user.
This means that even if traditional API permission controls are correct, data leakage can still occur through retrieval, context assembly, tool calls, or model output.
1.1 Three Core Concepts
| Concept | Core Objective | Problem Solved |
|---|---|---|
| Data isolation | Data between different users, tenants, and businesses is mutually invisible | Prevent cross-tenant and cross-user access |
| Privacy protection | Control the collection, use, storage, and dissemination of personal information and sensitive data | Prevent privacy leaks and misuse |
| Permission management | Clarify who can access what resources and what operations they can perform | Prevent unauthorized access and illegal operations |
These three are not independent security modules, but rather an integrated whole that works together.
For example, in an enterprise knowledge base system:
- Data isolation is responsible for ensuring that Enterprise A cannot read Enterprise B's knowledge base.
- Privacy protection is responsible for preventing employees' ID numbers and customers' phone numbers from being exposed unnecessarily.
- Permission management is responsible for determining whether a given employee has the right to read financial, R&D, or HR materials.
1.2 Core Security Objectives
A reliable AI data security system should meet the following requirements:
Confidentiality
Only authorized subjects can read data.
Integrity
Only authorized subjects can modify data, preventing data from being illegally tampered with.
Availability
Legitimate users can access resources normally when needed.
Traceability
Every important data access, permission change, and tool execution can be recorded and audited.
Least Privilege
Users, models, and Agents can only obtain the minimum permissions necessary to complete the current task.
II. Data Isolation: Security Boundaries from Tenants to Resources
Data isolation is the foundation of multi-user, multi-tenant AI systems.
Suppose a SaaS AI knowledge base platform serves multiple enterprises at the same time:
- Enterprise A uploads R&D documents.
- Enterprise B uploads financial materials.
- Enterprise C uploads customer service records.
If the system performs semantic retrieval only on document content without enforcing tenant permission filtering, then users of Enterprise A may retrieve documents belonging to Enterprise B.
This is a typical case of cross-tenant data leakage.
2.1 What Is Multi-Tenant Data Isolation
Multi-tenancy means that multiple mutually independent customers share the same application infrastructure, while their respective data, configurations, and permissions remain isolated.
Common isolation targets include:
| Isolation Target | Description |
|---|---|
| User isolation | Data between different users cannot be accessed without authorization |
| Tenant isolation | Data between different enterprises or organizations is fully isolated |
| Project isolation | Data isolation between different projects within the same tenant |
| Department isolation | Data access between different organizational departments is restricted |
| Session isolation | Contexts, history, and tool states of different sessions are not mixed |
| Vector isolation | Embeddings and retrieval results of different tenants are subject to access control |
| File isolation | Uploaded files, temporary files, and generated files have independent access boundaries |
2.2 Common Data Isolation Patterns
Pattern 1: Separate Databases
Each tenant uses a separate database.
Tenant A → Database A
Tenant B → Database B
Tenant C → Database C
Advantages:
- Clear isolation boundaries.
- Database-level permission management is easy to implement.
- Facilitates independent backup, recovery, and migration.
- Customers with high security requirements can deploy independently.
Disadvantages:
- The number of databases grows with the number of tenants.
- Higher operational and maintenance costs.
- Database upgrades and schema changes become more complex.
Suitable for scenarios with high data isolation requirements, such as finance, healthcare, government, and large enterprises.
Pattern 2: Shared Database, Separate Schemas
Multiple tenants share a database instance but use different schemas.
Database
├── tenant_a
│ ├── documents
│ └── users
├── tenant_b
│ ├── documents
│ └── users
└── tenant_c
├── documents
└── users
Advantages:
- Compared with separate databases, resource utilization is higher.
- A certain degree of logical isolation can be retained.
- Suitable for systems with a moderate number of tenants.
Disadvantages:
- Management becomes complex when there are many schemas.
- Database connections and migrations require additional handling.
- The application layer still needs to correctly identify the current tenant.
Pattern 3: Shared Database, Shared Data Tables
All tenants share the same table, and data is distinguished by tenant_id.
CREATE TABLE documents (
id BIGINT PRIMARY KEY,
tenant_id VARCHAR(64) NOT NULL,
owner_id VARCHAR(64) NOT NULL,
title VARCHAR(255),
content TEXT,
created_at TIMESTAMP
);
When querying, the tenant condition must be included:
SELECT *
FROM documents
WHERE tenant_id = :tenant_id
AND owner_id = :user_id;
Advantages:
- High resource utilization.
- Unified database structure.
- Suitable for a large number of small and medium-sized tenants.
Disadvantages:
- If a query omits the tenant condition, cross-tenant leakage may occur.
- Stricter database constraints and automated testing are required.
- Data permission logic can easily become scattered across business code.
Engineering recommendation: The shared database pattern must make the tenant identifier a mandatory constraint for data access, rather than relying on developers to remember to add WHERE tenant_id every time.
2.3 Comparison of the Three Isolation Patterns
| Dimension | Separate Database | Separate Schema | Shared Data Tables |
|---|---|---|---|
| Isolation strength | High | Medium-high | Depends on constraint design |
| Resource cost | High | Medium | Low |
| Operational complexity | High | Medium | Relatively low |
| Scalability | Relatively strong | Relatively strong | High |
| Data migration | Handled independently | Handled per Schema | Handled uniformly |
| Applicable scenarios | High-security customers | Medium-to-large SaaS | Large-scale SaaS |
2.4 How Tenant Context Is Passed
The system must not trust the tenant_id actively submitted by the client.
For example, a user can modify the tenant parameter in an HTTP request:
{
"tenant_id": "tenant_b",
"document_id": "doc_1001"
}
If the backend directly uses the tenant identifier passed in by the client, a user may forge an identity to access another company's data.
The correct approach is:
- The user submits identity credentials.
- The server verifies the credentials.
- Obtain the tenant to which the user belongs from trusted identity information.
- Inject the tenant context into the server-side request context.
- The data access layer automatically applies tenant filtering.
- Verify resource access permissions again before returning results.
flowchart TD
A["User Request"] --> B["Identity Authentication"]
B --> C{"Authentication successful?"}
C -->|No| X["Reject Request"]
C -->|Yes| D["Obtain Trusted User Identity"]
D --> E["Resolve User's Tenant"]
E --> F["Create Server-Side Tenant Context"]
F --> G["Execute Data Access"]
G --> H["Apply Tenant Filter"]
H --> I["Resource Permission Check"]
I --> J{"Allow Access?"}
J -->|No| X
J -->|Yes| K["Return Authorized Data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style D fill:#EAF3EC,stroke:#83A995,color:#315D49
style E fill:#EAF3EC,stroke:#83A995,color:#315D49
style F fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style G fill:#EAF3EC,stroke:#83A995,color:#315D49
style H fill:#EAF3EC,stroke:#83A995,color:#315D49
style I fill:#EAF3EC,stroke:#83A995,color:#315D49
style J fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style K fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style X fill:#F7EAE7,stroke:#C98D7C,color:#754438
The server-side tenant context should span the entire call chain, including databases, caches, vector databases, object storage, and Agent tools.
III. Data Isolation in RAG Systems
RAG is one of the scenarios where data isolation is most likely to go wrong.
Because RAG must not only control whether a user can access the database, but also control which knowledge chunks can enter the model context.
3.1 Why RAG Is Prone to Data Leakage
A typical RAG system includes:
- Document upload.
- Document parsing.
- Text chunking.
- Embedding vectorization.
- Vector storage.
- Similarity retrieval.
- Context assembly.
- Model generation.
Suppose the data of two enterprises is stored in the same vector database.
A user from Enterprise A asks:
Query the company's annual financial budget.
When the system performs vector retrieval, if tenant filtering is not applied, it may retrieve Enterprise B's financial budget document.
Even if the final model does not directly return the complete document, it may still leak sensitive information through summaries, numbers, or the reasoning process.
3.2 Vector Data Needs to Carry Permission Metadata
Each vector record should contain the necessary security metadata.
For example:
{
"chunk_id": "chunk_1001",
"document_id": "doc_1001",
"tenant_id": "tenant_a",
"department_id": "finance",
"owner_id": "user_001",
"access_level": "restricted",
"classification": "confidential",
"content": "年度预算相关内容",
"embedding": [0.12, 0.23, 0.34]
}
Among them:
tenant_id: The tenant it belongs to.department_id: The department it belongs to.owner_id: The resource owner.access_level: Access level.classification: Data sensitivity level.
These fields must not be used merely as ordinary business attributes; they should participate in retrieval permission decisions.
3.3 Permission Filtering Must Be Enforced During Retrieval
Incorrect approach:
results = vector_db.search(
query_embedding,
top_k=10
)
This approach considers only vector similarity and does not consider access permissions.
Correct approach:
results = vector_db.search(
query_embedding,
top_k=10,
filter={
"tenant_id": "tenant_a",
"department_id": "finance"
}
)
In real engineering, filter conditions should be generated by the server based on the authenticated identity and permission policy, rather than directly accepting user input.
Also note that different vector databases vary in their support for metadata filtering, hybrid search, and when filtering is executed. You should verify whether filtering truly applies to the candidate set, rather than merely performing surface-level filtering after retrieval is complete.
3.4 Pre-filtering vs. Post-filtering
There is a clear difference between the two approaches.
Pre-filtering
Restrict the accessible data set directly during the vector retrieval stage.
Advantages:
- Unauthorized documents are not returned to the application layer as candidate results.
- Reduces invalid candidate data.
- Makes it easier to meet strict data boundary requirements.
Disadvantages:
- Complex filter conditions may affect retrieval performance.
- Requires the underlying vector database to support reliable filtering capabilities.
Post-filtering
Retrieve similar results first, then filter based on permissions.
Advantages:
- Simple to implement.
- Permission judgments can be made in a unified business layer.
Disadvantages:
- Unauthorized data may already have entered application memory or intermediate logs.
- The number of results after filtering may be insufficient.
- Requires expanding the number of candidate retrievals, increasing computational cost.
- Sensitive content can easily be exposed in debugging, caches, and logs.
Recommendation: For highly sensitive data, prioritize pre-filtering and perform a secondary authorization check before results enter the model context. Post-filtering can only serve as a supplement and cannot replace underlying isolation.
3.5 Complete RAG Permission Control Flow
flowchart TD
A["User asks a question"] --> B["Authentication"]
B --> C["Retrieve tenant and user permissions"]
C --> D["Generate retrieval filter conditions"]
D --> E["Vector retrieval"]
E --> F["Recheck retrieval result permissions"]
F --> G{"Are all results authorized?"}
G -->|No| H["Remove unauthorized fragments"]
G -->|Yes| I["Build trusted context"]
H --> I
I --> J["Call the LLM"]
J --> K["Output content safety check"]
K --> L["Return to user"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#EAF3EC,stroke:#83A995,color:#315D49
style E fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style F fill:#EAF3EC,stroke:#83A995,color:#315D49
style G fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style H fill:#F7EAE7,stroke:#C98D7C,color:#754438
style I fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style J fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style K fill:#EAF3EC,stroke:#83A995,color:#315D49
style L fill:#DCEFE5,stroke:#4F8B70,color:#24563F
3.6 Consistency Between Document Permissions and Chunk Permissions
The RAG system has another issue that is easily overlooked: after document permissions change, already-generated Chunks may still retain the old permissions.
For example:
- The document initially belongs to the R&D department.
- The system splits the document into 100 Chunks.
- All Chunks are written to the vector database.
- An administrator adjusts the document permissions so that only the person responsible can view it.
- The Chunks in the vector database still retain the original department access permissions.
At this point, if permissions are not updated synchronously, a permission failure issue will arise.
Recommendations:
- Synchronously update associated Chunks when document permissions change.
- Record the association between documents and Chunks.
- Establish an event mechanism for permission change operations.
- If permission updates fail, prevent sensitive documents from continuing to be retrieved.
- Regularly perform consistency checks between document permissions and vector metadata.
For high-security scenarios, you can query an authoritative permission service based on the document ID at retrieval time, rather than fully trusting the permission copy stored long-term in the vector database.
IV. Privacy Protection: Control Where Data Comes From, How It Is Used, and Where It Flows
Data isolation addresses data boundaries between different parties.
Privacy protection focuses on whether the data itself should be collected, processed, stored, and disseminated.
4.1 Data Classification and Sensitivity Levels
Before designing a privacy protection system, it is first necessary to establish a data classification scheme.
| Data Level | Example | Protection Requirements |
|---|---|---|
| Public data | Product introductions, public documents | Standard access control |
| Internal data | Internal policies, general business materials | Login authentication and internal authorization |
| Sensitive data | Contracts, financial and HR materials | Strict authorization, encryption, and auditing |
| Highly sensitive data | Identity documents, payment credentials, authentication keys | Strong access control, data masking, and strict auditing |
Data classification should not only apply to databases but should also cover:
- Raw files.
- Document parsing results.
- Vector data.
- Model context.
- Cache.
- Conversation history.
- Agent tool results.
- Logs and monitoring data.
- Model output.
Otherwise, even if the original database is protected, sensitive information may still be exposed in other systems.
4.2 Data Minimization Principle
Data minimization is an important principle of privacy protection.
The core idea is:
Collect, process, and retain only the data necessary to accomplish a specific business objective.
For example, when a user asks about an order's logistics status, the system usually only needs:
{
"order_id": "ORDER_1001",
"shipping_status": "in_transit",
"estimated_delivery": "2026-11-26"
}
It does not need to pass all of the following information to the model:
{
"order_id": "ORDER_1001",
"user_name": "张某",
"phone": "13800000000",
"id_number": "完整身份证号码",
"bank_account": "完整银行卡号",
"shipping_status": "in_transit",
"estimated_delivery": "2026-11-26"
}
Even if the model can process this information, it does not mean the system should pass all of it into the context.
4.3 Data Masking
Data masking replaces, hides, or transforms sensitive information so that the original content cannot be directly exposed in a specific use case.
Common methods:
| Masking method | Example | Use case |
|---|---|---|
| Partial masking | 138****1234 | Page display |
| Fixed replacement | [PHONE] |
Model context |
| Hashing | SHA-256 value | Identifier matching |
| Tokenization | TOKEN_1001 |
Controlled mapping |
| Generalization | 35 years old → 30–40 years old | Statistical analysis |
| Deletion | Remove full ID number | Scenarios where the field is not needed |
Several concepts need to be distinguished:
Masking
Hides some characters and is mainly used for display.
Anonymization
Through irreversible or reasonably irreversible processing, makes the data impossible to identify a specific individual.
Pseudonymization
Uses substitute identifiers in place of real identities, but individuals may still be re-identified when additional information is present.
Encryption
Uses a key to convert data into ciphertext; entities holding the corresponding key can still decrypt it.
These methods are not interchangeable. For example, displaying a phone number as 138****1234 does not mean the original phone number has been anonymized.
4.4 Mask Data Before Model Calls
For systems that need to call external model services, it should be clearly defined which data may be sent to the model provider.
It is recommended to create a unified data masking layer:
import re
def mask_sensitive_data(text: str) -> str:
# Example: replace phone numbers
text = re.sub(
r"(?<!\d)1[3-9]\d{9}(?!\d)",
"[PHONE]",
text
)
# Example: replace email addresses
text = re.sub(
r"[\w.+-]+@[\w.-]+\.[A-Za-z]{2,}",
"[EMAIL]",
text
)
return text
Usage:
user_input = """
我的手机号是13800138000,
邮箱是user@example.com。
"""
safe_input = mask_sensitive_data(user_input)
response = llm.invoke(safe_input)
Note that these are only demonstration rules and cannot serve as a complete production-grade privacy detection system.
Production environments also need to handle:
- ID card numbers.
- Bank card numbers.
- Addresses.
- Internal enterprise keys.
- Personal health information.
- Custom business-sensitive fields.
- Text and face information in images.
- Private information in PDF, Excel, Word, and other files.
- Sensitive content in multiple languages and in altered formats.
At the same time, regular expressions cannot reliably identify all sensitive information. You can combine rule engines, NER models, DLP (Data Loss Prevention) systems, and business metadata to identify it.
4.5 Desensitization and Mapping to Original Data
Some business processes need to restore the real information after the model has processed it.
For example:
User input:
Please query Zhang San's orders.
Before it enters the model, the name is converted to:
Please query the orders of [PERSON_001].
The system stores the mapping internally:
mapping = {
"[PERSON_001]": "Zhang San"
}
The model returns:
[PERSON_001] has two recent orders.
A controlled business service decides whether the real name needs to be restored.
Note the following:
- The mapping table must not be sent to the model.
- The mapping table should be stored encrypted separately.
- Mapping relationships should be bound to the user, session, and tenant.
- Restoration operations must undergo permission verification.
- When restoration is not needed, the desensitized result should be returned directly.
4.6 The Complete Processing Chain for Privacy Protection
flowchart TD
A["Receive user data"] --> B["Data classification"]
B --> C["Sensitive information identification"]
C --> D{"Does it contain sensitive information?"}
D -->|No| F["Execute business processing"]
D -->|Yes| E["Desensitization or data minimization"]
E --> F
F --> G["Build model context"]
G --> H["Invoke model"]
H --> I["Output content check"]
I --> J{"Is sensitive information restoration needed?"}
J -->|No| K["Return safe result"]
J -->|Yes| L["Perform permission verification"]
L --> M{"Verification passed?"}
M -->|No| K
M -->|Yes| N["Controlled restoration"]
N --> K
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style E fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style F fill:#EAF3EC,stroke:#83A995,color:#315D49
style G fill:#EAF3EC,stroke:#83A995,color:#315D49
style H fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style I fill:#EAF3EC,stroke:#83A995,color:#315D49
style J fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style K fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style L fill:#EAF3EC,stroke:#83A995,color:#315D49
style M fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style N fill:#EAE8FA,stroke:#A49BD5,color:#51477D
V. Encryption Protection: Keeping Data Safe During Storage and Transmission
Desensitization cannot replace encryption.
Desensitization mainly controls the degree of data exposure, while encryption mainly prevents unauthorized parties from directly reading data.
5.1 Transport Encryption
Transport encryption is used to protect the confidentiality and integrity of data during network transmission.
Common technologies:
- HTTPS.
- TLS 1.2 / TLS 1.3.
- mTLS mutual authentication.
- Secure inter-service communication protocols.
For example:
Client
│
│ HTTPS / TLS
▼
API Gateway
│
│ TLS / mTLS
▼
Application Service
│
│ TLS
▼
Database
For cross-service calls, you must not assume trust just because the request occurs on the internal network.
5.2 Encryption of Data at Rest
Data at rest includes:
- Database records.
- Uploaded files.
- Vector database data.
- Cache persistence files.
- Object storage.
- Backup files.
Common encryption methods:
- AES-256-GCM.
- Cloud platform KMS.
- Envelope Encryption.
- Transparent Data Encryption (TDE).
5.3 Envelope Encryption
Envelope encryption is a common key management scheme.
It usually involves two layers of keys:
- DEK (Data Encryption Key): used to encrypt the actual data.
- KEK (Key Encryption Key): used to encrypt the DEK.
Basic process:
flowchart TD
A["Raw data"] --> B["Generate data encryption key DEK"]
B --> C["Encrypt data with DEK"]
B --> D["Encrypt DEK with KMS KEK"]
C --> E["Store data ciphertext"]
D --> F["Store encrypted DEK"]
E --> G["Need to read data"]
F --> G
G --> H["Request KMS to decrypt DEK"]
H --> I["Decrypt data with DEK"]
I --> J["Return raw data"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#EAF3EC,stroke:#83A995,color:#315D49
style D fill:#EAE8FA,stroke:#A49BD5,color:#51477D
style E fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style F fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style G fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style H fill:#EAF3EC,stroke:#83A995,color:#315D49
style I fill:#EAF3EC,stroke:#83A995,color:#315D49
style J fill:#DCEFE5,stroke:#4F8B70,color:#24563F
Advantages:
- Data keys can be generated and managed independently.
- The master key does not need to directly encrypt all business data.
- Rotating the KEK can reduce the risk of long-term key exposure.
- Key access permissions can be managed centrally.
5.4 Key Management Considerations
Do not hard-code keys directly in code:
# Incorrect example
API_SECRET = "my-secret-key"
Keys should also not be written in plaintext into configuration files and committed to the code repository.
Recommended:
- Use KMS or a dedicated key management system.
- Use Secret Manager to manage application keys.
- Isolate development, test, and production keys by environment.
- Restrict key read permissions.
- Rotate keys regularly.
- Log key usage and decryption activities.
- Do not write keys to ordinary logs.
It is also necessary to distinguish key rotation from data re-encryption: when rotating the KEK, the DEK can be re-wrapped; if the DEK needs to be replaced, the corresponding data usually needs to be re-encrypted.
6. Permission Management: Who Can Access Which Resources
Data isolation defines boundaries, privacy protection controls how data is used, and permission management determines specific access behavior.
A mature permission management system must answer all of the following:
- Who is accessing?
- What resource is being accessed?
- What operation is being performed?
- Under what conditions is access allowed?
6.1 Authentication and Authorization
These two concepts are easily confused.
Authentication
Confirming who the user is.
For example:
- Username and password.
- SMS verification code.
- OAuth 2.0.
- OpenID Connect.
- Multi-factor authentication (MFA).
Authorization
Confirming whether the user has permission to perform a certain operation.
For example:
- Whether they can read financial documents.
- Whether they can delete the knowledge base.
- Whether they can invoke database query tools.
- Whether they can modify user permissions.
Basic relationship:
flowchart TD
A["User request"] --> B["Authentication"]
B --> C{"Identity trusted?"}
C -->|No| D["Deny access"]
C -->|Yes| E["Retrieve user identity and attributes"]
E --> F["Perform authorization check"]
F --> G{"Has required permission?"}
G -->|No| D
G -->|Yes| H["Allow operation"]
H --> I["Record audit log"]
style A fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
style B fill:#EAF3EC,stroke:#83A995,color:#315D49
style C fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style D fill:#F7EAE7,stroke:#C98D7C,color:#754438
style E fill:#EAF3EC,stroke:#83A995,color:#315D49
style F fill:#EAF3EC,stroke:#83A995,color:#315D49
style G fill:#F7F4E8,stroke:#C7B77A,color:#675A2D
style H fill:#DCEFE5,stroke:#4F8B70,color:#24563F
style I fill:#E0F0FE,stroke:#93BCE8,color:#1E4976
6.2 RBAC: Role-Based Access Control
RBAC (Role-Based Access Control) is one of the most common permission management models.
Core idea:
Assign permissions to roles, and then assign roles to users.
For example:
| Role | Permission |
|---|---|
| Regular user | Query personal data |
| Department employee | Query department data |
| Department administrator | Manage department resources |
| System administrator | Manage system configuration |
| Security auditor | View audit records |
Relationship:
User → Role → Permission → Resource
Example:
roles = {
"user": {
"document:read:self"
},
"department_admin": {
"document:read:department",
"document:update:department"
},
"system_admin": {
"document:read:any",
"document:update:any",
"user:manage"
}
}
Authorization check:
def has_permission(user, permission):
user_roles = user.get("roles", [])
for role in user_roles:
if permission in roles.get(role, set()):
return True
return False
Advantages of RBAC:
- The role structure is clear.
- Easy to understand and manage.
- Suitable for systems with a relatively stable organizational structure.
- Permissions can be assigned in batches.
Limitations:
When permissions depend on dynamic conditions such as the department a resource belongs to, data classification level, time, or access location, RBAC alone may not be flexible enough.
6.3 ABAC: Attribute-Based Access Control
ABAC (Attribute-Based Access Control) dynamically determines whether to authorize access based on attributes of the subject, resource, operation, environment, and so on.
Common attributes:
| Attribute type | Example |
|---|---|
| Subject attributes | User ID, department, position, tenant |
| Resource attributes | Department the document belongs to, classification level, owner |
| Operation attributes | read, write, delete |
| Environmental attributes | Time, device, network location, risk level |
For example:
def authorize(user, resource, action):
if user["tenant_id"] != resource["tenant_id"]:
return False
if action == "read":
if resource["classification"] == "confidential":
return (
user["department_id"] == resource["department_id"]
and user["clearance"] >= 2
)
return False
This example shows that:
- The user and the resource must belong to the same tenant.
- The user's department must satisfy the resource access condition.
- The user's security clearance must meet the requirement.
Advantages of ABAC:
- It can express complex access policies.
- It is suitable for dynamic permission scenarios.
- It enables fine-grained data access control.
Limitations:
- Policy design and maintenance are more complex.
- Attribute sources must be trustworthy.
- Policies may conflict with one another.
- A robust policy testing mechanism is required.
6.4 How to Choose Between RBAC and ABAC
| Dimension | RBAC | ABAC |
|---|---|---|
| Authorization basis | Roles | Multi-dimensional attributes |
| Implementation complexity | Relatively low | Relatively high |
| Flexibility | Medium | High |
| Dynamic authorization | Relatively limited | Relatively strong |
| Management approach | Role and permission configuration | Policy and attribute management |
| Typical scenarios | Back-office management systems | Enterprise knowledge bases, finance, complex business |
In actual engineering practice, these can be used in combination:
- RBAC manages basic roles.
- ABAC manages resource-level access conditions.
- ACL manages special authorization for individual resources.
6.5 ACL: Access Control Lists
ACL (Access Control List) binds permissions directly to specific resources.
For example:
{
"document_id": "doc_1001",
"permissions": [
{
"subject": "user_001",
"actions": ["read", "write"]
},
{
"subject": "group_finance",
"actions": ["read"]
}
]
}
ACL is suitable for:
- Sharing individual files.
- Authorizing knowledge base documents.
- Project-level resource management.
- Authorization for specific users.
However, as the system scales up, a large number of ACLs increases the cost of permission maintenance and computation, so permission inheritance, caching, and unified policy management are needed.
6.6 Combining RBAC, ABAC, and ACL
Enterprise-grade systems usually do not need to choose just one model.
For example:
User
├── RBAC: determine basic roles
├── ABAC: evaluate department, classification level, and environment attributes
└── ACL: evaluate resource-level special authorization
The final authorization result should be computed by a unified policy decision service, rather than implemented separately by each business interface.
VII. Permission Management for AI Agents
One of the biggest differences between AI Agents and ordinary applications is that an Agent can not only read data but may also actively perform operations.
For example:
- Querying databases.
- Creating files.
- Deleting documents.
- Sending emails.
- Calling external APIs.
- Modifying business records.
- Executing workflows.
Therefore, permission management for Agents must be stricter than that of ordinary chat systems.
7.1 Agents Must Not Inherit Unlimited Permissions
Incorrect design:
agent = Agent(
tools=[
database_admin_tool,
filesystem_tool,
email_tool,
shell_tool
]
)
If all users can use the same Agent that holds administrator privileges, this creates a serious risk of privilege expansion.
Correct design:
- The Agent only receives the tools required for the current task.
- Each tool validates permissions independently.
- High-risk operations require additional approval.
- Resource access permissions are re-verified when a tool executes.
- Users cannot directly elevate Agent permissions through natural language.
7.2 User Permissions and Agent Permissions
Two kinds of permissions need to be distinguished:
User permissions
The operations the user themselves is allowed to perform.
Agent permissions
The operations the Agent can actually perform in the current task and execution environment.
Security principle:
Agent effective permissions
≤ user authorization scope
∩ scope allowed for the current task
∩ system security policy
Actual systems also need to consider service accounts, system-level capabilities, and delegated permissions that have been explicitly approved, but an Agent must not be granted all business permissions by default just because it is a system component.
7.3 Tool Invocations Must Pass Permission Checks
A unified tool execution gateway is recommended:
```python def execute_tool(user, tool, args): # 1. Verify that the tool is allowed if tool.name not in user["allowed_tools"]: raise PermissionError("Tool access denied") # 2. Verify resource ownership resource = load_resource(args["resource_id"]) if resource["tenant_id"] != user["tenant_id"]: raise PermissionError("Cross-tenant access denied") # 3. Verify operation permission if not authorize(user, resource, tool.action): raise PermissionError("Operation not permitted") # 4. Execute the tool return tool.execute(args) ```This example shows the basic checking process. A production environment should also validate tool parameters, operation scope, resource version, approval status and execution identity, to prevent TOCTOU (state changing between check and use) issues.
7.4 High-risk operations require human approval
Not every tool invocation should execute automatically.
Different execution policies can be designed according to risk level:
| Risk level | Example operation | Execution policy |
|---|---|---|
| Low risk | Query public knowledge | Automatic execution |
| Medium risk | Query internal business data | Execute after permission check |
| High risk | Modify business records | Permission check and approval |
| Extremely high risk | Delete critical data, fund operations | Strong authentication, human approval, audit |
Example flow: