feat(local-accounts): replace and remove keys, clear the password #90

Merged
christianmanivong merged 1 commits from fix/local-account-key-replace into main 2026-11-04 10:54:06 +00:00
3 changed files with 479 additions and 19 deletions

No files matched your search

+15
View File
@@ -7,6 +7,21 @@ recorded here; their history is the git log.
## [Unreleased]
### Added
- `LocalAccountsMixin.add_local_account(..., replaces=[...])`: the keys the new one takes
the place of go from the account, matched by their base64 whatever a line's options or
comment. Keys the person added on the host stay. The step is `old keys`; it runs even
when the new key could not be added (NetOrk/netork#2013).
- `add_local_account(..., clear_password=True)`: the account's password goes, and it logs
in with a key only. Step `password`. It cannot be combined with a `password_hash` or
with `admin=True`, as the sudo rule asks for that password. A driver supplies
`_account_clear_password`; one that does not fails the step and says so.
- `LocalAccountsMixin.remove_local_account_keys(name, keys)`: takes the named keys off an
account and leaves it open, its password and sudo as they are -- for a person who
deleted a key and has no new one. Step `keys`.
- A driver whose host keeps keys elsewhere overrides `_account_drop_keys` next to
`_account_add_key` and `_account_remove_keys`.
## [4.27.0] - 2026-11-03
### Added
+172 -18
View File
@@ -5,6 +5,14 @@ with their public key and, where they are to administer the host, may use
sudo with their own password. When they leave, the account is locked, not
deleted: their key goes, sudo goes, the login is refused, and the home stays.
**What the person changes follows them** (NetOrk/netork#2013). A key they
replace goes from the account as the new one comes in (``replaces``); a key
they delete goes without a new one (``remove_local_account_keys``). Either way
only the keys named go: one the person added on the host stays, and the
account stays open. A password they remove goes from the account too
(``clear_password``): it logs in with a key only and has no sudo, as the sudo
rule asks for that password.
:class:`LocalAccountsMixin` holds what is the same on every POSIX host -- the
checks, reading an account back, the order of the steps, the key file and the
sudo rule. A driver supplies the commands that differ between operating
@@ -48,7 +56,7 @@ from typing import TYPE_CHECKING, ClassVar
from typing_extensions import TypedDict
from napalm_device_types.fixes import run_fix_steps
from napalm_device_types.fixes import FixStep, run_fix_steps
from napalm_device_types.models import FixResultDict, FixStepDict, FixStepOutcomeDict
if TYPE_CHECKING: # pragma: no cover - for type checkers only
@@ -179,6 +187,18 @@ def check_public_key(key: str) -> None:
raise ValueError("not a public key: expected '<type> <base64> [comment]' on one line")
def _checked_keys(keys: Sequence[str]) -> list[str]:
"""*keys*, each one stripped.
:raises ValueError: when *keys* is one string, or one of them no public key.
"""
if isinstance(keys, str):
raise ValueError("expected a list of public keys, not one string")
for key in keys:
check_public_key(key)
return [key.strip() for key in keys]
def _command(argv: Sequence[str]) -> str:
return shlex.join(argv)
@@ -225,9 +245,11 @@ class LocalAccountsMixin:
# -- what a driver supplies ------------------------------------------------------
#
# ``_account_*`` are the driver's: the five below it must supply, the key
# store (``_account_key_files``, ``_account_read_keys``, ``_account_add_key``,
# ``_account_remove_keys``) it may replace. ``_accounts_*`` are this mixin's own.
# ``_account_*`` are the driver's: the five below it must supply, the two after
# them (``_account_create_with_uid``, ``_account_clear_password``) it may, and
# the key store (``_account_key_files``, ``_account_read_keys``,
# ``_account_add_key``, ``_account_drop_keys``, ``_account_remove_keys``) it may
# replace. ``_accounts_*`` are this mixin's own.
def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]:
"""The commands that create *name* with a home and :attr:`ACCOUNT_SHELL`.
@@ -265,6 +287,15 @@ class LocalAccountsMixin:
"""
raise NotImplementedError
def _account_clear_password(self, name: str) -> list[list[str]]:
"""The commands that take *name*'s password away; its key login stays as it is.
Not an empty password -- PAM's ``nullok`` lets anyone in without one --
and not a lock or an expiry, which sshd or PAM apply to a key too.
Only ``add_local_account(clear_password=True)`` asks for it.
"""
raise NotImplementedError
# -- reading ---------------------------------------------------------------------
def get_local_accounts(self, names: Iterable[str]) -> list[LocalAccountDict]:
@@ -339,6 +370,8 @@ class LocalAccountsMixin:
*,
password_hash: str | None = None,
admin: bool = False,
clear_password: bool = False,
replaces: Sequence[str] = (),
) -> LocalAccountChangeDict:
"""Give *name* an account that logs in with *public_key*, or open it again.
@@ -347,28 +380,71 @@ class LocalAccountsMixin:
:attr:`ACCOUNT_PASSWORD_SCHEME`) becomes its password; *admin* gives it
the sudo rule, which asks for that password -- so an administrator
needs one. Without *admin*, the rule and :attr:`ACCOUNT_ADMIN_GROUPS`
are taken away.
are taken away. Without *password_hash* the account keeps the password
it has, unless *clear_password* takes it away: the account then logs
in with a key only, and can have no sudo.
Steps: ``account``, then ``sudo`` and ``keys``, each of which runs when
the other failed.
*replaces* are keys *public_key* takes the place of -- the person's
old ones. They go from the account, matched by their base64 whatever
a line's options or comment; every other key stays.
:raises ValueError: for a name, key or hash no host takes, the login
user's own account, or a system account.
Steps: ``account``, then ``sudo``, ``password`` (with
*clear_password*), ``keys`` and ``old keys`` (with *replaces*), each of
which runs when another failed: an old key goes even when the new one
could not be added.
:raises ValueError: for a name, key or hash no host takes, a replaced
key that is none, *clear_password* with a *password_hash* or with
*admin*, the login user's own account, or a system account.
"""
check_account_name(name)
check_public_key(public_key)
if password_hash is not None:
self._accounts_check_hash(password_hash)
new = _key_blob(public_key)
old = [key for key in _checked_keys(replaces) if _key_blob(key) != new]
self._accounts_check_password(password_hash, admin=admin, clear=clear_password)
existing = self._accounts_changeable(name)
first = run_fix_steps(
[("account", lambda: self._accounts_open_or_create(name, existing, password_hash))]
)
parts = [first]
if first["success"]:
parts += [
run_fix_steps([("sudo", lambda: self._accounts_set_sudo(name, admin=admin))]),
run_fix_steps([("keys", lambda: self._accounts_add_key(name, public_key))]),
]
steps = self._accounts_after_open(name, public_key, admin, clear_password, old)
parts += [run_fix_steps([step]) for step in steps]
return self._accounts_result(name, parts)
def _accounts_after_open(
self, name: str, public_key: str, admin: bool, clear_password: bool, old: list[str]
) -> list[FixStep]:
"""The steps of ``add_local_account`` once the account is there, each on its own."""
steps: list[FixStep] = [("sudo", lambda: self._accounts_set_sudo(name, admin=admin))]
if clear_password:
steps.append(("password", lambda: self._accounts_clear_password(name)))
steps.append(("keys", lambda: self._accounts_add_key(name, public_key)))
if old:
steps.append(("old keys", lambda: self._accounts_drop_keys(name, old)))
return steps
def remove_local_account_keys(self, name: str, keys: Sequence[str]) -> LocalAccountChangeDict:
"""Take *keys* off *name*'s account, for a person who deleted them.
Only those keys go, matched by their base64 whatever a line's options
or comment; the other keys, the password and sudo stay, and the
account stays open -- to get a new key once there is one. A locked
account has none left to remove: the lock took them all.
Step: ``keys``.
:raises ValueError: for a name no host takes, no keys or one that is
none, the login user's own account, or a system account.
"""
check_account_name(name)
wanted = _checked_keys(keys)
if not wanted:
raise ValueError("no public key to remove")
if self._accounts_changeable(name) is None:
step: FixStepDict = {"step": "keys", "ok": False, "output": f"no account {name}"}
return {**_joined([step]), "account": None}
parts = [run_fix_steps([("keys", lambda: self._accounts_drop_keys(name, wanted))])]
return self._accounts_result(name, parts)
def lock_local_account(self, name: str) -> LocalAccountChangeDict:
@@ -490,6 +566,20 @@ class LocalAccountsMixin:
raise RuntimeError(f"cannot ask who has uid {uid}: {_said(result)}")
return result.stdout.split(":", 1)[0].strip() or None
def _accounts_check_password(
self, password_hash: str | None, *, admin: bool, clear: bool
) -> None:
""":raises ValueError: for a hash the host does not take, or a password to
clear that is to be set, or that sudo would ask for."""
if clear and password_hash is not None:
raise ValueError(
"a password to clear cannot be set too: clear_password or password_hash"
)
if clear and admin:
raise ValueError("an account without a password cannot use sudo: its rule asks for it")
if password_hash is not None:
self._accounts_check_hash(password_hash)
def _accounts_check_hash(self, password_hash: str) -> None:
prefixes = PASSWORD_SCHEMES[self.ACCOUNT_PASSWORD_SCHEME]
if not _CRYPT_RE.fullmatch(password_hash) or not password_hash.startswith(prefixes):
@@ -550,6 +640,16 @@ class LocalAccountsMixin:
return {"ok": False, "output": _said(failed)}
return {"ok": True, "output": done + (", password set" if password_hash else "")}
def _accounts_clear_password(self, name: str) -> FixStepOutcomeDict:
try:
commands = self._account_clear_password(name)
except NotImplementedError:
return {"ok": False, "output": "this driver cannot remove a password"}
failed = self._accounts_run(commands)
if failed is not None:
return {"ok": False, "output": _said(failed)}
return {"ok": True, "output": f"{name} has no password: it logs in with a key only"}
def _accounts_lock(self, name: str) -> FixStepOutcomeDict:
passwd = self._accounts_passwd(name)
if passwd is None:
@@ -683,9 +783,23 @@ class LocalAccountsMixin:
mine = self._accounts_key_file(name, path)
if mine is None:
return {"ok": False, "output": f"cannot read {path}"}
staged = self._accounts_stage("".join(f"{line}\n" for line in [*mine, public_key.strip()]))
failed = self._accounts_write_key_file(name, home, path, [*mine, public_key.strip()])
if failed is not None:
return {"ok": False, "output": f"{path}: {_said(failed)}"}
return {"ok": True, "output": f"key added to {path}"}
def _accounts_write_key_file(
self, name: str, home: str, path: str, lines: list[str]
) -> CommandResult | None:
"""*lines* as *name*'s key file *path*, written as *name*; None, or what failed.
Without lines the file goes: nothing is staged from an empty stdin.
"""
if not lines:
return self._accounts_run_as(name, [["rm", "-f", "--", path]])
staged = self._accounts_stage("".join(f"{line}\n" for line in lines))
try:
failed = self._accounts_run_as(
return self._accounts_run_as(
name,
[
["mkdir", "-p", "-m", "700", "--", f"{home}/.ssh"],
@@ -694,9 +808,49 @@ class LocalAccountsMixin:
)
finally:
self._accounts_unstage(staged)
def _accounts_drop_from(
self, name: str, home: str, path: str, blobs: set[str | None]
) -> FixStepOutcomeDict:
"""The keys of *blobs* out of *name*'s key file *path*; no output when none was in it."""
lines = self._accounts_key_file(name, path)
if lines is None:
return {"ok": False, "output": f"cannot read {path}"}
kept = [line for line in lines if _key_blob(line) not in blobs]
if len(kept) == len(lines):
return {"ok": True, "output": ""}
failed = self._accounts_write_key_file(name, home, path, kept)
if failed is not None:
return {"ok": False, "output": f"{path}: {_said(failed)}"}
return {"ok": True, "output": f"key added to {path}"}
return {"ok": True, "output": f"{len(lines) - len(kept)} removed from {path}"}
def _accounts_drop_keys(self, name: str, keys: list[str]) -> FixStepOutcomeDict:
home = self._accounts_home(name)
if home is None:
return {"ok": False, "output": f"no account {name}"}
return self._account_drop_keys(name, home, keys)
def _account_drop_keys(self, name: str, home: str, keys: list[str]) -> FixStepOutcomeDict:
"""Remove exactly *keys* from *name*'s key files in *home*, as *name*.
A key is matched by its base64, whatever a line's options or comment;
every other line stays. Afterwards none of *keys* may be left in
:meth:`_account_key_files`. A driver whose host keeps keys elsewhere
overrides this, with :meth:`_account_add_key`.
"""
blobs = {_key_blob(key) for key in keys}
said: list[str] = []
for path in authorized_keys_paths(home):
outcome = self._accounts_drop_from(name, home, path, blobs)
if not outcome["ok"]:
return outcome
said += [outcome["output"]] if outcome["output"] else []
left = self._account_read_keys(name, home)
if left is None:
return {"ok": False, "output": f"cannot read the key files of {name}"}
if any(_key_blob(line) in blobs for line in left):
return {"ok": False, "output": f"{name} still has a key that was to go"}
return {"ok": True, "output": "\n".join(said) or f"none of the keys is in {home}/.ssh"}
def _accounts_key_file(self, name: str, path: str) -> list[str] | None:
there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30)
+292 -1
View File
@@ -23,6 +23,8 @@ from napalm_device_types.local_accounts import (
from napalm_device_types.models import FixStepOutcomeDict
ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop"
#: The key Alice had before, on the laptop she lost.
OLD_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIOld alice@lost-laptop"
OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop"
HASH = "$6$salt$" + "x" * 86
#: Shell syntax a command for root must not hold: each is one fixed command.
@@ -61,6 +63,10 @@ class _Host:
self.ran: list[tuple[str, bool]] = []
self.staged = 0
def ran_words(self, first: str) -> list[str]:
"""The words of the last command run whose first word is *first*."""
return next(w for w in (shlex.split(c) for c, _ in reversed(self.ran)) if w[0] == first)
def is_admin(self, name: str) -> bool:
rule = self.files.get(sudoers_rule_path(_Driver.SUDOERS_DIR, name))
return name in self.other_rules or (self.includes_dropins and rule is not None)
@@ -200,6 +206,11 @@ class _Host:
self.accounts[args[0]].groups.remove(args[1])
return CommandResult("", "", 0)
def _clearpw(self, args: list[str], privileged: bool) -> CommandResult:
assert privileged
self.accounts[args[0]].password = None
return CommandResult("", "", 0)
class _Driver(LocalAccountsMixin):
ACCOUNT_SHELL = "/bin/sh"
@@ -238,6 +249,9 @@ class _Driver(LocalAccountsMixin):
def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]:
return ["leavegroup", name, group]
def _account_clear_password(self, name: str) -> list[list[str]]:
return [["clearpw", name]]
@pytest.fixture
def host() -> _Host:
@@ -362,7 +376,9 @@ def test_a_new_account_gets_the_key_and_the_sudo_rule(host: _Host, driver: _Driv
def test_every_command_root_runs_is_one_fixed_command(host: _Host, driver: _Driver) -> None:
driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True)
driver.add_local_account("alice", OLD_KEY, password_hash=HASH, admin=True)
driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY], clear_password=True)
driver.remove_local_account_keys("alice", [ALICE_KEY])
driver.lock_local_account("alice")
for command in _root_commands(host):
@@ -690,3 +706,278 @@ def test_a_key_file_the_host_adds_is_read_too(host: _Host) -> None:
[account] = _ExtraFile(host).get_local_accounts(["alice"])
assert account["authorized_keys"] == [OWN_KEY, ALICE_KEY]
# -- replacing a key (NetOrk/netork#2013) ----------------------------------------------
def _alice_keys(host: _Host) -> str:
return host.files.get("/home/alice/.ssh/authorized_keys", "")
def test_a_replaced_key_goes_and_the_persons_own_keys_stay(host: _Host, driver: _Driver) -> None:
_add_alice(host, keys=f"{OLD_KEY}\n{OWN_KEY}\n")
result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["account", "sudo", "keys", "old keys"]
assert _alice_keys(host) == f"{OWN_KEY}\n{ALICE_KEY}\n"
account = result["account"]
assert account is not None and account["authorized_keys"] == [OWN_KEY, ALICE_KEY]
def test_a_replaced_key_goes_from_every_key_file_with_any_options_or_comment(
host: _Host, driver: _Driver
) -> None:
# The same key with options in front and another comment is the same key.
blob = OLD_KEY.rsplit(" ", 1)[0]
_add_alice(host, keys=f'from="10.0.0.0/8" {blob} renamed\n# the laptop\n')
host.files["/home/alice/.ssh/authorized_keys2"] = f"{OWN_KEY}\n{blob}\n"
result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
assert result["success"], result["output"]
assert _alice_keys(host) == f"# the laptop\n{ALICE_KEY}\n"
assert host.files["/home/alice/.ssh/authorized_keys2"] == f"{OWN_KEY}\n"
assert not [p for p in host.files if p.startswith("/tmp/")]
def test_a_replaced_key_that_is_not_there_writes_nothing(host: _Host, driver: _Driver) -> None:
_add_alice(host, keys=f"{ALICE_KEY}\n")
result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
assert result["success"], result["output"]
assert host.staged == 0
assert "none of the keys" in result["steps"][-1]["output"]
def test_the_new_key_is_never_taken_for_a_replaced_one(host: _Host, driver: _Driver) -> None:
_add_alice(host, keys=f"{OLD_KEY}\n")
result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY, ALICE_KEY])
assert result["success"], result["output"]
assert _alice_keys(host) == f"{ALICE_KEY}\n"
def test_without_replaces_no_key_goes(host: _Host, driver: _Driver) -> None:
_add_alice(host, keys=f"{OLD_KEY}\n")
result = driver.add_local_account("alice", ALICE_KEY)
assert [s["step"] for s in result["steps"]] == ["account", "sudo", "keys"]
assert _alice_keys(host) == f"{OLD_KEY}\n{ALICE_KEY}\n"
@pytest.mark.parametrize("replaces", [["not a key"], [OLD_KEY, ""], OLD_KEY])
def test_a_replaced_key_that_is_none_is_refused(
host: _Host, driver: _Driver, replaces: list[str]
) -> None:
with pytest.raises(ValueError, match="key"):
driver.add_local_account("alice", ALICE_KEY, replaces=replaces)
assert _root_commands(host) == []
def test_the_old_key_goes_even_when_the_new_one_could_not_be_added(host: _Host) -> None:
class _AddFails(_Driver):
def _account_add_key(self, name: str, home: str, public_key: str) -> FixStepOutcomeDict:
return {"ok": False, "output": "disk full"}
_add_alice(host, keys=f"{OLD_KEY}\n{OWN_KEY}\n")
result = _AddFails(host).add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
assert not result["success"]
assert next(s for s in result["steps"] if s["step"] == "old keys")["ok"]
assert _alice_keys(host) == f"{OWN_KEY}\n"
@pytest.mark.parametrize(
("failing", "ignored", "said"),
[
({"as cat"}, set(), "cannot read"),
({"as install"}, set(), "authorized_keys"),
(set(), {"as install"}, "still has"),
],
)
def test_a_replaced_key_that_did_not_go_says_so(
host: _Host, driver: _Driver, failing: set[str], ignored: set[str], said: str
) -> None:
_add_alice(host, keys=f"{OLD_KEY}\n{ALICE_KEY}\n")
host.failing |= failing
host.ignored |= ignored
result = driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
old = next(s for s in result["steps"] if s["step"] == "old keys")
assert not old["ok"] and said in old["output"]
assert not result["success"]
# -- removing the password (NetOrk/netork#2013) ----------------------------------------
def test_clearing_the_password_leaves_a_key_only_account_without_sudo(
host: _Host, driver: _Driver
) -> None:
_add_alice(host, keys=f"{ALICE_KEY}\n")
host.files["/etc/sudoers.d/80-account-alice"] = sudoers_rule("alice")
result = driver.add_local_account("alice", ALICE_KEY, clear_password=True)
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["account", "sudo", "password", "keys"]
a = host.accounts["alice"]
assert a.password is None and not a.locked and a.groups == ["alice"]
assert "/etc/sudoers.d/80-account-alice" not in host.files
assert _alice_keys(host) == f"{ALICE_KEY}\n"
def test_a_new_account_without_a_password_gets_it_cleared_too(host: _Host, driver: _Driver) -> None:
result = driver.add_local_account("alice", ALICE_KEY, clear_password=True)
assert result["success"], result["output"]
assert ["clearpw", "alice"] == host.ran_words("clearpw")
def test_without_clear_password_the_password_stays(host: _Host, driver: _Driver) -> None:
_add_alice(host)
result = driver.add_local_account("alice", ALICE_KEY)
assert "password" not in [s["step"] for s in result["steps"]]
assert host.accounts["alice"].password == HASH
@pytest.mark.parametrize(
"kwargs",
[{"password_hash": HASH}, {"admin": True}],
)
def test_clearing_the_password_refuses_a_password_or_sudo(
host: _Host, driver: _Driver, kwargs: dict[str, object]
) -> None:
# The sudo rule asks for the password: an account without one cannot use it.
with pytest.raises(ValueError, match="password"):
driver.add_local_account("alice", ALICE_KEY, clear_password=True, **kwargs) # type: ignore[arg-type]
assert _root_commands(host) == []
def test_a_password_that_cannot_be_cleared_fails_its_step_only(
host: _Host, driver: _Driver
) -> None:
_add_alice(host)
host.failing.add("clearpw")
result = driver.add_local_account("alice", ALICE_KEY, clear_password=True)
assert not result["success"]
password = next(s for s in result["steps"] if s["step"] == "password")
assert not password["ok"] and "clearpw: failed" in password["output"]
# sudo and the key do not wait for it.
assert next(s for s in result["steps"] if s["step"] == "sudo")["ok"]
assert _alice_keys(host) == f"{ALICE_KEY}\n"
def test_a_driver_that_cannot_clear_a_password_says_so(host: _Host) -> None:
class _NoClear(_Driver):
_account_clear_password = LocalAccountsMixin._account_clear_password
_add_alice(host)
result = _NoClear(host).add_local_account("alice", ALICE_KEY, clear_password=True)
password = next(s for s in result["steps"] if s["step"] == "password")
assert not password["ok"] and "cannot remove" in password["output"]
assert host.accounts["alice"].password == HASH
# -- removing keys without a new one (NetOrk/netork#2013) -------------------------------
def test_removing_keys_takes_only_those_and_leaves_the_account_open(
host: _Host, driver: _Driver
) -> None:
_add_alice(host, keys=f"{ALICE_KEY}\n{OWN_KEY}\n")
host.files["/etc/sudoers.d/80-account-alice"] = sudoers_rule("alice")
result = driver.remove_local_account_keys("alice", [ALICE_KEY])
assert result["success"], result["output"]
assert [s["step"] for s in result["steps"]] == ["keys"]
assert _alice_keys(host) == f"{OWN_KEY}\n"
a = host.accounts["alice"]
assert not a.locked and a.password == HASH and a.groups == ["alice", "wheel"]
assert "/etc/sudoers.d/80-account-alice" in host.files
account = result["account"]
assert account is not None and account["authorized_keys"] == [OWN_KEY]
def test_removing_the_last_key_leaves_an_empty_key_file(host: _Host, driver: _Driver) -> None:
_add_alice(host, keys=f"{ALICE_KEY}\n")
result = driver.remove_local_account_keys("alice", [ALICE_KEY])
assert result["success"], result["output"]
assert _alice_keys(host) == ""
assert not host.accounts["alice"].locked
def test_removing_keys_changes_nothing_as_root(host: _Host, driver: _Driver) -> None:
# Root only asks whether a key file is there, and reads the account back
# (its lock, sudo -l); the files are written as the person.
_add_alice(host, keys=f"{ALICE_KEY}\n")
driver.remove_local_account_keys("alice", [ALICE_KEY])
for command in _root_commands(host):
words = shlex.split(command)
assert words[0] in {"test", "islocked", "sudo"}, command
if words[0] == "sudo":
assert words[:3] in (["sudo", "-n", "-u"], ["sudo", "-l", "-U"]), command
def test_removing_keys_of_an_account_that_is_not_there_fails(driver: _Driver) -> None:
result = driver.remove_local_account_keys("bob", [ALICE_KEY])
assert not result["success"]
assert "no account" in result["output"]
assert result["account"] is None
@pytest.mark.parametrize("keys", [[], ["not a key"], ALICE_KEY])
def test_removing_keys_refuses_what_is_no_list_of_keys(
host: _Host, driver: _Driver, keys: list[str]
) -> None:
_add_alice(host, keys=f"{ALICE_KEY}\n")
with pytest.raises(ValueError, match="key"):
driver.remove_local_account_keys("alice", keys)
assert _alice_keys(host) == f"{ALICE_KEY}\n"
@pytest.mark.parametrize(("name", "said"), [("netadmin", "logs in"), ("daemon", "system")])
def test_removing_keys_never_touches_the_login_user_or_a_system_account(
host: _Host, driver: _Driver, name: str, said: str
) -> None:
with pytest.raises(ValueError, match=said):
driver.remove_local_account_keys(name, [ALICE_KEY])
assert _root_commands(host) == []
def test_a_driver_with_its_own_key_store_drops_keys_there(host: _Host) -> None:
class _Store(_OwnKeyStore):
def _account_drop_keys(self, name: str, home: str, keys: list[str]) -> FixStepOutcomeDict:
gone = {k.split()[1] for k in keys}
self.store[name] = [k for k in self.store.get(name, []) if k.split()[2] not in gone]
return {"ok": True, "output": "dropped some"}
driver = _Store(host)
driver.add_local_account("alice", OLD_KEY)
driver.add_local_account("alice", ALICE_KEY, replaces=[OLD_KEY])
assert driver.store == {"alice": [f"/home/alice {ALICE_KEY}"]}
removed = driver.remove_local_account_keys("alice", [ALICE_KEY])
assert removed["success"], removed["output"]
assert driver.store == {"alice": []}