Skip to content
Tutorials Center
My learning

Topics

Lesson 28 of 39 ยท Security and Access

Field Security, sudo and Safe Coding

Protect Odoo data in code: field-level groups, sudo and with_user, checking access by hand, avoiding SQL injection with parameters, safe HTML and common security mistakes.

Groups, access rights and record rules protect data when people use the normal screens. Your own Python code can step around all of them, either on purpose (sudo()) or by accident (raw SQL, unchecked controllers). This lesson covers the remaining security tools and the mistakes that turn up in real code reviews.

The Odoo snippets are read-only. The runnable examples are Python stand-ins that show the same patterns, including a safe versus unsafe SQL query on an in-memory SQLite database.

Field-level security

Any field can have a groups argument in Python:

Python
class LibraryBook(models.Model):
    _name = "library.book"

    name = fields.Char(required=True)
    cost_price = fields.Float(groups="library.group_library_manager")

A user outside the group cannot read or write cost_price: the ORM raises an AccessError when asked for it directly, silently drops it from read() and from views, and removes it from the fields metadata. This is stronger than groups on a view element, which only hides it on that form. Use the field-level option for secrets (costs, salaries, personal data) and the view option for layout.

sudo, with_user and with_context

Python
book = self.env["library.book"].browse(book_id)

book.sudo().write({"state": "lost"})          # runs as superuser: no rights, no rules
book.with_user(other_user).read(["name"])      # runs as another user, with their rules
book.with_company(company).create(vals)        # changes the active company
book.with_context(active_test=False).search([])  # changes the context, not rights

sudo() returns the same records with a new environment where security is skipped. Since Odoo 13 the superuser is not a login; it is a flag on the environment. Use it only for a precise reason:

  • A portal user's action must create or update a technical record the user cannot normally touch.
  • A scheduled job needs to see all companies.

Rules of thumb:

  1. Check first, then sudo. Verify the user's right to the operation (ownership, a token, a group) before elevating.
  2. Keep the sudo scope tiny: record.sudo().write(...) on one record, not self.sudo() for a whole method.
  3. Never return sudo records to the user without selecting only the fields they may see; the records carry elevated environments around.
  4. Use with_user for background jobs that should behave as a real user so rules still protect data.
flowchart LR
    U["User request"] --> C{"Ownership / token<br/>checked in code?"}
    C -- No --> R["Reject"]
    C -- Yes --> S["record.sudo().write(small dict)"]
    S --> O["Response with only<br/>allowed fields"]

Elevate after checking, and only for the smallest operation.

Raw SQL and injection

Odoo's ORM builds safe SQL. If you write your own with self.env.cr.execute(...), always pass values as parameters, never format them into the string:

Python
# Dangerous: the name can break out of the quotes
self.env.cr.execute("SELECT id FROM library_book WHERE name = '%s'" % name)

# Safe: the database driver quotes the value
self.env.cr.execute("SELECT id FROM library_book WHERE name = %s", (name,))

For dynamic table or column names use psycopg2.sql helpers (Odoo exposes odoo.tools.SQL in recent versions), not string formatting. Also, after raw SQL that changes data you must invalidate the cache (self.env.invalidate_all() or invalidate_recordset()), because the ORM cache does not know about your direct changes. And raw SQL ignores every access check and record rule, so use it for read-only reporting and for performance, with the user's rights in mind.

A demonstration with SQLite

The standard sqlite3 module uses ? placeholders instead of %s, but the idea is identical. See how string formatting lets a crafted name bypass a filter.

Python SQL injection versus parameters

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

The unsafe query returns every row, secrets included, because the quote in the input closed the string. The parameterised version treats the whole text as data.

A sudo stand-in

This model shows how a short, checked elevation works compared with elevating everything.

Python Check first, then elevate

Press Run (or Ctrl + Enter) to see the result here.

Program input ยท what you'd type while the program runs

Type the answers before you press Run, one per line. Each time the program reads a line (with input()), it gets the next line from this box.

Other recurring pitfalls

  • Public controllers with auth="public" that read records by ID. Combine with an access token, or check the record belongs to the visitor.
  • csrf=False on a route without a very good reason. See Controllers and Routes.
  • Unescaped HTML: use t-out in templates (QWeb Templates) and Markup only for trusted text.
  • eval or safe_eval on user text: do not. Odoo's safe_eval is for admin-defined expressions and has had to be hardened repeatedly.
  • Returning sudo() data in a JSON route: select the fields explicitly.
  • Secrets in logs: never log passwords, tokens or API keys.

Check your understanding

Quick check ยท 4 questions

of 4 answered You scored / 4 ยท perfect!

  1. 1. What does groups="library.group_library_manager" on a Python field do?

    Field-level groups are enforced by the ORM, not just by the view.
  2. 2. What is the right way to pass a user-supplied name into self.env.cr.execute?

    Parameters are quoted by the database driver, which prevents SQL injection.
  3. 3. When using sudo(), what is the best practice?

    Elevate narrowly and only after your own check, since sudo skips all rights and rules.
  4. 4. Why must you invalidate the cache after raw SQL updates?

    Direct SQL bypasses the ORM, so cached values may be stale until invalidated.

Summary

  • Use groups on Python fields for data that must stay hidden, even outside views.
  • sudo() skips rights and rules: check first, elevate narrowly.
  • Always pass SQL values as parameters; invalidate the cache after raw writes.
  • Escape output, avoid csrf=False and unchecked public routes.
  • Test with a limited user, not only the administrator.

Next: QWeb PDF Reports