Skip to content

[20.0][MIG] password_security: migration to 20.0 - #1029

Open
BhaveshHeliconia wants to merge 80 commits into
OCA:20.0from
HeliconiaIO:20.0-mig-password_security
Open

BhaveshHeliconia wants to merge 80 commits into
OCA:20.0from
HeliconiaIO:20.0-mig-password_security

Conversation

@BhaveshHeliconia

Copy link
Copy Markdown

No description provided.

@OCA-git-bot OCA-git-bot added mod:password_security Module password_security series:20.0 labels Oct 5, 2026
@BhaveshHeliconia BhaveshHeliconia mentioned this pull request Oct 7, 2026
12 tasks
marchar1 added a commit to SuperbirdOdoo/server-auth that referenced this pull request Oct 23, 2026
@chaule97

chaule97 commented Dec 1, 2026

Copy link
Copy Markdown

Thanks for the migration. The code changes look right to me, but a few things need fixing before merge.

1. Deleted regression tests

The [MIG] commit deletes several tests that 19.0 added for real bugs, and I can't see a reason for it:

  • test_login.py: test_07_web_login_redirect, test_08_web_login_expire_pass_reset_token_is_valid, and the "user is kicked out" asserts at the end of test_06
  • test_totp.py: test_totp_expired_password_bounces_to_reset (the only test that runs PasswordSecurity2FAHome.web_totp)
  • test_reset_password.py: test_04_reset_password_with_token
  • test_password_history.py: the check that reusing a recent password raises UserError when history=1

I ported them locally to 20.0 using only the same mechanical changes you made to the surviving tests (session_store(), odoo.http.router.db_filter, self.csrf_token(), set_int, fields.Datetime.now()). They all pass on 20.0, and each one fails when the bug it guards is put back. Without them, CI stays green if you:

  • remove invalidate_recordset(["login_date", "log_ids"]) from web_login: the bounce lands on "Invalid signup token". The bug path still exists in 20.0, since _login() reads login_date before _update_last_login().
  • remove logout() from web_login: the user stays logged in after the bounce.
  • make web_totp return early: 2FA users with an expired password are never bounced.
  • break the do_signup(qcontext, do_login=False) signature: every token reset breaks.

Please restore them alongside your new test_password_history.py::test_02. That one catches a slicing bug ([:history+1]) the old tests miss, so the two sets complement each other.

Was there a specific failure that led to removing these? If any of them fails on your side, please share the traceback.

2. Rebase on current 19.0

The branch predates ea3f88a3 (Polish translation) on 19.0, so merging as is would drop those pl.po updates.

3. Comment in controllers/home.py

The new comment says the old request.session.logout(...) call "raised AttributeError which, if swallowed upstream, left the user authenticated". I don't think that's accurate. The AttributeError would surface as a 500, not a silently authenticated session. Could you reduce it to what the code does (logout is a module-level function in odoo.http.session in 20.0)?

lasley and others added 25 commits December 1, 2026 16:28
* [ADD] res_users_password_security: New module
* Create new module to lock down user passwords

* [REF] res_users_password_security: PR Review fixes
* Also add beta pass history rule

* [ADD] res_users_password_security: Pass history and min time
* Add pass history memory and threshold
* Add minimum time for pass resets through web reset

* Begin controller tests

* Fix copyright, wrong year for new file

* Add tests for password_security_home
* Left to do web_auth_reset_password

* Fix minimum reset threshold and finish tests

* Bug fixes per review

* [REF] password_security: PR review improvements
* Change tech name to password_security
* Use new except format
* Limit 1 & new api
* Cascade deletion for pass history

* [REF] password_security: Fix travis + style
* Fix travis errors
* self to cls
* Better variable names in tests

* [FIX] password_security: Fix travis errors
* Bump versions
* Installable to True
* Add Usage section to ReadMe w/ Runbot link
* `_crypt_context` now directly exposes the `CryptContext`
* Change all instances of openerp to odoo
* Add current time as password_write_date for admin user in demo, disabling the reset prompt - fixes OCA#652
* Switch security to be on correct model to fix OCA#674
…ord invalid (OCA#859)

* [FIX] password_security: Fix password stored

* [REF] password_security: use a unified check_password private method to validate rules and history password
* Add logic to overloaded web_login action to log out users with expired
passwords, preventing the password reset from being ignored
* Add unit test for new logic
This translates to Spanish all missing translations, 31 in total.
Since some implementation details are changed, I had to change some tests that were actually testing the implementation instead of the desired result of the method.
In a normal Odoo deployment, somebody in group *Administration / Access Rights* should be able to create users; but if this addon is installed, it gets this error:

    The requested operation cannot be completed due to security restrictions. Please contact your system administrator.

    (Document type: Res Users Password History, Operation: create)

This is now tested and fixed.
[The `website` addon returns an aditional redirection][1] that makes these tests fail if ran after installing `website`.

The tests were checking the returned value in a funky way anyways.

Now, instead of checking the final returned value, we check directly the parameters sent to the redirection method.

[1]: https://github.com/odoo/odoo/blob/3b85900fafc9469dca6e7c01fca6dac4f55d20f5/addons/website/controllers/main.py#L85-L89
Avoided requiring the module twice in JS.
Ivorra78 and others added 26 commits December 1, 2026 16:28
Currently translated at 100.0% (50 of 50 strings)

Translation: server-auth-16.0/server-auth-16.0-password_security
Translate-URL: https://translation.odoo-community.org/projects/server-auth-16-0/server-auth-16-0-password_security/es/
Currently translated at 100.0% (50 of 50 strings)

Translation: server-auth-16.0/server-auth-16.0-password_security
Translate-URL: https://translation.odoo-community.org/projects/server-auth-16-0/server-auth-16-0-password_security/it/
Replace fields on res.company by ir.config_parameter
Remove dead test for v16 migration script
Currently translated at 100.0% (50 of 50 strings)

Translation: server-auth-18.0/server-auth-18.0-password_security
Translate-URL: https://translation.odoo-community.org/projects/server-auth-18-0/server-auth-18-0-password_security/fr/
Currently translated at 68.0% (34 of 50 strings)

Translation: server-auth-18.0/server-auth-18.0-password_security
Translate-URL: https://translation.odoo-community.org/projects/server-auth-18-0/server-auth-18-0-password_security/sl/
Currently translated at 100.0% (50 of 50 strings)

Translation: server-auth-18.0/server-auth-18.0-password_security
Translate-URL: https://translation.odoo-community.org/projects/server-auth-18-0/server-auth-18-0-password_security/sl/
Automatic fixes from `pre-commit run -a` and also using ruff-odoo:

- Replace the `_()` helper by `self.env._()`, passing the interpolation
  values as arguments instead of applying `%` to the already translated
  string, so the placeholders stay part of the translatable term.
- Drop the resulting unused `_` import.
- Remove the redundant `string=` on `password_history_ids` and `user_id`,
  which repeats the label derived from the field name.
- Remove the unused `logging` import and its `_logger` in the controller.
- Rename the unused `pwd` unpacking to `_pwd` in test_signup.
- Regenerate README.rst and static/description/index.html.

Manual fixes, for what the hooks reported but did not resolve on their own

- models/res_users.py: UP031 on the minimum length regex. Solved with
  string concatenation rather than an f-string: the string is a regex and
  `{n,}` is a quantifier, so an f-string requires `f".{{{n},}}$"`, and
  doubling braces inside a pattern is easy to get wrong. The concatenation
  also matches the four sibling entries of the same list, which already
  build their fragment that way.
- impersonate_login/static/src/js/user_menu.esm.js: move `markup` into
  alphabetical position, as eslint `sort-imports` requires.
* res.users.groups_id renamed to group_ids

Odoo 19.0 refactored the groups relation on res.users: groups_id is gone,
replaced by group_ids (explicitly assigned groups) and all_group_ids
(including implied ones).

Without this, test_user_with_admin_rights_can_create_users fails with
AttributeError: 'res.users' object has no attribute 'groups_id'

* Opener takes the HttpCase instead of a cursor

In Odoo 19.0 odoo.tests.common.Opener.__init__ receives the HttpCase
instance (it reads http_case.cr and asserts http_case.opener is itself),
so passing self.env.cr no longer works.

Without this, the 15 post_install HttpCase tests fail with
AttributeError: 'psycopg2.extensions.cursor' object has no attribute 'cr'

* forward the extra do_signup arguments

In 19.0 auth_signup's do_signup() gained a do_login parameter, and
web_auth_reset_password() now calls it as do_signup(qcontext, do_login=False):
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/addons/auth_signup/controllers/main.py#L97
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/addons/auth_signup/controllers/main.py#L165

The override kept the old two-argument signature, so resetting a password or
signing up through a token failed with:

    PasswordSecurityHome.do_signup() got an unexpected keyword argument 'do_login'

Forwarding *args/**kwargs keeps the override working across signature changes.

Reported by @sergioM-S73 in
OCA#910 (comment)

The existing tests only exercised the token-less "send instructions" branch of
/web/reset_password, which never reaches that call. The added regression test
posts a real signup token, which is the path that broke.

* invalidate the stale login_date before the reset bounce

When a user whose password has expired logs in, the module kicks them out to
the reset password page, but in a real browser that page shows "Invalid signup
token".

In 19.0 res.users._login() became an instance method running on the request env
(in 18.0 it was a classmethod with its own cursor):
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/odoo/addons/base/models/res_users.py#L760

When the browser sends a tz cookie and the user already has a timezone,
"not user.tz or not user.login_date" reaches login_date and loads it into the
env cache, before _update_last_login() creates the new res.users.log:
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/odoo/addons/base/models/res_users.py#L771-L775

login_date is a related field on log_ids.create_date and _update_last_login()
only creates a log record, so nothing refreshes that cached value. The expiry
bounce then calls _get_signup_url() -> _generate_signup_token(), which signs
login_date into the payload, so the token carries the stale date and is later
rejected:
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/addons/auth_signup/controllers/main.py#L149

Reported by @kwoychesko in
OCA#910 (comment)

The regression test needs both a tz cookie and a backdated res.users.log:
create_date is truncated to the second, so on the shared test cursor the stale
and the fresh login_date would otherwise be identical. Header-less requests
never reach that branch, which is why the rest of the suite stays green.

* do not rely on demo data in tests

The OCA CI runs the suite without demo data, so base.user_demo does not exist
there and three tests failed with:

    ValueError: External ID not found in the system: base.user_demo

Each of them now builds its own user with new_test_user() instead:

- test_totp and test_03_reset_password_admin used the demo user only as a
  non-admin account. Its "demo" password is no longer usable as such, since it
  does not satisfy the policy this very module enforces.
- test_user_with_admin_rights_can_create_users also needs
  base.group_partner_manager: creating a user creates its partner, and
  base.user_demo carried that group, while base.group_erp_manager alone does
  not grant it.
- auth_signup flags a brand new user with signup_type="signup", which
  base.user_demo was not, so test_totp clears it with signup_cancel() before
  asserting that action_expire_password() sets it to "reset".

Reproduced locally by disabling with_demo in the configuration file.

The res.users.log used by test_08 to backdate a previous login is no longer
built with a raw UPDATE. Its create_date comes from cr.now(), a PostgreSQL
NOW() cached for the whole transaction, so freezegun cannot move it and it
cannot be passed in the create values either, since LOG_ACCESS_COLUMNS are
dropped from them:
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/odoo/orm/models.py#L4783
The cursor clock is patched around the create instead, and the resulting date
is asserted. sudo() is needed for the admin-only create on res.users.log and
keeps env.uid, so create_uid still points at the user.

test_05 mocked AuthSignupHome.get_auth_signup_qcontext without autospec. A
plain MagicMock fabricates any attribute on access, original_routing included,
so http.py mistakes that helper for a routed endpoint while building the
routing map:
https://github.com/odoo/odoo/blob/13e9e827dc21103052e8607d16f23c07adeb5634/odoo/http.py#L910-L913
It then warns once per controller in the mro, "is a controller endpoint
without any route, skipping", which only shows up when auth_oauth and
auth_oidc share the database and widen that mro. autospec=True keeps the
attribute absent, and the warnings with it.

Since the users these tests need can no longer come from demo data, they are
built once per class in setUpClass instead of once per test method. Odoo runs
every test method inside its own savepoint, so a test that mutates the shared
user, adding a group for instance, is rolled back before the next one starts.
Verified with a throwaway pair of tests: one adding base.group_erp_manager to
the shared user, the next asserting it is gone. It is.
Nothing exercised PasswordSecurity2FAHome.web_totp. The existing test stays at
the model level and calls action_expire_password() directly, so the whole body
of that controller never ran, and Codecov reported the file at 40% on the
migration PR.

The new test walks the real second factor: it enables 2FA with a totp_secret,
expires the password, posts the first factor to /web/login and then the token
to /web/login/totp, and asserts the bounce lands on a usable
/web/reset_password.

Checked by mutation: forcing the early return of web_totp makes the test fail,
so the bounce is really exercised rather than merely imported.

Note that the stale login_date that web_login guards against does not arise
here. Two factor authentication spans two requests and _login() runs on the
first one, so the second arrives with a fresh cache; removing the
invalidate_recordset() call from web_totp fails no test. It is kept there for
symmetry with web_login, not because a test pins it down.
Users created from data files can have passwords that do not comply with
the configured policy, which causes modules that define such users to
fail during installation, even demo data.

To fix this, the policy check is skipped while loading data files.

Note that Tests are unaffected because users created there are through
the ORM, so the policy is still covered.

Closes OCA#865
While modules are loaded with tests enabled, there is no running test
yet, so `current_test` is a boolean instead of a test case. Creating
users from data files at that point, even demo data, fails with an
AttributeError, and the whole data file is discarded.

To fix this, `test_module` is read only when a test is running.
Currently translated at 22.0% (11 of 50 strings)

Translation: server-auth-19.0/server-auth-19.0-password_security
Translate-URL: https://translation.odoo-community.org/projects/server-auth-19-0/server-auth-19-0-password_security/pl/
@BhaveshHeliconia
BhaveshHeliconia force-pushed the 20.0-mig-password_security branch from af9d831 to 308c6dd Compare December 1, 2026 11:02
@oca-cla-bot

oca-cla-bot Bot commented Dec 1, 2026

Copy link
Copy Markdown

The following commit authors need to sign the Contributor License Agreement:

CLA not signed

@BhaveshHeliconia

Copy link
Copy Markdown
Author

@chaule97 Thanks a lot for the thorough review, and for porting the tests yourself to check. You were right on all three points — all addressed in the latest push.

@chaule97 chaule97 left a comment

Copy link
Copy Markdown

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

LGTM

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment

Labels

mod:password_security Module password_security series:20.0

Projects

None yet

Development

Successfully merging this pull request may close these issues.