ac-rules-expert
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 DocTypetweaks/tweaks/doctype/query_filter/- Query Filter DocTypetweaks/tweaks/doctype/ac_resource/- AC Resource DocTypetweaks/tweaks/doctype/ac_action/- AC Action DocTypetweaks/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
More from kehwar/frappe_tweaks
frappe-tweaks-power-query-expert
Expert guidance for connecting Power Query (Power BI, Excel) to Frappe apps and reports. Use when building Power Query M code for Frappe data access, integrating Frappe reports with Power BI/Excel, implementing authentication for Power Query connections, handling heavy/long-running reports with report_long_polling API to avoid timeouts, applying column types and transformations, or troubleshooting Power Query caching and connection issues.
6open-observe-api-expert
Expert guidance for OpenObserve API integration in Frappe Tweaks. Use when creating, configuring, or troubleshooting OpenObserve API DocType, implementing send_logs() or search_logs() functionality, integrating with Server Scripts/Business Logic/Client-side code, debugging connection issues, or implementing logging, monitoring, error tracking, performance metrics, or audit trail use cases.
5frappe-ci-expert
Expert guidance for setting up CI/CD tests for Frappe apps. Use when users ask about GitHub Actions workflows, CI test setup, continuous integration for Frappe apps, running tests in CI environments, database setup for CI, bench configuration in CI, or automating tests for Frappe/ERPNext applications.
4workflow-expert
Expert guidance on Frappe Workflow system including workflow structure, states and transitions, workflow actions, email notifications, permission hooks (before_transition, after_transition, filter_workflow_transitions, has_workflow_action_permission), and best practices. Use when creating workflows, implementing workflow logic, understanding state transitions, working with workflow actions, configuring email notifications, or troubleshooting workflow-related issues.
4report-expert
Expert guidance on Frappe reports including report types, structure, creation workflow, and best practices. Use when creating standard script reports, query reports, understanding report structure, working with columns and filters, or troubleshooting report-related issues.
4api-reviewer
Security review and analysis for Frappe API endpoints decorated with @frappe.whitelist(). Use when reviewing API security, checking for permission vulnerabilities, scanning for unprotected endpoints, validating role restrictions, or auditing API endpoints for security best practices. Helps identify missing frappe.only_for(), frappe.has_permission(), or frappe.get_list() usage.
4