Security and Access Control
Status: model and record access are decided by the AccessPolicy (crates/erp-orm/src/access/mod.rs, not part of the published documentation)
trait in erp-orm and enforced on every ORM operation by the access engine (ADR 0035; how addons
work with it: access.md). CSV access lists are parsed by erp-data (ADR 0019), and field-level
permissions are declared via groups attributes in erp-registry. Compiling the ir.access rows into a policy,
field access, capability resolution and authentication are delivered separately; see the sections below.
1. Access rows (security/ir.access.csv)
Section titled “1. Access rows (security/ir.access.csv)”Odoo 20 keeps grants and filters in one table, ir.access, and addons ship its rows in
security/ir.access.csv (loaded by erp-data like any CSV data file; the file name names the model). The
columns are Odoo’s own (odoo/odoo/addons/base/security/ir.access.csv):
id,name,model_id,group_id/id,operation,domainaccess_library_book_user,library.book user,library.book,library.group_library_user,r,access_library_book_manager,library.book manager,library.book,library.group_library_manager,crud,library_book_own_company,books of my companies,library.book,,rwcd,"[('company_id', 'in', company_ids)]"| Column | Meaning |
|---|---|
id | External id of the row within the addon. |
name | Human-readable label. |
model_id | Technical model name the row applies to (library.book). |
group_id/id | External id of a res.groups record. Empty means the row applies to everyone. |
operation | Letters for the operations the row covers, in c, r, u, d order: c create, r read, u write (update), d delete (unlink); the model accepts the non-empty subsets (crud, cr, ud, r, …). w is not a letter. |
domain | Optional record filter (Odoo domain syntax); empty means all records. |
How rows combine (Odoo 20, odoo/odoo/orm/models.py:3601-3647; ADR 0035):
- A row with a group is a permission: members of that group may perform the listed operations on the records its domain matches. Permissions of all the user’s groups are ORed.
- A row without a group is a restriction: it narrows every user’s access to the records its domain matches, and restrictions are ANDed. A restriction never grants anything on its own: with no matching permission the access domain is empty (false).
- The access domain for a model and operation is
OR(permissions) AND AND(restrictions).
erp-security compiles the rows into the installed policy: PolicySource loads them, the compiler
turns each domain into a predicate and the ORM enforces it through AccessPolicy (section 3). What a domain
may contain (user.id, company_ids, user paths, literal searches, the access operator) and what is refused,
with the rewrites, is in access-rules.md.
2. Field-Level Access Control (groups attribute)
Section titled “2. Field-Level Access Control (groups attribute)”Individual sensitive fields can be restricted to specific user groups directly in the model declaration.
In model structs using the #[model] macro, specify groups = "..." on the #[field(...)] attribute:
use erp_sdk::prelude::*;
#[model]pub struct EmployeeSalary { #[field(char, required = true)] pub employee_name: Arc<str>,
// Field restricted strictly to HR Managers #[field(monetary, groups = "hr.group_hr_manager")] pub base_salary: Option<Decimal>,}Programmatic declarations configure this via FieldDecl::groups (crates/erp-registry/src/decl.rs, not part of the published documentation):
FieldDecl::new("base_salary", KindDecl::Monetary(MonetaryField::new())) .groups("hr.group_hr_manager")The declared group string is stored in FieldSpec.groups (crates/erp-registry/src/spec.rs, not part of the published documentation) in the compiled
registry. The engine checks it on every ORM path (read, write, create, commands, domains, order, group by,
fields_get); see field-access.md. Which groups a user is in, and so what the text means for
them, comes from the policy of erp-security, built from the group tables; the exact meaning of the text (!group,
., the technical group) is in field-access.md.
3. The access policy and _access_domain
Section titled “3. The access policy and _access_domain”The ORM asks the installed AccessPolicy (crates/erp-orm/src/access/mod.rs, not part of the published documentation) (v2, ADR 0035), a
synchronous, immutable snapshot. For a principal binding (the user, its interned groups and companies,
its elevation) it answers the model-level check and returns the record predicate of an operation as an
AccessDomain (crates/erp-orm/src/access/domain.rs, not part of the published documentation): a domain whose user values are parameters
(user.id, company_ids, …) bound by each statement, so one predicate serves every user with the same
groups:
pub trait AccessPolicy: Send + Sync + 'static { fn check_model(&self, b: &PrincipalBinding<'_>, model: &ModelSpec, op: Operation) -> Result<()>; fn access_domain(&self, b: &PrincipalBinding<'_>, model: &ModelSpec, op: Operation) -> Result<AccessDomain>; // plus the snapshot's identity and generation, group interning and closure, // capabilities, explain and `check_scope` (the lifts and named operations of a scoped // elevation block) // (see the rustdoc)}A policy implemented outside erp-security keeps the default check_scope: it refuses every lifted
rule of a scoped elevation block, since such a policy has no restriction rules to lift (what a block
grants under the compiled policy: access.md, scoped elevation blocks).
The engine pins one snapshot per transaction, applies the predicates in SQL on searches and record
checks, memoizes record checks per transaction, and rebuilds the snapshot privately when the
transaction changes the access tables (design note §3.3, §3.4). Addons change a model’s predicate in
code with an #[access_domain] override, and check access with check_access, has_access and
filtered_access: see access.md.
Operation Kinds
Section titled “Operation Kinds”The Operation enum identifies the model-level action:
Operation::Read(“read”)Operation::Write(“write”)Operation::Create(“create”)Operation::Unlink(“unlink”)
Enforcement Rules
Section titled “Enforcement Rules”-
Fail-closed: If no
AccessPolicyis installed,erp-orminstallsStaticPolicy::DenyAll: every operation outside superuser mode is refused. -
SQL domain fusion (ADR 0002 §6): a search ANDs the read predicate into its statement, after your domain; record checks select the allowed ids with one statement per batch. Records are never filtered in memory.
FALSEhides all records;TRUErestricts nothing. -
Bootstrap and test policies: until
erp-securitycompiles their.accessrows,StaticPolicy(crates/erp-orm/src/access/static_policy.rs, not part of the published documentation) serves bootstrap and tests that do not exercise access:StaticPolicy::AllowAll: permits all operations.StaticPolicy::SuperuserOnly: permits operations only in superuser mode.StaticPolicy::DenyAll: denies all operations.
Engine tests use
erp_testkit::DomainPolicy(record predicates per model and operation, group permissions, overrides) anderp_testkit::RulesPolicy.
4. Where the policy lives
Section titled “4. Where the policy lives”base holds the policy in its own tables, Odoo’s: ir.access (ir_access), res.groups
(res_groups, with the implications in res_groups_implied_rel), res.groups.privilege, the
groups of custom fields (ir_model_fields_group_rel) and ir.capability (ir_capability, which
groups hold a named capability). Every process compiles them into one policy snapshot and
re-reads them only when they change:
- Any write counts, however it is made. A statement-level trigger on each of these tables
records one
policychange per transaction (the ORM,security/ir.access.csvloading, raw SQL, the cascade of a deleted model or group,TRUNCATE). Other processes rebuild their snapshot at their next transaction; nothing is cached past that. - Your own transaction sees its own changes at once (SPEC-SEC-018). Writing a rule or a group,
or a user’s
group_ids,company_ids,company_idoractive, makes the next operation of the same transaction flush those writes and decide with a private snapshot and the re-read groups and companies of the users acting in it. Removing yourself from the group that lets you read a model hides its records from your next search, with no explicit flush. - Membership is read, not compiled. A user’s groups and companies are read when a transaction starts, so adding a user to a group changes nothing for other users and costs no rebuild.
An addon that keeps rows the policy compiles (rare: share tables read by a grant need nothing,
see models.md, signal triggers) declares the trigger on its model and registers the model, so a
transaction that writes it re-reads its policy:
use erp_sdk::access::{POLICY_SOURCE_WRITES, PolicySourceWrite, SourceKind};
// in Cargo.toml: linkme = "0.3" (the registration is a link-time slice)#[linkme::distributed_slice(POLICY_SOURCE_WRITES)]static POLICY_ROWS: PolicySourceWrite = PolicySourceWrite::new("library.policy_row", SourceKind::Policy);SourceKind::Membership marks a model whose writes change who belongs where (re-read, no
rebuild); .fields(&["..."]) limits the count to writes of those fields (creates and deletes always
count). A registration naming a field the model does not have fails the server start.
Capabilities (capabilities.md): base ships data/ir.capability.csv, which gives the core
capabilities (policy.explain_others, policy.customize, principal.impersonate, audit.read,
company.all, rpc.debug_errors) to base.group_system. An addon that declares a capability ships
its own row in the same format; a declared capability without a row is an error of the policy
build, and asking for it fails.
When a rule cannot be compiled it denies the operations it covers and is listed by
erp access report; erp access disable-rule <module.name> switches it off (see cli.md).
5. Users, groups and roles (base)
Section titled “5. Users, groups and roles (base)”What base enforces on res.users and res.groups, and the hooks an addon has.
User types. base.group_user (internal), base.group_portal and base.group_public are
disjoint. A user may not hold two of them, directly or through implied groups, and a group may
not imply two of them; both raise a Validation error naming the user or group.
Implied groups. implied_ids is the direct implication; all_implied_ids and
all_implied_by_ids are the reflexive transitive closures (cycles are allowed and closed). A user’s
all_group_ids is the closure of group_ids. Call _apply_group / _remove_group on a set of
groups to add or remove an implied group on them and on every group they imply; members gain or
lose it with the implication. A group name may not start with -.
Default groups and roles. A user created without group_ids gets base.group_user plus the
groups the group with external id base.default_user_group implies. Groups given are never
completed, an explicit empty set stays empty, and a default_group_ids context key wins. The
read-only role field is group_system, light_user, regular_user or false, computed from
all_group_ids (typed as erp_addon_base::res_users::Role). Its search is a domain over group_ids
(role_domain, four statements however many users there are) and users_with_role(tx, &env, &[Some(Role::System)])
runs it in your environment: record rules and active_test apply as for any search, and the result is
not elevated. A group is
light when its external id is in res.groups._get_light_group_xmlids: override that method to
add the light groups of your addon, then every group of yours that is not light makes its holders
regular users, and base.group_user_regular is kept implied by the least-privileged regular group of
each privilege. The form’s role toggle is an onchange on role.
The last administrator. Taking base.group_system away from the last active administrator fails
with “You must have at least an administrator user.” whatever the way: a command, SET or clear on the
user’s group_ids or on the group’s user_ids, archiving the user, deleting the user (deleting the group
itself is refused too). Odoo guards only the user-side group_ids write; these are stricter on purpose.
The check locks the remaining administrators’ rows, so two transactions removing two different
administrators at the same time cannot both commit: the loser gets a Concurrency error (SQLSTATE
40001/40P01), which Orm::run retries. Call erp_addon_base::res_users::ensure_an_administrator(tx)
from your own code that changes administrators by raw SQL.
Missing groups are errors. The rules look base.group_* up by external id. A database without
base.group_system (or base.group_user for new users, or the three groups of the role onchange) is a
Programming error, not a database where the rules do not apply; so is a registry without the
ir.model.data model (compose erp_data::model_data::ADDON), and so is a database without
base.group_user_regular when a group is created or rearranged (Odoo returns quietly there; we do not,
because it would leave every regular user without the marker). The one exception is Odoo’s “base is
installing” state: the data loader calls Transaction::begin_base_install(&grant) with the module system’s grant
(ModuleSystem builds its ORM with it and lends it to the load session) around each of base’s data files, and
refuses a base file when its session has no grant (erp_modules::Error::BaseInstallGrantMissing). The state lives in the Rust transaction object, not in the
database and not in the context (the client controls the context, a database-level SET could keep a
setting on for good): turning it on needs the BaseInstallGrant of the Orm that opened the transaction (OrmBuilder::build_with_base_install_grant returns it
next to the Orm; plain build() mints none, the module-install executor receives it from the build site before cron,
hooks or RPC start, and it is never reachable from a Transaction or Env). Transaction::begin_base_install(&grant) is refused with an Access
error for another Orm’s grant or unless the transaction was opened as the System principal (the stage ORMs that
Orm::rebuild makes for one module operation share the original’s grant, so it holds after switch_orm), and turning it on is
logged at warn; end_base_install is always allowed. A savepoint that rolls back restores the flag it had on entry. Lookups that only
define sets (user types, light groups, the regular marker, internal groups) skip an absent group, as Odoo
does. A group that is not saved (a new record without an origin) passed to the group helpers
(_is_light_groups, _has_cycle, _reduce_to_light_groups, …) is a Programming error; the empty
set is light.
Roles. The role onchange accepts light_user, regular_user, group_system or empty (no change); any
other value is an error, not a no-op.
Two user types at once. Two transactions that put the same user into the portal group and into the
internal group would both pass the disjointness check under REPEATABLE READ (Odoo has the same gap). The
check therefore updates the affected user rows first, in id order, so the second transaction fails with a
Concurrency error (40001) that Orm::run retries. This covers group_ids writes on res.users and
user_ids links on res.groups; a change of the group graph that merges user types is not serialised.
share. True for users outside the internal user type; it follows the user’s groups and is
recomputed for all users, in one set-based statement, when the group graph changes. Without
base.group_user in the database nobody is internal and every user is share = true. Stored fields that
depend on share are not notified by the set-based recompute (the ORM has no public modified hook yet).
Self-service fields. Mark the res.users fields an internal user may edit on their own record
with user_writeable on the field (#[field(char, user_writeable)]). Users outside
base.group_system (Settings administrators; superuser mode is also exempt) are denied writes on every
other field with the field access error. This includes Access Rights users (base.group_erp_manager):
they may save another user’s self-service fields, but not password, login, groups or any other
field (SPEC-SEC-033). The check costs no statement and fields_get reports those fields read-only.
A field you add to res.users is therefore administrator-only unless you mark it. company_id is marked:
an internal user changes their own default company, and _check_user_company keeps it among company_ids
(below), so a self-write cannot lock the user out; company_ids stays administrator-only, so a self-write
cannot widen access. A scoped elevation does not widen the mask.
Default company (ADR 0170, SPEC-COMPANY-025..031). company_id is required by rule, not by a NOT NULL
column (the bootstrap inserts the superuser before any company exists, and raw SQL can still write NULL):
default_getgives a new user the environment’s company (tx.companies(env), first entry) for bothcompany_idandcompany_ids. ASystemprincipal that names no company takes the database’s only active company, and gets no default when there are several (the create is then refused, below).- Every ORM create, including sudo creates by signup/SSO addons, that passes
company_idand nocompany_idsallows that company. Provisioning code sets both fields deliberately. - An active user’s
company_idmust be one of itscompany_ids(#[constrains("company_id", "company_ids", "active")],erp_addon_base::res_users::check_user_companies):Validation, naming the user and the user’s allowed companies (not the chosen company: a user who writes their owncompany_idmay not read it). Inactive users and databases without any company are not checked. The relation rows are read, so an archived default company is still “allowed” and keeps its own refusal (SPEC-COMPANY-021). The check locks the membership and user rows it relies on, so two transactions that each remove a part of the same fact conflict: the loser getsConcurrencyandOrm::runretries. company_idisondelete = "restrict": deleting a company that is some user’s default company is aValidationerror namingres.users; a company that is only in a user’scompany_idscan be deleted and the membership row goes with it.- An addon that creates users in code passes
company_id(andcompany_ids) or creates them in an environment whose company is set. - The base 1.10 migration (
assign_user_companies) fills existing rows or refuses before any fill. R1b never adds membership: active users with an out-of-set default and no active allowed company refuse; inactive users in that shape stay unchanged. R1a instead selects the lowest-id active allowed default, changing sign-in company and company-dependent values without changing memberships. Seedocs/user/users.md. - After 1.10, NULL defaults are legal only for the superuser and inactive users. Other NULLs come from a writer
outside ORM enforcement. NULL alone is not a sign-in refusal when allowed companies exist. The idempotent
assign_user_companieshelper can be explicitly rerun in a supported migration transaction to repair those defaults or refuse with the affected ids. It cannot reverse historical R1b grants: see the operator guide.
_allow_sudo_commands. res.users and res.groups set allow_sudo_commands = false: an
x2many command (create, update, delete, link) from another model that targets them runs as the
transaction’s original user, even from sudo() or with_user(..). group.write({user_ids: [..]})
therefore cannot be used to bypass the access rules of users. Set allow_sudo_commands = false on
your own models the same way when a sudo write on a parent must not reach them.
Commands on these models run as the request’s user in both directions: a command targeting
res.users or res.groups always runs as the transaction’s original user, so an administrator’s request
that works with_user(portal_user) runs those commands as the administrator again (Odoo does the same).
Not yet: res.partner links (partner_id, partner_share), passwords and login (planned).
Adding a preference to My Preferences
Section titled “Adding a preference to My Preferences”The My Preferences dialog (base.users_preferences_form, opened from the user menu) is an ordinary form view,
so an addon adds its own preference without editing base: a user_writeable field on res.users, and a view
that inherits the dialog and puts the field in one of its named groups. mail does exactly this for the
notification choice (addons/mail/src/res_users.rs, addons/mail/views/res_users_views.xml,
SPEC-PREFS-015 and SPEC-PREFS-016).
The dialog has two named groups for this: other_preferences (right column of the Preferences page) and
calendar_preferences (Calendar page). Inside the group, position="inside" appends after the fields already
there.
#[extend(ResUsers, addon = "mail", inherit = [MailThread])]pub struct UsersThread { /// How the user wants notifications delivered; their own choice, so it is `user_writeable`. #[field( selection, selection = [("email", "E-mail"), ("inbox", "Inbox")], default = "email", user_writeable )] pub notification_type: Option<Arc<str>>,}<record id="users_preferences_form_inherit_mail" model="ir.ui.view"> <field name="name">res.users.preferences.form.inherit.mail</field> <field name="model">res.users</field> <field name="inherit_id" ref="base.users_preferences_form"/> <field name="arch" type="xml"> <xpath expr="//group[@name='other_preferences']" position="inside"> <field name="notification_type" widget="radio" string="Notifications" options="{'horizontal': True}"/> </xpath> </field></record>Rules to keep in mind:
- The field must be
user_writeable. Without it a user outsidebase.group_systemis refused on save with the field access error (SPEC-SEC-033), and the dialog would show a field nobody can save. Mark only what is the user’s own business and what no other user’s data depends on; each field of the dialog carries a one-line justification in its rustdoc. - A selection field can be a horizontal radio (
widget="radio",options="{'horizontal': True}"); a short text field takes the plain widgets (email,phone,char). - Do not make a field
requiredat the column unless every writer sets it: the database default exists only for booleans (ADR 0171), so a rawINSERT INTO res_usersthat omits a required column is refused.mailkeepsdefault = "email"and refuses an empty value with a#[constrains]rule instead. Schema sync adds a new column with its static default, so rows that exist at upgrade are filled; only a row inserted by raw SQL afterwards holds no value, and that means the default. - The named groups are not on the wire: the client receives the combined form, and group names matter only for
your xpath. The dialog accepts no other element than the form grammar of
human-form-layout.md. - Test it with two addons: the dialog described with and without yours installed
(
crates/erp-cli/tests/user_preferences_mail.rs), and a self-write of the new field by a user outsidebase.group_system.
6. Coming in Milestone 3
Section titled “6. Coming in Milestone 3”These arrive with the named board tasks; nothing below is on main yet:
- Access engine (ADR 0035): the engine (record checks on every operation, the
#[access_domain]chain, principal parameters) is in place, described inaccess.md; still to come:ir.accesscompiled to SQL predicates per model, operation and group set; field access by groups andir.capability; scoped, named and audited elevation blocks (sudo()stays in the core for parity and is refused in shipped addon code). - Authentication: login, credentials and API keys.
- RPC and server (ADR 0034): JSON-2 over HTTP with request limits.
- Background jobs (background jobs), the event outbox and the realtime bus: background jobs, the event outbox and the realtime bus.
Each of these tasks adds its own page to this guide when it lands.
7. Approval policies (ir.approval.policy, ADR 0169)
Section titled “7. Approval policies (ir.approval.policy, ADR 0169)”An approval policy says which RPC entry calls of users need a decision by another person before
they run. It works on calls, not records (ADR 0169 D11): the writes a method makes on other models,
jobs and System calls never consult it. Until the approval dispatch lands, the
revisions can be drafted, checked and resolved, but no call is held for approval yet. The model refuses an
active Approve or Deny revision for users with a validation error: creating, copying (with active = true) or activating one is
refused (“requiring approval for or denying calls of users is not available yet in this release”; a copy of an
already active revision is refused earlier, as a duplicate of its selector); a revision
saved archived can be prepared, and archiving is never refused. Allow revisions and agent or service revisions
are not fenced (SPEC-TRUST-026).
Who configures them. Only members of base.group_system (Settings Administration) may create or
archive revisions, and only for their active companies; a revision for every company is global administration.
Every other user gets the ordinary access refusal. Each change made through RPC
leaves the call’s row in the audit trail.
Revisions. One row is one revision: a selector, an outcome (allow, approve, deny) and, for
approve, the people who may decide (named users and groups). A revision never changes after
creation except active: to change a policy, create the new revision and archive the old one.
Revisions are never deleted. The selector is:
| Field | Meaning |
|---|---|
company_id | one company, or empty for every company |
principal_kind | user (agent and service revisions are stored but not resolved yet) |
effect | the effect class of the method (read, write, destructive, external) |
model, method | an exact model and optionally an exact method; empty model means every model |
Which revision applies. For a call, the most specific active revision wins: a revision of the call’s company before one for every company; then model and method, then model, then every model. Two active revisions with the same selector cannot be written. The companies of a call on records that all have a company are the caller’s active companies plus those companies. A create, a call on a record without a company and a call without target records (a model method) are resolved for every company the caller is allowed in, plus, for a create, the companies the new records get when known. All these companies must select the same revision, otherwise the call is refused: choosing the active company never passes over another company’s revision.
Who may approve. The eligible set is computed when the call is resolved: the named users and the current members of the named groups (through implied groups), never the user making the call or the user impersonating them, never archived, portal (share) or superuser accounts, and only users allowed in every company the call is resolved for (for a create, every company the requester is allowed in). A call whose set is empty is refused before anything is stored.
What is refused at write time. approve for read calls; approve for external calls of
users; an allow revision for agents or services; an unknown model; a method that the model does not
expose over RPC with that effect; approvers on an allow or deny revision; an active user approve
revision with no approver; more named users plus groups than the configured operating limit (default/hard ceiling 64); a named approver who is archived, a
portal user or the superuser. Each message names the revision.
In code. Addon code that needs the outcome of a call uses
erp_addon_base::ir_approval_policy::resolve(env, tx, &call), where call states the facts of the call:
ApprovalCall::on_records(model, method, &record_companies) (one Option<CompanyId> per target record, None
for a record without a company), ApprovalCall::create(model, method, &known_companies) or
ApprovalCall::model_level(model, method). resolve returns Unmanaged, Allow, Approve { revision, approvers } or Deny. The effect is the method’s
current effect in the registry; a method revision written for an earlier effect (an addon raised it) refuses the
call until an administrator replaces it. Pass one entry for every target record: a record left out is not
resolved for its company, while a record without a company widens the call. A caller who may not read the revisions involved gets “This action needs an approval that
is not set up correctly; ask an administrator.” instead of the detail; the detail goes to the server log
(erp::approvals) only, never to the error’s debug field. The default data
ships two inert agent revisions (destructive and external calls need approval) and no user revision.
Approval operating limit
Section titled “Approval operating limit”base.approval_max_approvers is an administrator-managed, database-global declared setting (default 64, inclusive range 1–64). Declared Settings storage is its only authority; an identically named system parameter has no effect. ir_approval_policy::MAX_APPROVERS remains the immutable hard ceiling. Native policy creation/reactivation and eligible-set resolution use the transaction-visible setting; a missing stored value uses the declaration default and corrupt storage refuses.
Use ir_approval_policy::eligible_approvers when checking current eligibility. It bounds both named users plus groups and distinct eligible humans without truncation, retaining requester exclusions and company checks. A future decision or execution coordinator must reread eligibility and retain immutable invocation checks; this helper alone does not implement approval execution.
Settings refuses a lower value while an active revision has too many named references or potential internal-human approvers. Without a requester at configuration time, the latter count excludes inactive, share and superuser accounts, applies a company-specific revision’s company, and counts the union for a global revision. Policy edits and Settings writes synchronize through the global scope row version. Ordinary read snapshots follow transaction admission semantics, without a process-local cache.