Authentication for addon authors
Native API key primitives
Section titled “Native API key primitives”erp_security::auth::apikey provides the native format and keyed-digest building
blocks defined by ADR 0037. GeneratedApiKey::generate() returns redacted,
zeroizing secret text; expose() explicitly borrows that text for the eventual
one-time response. NativeApiKey::parse() validates a borrowed canonical token.
ApiKeyHasher, derived from DatabaseSecret, produces the digest and key id for
storage. These primitives do not authenticate a user, grant access or persist a
key. Addon business code uses the authorized erp_sdk::auth::apikey_manage API,
rather than inserting key rows directly.
The apikey module’s rustdoc contains a compiling example of generation and
digest preparation. Never log the exposed text or serialize the hasher. A display
prefix is only a label; it cannot identify or authenticate a credential.
What an addon can use and extend in password login and sessions (design:
docs/design/m3-auth.md §14). Everything is in erp_sdk::auth. Native API key verification and browser HTTP routes are described here; programmatic native key management is described below; MFA and SSO remain separate deliveries.
What base provides
Section titled “What base provides”| Piece | Where | What it does |
|---|---|---|
res.users.password | addons/base/src/res_users_auth.rs | write it in clear, it is stored hashed (Argon2id by default), it always reads empty. An empty password and one over 1,024 bytes (“A password may have at most 1024 bytes.”) are refused. Setting it ends every session of the user at once, with the session-end hooks. |
res.users.login | same | unique (“You can not have two users with the same login!”) |
res.users._check_credentials(credential, env) | same | verifies a credential for one user; the base implementation checks the password |
res.users.context_get() | same | {lang, tz, uid} of the calling user (JSON-2, read effect) |
res.users.log | addons/base/src/res_users_log.rs | one row per successful login (create_uid, create_date) |
ir.config_parameter | addons/base/src/ir_config_parameter.rs | database-wide settings with a typed API |
Logins themselves run in the framework (Auth::authenticate, erp-security), not in an addon: the server
calls it, and it calls _check_credentials through dispatch, so an addon override takes part.
A login is two short transactions with no database connection held in between: one flight reads the throttle rows, the user and the installed languages; the password is hashed on the hashing pool; one flight writes the verdict (the failure count, or the session). The success is written only if the user’s stored password and active flag are still the ones the first flight read: a password changed while the login was verified makes it fail with “Access Denied”, and nothing is written.
What the server (and anyone calling authenticate) must know
Section titled “What the server (and anyone calling authenticate) must know”- Cancellation. Dropping the
authenticatefuture (a client that hangs up, a deadline) is safe: after the first flight the rest runs in a task of its own, so a guess is verified and counted even when its caller is gone, and a success leaves a session row nobody holds (idle collection ends it). Call it inside a Tokio runtime. - Client address.
LoginRequest::new(login, password, client)takes the address explicitly:ClientAddr::Known(addr)(the address after the trusted-proxy rule) from every HTTP route,ClientAddr::InProcess("reason")only for tools, jobs and tests. In process there is no address cooldown, no pre-filter and no trusted pair, so an HTTP route must never use it.Debugof a request prints neither the login nor its length (users type passwords into the login field). - Admission. At most
min(2 × hashing permits, primary pool size / 2)logins are in progress per ORM lineage, shared by everyAuthhandle and retained through detached work. The half-pool reservation also applies before an addon installs a credential override. A login that waits longer than the hashing pool’s queue wait fails withLoginError::Overloaded { retry_after }(503 withRetry-After). A login can wait for the admission, for the settings (only after they changed: another request’s reload, or its own; both share one deadline of the queue wait, and the reload’s statement carries the same limit), and for its hashing permit, each up to the queue wait: three queue waits and one hash, and four queue waits and two hashes when the credential changed while it was verified (the login reads phase A again and verifies once more, once). A rehash of a correct password, or the cost floor’s dummy after a wrong one, adds one queue wait and one hash to the verify it follows (so up to six waits and four hashes for a login restarted between two rehashes). The database statements of the login are bounded by the ORM’s transaction limits, not by the queue wait: per try, and the failure count and the success statement each run up to three tries after a deadlock (5 – 25 ms apart), with the admission permit held. A session check that cannot read the settings within the queue wait fails withResourceExhaustedandCondition::Overloaded(503 too); a check whose keys changed while it ran reads them a second time, so it waits up to two queue waits for them. The hashing pool refusing one attempt’s hash before it was verified (its own wait expired) answers “Access Denied” and is not counted; once the stored hash was verified, a wrong password is always counted. - Denial cost. A wrong password on a hash cheaper than the current parameters, or of another scheme (an imported Odoo PBKDF2 hash), also runs a dummy verify at the current parameters, so no denial is cheaper than an unknown login’s. It is a floor: such a denial may take longer, which is accepted (BUG-082’s residual; a later change may close it).
- Hashing settings.
password.hashing.argon2_memory_kibabove what a hashing permit reserves (admission.hash_memory_kib) is refused when written (checked against the writing node’s pool) and stopsAuth::new. It can still reach a running node: one whoseadmission.hash_memory_kibis smaller than the writing node’s, or any node afterpassword.hashing.schemeis switched toargon2idover a larger memory value written earlier. That node logs the settings aterroronce per settings generation (AuthStats::settings_over_reservation) and keeps answering: unknown and inactive logins still verify a dummy (made within its reservation) and are counted; a correct password whose stored hash fits logs in without the rehash (AuthStats::rehash_skipped); a user whose stored hash another node made over this node’s reservation is refused through this node like a wrong password, “Access Denied” and counted, logged aterrornamingadmission.hash_memory_kib. Give every node the sameadmission.hash_memory_kib. - Sessions per user. A user keeps at most 100 sessions; the login past that ends the oldest, with the session-end hooks.
- Trusted address. The per-login cooldown (failures of one login from any address) never refuses the correct password from an (address, login) pair that logged in successfully within the last 30 days; any other address stays under the cooldown, and wrong passwords from the trusted pair still count. The address cooldown applies to everyone. A login keeps at most 16 trusted pairs: the oldest go first. A success clears no failure counter: they decay.
- Throttle rows. Their keys are an HMAC under a key derived from
database.secret, never a plain hash of the login or the address;Auth::throttle_keygives the key of a row. Rotating the secret resets the counters. - Password and login changes end sessions. Setting a password, or renaming the user’s
login, ends every session of the user at once, with the hooks, the caller’s own included (a plannedchange_passwordwill keep the current one). A login that rehashes the stored password (an imported Odoo hash, or raised hashing parameters) sweeps obsolete tokens against the current user fields and trusted key source in independently committed batches of at most 1,000 sessions. Concurrent valid sessions survive, including credentials that cycle back to a previous value. Each batch locks user, key source, then sessions; malformed tokens, missing/malformed keys or an unknown key id stop that batch without deleting any of its rows. Earlier batches may already have committed. The sweep stops with a counted/logged error after 100 full batches; token validation still governs access. Writing passwords for many users hashes them on every permit of the pool but one at once (the one left keeps logins going), inside the writing transaction. - Logout takes an id, which is not a secret.
Auth::logout(id)ends the sessionid. Session ids appear in CSRF tokens and audit rows, so pass only the id of the session the request just checked, or, on a devices page, an id you have checked belongs to the requesting user; never an id the client merely sends.
Overriding _check_credentials
Section titled “Overriding _check_credentials”Override it to add a condition to every login of a user, and call super for the check itself. The method
runs as the user being logged in, in superuser mode, in a REPEATABLE READ transaction of its own that the login
keeps open through the check (it commits with a success, so the override’s writes stand, and rolls back with a
refusal); return an error to refuse. Without an override the login checks the password with no transaction at
all, so an override costs a held connection for the length of the hash: keep the check itself cheap.
use erp_sdk::auth::{AuthInfo, CheckEnv, Credential, access_denied};use erp_sdk::prelude::*;
#[methods(ResUsers)]impl ResUsersLoginHours { #[method(override)] async fn _check_credentials( this: &RecordSet<ResUsers>, tx: &mut Transaction, credential: Arc<Credential>, env: CheckEnv, sup: Super, ) -> Result<AuthInfo> { let info: AuthInfo = sup.call(tx, this.as_records(), (credential, env)).await?; if !within_login_hours(tx, info.uid()).await? { // the same refusal as a wrong password: the client cannot tell them apart return Err(access_denied()); } Ok(info) }}Rules:
- Refuse with
access_denied()(kindAccessDenied, text “Access Denied”): the attempt counts as a failure for the cooldown. Any other error fails the login with that error and rolls its transaction back; it is not counted as a failed attempt. - Never log or put into an error the password, the stored hash or the
Credential(itsDebugis redacted). Credentialis#[non_exhaustive]: match it with a_arm. OnlyCredential::Passwordexists today; other credential types are planned.- The failure counting, the cooldown and the timing of unknown logins are the framework’s; an override does not need to (and cannot) change them.
Adding a login cooldown rule: _on_login_cooldown
Section titled “Adding a login cooldown rule: _on_login_cooldown”Override res.users._on_login_cooldown(context) to ask for a stricter cooldown than the
base.login_cooldown_* settings (ADR 0076). Call super, then add rules to the policy it returns:
#[method(override)]async fn _on_login_cooldown(this: &RecordSet<ResUsers>, tx: &mut Transaction, context: LoginCooldownContext, sup: Super) -> Result<LoginCooldownPolicy> { let policy: LoginCooldownPolicy = sup.call(tx, this.as_records(), (context,)).await?; policy.with_login_rule(3, Duration::from_secs(300))}- The attempt is refused when the core rule or an added rule is in force, using the same shared
failure counters; a policy cannot disable a core rule, accept a credential or keep a counter.
Rules combine along a
superchain by keeping the stricter threshold and the longer duration. Bounds: address threshold1..=1_000_000, login threshold1..=4_000_000, whole seconds1..=604_800; anything else is aValidationerror naming the field. - An added login rule keeps the trusted-pair exception; an added address rule applies only with an actual client address.
- The hook runs once per attempt (and again before a restart), before any credential work, as the
superuser in a read-only transaction that is always rolled back. It is told only the
submitted login (which may name no user), the client address and the current settings, never a
user id, hash or password. A hook that looks the login up in the database makes known and unknown
logins take different times: that is yours to avoid. Do not make external calls and keep it short: it holds a login admission permit and a
connection while it runs. One call has a deadline (
AuthConfig::cooldown_hook_deadline, default 5 s, 10 – 60,000 ms): past it the task is aborted and the attempt refused like any hook failure. Await, do not block the thread: a blocking call is not interrupted. - A hook error, panic or invalid rule refuses the attempt (
LoginError::Failed); nothing is verified or counted. The caller gets a fixed text; your error goes to theerp::authlog. - The pre-filter and over-long credentials are refused before any database work and never call the hook.
Extending user login lookup: _get_login_domain and _get_login_order
Section titled “Extending user login lookup: _get_login_domain and _get_login_order”ADR 0075 defines these hooks; docs/adr/0126-login-rollout-admission.md (ADR 0126) defines
serving admission. Auth::new refuses a registry that overrides either selection hook with
ErrorKind::Programming and custom login selection requires an active membership-bound rollout.
There is no exact-login fallback. Served composition uses Auth::with_membership(orm, config, pool, member.admission()), derived from an actual registered membership. It validates helper
publication, schema, database, binary declaration and registry association. Starting membership
may compose Auth; authentication still requires live serving admission and an enabled rollout.
The native binary declares auth.login_principal, version 1, as part of its combined identity.
Registration precedes composition, and a changed catalogue requires membership restart. Operators
follow the rollout procedure to publish isolated
NOLOGIN-owned helpers, approve exact eligible digests and confirm legacy-service fencing.
An ordinary node rollout window never enables this feature.
Every attempt retains its original feature generation through hashing, restart and detached verdicts. Successful finalization revalidates it under protection held through session commit; disable waits for earlier protected commits. New custom authentication refuses while disabled. While enabled, a bound base-only peer also applies principal accounting, and an unbound base service refuses before real verification. Failed guesses remain counted after disable/disconnect; pre-disable sessions retain normal session semantics.
Selection plus credential overrides preserve the SESSION refusal. Membership-bound credential overrides also refuse until SESSION, including when disabled, to avoid acquiring feature protection after an override’s user locks. This is an explicit native compatibility limit; the existing unbound inactive base path retains its query/flight contract.
Integration fixtures can explicitly call
erp_security::auth::test_support::login_selection_auth when the default-off
test-support feature is enabled. This helper bypasses only the rollout
refusal; model, schema, settings, pool and unsupported credential-composition checks
still apply. Enabling that feature alone does not change Auth::new. The helper is
fixture-only, is not re-exported through the SDK and is not an activation mechanism.
Plan construction and candidate execution are internal to the service; addon hooks produce
raw domain/order values which the framework admits before compiling or executing them.
Candidate selection domain: _get_login_domain
Section titled “Candidate selection domain: _get_login_domain”The hook receives LoginLookup, not a String. It returns LoginDomain; the
framework admits the returned AST against the pinned registry before compiling
SQL. Native hooks are trusted deterministic metadata functions. ORM database,
record, transaction and changed-environment effects are forbidden in their scope;
this does not sandbox native Rust’s direct I/O.
The following integration fragment uses the checkpoint’s actual API. The addon
must declare login_alias as a stored char field on res.users; imports and its
model declaration are omitted. This fragment has not independently been compiled
as a guide example; the executable alias/super fixtures are in
crates/erp-test-models/src/test_login_selection.rs.
#[method(override)]async fn _get_login_domain( this: &RecordSet<ResUsers>, tx: &mut Transaction, lookup: LoginLookup, sup: Super,) -> Result<LoginDomain> { let base: LoginDomain = sup.call(tx, this.as_records(), (lookup.clone(),)).await?; let alias = Domain::condition("login_alias", Operator::Eq, lookup.as_str()) .map_err(|_| Error::validation("invalid alias selection domain"))?; Ok(LoginDomain::custom(Domain::or([base.domain().clone(), alias])))}Supported fields are physical local stored id/integer, boolean, char and static
selection columns. Related/computed/search-callback, inherited, translated,
company-dependent and relational fields are refused. Supported operators are
=, !=, <, <=, >, >=, in, not in with scalar operands; membership
requires a collection. The ordinary domain optimizer/compiler supplies null and
Boolean semantics. No raw SQL, dynamic time/context expression or pattern operator
is admitted. Base domain construction is fallible: LoginDomain::exact_login(...)
returns Result<LoginDomain>.
Default ceilings derive from QueryLimits: 65,536 plan bytes, depth 16,
512 conditions, 128 distinct fields and 8 effective order terms; auth also bounds
AST nodes at 1,024 and membership elements at 512. Core predicates and ordering
share the aggregate admission budget. Witness transfer is independently bounded.
Exact aggregate-boundary proof is still pending. Normal ORM transaction deadlines
apply; this checkpoint does not establish a separate 500 ms selection deadline.
Core selection always enforces active = true, total ordering and LIMIT 1.
Constant/empty domains retain domain semantics and the core active filter. An
unknown/inactive candidate uses dummy password verification; malformed hook
results return an error rather than silently selecting through the base path.
No timing-equality or identical-accounting claim is made.
Resolution ordering: _get_login_order
Section titled “Resolution ordering: _get_login_order”An addon with a stored integer login_priority may return this order. As above,
this is an integration fragment whose omitted model/import context must be supplied.
#[method(override)]async fn _get_login_order( _this: &RecordSet<ResUsers>, _tx: &mut Transaction, _sup: Super,) -> Result<LoginOrder> { Ok(LoginOrder::custom(vec![LoginOrderTerm::desc("login_priority")]))}The framework validates the fields, refuses duplicate/empty ordering and appends
id ASC when id is absent. An explicit id direction is retained. The effective
order, including that tie-breaker, must fit the ceiling of eight terms.
Phase B witness validation and restart semantics
Section titled “Phase B witness validation and restart semantics”Password hashing runs outside a database transaction. After a successful verify,
custom selection opens a READ COMMITTED finalization transaction, protects its
original active rollout generation, then takes SHARE ROW EXCLUSIVE on res_users,
reruns the hooks and ordered selection,
compares the complete plan/winner witness, and retains the guard through
rehash/session persistence and commit. A mismatch restarts the entire attempt
once; a second mismatch denies it. Tokens use canonical stored login, not alias.
The checkpoint’s focused tests prove the guard exists at session insertion and
exercise a competitor reordered while hashing; broader race cases remain open.
Failed guesses write address, submitted-login and selected UID counters atomically. A wrong password creates no trusted UID/address pair. The UID cooldown is checked before password verification and survives alias/address changes; only exact UID/address trust can exempt that dimension. Existing address protection remains. Old counters are retained during schema migration, and bounded GC now covers both principal kinds. The rollout report records process-level shared-budget and disable coverage; native alias HTTP acceptance, broader trust-expiry/cap coverage and whole-case certification remain open.
Both constructors refuse selection overrides combined with _check_credentials
overrides for now; that composition error takes precedence over
the unbound custom-selection refusal. Digest-bound membership and activation are
implemented. Remaining race coverage, boundary and type matrices, the full mapping,
parity regeneration and compiled examples are still open. The functional page is
docs/user/login-selection.md. The operator procedure is available at
Custom login selection rollout.
This checkpoint does not establish whole-LOGIN acceptance or deployment readiness.
Adding fields to the session token: _get_session_token_fields
Section titled “Adding fields to the session token: _get_session_token_fields”A session’s token covers id, login, password and active of its user, so changing any of them
ends the user’s sessions at their next check. An addon that adds a credential factor (a TOTP secret,
a linked account’s token) adds the name of the user field to that set (H58 TOKEN, SPEC-AUTH-041
and SPEC-AUTH-042; decision: ADR 0155). Override
res.users._get_session_token_fields, call super, and add names:
#[method(override)]async fn _get_session_token_fields(this: &RecordSet<ResUsers>, tx: &mut Transaction, sup: Super) -> Result<SessionTokenFields> { let fields: SessionTokenFields = sup.call(tx, this.as_records(), ()).await?; fields.with_field("totp_secret")}- Names only. The result is a bounded set of names: at most 16 added fields, each
[a-z_][a-z0-9_]*of at most 63 bytes. The hook returns no SQL, no value and no per-user decision; the framework reads the values in the statements that already read the base fields (no extra round trip) and encodes them. The type cannot remove a base field, and a duplicate (a base field, or a name added twice along the chain) is aValidationerror, not a silent merge. - Resolved once per registry. The hook runs once, when the
Authservice of the registry is built, as the superuser in a read-only transaction that is always rolled back, where any query or write is refused, with a bound (AuthConfig::with_token_plan_hook_deadline_ms, default 10 s, 10 – 60,000 ms). It is not called per login or per request. The service is not built, and nothing is issued or checked, when the plan is refused. There is no fallback to the base fields: a hook error or panic, a name that is no field ofres.users, a field that is not stored or is translated or company dependent, a type other than boolean, integer, selection, many2one (the id) andcharwith asizeof at most 16,384 (sofloat,monetary,date,datetime,textand acharwithout a size are refused: their text form depends on session settings or their size is not bounded), and anyone2manyormany2manyfield, give aProgrammingerror naming the field. Odoo’sauth_totpdeclarestotp_secretas a non-stored computedCharover a hand-made column (odoo/addons/auth_totp/models/res_users.py:33,:40-41); that shape is refused, a native TOTP addon declares a stored, sizedchar. An install-time check of the plan is planned. Relation fields (a passkey list) are not supported yet. - What changes a token. A change of an added field’s value, including
NULLto a value and back, ends the user’s sessions at their next check, on any node, with the sameSessionExpiredanswer (“user is not connected”) as any other mismatch. A field that isNULLadds nothing to the token (Odoo’s rule), so installing an addon does not log anyone out until a value is set. Values are read from the primary at every check; nothing caches them, so another node sees a change at its next request. A value over 64 KiB is refused with an error, never cut. - Everywhere the same plan. Login issuance (a factor changed while the password was being verified makes the login restart and read it again), the session check (also the cookie checked beside an API key), the current session after the user’s own password change or an administrator reset, and the cleanup after a password rehash all use it.
- Who may write the field. Anyone allowed to write an added field can end that user’s sessions
(and a write by the session’s own user changes the token under it). Give the field restrictive
groups, as Odoo does for its secrets. Do not add a field the framework updates on every write, such aswrite_uid: any write to the user, by anyone, would then end all of that user’s sessions. - Not combined with custom login selection yet. An addon that overrides
_get_login_domainor_get_login_ordertogether with a plan that adds fields makes the service refuse to start with an error saying that token fields and custom login selection cannot be combined yet. - Mixed versions. A node whose plan differs from the one a session was issued under computes a
different token for users whose added fields are not
NULLand refuses the session like any mismatch (the row is deleted; the user logs in again). Upgrade all nodes of a database together.
Hashing a password yourself
Section titled “Hashing a password yourself”Writing password on res.users hashes it. When an addon stores another secret the same way, use
hash_password(tx, password) (the database’s current parameters, on the database’s hashing pool: the one
handed to its Auth, so every hash of the ORM lineage shares one bound). For direct verification, retain
auth::pool::for_env(env) and use its PoolBinding::run around StoredHash::parse(..)?.verify(..).
That lease survives cancellation until the blocking hash finishes, including data loading before the
first Auth. Never hash on the async runtime; the pool bounds concurrent CPU and memory use.
Ending sessions: the session-end hook
Section titled “Ending sessions: the session-end hook”An addon that keeps rows per session (push subscriptions, devices, websocket presence) registers a hook. It
runs in the transaction that deletes the session rows, for every reason: logout, archiving or deleting the
user, setting the user’s password, a rehash at login (sessions with obsolete tokens), the per-user cap of 100, a
refused check, collection of expired sessions. Delete your rows there; returning an error fails the
whole deletion, so the session survives with your rows. Use raw statements only (query, execute,
batch), never the record API. The dispatcher enforces this for every caller with
Transaction::raw_statements_only(), including user changes inside REPEATABLE READ
transactions. Record access fails with Programming; READ COMMITTED retains its existing
isolation-specific diagnostic. Cached reads, prebuilt query execution, stream advancement,
method continuations and explicit ORM flushes are restricted too. The caller’s prior
restriction is restored when the hook returns, errors or is cancelled; existing transaction
cancellation and rollback requirements still apply. Transaction metadata and projections of
values already held by native code remain available. This is a consistency contract for
trusted native addons, not a Rust or SQL sandbox (ADR 0078).
use erp_sdk::BoxFuture;use erp_sdk::auth::SessionEnd;use erp_sdk::prelude::*;
erp_sdk::auth::session_end_hook!(DROP_DEVICES, addon = "my_addon", run = drop_devices);
fn drop_devices<'a>(tx: &'a mut Transaction, ended: &'a SessionEnd) -> BoxFuture<'a, Result<()>> { Box::pin(async move { let ids: Vec<String> = ended.sessions().iter().map(|s| s.id().to_text()).collect(); tx.execute("DELETE FROM my_addon_device WHERE session_id = ANY($1)", &[&ids]) .await?; Ok(()) })}ended.reason() tells why (EndReason::Logout, Revoked, Expired, CredentialChanged for a password
set or a rehash at login, OverCap for the per-user cap). The hook of an addon that is not
installed in the database never runs. Keep the work set-based: one statement for all ended sessions, never a
loop of per-session queries (collection ends up to 1,000 sessions per transaction).
ir.config_parameter
Section titled “ir.config_parameter”Use the typed API, as Odoo 20 does: get_str, get_int, get_float, get_bool and set_str, set_int,
set_float, set_bool, from Rust (records("ir.config_parameter")?.call(tx, "get_int", (key, default)))
or over JSON-2. A missing key or an empty value gives the default; a value of the wrong type is a
Validation error naming the key (Odoo returns the default and logs a warning; we fail loudly, BUG-083 for
the setter). Setters return the previous value only after model and existing-row write and read
authorization, including a no-op. Missing keys still require normal create permission. Malformed-value
errors name the key and expected type and never include the stored value.
database.secretcannot be read, searched, exported or written by any caller without full elevation, whatever the groups (ADR 0037 decision 8): it signs the session tokens. In-process code that needs it runs in superuser mode. Never copy it into another record, a log or a response.- The keys
basecreates (database.secret,database.uuid,database.create_date,base.login_cooldown_after,base.login_cooldown_duration) cannot be renamed or deleted. - Every write invalidates the authentication settings cache on every node, so a changed cooldown or session limit applies to the next login or check without a restart.
Checking, rotating and touching sessions
Section titled “Checking, rotating and touching sessions”Auth::begin_session(&secret, CredentialOptions::new()) (erp_orm::CredentialOptions, re-exported) opens the request’s transaction with the session
check in its opening flight (CredentialOptions carries the context, limits and read intent; nothing else
is accepted). Auth::rotate and Auth::touch(&[Touch::new(id).addr(ip).agent(ua)]) are one READ COMMITTED
round trip each, outside the request’s transaction; a touch skips rows another transaction holds, and two
rotations of one secret converge on one successor (the second returns None). A row whose key id this node
does not hold is refused but kept (another node may hold the key during a rollout).
Sessions in tests
Section titled “Sessions in tests”erp_testkit::Harness creates the core tables of the crates linked into the test, the session and
throttle tables among them, as Orm::sync_schema does on a real server. The helpers in
crates/erp-test-models/tests/auth_support/mod.rs show a database ready for logins (the init hooks of
ir.config_parameter and res.users, an administrator, users with passwords).
Native lifecycle authorization
Section titled “Native lifecycle authorization”Trusted composition can call Auth::check_session_in(&mut tx, &secret) when ModuleSystem owns the
primary transaction. Its opaque SessionAuthorization exposes the current human principal/session
and has_groups; the policy is compiled from that transaction’s rows, even when the engine’s root
policy is System-only. It does not change transaction authority. Only the native lifecycle engine
binds the validated actor before schema/data effects. Addon RPC code must use its existing caller
transaction and must never use this seam as an elevation or install API.
Identity confirmation and a self-service password change
Section titled “Identity confirmation and a self-service password change”Auth::check_identity(Some(cookie_secret)) checks the current HTTP session’s identity window.
IdentityCheck::Required.action() returns the typed res.users.identitycheck window descriptor;
the adapter renders confirmation and resubmits its fixed operation. None is refused with the
SEC-041 no-HTTP error. An identity observation is never authority to skip the operation’s own check.
Auth::confirm_identity(cookie_secret, password, client) verifies that session’s user through the
existing credential-dispatch and shared-throttle path and stores confirmation in PostgreSQL. Pass
ClientAddr::Known from an HTTP adapter. Confirmation is per session, not per user, and expires at
ten minutes; future timestamps are not accepted. It does not create a login session or upgrade a
legacy hash. Failed guesses are recorded even when the caller disconnects during verification.
Auth::change_password(Some(cookie_secret), new_password) takes the same admission before opening
any transaction. A stale identity returns IdentityCheck::Required without mutation. Success returns
Verified after committing the password, the current session’s refreshed token and the revocation of
other sessions together. The cookie and stable session id survive. A session-end hook failure rolls
all of that back. Concurrency errors require retrying the complete service operation.
This service owns its transactions: invoke it before opening an ordinary RPC transaction. It is a dedicated self-service path, not a call to the password field’s inverse. Credential-check overrides participate in confirmation and session-end hooks participate in revocation; password-field inverse overrides do not participate. Ordinary password-field writes retain their revoke-all behavior. The HTTP/RPC adapter, transient wizard model and rendered UI are not supplied by this typed API.
Identity confirmation and password change reject more than 100 stored sessions for the current
user with Validation, including expired/pending rows. End excess sessions and retry. The bound
is checked under the user lock before confirmation/password/token mutation; password change
revokes every other admitted session and runs its hooks in the same transaction.
Native API key issuance
Section titled “Native API key issuance”erp_sdk::auth::IssueRequest::new validates a typed subject, name, kind, scope
and optional naive-UTC expiry. The store currently admits only KeyKind::User
and KeyScope::Rpc: unrestricted models and methods, writable access, subject
capabilities. There is no JSON-to-authority deserializer. Agent and service
requests return the ADR 0037 principal gate; MCP user requests are refused.
Labels are nonempty after trimming and at most 128 bytes.
Addons that renew or create keys for the current user should call
erp_sdk::auth::apikey_manage::generate, which validates the presented key,
scope and policy and then delegates here. erp_sdk::auth::issue itself audits in the
caller’s transaction: it writes one api_key.issued event built from the inserted row, and
the transaction needs an OperationIdentity, otherwise the commit fails with an audit
error and no key survives. There is no unaudited issuance path.
Pass the tenant’s ApiKeyHasher to erp_sdk::auth::issue in the caller’s
transaction. Rebuild the hasher after database.secret rotation; never reuse
another tenant’s material. A subject-row version fence precedes policy/count
reads. The database supplies the clock and effective groups. Non-system subjects
must supply an expiry within their groups’ maximum duration (one day when the
maximum is zero or absent). Persistent keys are reserved for system subjects.
The native store handles issuance. Programmatic management delegates to it after
validating the current user and the supplied key; native verification and scheduled
collection use the same database expiry semantics.
Use Orm::run for whole-transaction serialization/deadlock retry. Construct the
one-time secret inside each attempt; never produce a response, log or external
effect within that retryable closure. Only return the IssuedApiKey from the
committed attempt. Explicit transactions surface Concurrency unchanged: roll
back and retry the complete unit of work, never only its INSERT.
The issuance result and its secret have no Debug, Display, Clone or serialization
implementation. After commit succeeds, consume the result with into_secret(),
then explicitly borrow expose() for the one-time response. Do not expose any
secret before successful commit. Rollback or connection loss revokes pending
issuance automatically. Secret storage zeroizes on drop.
base.programmatic_api_keys_limit imposes a tenant-local active-key cap per
subject, defaulting to 10 when absent; a present value must be positive.
The predicate includes persistent keys and expiration_date >= database time. Malformed configuration
refuses issuance. The caller must belong to base.group_system, or the strictly
parsed base.enable_programmatic_api_keys setting must be true. Delegation requires actual system
group membership; sudo/core elevation alone does not grant it.
Public management endpoints and credential checks are planned.
Generic ORM create/write cannot bypass issuance.
Issuance, revocation and expired-key collection are recorded in the audit trail with typed events
(erp_sdk::audit::AuthEvent) in the same transaction as the change; see the audit trail. The
events carry key ids and enums, never a key, a digest, a display prefix or a key name.
Native API key verification
Section titled “Native API key verification”Transport integrations authenticate with Auth::begin_api_key(ApiKeyRequest, CredentialOptions).
Construct the request with the submitted credential, exact KeyScope and the client IP resolved
by the trusted proxy boundary. Optional .uid(...) constrains the expected subject; optional
.session(...) checks cookie precedence. Keep the input out of diagnostics and retain it only
for the request and its bounded RPC retries. The returned transaction is authorized by the key
row and the current subject’s groups and companies. Finish it with commit or rollback.
A user key’s validated scope also supplies Actor::ApiKey; a human session without a key has
no key actor. Native user keys currently use the subject’s capabilities and unrestricted model
and method scope. Agent and service keys are refused until scoped principals exist. Imported legacy
40-hex credentials (rows carrying legacy_index and legacy_hash, ADR 0037 decision 5) verify
with their original PBKDF2-SHA512 hash under the same route audience, expiry, active-user, uid and
kind rules as native keys. Re-issue a native key to stop paying the hash cost; deleting the row
(erp auth emergency-revoke --key <id>) refuses the key on the next request on every node.
res.users.apikeys.last_used_at records when a key was last accepted. It is a coarse signal,
not an access log: it moves at most once an hour per key across the whole cluster, using the
database clock (naive UTC), and a key never used has it empty. The write is bookkeeping. It
runs outside the request transaction, never touches write_date, and a failure is logged at
warn with the key id and counted, never raised to the request.
ApiKeyBegin.last_use carries the work for a caller of begin_api_key. It is Some only when
the key is due, and it is an ApiKeyLastUse ticket: dropping it launches the write, so hold
it until the request transaction has ended (commit or rollback), then drop it. Dropping it
earlier is safe except for one case: the request transaction is REPEATABLE READ, so any such
transaction that took its snapshot before a write of this key committed, and then updates,
deletes or locks (FOR UPDATE) that key row, gets a serialization failure (40001). That is the
same request when it dropped the ticket early (a key revoking itself), and also another request
that revokes or changes this key while a write from a different request commits in between; the
RPC layer retries such a failure as a whole attempt. If you call begin_api_key more than once
for one request (a preflight, then the real opening), keep the first ticket and call
ApiKeyLastUse::discard on the others: it throws a ticket away without writing. A ticket
dropped while the runtime shuts down may record nothing. Ignoring the field entirely is also fine; the ticket is
dropped with the ApiKeyBegin. One write per process and ORM lineage runs at a time; a ticket
dropped while another write runs is skipped (AuthStats::last_use_skipped) and the key’s next
use is due again. Outcomes are in AuthStats::last_use_writes, last_use_noops (not due any
more, row locked or deleted) and last_use_errors.
Verification reads tenant-primary PostgreSQL in the opening transaction flight. Acceptance is
never cached: revocation, expiry and user deactivation apply to the next transaction on another
node too. Only tenant settings and cryptographic derivation are cached by settings generation.
A stale or invalid optional cookie does not grant authority and does not extend or delete its
session. A valid cookie belonging to another user raises Access with
Session user does not match the used apikey. A failed key never falls back to cookie access.
The HTTP adapter first uses the existing bounded process address prefilter once per external bearer request; RPC rechecks do not consume additional flood tokens. The shared tenant address throttle covers invalid native bearer attempts. Cooldown and database
failures propagate; they cannot turn into authorization. ApiKeyCooldown is the typed error source
used by the HTTP adapter to return 429 and Retry-After. Malformed, unknown, revoked, inactive-user,
expired and wrong-scope native keys return AccessDenied with Invalid apikey. The HTTP adapter
returns 401 and WWW-Authenticate: bearer. Submitted credentials are never included in errors.
The canonical HTTP entry point is POST /erp/json/2/<model>/<method> with a single Bearer
Authorization header. Native bearer requests are stateless. Cookie JSON-2 requests retain their
same-origin checks. Bearer requests with an Origin must name the configured public origin; no
cross-origin allowlist is configured by this slice. Module installation continues to require a
human session and its existing CSRF checks. No legacy XML-RPC or JSON-RPC endpoint is added.
Password-change integration (ADR 0138)
Section titled “Password-change integration (ADR 0138)”The browser password operations are a closed, request-local interface. They run after RPC parsing,
exposure and binding but own their sensitive authentication transactions. Never call the Auth
service from an ordinary model transaction. Identity authority is the presented browser cookie;
context, caller-supplied user IDs, API keys and a prior principal snapshot do not replace it.
Own changes call Auth::change_password after Auth::confirm_identity when required. The legacy
res.users.change_password(old_passwd, new_passwd) explicitly verifies its old password on every
call. Administrator resets use validated PasswordReset inputs and a fresh manager authorization.
They do not grant general user-write permission. Every target must be visible to the actor under
res.users’ generated company restriction with all of the actor’s companies active (through its
share escape this scopes portal users only); an actor without base.group_system also needs every
target, internal users included, to share one of its companies; a target holding base.group_system
needs an actor holding it; the superuser row is never a target (ADR 0138 Amendment 1). These run
through SessionAuthorization::check_reset_targets when the wizard opens, in Auth’s preflight and
after the final locks; a refused target answers like a missing one
(erp_security::auth::missing_reset_target). Reset lines (change.password.user) are created only
by the wizard open, in superuser mode: the line model’s create refuses every other creation with the
same answer, so addon code cannot add a line through create. The visibility call underneath,
Transaction::visible_under_company_restriction (ADR 0190), takes an explicit policy, principal and
company set; it is a check for core services, not an addon API. An empty administrator line skips mutation;
password byte and selected-user/session limits fail before partial effects. The current actor’s
cookie is retained when its own password changes; affected other sessions end through the existing
transactional hooks.
Wizard secret fields are nonstored and read empty. Do not generically save them: send only the fixed operation parameters documented in ADR 0138. No password enters a persisted replay request, action context, tracking or debug output. Managed submissions refuse Idempotency-Key explicitly; a missing commit answer is uncertain and must never trigger automatic replay.
The web client implements this in addons/web/static/src/client/password-flow.ts. The
three submissions (res.users.identitycheck.run_check, change.password.own.change_password,
change.password.wizard.change_password_button) skip the save: the wizard dialog validates the form and
sends the typed values as operation parameters (password; new_password and confirm_password; changes
as {line_id, new_passwd} per selected-user line). The four password models never send an edit to onchange.
When an operation answers with the identity confirmation, the client keeps that operation in memory and sends
it again, once, after the confirmation succeeds; the server stores no callback. The set is closed: an addon
cannot add a password submission to it.
Native base-only managed entry implementations are the initial supported composition. A hidden
entry stays hidden; additional implementation overrides are refused explicitly, rather than
silently skipped. Credential and session-end hooks retain their current dispatch. As in the
existing self-change service, Auth-owned password mutation does not dispatch _set_password
overrides. No broader addon parity is claimed.
Native API key management
Section titled “Native API key management”erp_sdk::auth::apikey_manage::generate(tx, key, scope, name, expiry) verifies an
active native user key owned by the transaction’s current user, with the requested
scope, then returns IssuedApiKey. Commit before exposing its secret. It creates
a replacement without deleting the old key: store the new credential securely,
verify it, then call revoke(tx, old_key). Revocation deletes the row atomically;
every replica rejects it on its next authenticated transaction. Deletion invalidates
the apikeys named cache; signal-enabled commits publish that generation atomically. Generic create,
write and unlink cannot bypass these APIs, including under sudo. Only native
unrestricted user keys with rpc scope are admitted in this slice. Agent/service
and imported legacy credential support retain their existing future-task gates.
The public model methods are res.users.apikeys.generate(key, scope, name, expiration_date) and res.users.apikeys.revoke(key). Generation returns the new
credential string once; revoke returns true. A refused key answers AccessDenied:
“The provided API key is invalid or does not belong to the current user.” from generation (Odoo’s
text), “The provided API key is invalid.” from revoke. Revoke deletes only an rpc key of the
current user and gives that one answer for an unknown, foreign, expired, wrongly scoped or malformed
key. This differs from Odoo on purpose (ADR 0037 decision 5): Odoo lets a system user revoke any key,
ignores the scope and answers a foreign key with a different error; one uniform answer tells a
caller nothing about other users’ keys. Generation also checks the presented key before the
active-key limit, where Odoo checks the limit first. expiration_date accepts a UTC
Odoo date/datetime string, or null for a system subject’s persistent key. Invalid
dates, wrong argument types, unknown arguments and invalid metadata fail. Body
size, argument binding, authenticated principal scope and write-effect admission
remain the normal RPC boundaries. Idempotency-Key is explicitly refused for
generation before execution: the generic replay store must never persist a
credential response. Other methods retain their existing replay behavior.
Management requires base.enable_programmatic_api_keys unless the actual current
user belongs to base.group_system. Malformed present configuration fails loudly.
The tenant-wide active-key limit and subject lifetime policy apply to replacements
as they do to issuance; renewal therefore needs one free slot before revoking the
old key. Possession of another user’s credential does not confer ownership. A user
may revoke their current key; its current request commits and subsequent requests
fail. No accepted-credential cache or plaintext key store is introduced. Never log
request bodies or credential responses; server responses use Cache-Control: no-store.
collect_expired(tx, limit) is a core-System-only raw-SQL primitive, with a bound
of 1 through 1000 rows. The existing authentication collector invokes one batch per
run, under its durable scheduling fence, and reports GcReport.api_keys. A partial
expiration index supports selection. Concurrent collectors skip locked rows;
rollback makes work available to a later collector. Persistent keys and keys at
or after the inclusive database expiry boundary remain untouched. No additional
service or per-node accepted-key cache is needed. Product performance evidence is
DEFERRED_PERFORMANCE under ADR 0065.
Lifecycle audit events (ADR 0151)
Section titled “Lifecycle audit events (ADR 0151)”Every key lifecycle change writes a typed event into the transaction’s audit row
(erp_event.ir_audit_entry), so the event commits or rolls back with the key itself
and never needs a hand-written audit statement. The events are built only from ids,
closed enums, flags and counts (erp_orm::audit::AuthEvent); no constructor takes a
key string, digest, display prefix or key name, so none of them can reach the trail.
| Operation | Event | Notes |
|---|---|---|
apikey_store::issue (so also apikey_manage::generate) | api_key.issued | key id, owner, creating user, kind, route, expiry, built from the inserted row; allowlist lengths are null for user keys; exactly one event per key |
apikey_manage::revoke | api_key.revoked | cause is self when the transaction’s own key is the revoked one, programmatic (naming the revoking key) when another key revoked it, owner for a session without a key actor (an impersonation chain is looked through to the original actor) |
apikey_manage::collect_expired | api_keys.collected | one event per committed batch naming exactly the deleted ids (at most MAX_COLLECTED_KEYS, 1000), row origin auth; an empty batch writes nothing. The collector loops batches until a short one, bounded by its per-run row cap |
An operator can also end keys and sessions on the owner connection with erp auth emergency-revoke
(cli.md). That path writes an emergency.revocation header and one
api_key.revoked event per key with cause emergency, in its own cli row, and it works while the runtime role
cannot write audit rows; every revocation made through the runtime role still fails when audit is unavailable.
See the audit trail.
A renewal is two operations and therefore two events: generate records the issuance,
and the later revoke of the old key records its own event (cause self or
programmatic; the renewed cause is reserved for a single-call replacement flow
that this slice does not provide). Audited writes need an OperationIdentity on the transaction (RPC and the
collector supply one; test harnesses opt in with identify_transactions). If the audit store is not ready or the audit row cannot be
written, the operation fails as a whole and the key change rolls back; there is no
silent fallback. Collection keeps its cluster-wide exclusion from the existing
authentication collector’s durable PostgreSQL fence plus FOR UPDATE SKIP LOCKED;
the audit event is written in the same batch transaction. Missing functional page:
docs/user/api-keys.md (the audit trail reader is separate planned work).
Operator configuration and session policy (ADR 0200)
Section titled “Operator configuration and session policy (ADR 0200)”AuthConfig now holds six node admission/execution options, loaded from server [auth] TOML.
The actual served constructor and registry rebuilds receive the validated node configuration.
The three former session timing builders/getters are removed: use the database’s validated
AuthSettings::session_policy() snapshot, with SessionPolicy timing getters. Do not construct a
node-specific session policy or cache one beyond its config_parameter generation.
Database System Parameters (whole seconds, changed by a Settings administrator in Technical → System Parameters):
| Key | Default | Minimum | Maximum |
|---|---|---|---|
sessions.touch_interval_seconds | 60 | 1 | 3600 |
sessions.rotation_interval_seconds | 10800 | 60 | 86400 |
sessions.rotation_grace_seconds | 120 | 5 | 600 |
Touch must be shorter than effective sessions.max_inactivity_seconds; grace must be shorter than
rotation. A refusal names both keys and values. Missing, null and empty values restore defaults;
clearing or deleting a key also checks the resulting pair. Change the longer interval first when
increasing both, or the shorter one first when decreasing both.
Node settings (quoted dotted keys in server [auth] TOML, applied after restart):
| Key | Default | Minimum | Maximum |
|---|---|---|---|
limits.credential_bytes | 1024 | 64 | 4096 |
throttle.login_burst | 20 | 5 | 1000 |
throttle.login_rate_per_sec | 2.0 | 0.1 | 1000 |
throttle.table_entries | 4096 | 64 | 1048576 |
limits.cooldown_hook_deadline_ms | 5000 | 10 | 60000 |
limits.token_plan_hook_deadline_ms | 10000 | 10 | 60000 |
Only the refill rate may be fractional. These values bound input before database work, local prefilter memory/work and local hook execution; they may differ across nodes. Shared database cooldown remains authoritative. Wrong types, unknown keys, non-finite rates and out-of-range values stop startup by name, without raw input in diagnostics. Zero never means unlimited.
Upgrade: remove startup_limits."session.touch_interval_secs" from every node file before the
restart. Use the database touch parameter instead; there is no automatic import. Restart nodes
together; mixed-version policy compatibility is not claimed. Restore the previous binary and
configuration together if admission fails. Existing auth hooks and hash parameters are unchanged. Standalone Auth callers still supply AuthConfig for local admission;
session timing is read from the database even for these callers. Scalar validate_setting checks
individual ranges; the base parameter model additionally validates the effective correlated policy
under a transaction advisory lock and repeatable-read conflict fence, including create batches, writes, renames, clearing and unlink.
Direct SQL bypasses write validation but invalid stored values are refused at startup/reload/touch.
Touch loads the four non-secret policy parameters in its update transaction. Normal session checks reuse the existing validated settings cache and generation retry; lifecycle and identity checks use their transaction’s policy. This changes touch batch query work; latency and allocation evidence is deferred to milestone end. The grace floor is five seconds so overlapping requests have a positive predecessor window. The database remains authoritative when a node dies.
Exchanging a password for a device API key: POST /erp/session/api-key
Section titled “Exchanging a password for a device API key: POST /erp/session/api-key”Native clients without a browser session obtain an rpc-scoped user API key by posting a closed JSON
object { "db", "login", "password", "device_name" } (Content-Type: application/json, optional
charset=utf-8, body <= 16 KiB, device_name non-empty trimmed and <= 128 bytes) to
POST /erp/session/api-key.
- Authentication & cooldowns: runs non-interactively (
interactive = false) through the sameAuth::authenticatepipeline, pre-filter, dummy hash, and shared address/login cooldowns asPOST /erp/login. Accounts requiring a second factor or pending MFA are refused (403). - Session & quota hygiene: authentication, key issuance (
IssueRequest::at_policy_maximum,AuditOrigin::Auth, correlated with the HTTP request id), and logout of the temporary browser session run inside one cancellation-safe task. If the client disconnects before issuance, no key is issued and the temporary session is still ended. - Response & revocation: returns
200JSON{ "api_key", "expires_at", "uid" }withCache-Control: no-storeand noSet-Cookie. Cross-origin browser requests are refused (403). Clients revoke their own key on logout viares.users.apikeys/revoke.