Skip to content
ERPForAll DocsDevelopment

    Record access in addons: access domains, parameters and checks

    Status: the access engine of ADR 0035 (design note docs/design/m3-access-engine.md §2.2, §3.3, §3.4). The rules themselves are ir.access rows (security.md §1), loaded and compiled into the policy described here by erp-security (erp_security::source::PolicySource, with erp_security::resolver::Resolver for the users’ groups and companies). Engine tests also use erp_testkit::DomainPolicy. Field access by groups is described in field-access.md.

    Every Rust example on this page is compiled and run as a doctest of erp-test-models, like the examples of models.md.

    Access has two levels, as in Odoo:

    1. The model check: may this user read (write, create, delete) records of this model at all? Answered from the policy snapshot, no query.
    2. The record predicate: which records? A domain over the model (Odoo’s _access_domain), compiled to SQL and evaluated by PostgreSQL, never record by record in Rust.

    The engine applies them on every ORM operation, in Odoo’s order:

    OperationWhat is checked
    search, search_count, read_group, name_searchthe model check, then the read predicate as one more condition after your domain, in the same statement
    reading fields of recordsevery record must match the read predicate, else erp.access
    writethe write predicate on every record, before the change
    createthe create predicate on the new records: decided by the INSERT itself when it reads only the new row’s own columns, otherwise one statement after the create (the row must exist to be matched)
    unlinkthe unlink predicate on every record, before anything is deleted
    x2many valuesonly the related records the user may read are listed
    many2many commands that link recordsthe linked records must be readable
    onchangethe write check of the edited record

    A record check is one SELECT id … WHERE id = ANY($1) AND <predicate> per batch of ids. The read and write results are remembered for the rest of the transaction, until the transaction writes a field one of the predicates reads, so reading the same records again costs no query. Superuser mode (sudo(true)) passes every check. A new record that is not yet in the database and has no origin keeps field checks only; a new-record shadow of a database record (one with an origin) requires read access to that origin record.

    Cached values are shared within a transaction, including across with_user and sudo environments. A value in that cache grants no permission: scalar reads (cell, value, cells, values) and row/fetch APIs use the current environment’s model, record and field checks. Reading as sudo and then dropping sudo cannot carry that permission into the next read. The permission memo is keyed separately by principal and policy. ADR 0084 proposes this deliberate strengthening of Odoo’s direct cached field access; lead acceptance is pending.

    Raw SQL that writes ORM tables (tx.execute, tx.batch) is invisible to these memos and to the record cache: follow it with tx.invalidate_model(..) or tx.invalidate_records(..) (or tx.invalidate_all()), which ends both the cached values and the remembered access checks.

    A refusal is an erp.access error (ErrorKind::Access) with Odoo’s texts: at model level Your access rights do not let you modify 'Book' (library.book) records. and the groups that would allow it; at record level Access rules protect some of these records. …, which in debug mode (an internal user with base.group_no_one) lists the denied records and the rules to blame. The record-level text costs one statement on the error path (two in debug mode).

    A compiled predicate never holds the user’s values: user.id, the companies and “now” are parameters, bound by each statement for the user it runs for. One predicate, and one SQL text, serves every user with the same groups. In Rust a parameter is a PrincipalParam (crates/erp-domain/src/param.rs, not part of the published documentation), used as the value of a condition:

    use erp_sdk::access::{NowKind, PrincipalParam, UserPath};
    use erp_sdk::domain::Value;
    use erp_sdk::prelude::*;
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    // Odoo: [('user_id', '=', user.id)]
    let mine = Domain::condition("user_id", Operator::Eq, PrincipalParam::Uid)?;
    assert_eq!(mine.to_string(), "[('user_id', '=', user.id)]");
    // Odoo: [('company_id', 'in', company_ids + [False])]
    let my_companies = Domain::condition(
    "company_id",
    Operator::In,
    Value::List(vec![PrincipalParam::CompanyIds.into(), Value::Bool(false)]),
    )?;
    assert_eq!(
    my_companies.to_string(),
    "[('company_id', 'in', [company_ids, False])]"
    );
    // Odoo: [('partner_id', '=', user.partner_id.id)]
    let own_partner = Domain::condition(
    "partner_id",
    Operator::Eq,
    PrincipalParam::UserPath(UserPath::parse("partner_id.id")?),
    )?;
    assert_eq!(
    own_partner.to_string(),
    "[('partner_id', '=', user.partner_id.id)]"
    );
    // Odoo: [('deadline', '>=', context_today())] on a date field
    let open = Domain::condition("deadline", Operator::Ge, PrincipalParam::Now(NowKind::Date))?;
    assert_eq!(open.to_string(), "[('deadline', '>=', context_today())]");
    # Ok(())
    # }
    ParameterOdooValue
    PrincipalParam::Uiduser.idthe user’s id
    PrincipalParam::CompanyIdcompany_idthe current company
    PrincipalParam::CompanyIdscompany_idsthe allowed companies (a list: in an in list it adds all of them)
    PrincipalParam::Now(NowKind::Date) / Now(NowKind::Timestamp)context_today() / datetime.datetime.now()the transaction’s start, compared with date or datetime fields
    PrincipalParam::UserPath(path)user.partner_id.id, user.employee_ids.idsa field path from the user’s res.users row, ending in id (one id, False when a link is empty) or ids (the ids reached)
    PrincipalParam::GrantIds { .. }link grantsnot available yet; binding one is refused

    Rules for parameters:

    • Only Rust code builds them. No client domain, JSON value or data file can contain one.
    • They are decided in SQL only. A search binds them like an access predicate does; filtered_domain and other in-memory evaluation refuse a domain with a parameter (erp.programming).
    • Rewrites that need the value refuse them with a message naming the parameter: like/ilike, =?, a boolean field, a Now of the wrong kind (NowKind::Date on a datetime field).

    #[access_domain]: changing the predicate in code

    Section titled “#[access_domain]: changing the predicate in code”

    Most access is data (ir.access rows). When a model needs a rule that rows cannot express, an addon overrides the predicate with an #[access_domain] function in a #[methods] block, the Rust form of Odoo’s _access_domain override. It receives the predicate of the rest of the chain through sup and returns the new one; it narrows with & or widens with |:

    # erp_sdk::addon!(name = "library");
    use erp_sdk::access::{AccessCtx, AccessSuper, Operation, PrincipalParam};
    use erp_sdk::prelude::*;
    #[model(name = "library.book", description = "Book")]
    pub struct Book {
    #[field(char, required)]
    pub name: Option<Arc<str>>,
    #[field(many2one, comodel = "res.users")]
    pub owner_id: Option<RecId>,
    #[field(boolean)]
    pub restricted: bool,
    }
    #[methods(Book, addon = "library")]
    impl Book {
    /// Restricted books are read by their owner and by librarians only.
    #[access_domain]
    fn _access_domain(ctx: &AccessCtx, op: Operation, sup: AccessSuper) -> Result<Domain> {
    let policy = sup.call(ctx, op)?;
    if op != Operation::Read || ctx.has_group("library.group_librarian")? {
    return Ok(policy);
    }
    let open = Domain::condition("restricted", Operator::Eq, false)?;
    let owned = Domain::condition("owner_id", Operator::Eq, PrincipalParam::Uid)?;
    Ok(policy & (open | owned))
    }
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }
    • Signature: fn(ctx: &AccessCtx, op: Operation, sup: AccessSuper) -> Result<Domain>, synchronous, no self. The macro refuses an async fn, another signature, or a function that is also a #[method], #[compute], #[constrains], #[onchange] or #[rpc].
    • No user values, no I/O. The function runs while the policy compiles a predicate, and the result is reused for every user with the same groups. AccessCtx tells it the groups (has_group), the kind of principal (class(): internal, portal, public …), the elevation kind and the model; the user’s id, companies and context are not there. Use parameters for them, as owned does above.
    • has_group("module.name") answers for the user’s effective groups. A malformed or unknown external id is an erp.programming error, never false: a typo must not silently deny or allow.
    • Chain order: each addon contributes at most one override per model; the overrides run in the model’s method resolution order, the most recently loaded addon first, exactly like #[method(override)] chains (models.md). The bottom of the chain is the predicate the policy computed from the rows.
    • Your addon must declare the model: an override in an addon without a #[model] or #[extend] of that model, or a second override of one model by the same addon, stops the server at startup (example below).
    • An error denies: returning Err refuses the operation with that error.
    • Superuser mode never calls the chain (it passes every check).
    # erp_sdk::addon!(name = "library");
    # use erp_sdk::prelude::*;
    # #[model(name = "library.book", description = "Book")]
    # pub struct Book {
    # #[field(char)]
    # pub name: Option<Arc<str>>,
    # }
    pub mod library_extra {
    use erp_sdk::access::{AccessCtx, AccessSuper, Operation};
    use erp_sdk::prelude::*;
    use super::Book;
    erp_sdk::addon!(name = "library_extra", depends = ["library"]);
    pub struct Rules;
    /// Wrong: this addon has no `#[extend(Book, addon = "library_extra")]`.
    #[methods(Book, addon = "library_extra")]
    impl Rules {
    #[access_domain]
    fn _access_domain(ctx: &AccessCtx, op: Operation, sup: AccessSuper) -> Result<Domain> {
    sup.call(ctx, op)
    }
    }
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let err = erp_testkit::Harness::builder([&ADDON, &library_extra::ADDON])
    .check()
    .unwrap_err()
    .to_string();
    assert!(err.contains(
    "(addon 'library_extra') has no declaration of model 'library.book' in addon \
    'library_extra': add an #[extend] (or #[model]) for it in that addon"
    ));
    # Ok(())
    # }

    The override applies wherever the predicate does: searches, record checks, the access operator and filtered_access. A related field read as the user, or a search through a non-sudo relation, sees the override of the related model.

    Delegation (_inherits) and the parent’s access

    Section titled “Delegation (_inherits) and the parent’s access”

    A model that delegates to a parent (inherits = [("parent.model", "field")]) is reachable only where its parent is: the parent’s predicate is ANDed into the model’s own, and a parent the user may not touch at all denies the model too (Odoo’s _check_inherits_access). A model whose own rules should decide alone, like Odoo’s mail.mail over mail.message, says inherits_access = false:

    # erp_sdk::addon!(name = "library");
    # use erp_sdk::prelude::*;
    #[model(name = "library.message", description = "Message")]
    pub struct Message {
    #[field(char)]
    pub body: Option<Arc<str>>,
    }
    /// An outgoing mail of a message: its own rules decide who sees it.
    #[model(
    name = "library.mail",
    description = "Outgoing Mail",
    inherits = [("library.message", "message_id")],
    inherits_access = false
    )]
    pub struct Mail {
    #[field(many2one, comodel = "library.message", required, ondelete = "cascade")]
    pub message_id: Option<RecId>,
    }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    let registry = erp_testkit::Harness::builder([&ADDON]).registry_only()?;
    assert!(!registry.model("library.mail").unwrap().inherits_access);
    assert!(registry.model("library.message").unwrap().inherits_access);
    # Ok(())
    # }

    The default is true; the newest declaration that sets it wins, so an addon’s #[extend] can change it. Whom the error message names as allowed groups still intersects with the parents’ (Odoo’s _get_groups_with_access does too).

    Recordsets have Odoo’s three access helpers (erp_sdk::access::Operation names the operation):

    # erp_sdk::addon!(name = "library");
    # use erp_sdk::prelude::*;
    # #[model(name = "library.book", description = "Book")]
    # pub struct Book {
    # #[field(char)]
    # pub name: Option<Arc<str>>,
    # }
    use erp_sdk::access::Operation;
    # async fn example(mut tx: Transaction, books: RecordSet<Book>) -> Result<()> {
    // `erp.access` unless every book may be written (Odoo `check_access('write')`)
    books.check_access(&mut tx, Operation::Write).await?;
    // the same as a boolean (Odoo `has_access('unlink')`)
    let can_delete: bool = books.has_access(&mut tx, Operation::Unlink).await?;
    // the books the user may read, in order (Odoo `_filtered_access('read')`)
    let readable: Records = books.filtered_access(&mut tx, Operation::Read).await?;
    # let _ = (can_delete, readable);
    # Ok(())
    # }
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    In a domain, the access operator asks the same question: ('id', 'access', 'write') keeps the records the user may write, ('partner_id', 'access', 'read') the records whose partner the user may read (a many2one or id field, and read, write, create or unlink as the value).

    Changing data with SQL. The memo of record checks follows ORM writes. After changing with SQL data that predicates read, call tx.invalidate_model(..), tx.invalidate_records(..) or tx.invalidate_all(), as you would for cached values: they also forget the memoized checks that read the invalidated fields.

    Where Odoo code calls sudo() to read or write one thing the user may not, open a named block that names exactly that (ADR 0164; ADR 0035 decision 5). Transaction::elevated takes the caller’s environment, a reason (a dotted name, ElevationReason), an ElevationScope (models, operations and, optionally, fields) and the body. The body gets an environment of the same user carrying the scope:

    use erp_sdk::prelude::*;
    use erp_orm::audit::ElevationReason;
    use erp_orm::{ElevationScope, Operation, OperationSet, ScopeItem};
    async fn author_names(tx: &mut Transaction, env: &Env) -> Result<Vec<Value>> {
    let users = tx.registry().model_id("res.users")
    .ok_or_else(|| Error::programming("res.users is missing"))?;
    let scope = ElevationScope::new([ScopeItem::new(users, OperationSet::of([Operation::Read]))?])?;
    tx.elevated(env, ElevationReason::new("library.author.read_name")?, scope, async |tx, env| {
    env.records("res.users")?.search(tx, &Domain::TRUE).await?.values(tx, "name").await
    })
    .await
    }

    What the runtime guarantees today:

    • The environment lives only as long as the block. When the body returns, fails, panics or its future is dropped, the block closes. Using its environment or its recordsets afterwards, or in another transaction, is refused with Programming (“elevated environment of block … (reason ’…’) used outside it”), whatever the cache already holds. Return plain values from the body, not environments or recordsets. A panic or a dropped future also cancels the transaction (as an interrupted savepoint does): writes the body left pending are never flushed, and the transaction must be rolled back.
    • The elevation is audited before the body runs. Entry records the reason, the scope and who acted in the transaction’s audit row; equal blocks are one entry with a count. When the audit store is not ready the body does not run.
    • A scope never reaches superuser mode. sudo(true) or with_user of the superuser on a block environment gives an environment that refuses every use (”… cannot be widened to superuser mode”), and so do the audited escape hatches (unscoped sudo, a superuser server action). Other derivations (with_context, with_company, sudo(false), with_user of another user) keep the block’s lifetime; a with_user of another user is admitted only when the block’s user itself holds principal.impersonate (a scope never carries a capability; SPEC-PRIN-029). The engine’s own privileged steps keep working inside a block: the body of a compute_sudo field, for example, runs in superuser mode bound to the block, which grants nothing beyond what that compute already runs with outside any block, and ends with the block.
    • Library code that calls sudo(true) fails inside a block until it is migrated (the mail, base and web libraries are planned): for example base’s decimal precision lookup (a write of a field with a named precision that this transaction has not resolved yet), and mail posting and followers. Such calls get the “cannot be widened to superuser mode” error. Resolve or prepare those values before the block, or wait for the slice that moves that library code to its own block.
    • Nested blocks do not add up. A block opened inside another carries only its own scope, so library code that opens its own block (mail posting, numbering) works from inside yours. The outer environment stays valid until the outer block closes.
    • Pending writes are flushed before the block closes, also when the body returned an error; if that flush fails as well, one error carries both messages. A read-only API key stays read-only inside a block.

    What is refused before the body, with Programming unless said otherwise:

    • a transaction that must be rolled back: cancelled, aborted or released (“cannot open an elevation block: the transaction is aborted or released; roll back” for the last two), or poisoned, which is refused with the poison’s own error (its kind and message, for example the Validation error that poisoned it);
    • a read-only transaction without a read-audit owner (“scoped elevation requires an audited transaction: this read-only transaction has no read-audit owner”); RPC read-effect calls are opened by the server with an owner, which writes one read_ok attempt row before the result is released (an addon does not declare an owner: the P6 lint will enforce that, and until then core review does);
    • a model or field id that is not in the transaction’s registry;
    • a lifted rule the access policy refuses (see below). A refused entry takes no block identity and records no evidence.

    What a scope grants (ADR 0164 D3):

    • For each (model, operation) the scope names, the permission rules count as granted: the user needs no ir.access permission row for it. Every restriction (group-less rule) still applies, including the generated company restriction and rules that reach the company through a relation. An access condition or rule operator inside such a restriction is decided for the user without the block, so naming its target model too does not widen it. An _inherits child keeps its parent’s predicate: the scoped one when the scope names the parent for that operation, the user’s ordinary one otherwise.
    • Everything the scope does not name (another operation of the same model, another model) is decided exactly as for the user without the block, with the same error kind and message.
    • A rule that bears the company. For a scope, a rule bears the company when it does not compile, is the generated company restriction, names company_id, company_ids or the company parameters (company_ids, company_id), is a rule of res.company, or reads (directly, through a relational path, an any sub-domain, a literal search or a user.<path>) a field of res.company, a many2one, one2many or many2many whose comodel is res.company under any name (ir.job’s run_as_company included), or a reference or many2one_reference field (it cannot be proven not to point at a company). The check sees company relations only through field types (relations to res.company, reference fields, rules of res.company): a plain integer or char field holding a company id, or a many2one to a model that _inherits res.company, is not detected, so do not rely on the check for those.
    • Lifting a restriction: ScopeItem::lift names restrictions to drop for the item’s operations. A lift is accepted only for a restriction of the item’s model that compiles, does not bear the company, holds no access condition or rule operator, and applies to at least one operation the item names. Anything else (a permission, another model’s rule, an unknown external id) is refused at entry with Programming naming the rule and the reason, for example “cannot lift restriction rule ‘my_addon.rule_x’ (Rule X) on my.model: it bears the company (it reads my.model.owner_company, a relation to res.company), and a scope never lifts a company restriction”. A policy without restriction rules (a fixed or test policy) refuses every lift.
    • A named operation whose company confinement is only in permissions is refused at entry with Programming, before the block takes an identity or records anything: when a permission rule of the model for that operation bears the company and no restriction of the model for that operation confines to companies, naming it would drop the model’s only company filter. Only the generated company restriction counts as company confinement: a handwritten restriction never does, even one naming company_id or the company parameters ([('company_id', '!=', False)] or ['|', ('public', '=', True), ('company_id', 'in', company_ids)] confine nothing to the user’s companies), nor a rule of res.company or one reading a reference field. A permission with an access condition or a rule operator bears the company too: it brings in the target model’s whole predicate, company restriction included, so a line confined only through its document ([('order_id', 'access', 'read')]) is not nameable. To keep a model with a company_id nameable in a scope, give it a company_access that generates its company restriction (res.company takes no declaration, and every permission of it bears the company, so an operation of it with a permission is never nameable). All permission rules of the model count, not only those of the user’s groups, so the answer does not depend on who opens the block. Example: “the scope names read on ‘res.company’, which keeps no generated company restriction and whose permission rules (base.access_company_system, base.access_company_internal) may bear the company: scoped elevation cannot open it (ADR 0164 A6)”. In the shipped rules of base, mail, uom and product this refuses every operation on res.company, Read on mail.message, and Read, Write and Unlink on mail.activity (their document rules read the res_id reference); models with a generated company restriction, such as res.currency.rate, stay nameable. This fail-closed rule is accepted (ADR 0164 D3).
    • Not changed: field access. A field restricted by groups stays closed inside a block until field masks for scoped blocks exist (planned). The company set never grows, and a read-only API key stays read-only.

    Scoped elevation is never the way to act in a company the user is not in (ADR 0164 A6).

    The policy snapshot is compiled from the access tables, and a user’s groups and companies are resolved from the user tables. When a transaction changes them through the ORM, the engine flushes what is pending, rebuilds the policy for that transaction alone and resolves the users again before its next decision (design note §3.4), so a transaction sees its own access changes. base registers its tables for this. An addon whose table feeds the policy or the resolution of users registers it with policy_source!; a table that predicates only read (a project’s members, a document’s followers) needs no registration:

    # erp_sdk::addon!(name = "library");
    # use erp_sdk::prelude::*;
    use erp_sdk::access::{PolicySourceWrite, SourceKind};
    #[model(name = "library.role", description = "Library role")]
    pub struct Role {
    #[field(many2one, comodel = "res.users")]
    pub user_id: Option<RecId>,
    #[field(boolean, default = true)]
    pub active: bool,
    }
    erp_sdk::access::policy_source!(
    /// Roles put users in groups: a membership the resolver reads.
    pub ROLES = PolicySourceWrite::new("library.role", SourceKind::Membership)
    .fields(&["user_id", "active"])
    );
    # fn main() -> std::result::Result<(), Box<dyn std::error::Error>> {
    # erp_testkit::Harness::builder([&ADDON]).check()?;
    # Ok(())
    # }

    SourceKind::Policy marks a table the policy is compiled from, SourceKind::Membership one the users’ groups and companies are resolved from. Every create and unlink counts; a write counts when it touches one of the listed fields (all fields without .fields(..)). The server checks the listed fields at startup. Core code that changes such tables with SQL (data loading, uninstall, migrations) calls tx.mark_policy_dirty() instead.