server.user: password_lock=True on a new FreeBSD user runs a redundant pw lock
Follow-up from the review of #2014 (password_lock option for server.user).
Describe the bug
On FreeBSD, creating a new user with password_lock=True runs pw lock on a password field that is already disabled.
pw useradd leaves the password field as * (disabled). _user_password_lock in src/pyinfra/operations/server.py only treats the *LOCKED* prefix as locked, so is_locked is False for * and the operation yields pw lock someuser. pw lock prepends *LOCKED* to whatever is there, so the field becomes *LOCKED**.
Harmless in practice (the account is locked either way and the next run is a no-op), but the extra command is noise and the doubled marker is ugly.
To Reproduce
from pyinfra.operations import server
server.user(
name="Create locked user",
user="someuser",
password_lock=True,
)
against a FreeBSD host yields:
pw useradd -n someuser -d /home/someuser
pw lock someuser
The second command is unnecessary.
Expected behavior
A fresh FreeBSD user whose password field is * should be treated as already locked, so password_lock=True is a no-op after creation.
Suggested fix
In _user_password_lock, treat a FreeBSD password field of exactly * as locked, for example:
is_locked = current_password.startswith(_password_lock_prefix(os_type)) or (
os_type == "FreeBSD" and current_password == "*"
)
The unlock path is unaffected: password_lock=False on a * field must still run pw usermod -n USER -w none so the user can set a password, which is the point of the feature (#1279).
Note: the password_lock option is added by #2014, which is open at the time of writing. This issue only applies once that PR merges.
Before I send a PR: on FreeBSD the extra pw lock may not be only cosmetic. Reading the FreeBSD sources (not a run on a FreeBSD host), pam_unix refuses a *LOCKED* field at the account stage and the stock sshd uses PAM, so a user created with password_lock=True currently cannot log in with an SSH key either, while a plain * only rules out a password. Treating * as locked would change that.
Should password_lock mean the account-wide lock (keep pw lock, and I can add a docstring line), or password only (the change proposed here)? The fix and fixtures for the second are ready.