Writing ir.access rules
Status: implemented in erp-security. The compiler described here turns the domain column of your
security/ir.access.csv rows into the predicate the ORM puts in every statement. Loading the
rows from the database (ir.access, res.groups) and the erp access report command come with
the same slice. Design: ADR 0035 decision 2 and docs/design/m3-access-engine.md §3.1.
How rows combine (permissions OR, restrictions AND, _inherits parents) is in
security.md §1. This page is about the domain column.
A rule is compiled once, not evaluated per user
Section titled “A rule is compiled once, not evaluated per user”Odoo evaluates a rule’s domain in Python for each user, with user, company_ids, company_id
and time as values. ERPForAll compiles it once per policy: those names are symbols that
become statement parameters (the user id, the allowed companies, the transaction’s start time)
or sub-selects (a path from the user’s row). One compiled predicate then serves every user with
the same groups, and nothing is evaluated in memory.
The price: a rule can only use the forms below. Everything else is refused with a message that says what to write instead. Most Odoo rules need no change.
What a rule may use
Section titled “What a rule may use”| You write | It means |
|---|---|
Literals: 1, -1, 2.5, 'text', True, False, None, lists and tuples | The value (None is False) |
user.id | The user’s id |
user, user.ids as a value | The list of the user’s id (('user_id', '=', user)) |
user.partner_id.id, user.partner_id.commercial_partner_id.id | One id along a path of stored many2one fields from the user’s row; False when a link on the path is empty |
user.employee_id.ids, user.all_group_ids.ids, user.partner_id | The ids along a path of stored relational fields; an empty list when a link is empty |
company_ids | The ids of the companies the user works in now (the company switcher) |
company_id | The current company |
company_ids + [False], user.partner_id.child_ids.ids + [3] | A list holding those ids and the literals |
time.strftime('%Y-%m-%d'), context_today(), fields.Date.today(), datetime.date.today() | Today (a date), when the transaction started |
time.strftime('%Y-%m-%d %H:%M:%S'), datetime.now(), datetime.datetime.now(), fields.Datetime.now() | Now (a timestamp), when the transaction started |
('f', 'in', user.env['m'].search([...]).ids) (also not in, =, !=, without .ids) | A sub-query: f must hold ids of m; the search domain must be literal; archived records of m are left out unless the domain names its active field, as search does |
('f', 'access', 'read') (write, create, unlink) on a many2one or id | The record that f points to (or the record itself for id) must pass the rules of that operation for the same user |
Conditions use Odoo’s list syntax with the prefix operators '&', '|', '!'. Paths such as
('partner_id.country_id', '=', 5) and any conditions are allowed; inside a rule they never
apply the related model’s own rules (Odoo’s any!). The internal operators any! and
not any! are not accepted in a rule string, as in Odoo.
A search by a user does apply the related model’s rules: ('product_tmpl_id', 'any', [...]),
('product_variant_ids.standard_price', '>', 0) or a one2many or many2many condition keeps only
the related records that user may read. A related model’s rule may use child_of and parent_of
(the product rules’ ('company_id', 'parent_of', company_ids)): it is resolved before the search
runs, the same way as the searched model’s own rule, and the search stays one statement.
Examples, as they appear in security/ir.access.csv:
id,name,model_id,group_id/id,operation,domainlibrary_book_own,own books,library.book,library.group_library_user,crud,"[('user_id', '=', user.id)]"library_book_company,books of my companies,library.book,,crud,"[('company_id', 'in', company_ids + [False])]"library_book_partner,books of my company's partner,library.book,base.group_portal,r,"[('partner_id', 'child_of', user.partner_id.commercial_partner_id.id)]"library_loan_book,loans of readable books,library.loan,library.group_library_user,r,"[('book_id', 'access', 'read')]"Operators an addon declares
Section titled “Operators an addon declares”Some access decisions cannot be written with the forms above because the record to test is chosen
by data: a message points at its document by a model name and an id (mail.message.model and
res_id, a many2one_reference field), and the documents are of many models. An addon can
declare a rule operator for such a case. It is a spelling that is valid in the domain text of
ir.access rows only, and the policy compiler expands it when it builds the predicate.
erp_sdk::rule_operator!(pub THREAD_ACCESS = "thread_access" { addon: "mail", // ignored while this addon is not installed model: "mail.message", // the only model whose rows may use it field: "res_id", // the many2one_reference field the condition names inherits: "mail.thread", // the models it ranges over operations: [Read], // the values a row may give});A row then writes ('res_id', 'thread_access', 'read') next to ordinary conditions:
access_mail_message_user,mail.message.user,model_mail_message,base.group_user,r,"['|', ('author_id', '=', user.partner_id.id), ('res_id', 'thread_access', 'read')]"What the compiler does with it, for each group set and company shape (once, memoized with the rest
of the predicate): one branch per concrete model that inherits inherits (abstract, transient and
the declaring model itself are left out) and that the principal may read at model level, each
model = M AND res_id pointing at a record of M that passes M’s own rules for that operation.
The branches hold parameters, never the id of a user or a company, so one predicate serves every
user. A model the principal cannot read has no branch; no branch at all is FALSE. A record of M
that no longer exists matches nothing, also where M allows everything.
What it refuses, each as a rule error that denies the rows concerned (like any rule that does not compile) or, for a declaration, as a refusal to build the policy:
| Refused | Message or effect |
|---|---|
The spelling outside ir.access row text (an RPC, search or list-syntax domain) | The ordinary Invalid operator in condition ('res_id', 'thread_access', 'read'): it is not a domain operator |
| Another model, another field, or a value the declaration does not list | The 'thread_access' operator works only on mail.message in condition ..., ... only on the field 'res_id' ..., Invalid value for 'thread_access' operator in condition ... |
A negation over it: '!', or the operator inside the sub-domain of a not any | a declared rule operator cannot be negated: ... |
A cycle through the access operator (M’s rule needs the message again) | the rules on the cycle fail with the usual access cycle error |
Blast radius: the expansion needs the combined read predicate of every model it ranges over that the
principal may read at model level. A rule that does not compile, or an access cycle, on any such
model therefore fails the reads of the declaring model (for thread_access, every mail.message
read) for every group that reaches that model, with that rule’s error. It is never skipped.
A declaration of an addon that is not installed in the database is ignored (the spelling is then an
invalid operator); one of an installed addon whose model or field is missing refuses to build.
| A declaration with a malformed or duplicate name, the name of a core operator, a field that is not a many2one_reference, or a model the registry does not have | rule operator '<name>' (declared in <module>): <reason> (ADR 0032 Amendment 1); the policy does not build |
The first declaration is thread_access of the mail addon (read only; posting and writing map
to the document’s operations in a later slice). Design: ADR 0032 Amendment 1,
docs/design/m4-mail-core-a1-access.md. The declaration must be linked into the server (the addon
crate is linked), or the spelling is an invalid operator in the rows that use it.
What is refused, and what to write instead
Section titled “What is refused, and what to write instead”| Refused | Why | Write instead |
|---|---|---|
user.has_group('x.group_y') | A group check is the rule’s group | Two permission rows: one for x.group_y with the wider domain, one for the other group with the narrower one. Permissions OR, so members of x.group_y get both |
user.name, user.login, any non-id value of the user | Rules compare record ids | A path ending in .id or .ids |
user.env.companies..., user.env.ref(...), user.env['m'].search(<domain with user or company>) | Computed from the environment in Python | company_ids; a literal search; a path from user |
Arithmetic and string formatting (user.id + 1, '%s' % x, datetime.now() - timedelta(days=1)) | Computations are not compiled to SQL | A literal, a path, or the plain now/today forms |
.id after a one2many or many2many (user.employee_ids.id) | It names several records | .ids |
Names Odoo addons add to the rule context (website) | Not supported until an addon can declare a rule symbol | — |
A domain on a rule of ir.access itself | The table that repairs a broken policy is governed by permissions only (Odoo refuses it too) | A permission without domain |
Example of the has_group rewrite. In place of one row
sale_order_rule,orders,sale.order,sales_team.group_sale_salesman,r,"[] if user.has_group('sales_team.group_sale_salesman_all_leads') else [('user_id', '=', user.id)]"ship two:
sale_order_own,own orders,sale.order,sales_team.group_sale_salesman,r,"[('user_id', '=', user.id)]"sale_order_all,all orders,sale.order,sales_team.group_sale_salesman_all_leads,r,When a rule does not compile
Section titled “When a rule does not compile”- When the row is written (
ir.accesscreate or write), the domain is checked against the model: an unknown field, operator or form is aValidationErrorwith Odoo’s text,Invalid domain <domain>: <reason>. So a broken rule normally never reaches the table. - When the policy is built (after a module upgrade changed a model, or rows written with SQL),
a rule that does not compile denies its model’s operations to everyone it applies to (its group’s
members, or everyone for a restriction) with
Access rule '<name>' (<id>) on <model> cannot be compiled: <reason>. It is never skipped and never turned into “everything”. The build report lists it;erp access reportprints the report anderp access disable-rule <xmlid>archives the rule. accesscycles: rules whoseaccessconditions lead back to themselves (sale.orderread needsres.partnerread, which needssale.orderread) are rule errors of every rule on the cycle.
Differences from Odoo you may notice
Section titled “Differences from Odoo you may notice”- “Today” and “now” are the transaction’s start time; Odoo keeps the value in a cache until the next clear.
user.<path>.idand.idsare read in the statement itself, so a change of the user’s partner or employee is seen at once. Every field on the path must be stored.- Rules that compute on user values are refused instead of evaluated (see above).
- Write-time validation also checks the
accessconditions’ field and operation; Odoo only checks them when the rule is used.
Multi-user acceptance
Section titled “Multi-user acceptance”An access CSV is an input to authorization, not a complete acceptance oracle. For addon acceptance, author expected outcomes independently from the rows being tested. Reconcile the installed concrete and transient models (including extensions and auto-installed bridges) with an explicit manifest. Keep abstract models as named exclusions, never as silent skips.
Use an ordinary authenticated administrator and ordinary internal users with verified groups and separate companies. A Full/System setup environment is not an administrative test subject. Anonymous HTTP denial does not test an authenticated public group’s rules. Supply valid model-specific CRUD payloads; a validation error on bad input cannot prove authorization. Verify successful mutations by readback and refusals by absence of mutation, including mixed batches.
Check generated company restrictions, field groups/runtime hooks, related fields, menu discovery and direct execution separately. Service-owned or immutable models need an explicit documented refusal and a supported positive control. Do not add blanket grants just to make their generic CRUD probes succeed. Attachments and chatter require a demonstrably unreadable parent; a foreign-company contact can still be shared under its declared policy.
A staged source inventory and acceptance protocol exist; execution remains pending the multi-user fixture and test packages. Their eventual oracle must fail on unknown models or unresolved expected policy, never update its baseline automatically.
Inventory operation grants
Section titled “Inventory operation grants”Inventory declares role permissions in its addon data. Move-line read is granted to the roles that can read moves; line create, write and delete are granted to the roles that can write moves. The same role mapping covers line serial children and correction records. An ordinary employee has no move-line grant. This mapping deliberately allows an operator to remove an editable line while retaining the move itself.
These are explicit group rows, not automatic inheritance of a parent record’s domains. A bridge adding a sales, purchasing, portal, barcode or quality role must declare its corresponding line permissions and any required record restrictions. In particular, portal access to a transfer must not become unrestricted line access. Other addon grants remain additive.
Company confinement comes from model company_access declarations and their generated rules.
Required-company balances and lines use exact scope with empty company denied. Explicitly
shared locations, lots and routes permit empty company. Do not insert a sentinel company or
duplicate the generated restrictions in an access CSV. Parent-owned location-policy and serial
child rows use their declared parent scope. Lot-name scope and topology-version records have
no ordinary permission rows, which means refusal rather than unrestricted access.
Group and privilege defaults are editable records. The inventory light-group override composes with the inherited classification; its manifest invokes reclassification after loading the feature identities. Normal upgrades preserve group customization. The privilege category field is not available in the base model yet. Package permissions are intentionally withheld until the package model supplies a company declaration.