AC Rules Expert
Expert guidance for the Frappe Tweaks AC Rule system - an advanced access control framework that extends Frappe's built-in permissions with fine-grained, rule-based access control.
Overview
The AC Rule system provides:
- Fine-grained access control: Control access at the record level, not just doctype level
- Dynamic filtering: Use SQL, Python, or JSON filters to determine access
- Rule-based logic: Define complex access rules with Permit/Forbid semantics
- Principal-based: Define who has access (users, roles, user groups, or custom logic)
- Resource-based: Define what is being accessed (doctypes, reports, or custom resources)
- Action-based: Control specific actions (read, write, delete, etc.)
Implementation Status
Current State:
- ✅ DocTypes: Fully implemented - Automatic permission enforcement via Frappe hooks
- ✅ Reports: Fully functional - Manual integration required (call API and inject SQL)
- ✅ Workflows: Fully implemented - Automatic transition filtering and permission enforcement
- 🔄 Migration: Deprecated systems (Event Scripts, Server Script Permission Policy) being phased out
Quick Start
Creating AC Rules
- Create Query Filter: Define who (principals) or what (resources) the rule applies to
- Create AC Resource: Define the DocType or Report being controlled
- Create AC Rule: Tie together principals, resources, and actions
DocType Integration (Automatic)
No code needed - AC Rules are automatically enforced for DocTypes through Frappe permission hooks.
Workflow Integration (Automatic)
No code needed - AC Rules automatically filter workflow transitions and enforce action permissions through Frappe workflow hooks.
Report Integration (Manual)
from tweaks.tweaks.doctype.ac_rule.ac_rule_utils import get_resource_filter_query
def execute(filters=None):
result = get_resource_filter_query(report="Your Report", action="read")
if result.get("access") == "none":
return [], []
ac_filter = result.get("query", "1=1")
data = frappe.db.sql(f"""
SELECT * FROM `tabDocType`
WHERE {ac_filter}
""", as_dict=True)
return columns, data
Core Components
The system consists of four main DocTypes:
- AC Rule: Central component that defines access control rules (Permit/Forbid)
- Query Filter: Reusable filter definitions (JSON, SQL, or Python)
- AC Resource: Defines what is being accessed (DocType or Report)
- AC Action: Defines controllable actions (read, write, delete, etc.)
See references/core-components.md for detailed documentation.
Rule Evaluation
Rules are evaluated through:
- Rule Map Generation: Organize rules by resource and action
- Principal Resolution: Determine which users match the rule
- Resource Resolution: Determine which records match the rule
- SQL Generation: Convert filters to SQL WHERE clauses
Final Logic: (Permit1 OR Permit2 OR ...) AND NOT (Forbid1 OR Forbid2 OR ...)
See references/rule-evaluation.md for evaluation flow and SQL generation.
Integration
DocTypes (Automatic)
Implemented via Frappe permission hooks - no manual integration needed:
- Read operations: Filtered automatically in list views and queries
- Write operations: Filtered automatically for create, write, delete, submit, cancel
Reports (Manual)
Must explicitly call get_resource_filter_query() and inject SQL into report queries.
See references/integration.md for complete integration guide and API documentation.
Usage Examples
Common patterns and complete examples:
- Sales Team Access Control: Restrict report to user's managed customers
- Restrict Archived Records: Prevent access to archived data
- Tenant-Based Multi-Tenancy: Isolate data by tenant
- Department-Based Access: Access based on user's department with exceptions
- Complex SQL Filters: Subqueries and multi-table joins
- Multiple Permit Rules: Combine rules for managers and team leaders
See references/examples.md for complete code examples.
Debugging and Auditing
Available Reports (System Manager role required):
- AC Permissions - System-wide access audit (who has access to what)
- Query Filters - Debug filter SQL generation with user impersonation
- AC Principal Query Filters - See which users match each principal filter
Common Workflows:
- Why does User X have access? → AC Permissions Report
- Test a Query Filter → Query Filters Report with impersonation
- Who matches a Principal Filter? → AC Principal Query Filters Report
See references/debugging-reports.md for detailed documentation and workflows.
Troubleshooting
Common issues:
- Rules Not Applying: Check enabled status, date range, principal/resource matches
- Incorrect Filtering: Verify SQL generation, reference doctypes, exception flags
- Performance Problems: Analyze query complexity, consolidate rules, add indexes
- Access Denied: Check Forbid rules, verify user/record matches, test with Administrator
See references/troubleshooting.md for debugging techniques and solutions.
Best Practices
- Use Standard Mode for simple mappings, Bypass for complex operations
- Validate source/target before syncing
- Handle missing targets gracefully
- Use context for runtime parameters
- Set appropriate timeouts for operation complexity
- Use specific queues for heavy operations
- Test with different user roles and edge cases
- Always escape user input in SQL filters
- Monitor performance with complex rule sets
- Document rule logic and purpose
Source Code Locations
tweaks/tweaks/doctype/ac_rule/ - AC Rule DocType
tweaks/tweaks/doctype/query_filter/ - Query Filter DocType
tweaks/tweaks/doctype/ac_resource/ - AC Resource DocType
tweaks/tweaks/doctype/ac_action/ - AC Action DocType
tweaks/tweaks/doctype/ac_rule/ac_rule_utils.py - Core utilities and API
Reference Files
For detailed information:
- core-components.md: Detailed documentation on AC Rule, Query Filter, AC Resource, AC Action
- rule-evaluation.md: Rule map generation, permission evaluation, SQL generation
- integration.md: DocType and Report integration, API endpoints
- examples.md: Complete usage examples and code patterns
- debugging-reports.md: Reports for debugging and auditing permissions
- troubleshooting.md: Common issues, debugging techniques, solutions
1---2name: frappe-tweaks-ac-rules-expert3description: Expert guidance for creating, implementing, and troubleshooting AC (Access Control) Rules in Frappe Tweaks - an advanced rule-based permission system. Use when working with AC Rules, Query Filters, AC Resources, AC Actions, implementing fine-grained access control, debugging permission issues, creating principal/resource filters, integrating with DocTypes or Reports, or understanding rule evaluation and SQL generation.4---56# AC Rules Expert78Expert guidance for the Frappe Tweaks AC Rule system - an advanced access control framework that extends Frappe's built-in permissions with fine-grained, rule-based access control.910## Overview1112The AC Rule system provides:13- **Fine-grained access control**: Control access at the record level, not just doctype level14- **Dynamic filtering**: Use SQL, Python, or JSON filters to determine access15- **Rule-based logic**: Define complex access rules with Permit/Forbid semantics16- **Principal-based**: Define who has access (users, roles, user groups, or custom logic)17- **Resource-based**: Define what is being accessed (doctypes, reports, or custom resources)18- **Action-based**: Control specific actions (read, write, delete, etc.)1920## Implementation Status2122**Current State**:23- ✅ **DocTypes**: Fully implemented - Automatic permission enforcement via Frappe hooks24- ✅ **Reports**: Fully functional - Manual integration required (call API and inject SQL)25- ✅ **Workflows**: Fully implemented - Automatic transition filtering and permission enforcement26- 🔄 **Migration**: Deprecated systems (Event Scripts, Server Script Permission Policy) being phased out2728## Quick Start2930### Creating AC Rules31321. **Create Query Filter**: Define who (principals) or what (resources) the rule applies to332. **Create AC Resource**: Define the DocType or Report being controlled343. **Create AC Rule**: Tie together principals, resources, and actions3536### DocType Integration (Automatic)3738No code needed - AC Rules are automatically enforced for DocTypes through Frappe permission hooks.3940### Workflow Integration (Automatic)4142No code needed - AC Rules automatically filter workflow transitions and enforce action permissions through Frappe workflow hooks.4344### Report Integration (Manual)4546```python47from tweaks.tweaks.doctype.ac_rule.ac_rule_utils import get_resource_filter_query4849def execute(filters=None):50 result = get_resource_filter_query(report="Your Report", action="read")51 52 if result.get("access") == "none":53 return [], []54 55 ac_filter = result.get("query", "1=1")56 57 data = frappe.db.sql(f"""58 SELECT * FROM `tabDocType`59 WHERE {ac_filter}60 """, as_dict=True)61 62 return columns, data63```6465## Core Components6667The system consists of four main DocTypes:68691. **AC Rule**: Central component that defines access control rules (Permit/Forbid)702. **Query Filter**: Reusable filter definitions (JSON, SQL, or Python)713. **AC Resource**: Defines what is being accessed (DocType or Report)724. **AC Action**: Defines controllable actions (read, write, delete, etc.)7374See [references/core-components.md](references/core-components.md) for detailed documentation.7576## Rule Evaluation7778Rules are evaluated through:791. **Rule Map Generation**: Organize rules by resource and action802. **Principal Resolution**: Determine which users match the rule813. **Resource Resolution**: Determine which records match the rule824. **SQL Generation**: Convert filters to SQL WHERE clauses8384**Final Logic**: `(Permit1 OR Permit2 OR ...) AND NOT (Forbid1 OR Forbid2 OR ...)`8586See [references/rule-evaluation.md](references/rule-evaluation.md) for evaluation flow and SQL generation.8788## Integration8990### DocTypes (Automatic)9192Implemented via Frappe permission hooks - no manual integration needed:93- Read operations: Filtered automatically in list views and queries94- Write operations: Filtered automatically for create, write, delete, submit, cancel9596### Reports (Manual)9798Must explicitly call `get_resource_filter_query()` and inject SQL into report queries.99100See [references/integration.md](references/integration.md) for complete integration guide and API documentation.101102## Usage Examples103104Common patterns and complete examples:1051061. **Sales Team Access Control**: Restrict report to user's managed customers1072. **Restrict Archived Records**: Prevent access to archived data1083. **Tenant-Based Multi-Tenancy**: Isolate data by tenant1094. **Department-Based Access**: Access based on user's department with exceptions1105. **Complex SQL Filters**: Subqueries and multi-table joins1116. **Multiple Permit Rules**: Combine rules for managers and team leaders112113See [references/examples.md](references/examples.md) for complete code examples.114115## Debugging and Auditing116117**Available Reports** (System Manager role required):1181191. **AC Permissions** - System-wide access audit (who has access to what)1202. **Query Filters** - Debug filter SQL generation with user impersonation1213. **AC Principal Query Filters** - See which users match each principal filter122123**Common Workflows**:124- Why does User X have access? → AC Permissions Report125- Test a Query Filter → Query Filters Report with impersonation126- Who matches a Principal Filter? → AC Principal Query Filters Report127128See [references/debugging-reports.md](references/debugging-reports.md) for detailed documentation and workflows.129130## Troubleshooting131132Common issues:133- **Rules Not Applying**: Check enabled status, date range, principal/resource matches134- **Incorrect Filtering**: Verify SQL generation, reference doctypes, exception flags135- **Performance Problems**: Analyze query complexity, consolidate rules, add indexes136- **Access Denied**: Check Forbid rules, verify user/record matches, test with Administrator137138See [references/troubleshooting.md](references/troubleshooting.md) for debugging techniques and solutions.139140## Best Practices1411421. Use Standard Mode for simple mappings, Bypass for complex operations1432. Validate source/target before syncing1443. Handle missing targets gracefully1454. Use context for runtime parameters1465. Set appropriate timeouts for operation complexity1476. Use specific queues for heavy operations1487. Test with different user roles and edge cases1498. Always escape user input in SQL filters1509. Monitor performance with complex rule sets15110. Document rule logic and purpose152153## Source Code Locations154155- `tweaks/tweaks/doctype/ac_rule/` - AC Rule DocType156- `tweaks/tweaks/doctype/query_filter/` - Query Filter DocType157- `tweaks/tweaks/doctype/ac_resource/` - AC Resource DocType158- `tweaks/tweaks/doctype/ac_action/` - AC Action DocType159- `tweaks/tweaks/doctype/ac_rule/ac_rule_utils.py` - Core utilities and API160161## Reference Files162163For detailed information:164- **[core-components.md](references/core-components.md)**: Detailed documentation on AC Rule, Query Filter, AC Resource, AC Action165- **[rule-evaluation.md](references/rule-evaluation.md)**: Rule map generation, permission evaluation, SQL generation166- **[integration.md](references/integration.md)**: DocType and Report integration, API endpoints167- **[examples.md](references/examples.md)**: Complete usage examples and code patterns168- **[debugging-reports.md](references/debugging-reports.md)**: Reports for debugging and auditing permissions169- **[troubleshooting.md](references/troubleshooting.md)**: Common issues, debugging techniques, solutions