diff --git a/CHANGELOG.md b/CHANGELOG.md index 7a297b9..8279e69 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -14,6 +14,17 @@ recorded here; their history is the git log. 3.12 venv no longer has. ### Added +- `LocalAccountsMixin` (`napalm_device_types.local_accounts`): personal login accounts + on a host. `get_local_accounts(names)` reads them back (groups, lock, sudo, key + files), `add_local_account(name, public_key, password_hash=, admin=)` creates or + reopens one, `lock_local_account(name)` takes its keys and sudo away and refuses + every login while keeping its home. Every command root runs is one fixed command, + the key files are read and written as the account itself, and the sudo rule is a + drop-in of its own, checked with `visudo` and `sudo -l`. A driver supplies the + commands that create, open and lock an account and take it out of a group, and may + replace where the keys are kept (`_account_key_files`, `_account_read_keys`, + `_account_add_key`, `_account_remove_keys`; default `~/.ssh/authorized_keys`) + (NetOrk/netork#1793). - `OpenSshServerMixin.exempt_from_ssh_penalties`: puts the address the host sees the managing client at (`$SSH_CONNECTION`) into `PerSourcePenaltyExemptList`, in `/etc/ssh/sshd_config.d/00-netork-penalty-exempt.conf`, next to the host's diff --git a/napalm_device_types/__init__.py b/napalm_device_types/__init__.py index b61a8ae..35e95ed 100644 --- a/napalm_device_types/__init__.py +++ b/napalm_device_types/__init__.py @@ -48,6 +48,7 @@ instead of being restated on every role that happens to need it: * :class:`~napalm_device_types.interface_filter.InterfaceFilterMixin` * :class:`~napalm_device_types.kernel.KernelFactsMixin` * :class:`~napalm_device_types.listening.ListeningSocketsMixin` +* :class:`~napalm_device_types.local_accounts.LocalAccountsMixin` * :class:`~napalm_device_types.host_firewall.HostFirewallMixin` * :class:`~napalm_device_types.mac_acl.MacAclMixin` * :class:`~napalm_device_types.nat_vpn.NatVpnMixin` @@ -123,6 +124,11 @@ from napalm_device_types.listening import ( ListeningSocketsUnavailable, parse_listening_sockets, ) +from napalm_device_types.local_accounts import ( + LocalAccountChangeDict, + LocalAccountDict, + LocalAccountsMixin, +) from napalm_device_types.mac_acl import MacAclMixin from napalm_device_types.management_controller import ManagementControllerDriver from napalm_device_types.media import MediaDriver @@ -317,6 +323,9 @@ __all__ = [ "ListeningSocketsMixin", "ListeningSocketsUnavailable", "parse_listening_sockets", + "LocalAccountsMixin", + "LocalAccountDict", + "LocalAccountChangeDict", "PhoneDriver", "PingSweepMixin", "PortSpec", diff --git a/napalm_device_types/local_accounts.py b/napalm_device_types/local_accounts.py new file mode 100644 index 0000000..d579bc7 --- /dev/null +++ b/napalm_device_types/local_accounts.py @@ -0,0 +1,588 @@ +"""Personal login accounts on a host: reading them, adding one, locking one again. + +A person who is to work on a host gets an account of their own: they log in +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. + +: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 +systems: creating, opening and locking an account, reading its lock, and +taking it out of a group. + +**Every command root runs is one fixed command**, with no shell syntax of its +own -- ``useradd ...``, ``install -m 440 ...``, ``rm -f -- `` -- so a +sudoers allowlist of commands can name each one. What goes into a file is +staged first, without privilege; root never reads stdin, where a sudo that +does not prompt would leave the password. + +**Nothing root runs follows the person's files.** The key files live in a home +the person owns, where a symbolic link may point anywhere, so they are read and +written as that person (``sudo -n -u ``). Only the existence of a key +file is asked as root. + +**The sudo rule is a file of its own** in the drop-in directory sudo includes, +`` ALL=(ALL) ALL``: the person's own password, as on a new VM. A group +alone is not enough, as some distributions grant ``%wheel`` and others +``%sudo``. ``visudo`` checks the rule before it is installed, and ``sudo -l`` +afterwards shows whether it took effect. A rule elsewhere -- cloud-init's +``90-cloud-init-users`` -- is not edited; it is reported. + +**The login user's own account and system accounts are never touched**: +locking the first would lock the caller out. +""" + +from __future__ import annotations + +import re +import shlex +from collections.abc import Iterable, Sequence +from typing import TYPE_CHECKING, ClassVar + +from typing_extensions import TypedDict + +from napalm_device_types.fixes import run_fix_steps +from napalm_device_types.models import FixResultDict, FixStepDict, FixStepOutcomeDict + +if TYPE_CHECKING: # pragma: no cover - for type checkers only + from napalm_device_types.channel import CommandResult + +#: A login name every POSIX host takes as it is: lowercase, a letter or an +#: underscore first, at most 32 characters. It is also safe in a root command. +ACCOUNT_NAME_RE = re.compile(r"[a-z_][a-z0-9_.-]{0,31}") + +#: The crypt(3) prefixes of each password scheme a driver may take. +PASSWORD_SCHEMES: dict[str, tuple[str, ...]] = { + "sha512": ("$6$",), + "bcrypt": ("$2b$", "$2a$", "$2y$"), +} +_CRYPT_RE = re.compile(r"\$[0-9a-z]+\$[./0-9A-Za-z$]+") + +#: The public key types OpenSSH takes in a key file. +_KEY_TYPE_RE = re.compile( + r"(ssh-ed25519|ssh-rsa|ecdsa-sha2-nistp(256|384|521)" + r"|sk-ssh-ed25519@openssh\.com|sk-ecdsa-sha2-nistp256@openssh\.com)" +) +_KEY_BLOB_RE = re.compile(r"[A-Za-z0-9+/]+={0,3}") + +#: Before the rule's file name; after cloud-init's ``90-`` it would win, so before it. +SUDOERS_FILE_PREFIX = "80-account-" + +#: A line of ``sudo -l`` that lets the account run every command as root. +_RUN_ALL_RE = re.compile(r"^\s*\(ALL(\s*:\s*ALL)?\)\s+([A-Z_]+:\s*)*ALL\s*$", re.MULTILINE) + +#: Stages stdin as a file anyone may read -- the person reads the key file +#: from it -- and prints its path. The content is a public key or a sudo rule. +_STAGE = 't=$(mktemp) && chmod 644 "$t" && cat > "$t" && printf %s "$t"' + + +class LocalAccountDict(TypedDict): + """A person's account as the host has it (``get_local_accounts``).""" + + name: str + uid: int + home: str + shell: str + #: Primary group first. + groups: list[str] + #: No login, with a key or a password. + locked: bool + #: ``sudo -l`` lets it run every command as root. + admin: bool + #: The lines of its key files; None when they could not be read (a locked + #: account cannot run a command any more). + authorized_keys: list[str] | None + + +class LocalAccountChangeDict(FixResultDict): + """The result of ``add_local_account`` and ``lock_local_account``.""" + + #: The account read back after the change; None when it is not there or + #: could not be read. + account: LocalAccountDict | None + + +def sudoers_rule(name: str) -> str: + """The rule that lets *name* run everything as root, with its own password.""" + return f"{name} ALL=(ALL) ALL\n" + + +def sudoers_rule_path(directory: str, name: str) -> str: + """Where *name*'s rule lives in *directory*. + + sudo skips a file whose name holds a dot, so a dot becomes ``_2e``, and an + underscore ``__``: no two names share a file. + """ + escaped = name.replace("_", "__").replace(".", "_2e") + return f"{directory}/{SUDOERS_FILE_PREFIX}{escaped}" + + +def authorized_keys_paths(home: str) -> tuple[str, str]: + """The key files sshd reads in *home* unless configured otherwise.""" + return f"{home}/.ssh/authorized_keys", f"{home}/.ssh/authorized_keys2" + + +def check_account_name(name: str) -> None: + """:raises ValueError: when *name* is no login name every host takes.""" + if not ACCOUNT_NAME_RE.fullmatch(name): + raise ValueError(f"not an account name: {name!r}") + + +def _key_blob(line: str) -> str | None: + """The base64 part of a key file line, options and comment aside.""" + words = line.split() + for i, word in enumerate(words[:-1]): + if _KEY_TYPE_RE.fullmatch(word): + return words[i + 1] + return None + + +def check_public_key(key: str) -> None: + """:raises ValueError: when *key* is not one OpenSSH public key on one line.""" + words = key.split() + if ( + "\n" in key.strip() + or len(words) < 2 + or not _KEY_TYPE_RE.fullmatch(words[0]) + or not _KEY_BLOB_RE.fullmatch(words[1]) + ): + raise ValueError("not a public key: expected ' [comment]' on one line") + + +def _command(argv: Sequence[str]) -> str: + return shlex.join(argv) + + +def _as(name: str, *argv: str) -> str: + """*argv* run as *name*, from root: nothing it does reaches beyond that account.""" + return _command(["sudo", "-n", "-u", name, *argv]) + + +def _said(result: CommandResult) -> str: + return (result.stderr or result.stdout).strip() or f"exit {result.exit_code}" + + +class LocalAccountsMixin: + """Reads, adds and locks personal accounts; a driver supplies the OS's commands. + + Mixed in by the drivers that can, so ``callable(getattr(driver, + "add_local_account", None))`` says whether a driver can. + """ + + #: The login shell of a new account. + ACCOUNT_SHELL: ClassVar[str] = "/bin/sh" + #: The password scheme the host's accounts take, a key of :data:`PASSWORD_SCHEMES`. + ACCOUNT_PASSWORD_SCHEME: ClassVar[str] = "sha512" + #: Groups that make an account an administrator; a person without sudo leaves them. + ACCOUNT_ADMIN_GROUPS: ClassVar[tuple[str, ...]] = ("wheel",) + #: The lowest uid of a person's account; below are the system's. + ACCOUNT_MIN_UID: ClassVar[int] = 1000 + #: The drop-in directory sudo includes. + SUDOERS_DIR: ClassVar[str] = "/etc/sudoers.d" + #: The group of root's files. + ROOT_GROUP: ClassVar[str] = "root" + + if TYPE_CHECKING: # pragma: no cover - declared for type checkers only + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: ... + + # -- 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. + + 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`. + + Without *password_hash* the account takes no password, only a key. + """ + raise NotImplementedError + + def _account_open( + self, name: str, password_hash: str | None, *, locked: bool + ) -> list[list[str]]: + """The commands that let *name* log in again, with *password_hash* if given.""" + raise NotImplementedError + + def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]: + """The commands that refuse *name* every login, a key's too; none when *locked*.""" + raise NotImplementedError + + def _account_locked(self, name: str, passwd: list[str]) -> bool: + """Whether *name* is locked; *passwd* is its ``getent passwd`` line, split. + + :raises RuntimeError: when that cannot be read. + """ + raise NotImplementedError + + def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]: + """The command that takes *name* out of *group*; *groups* are all of its own.""" + raise NotImplementedError + + # -- reading --------------------------------------------------------------------- + + def get_local_accounts(self, names: Iterable[str]) -> list[LocalAccountDict]: + """The accounts of *names* the host has, in that order; a missing one is left out. + + :raises ValueError: for a name that is no account name. + :raises RuntimeError: when an account cannot be read. + """ + wanted = list(names) + for name in wanted: + check_account_name(name) + found = (self._accounts_read(name) for name in wanted) + return [account for account in found if account is not None] + + def _accounts_passwd(self, name: str) -> list[str] | None: + result = self.run_command(_command(["getent", "passwd", name]), timeout=30) + if result.exit_code == 2: + return None + fields = result.stdout.strip().split(":") + if result.exit_code != 0 or len(fields) < 7 or fields[0] != name: + raise RuntimeError(f"cannot read the account {name}: {_said(result)}") + return fields + + def _accounts_read(self, name: str) -> LocalAccountDict | None: + passwd = self._accounts_passwd(name) + if passwd is None: + return None + groups = self.run_command(_command(["id", "-Gn", name]), timeout=30) + if groups.exit_code != 0: + raise RuntimeError(f"cannot read the groups of {name}: {_said(groups)}") + home = passwd[5] + return { + "name": name, + "uid": int(passwd[2]), + "home": home, + "shell": passwd[6], + "groups": groups.stdout.split(), + "locked": self._account_locked(name, passwd), + "admin": self._accounts_admin(name), + "authorized_keys": self._account_read_keys(name, home), + } + + def _accounts_admin(self, name: str) -> bool: + result = self.run_command(_command(["sudo", "-l", "-U", name]), privileged=True, timeout=30) + if result.exit_code != 0: + raise RuntimeError(f"cannot ask sudo about {name}: {_said(result)}") + return bool(_RUN_ALL_RE.search(result.stdout)) + + def _account_key_files(self, name: str, home: str) -> tuple[str, ...]: + """Every file sshd reads *name*'s keys from; a host that adds one of its own says so.""" + return authorized_keys_paths(home) + + def _account_read_keys(self, name: str, home: str) -> list[str] | None: + """The lines of :meth:`_account_key_files`, read as *name*; None when it cannot.""" + lines: list[str] = [] + for path in self._account_key_files(name, home): + there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30) + if there.exit_code != 0: + continue + result = self.run_command(_as(name, "cat", "--", path), privileged=True, timeout=30) + if result.exit_code != 0: + return None + lines += [ln for ln in result.stdout.splitlines() if ln.strip()] + return lines + + # -- changing ---------------------------------------------------------------------- + + def add_local_account( + self, + name: str, + public_key: str, + *, + password_hash: str | None = None, + admin: bool = False, + ) -> LocalAccountChangeDict: + """Give *name* an account that logs in with *public_key*, or open it again. + + An account that is there is opened again and keeps its other keys; a + new one gets a home. *password_hash* (crypt(3), in + :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. + + Steps: ``account``, then ``sudo`` and ``keys``, each of which runs when + the other failed. + + :raises ValueError: for a name, key or hash no host takes, 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) + 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))]), + ] + return self._accounts_result(name, parts) + + def lock_local_account(self, name: str) -> LocalAccountChangeDict: + """Lock *name*: its keys go, every login is refused, sudo goes; its home stays. + + Steps ``keys``, ``lock`` and ``sudo``, each run when one before failed: + the lock matters most. A sudo rule outside the drop-in directory is + reported, not edited -- with the account locked it can no longer be used. + + :raises ValueError: for a name no host takes, the login user's own + account, or a system account. + """ + check_account_name(name) + if self._accounts_changeable(name) is None: + step: FixStepDict = {"step": "account", "ok": False, "output": f"no account {name}"} + return {**_joined([step]), "account": None} + parts = [ + run_fix_steps([("keys", lambda: self._accounts_remove_keys(name))]), + run_fix_steps([("lock", lambda: self._accounts_lock(name))]), + run_fix_steps( + [("sudo", lambda: self._accounts_set_sudo(name, admin=False, locked=True))] + ), + ] + return self._accounts_result(name, parts) + + 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): + raise ValueError(f"not a {self.ACCOUNT_PASSWORD_SCHEME} password hash") + + def _accounts_changeable(self, name: str) -> list[str] | None: + """*name*'s passwd line, None when there is none. + + :raises ValueError: for the login user's own account or a system account. + :raises RuntimeError: when the login user cannot be told. + """ + login = self.run_command("id -un", timeout=30).stdout.strip() + if not login: + raise RuntimeError("cannot tell which account this driver logs in with") + if name == login: + raise ValueError(f"{name} is the account this driver logs in with") + passwd = self._accounts_passwd(name) + if passwd is not None and int(passwd[2]) < self.ACCOUNT_MIN_UID: + raise ValueError(f"{name} is a system account (uid {passwd[2]})") + return passwd + + def _accounts_result(self, name: str, parts: list[FixResultDict]) -> LocalAccountChangeDict: + steps = [s for part in parts for s in part["steps"]] + result = _joined(steps) + account: LocalAccountDict | None = None + try: + account = self._accounts_read(name) + except RuntimeError as exc: + result["output"] += f"\n[read back] {exc}" + return {**result, "account": account} + + def _accounts_root(self, argv: Sequence[str]) -> CommandResult: + return self.run_command(_command(argv), privileged=True, timeout=60) + + def _accounts_run(self, commands: list[list[str]]) -> CommandResult | None: + """Run *commands* as root in order; the first that failed, or None.""" + for argv in commands: + result = self._accounts_root(argv) + if result.exit_code != 0: + return result + return None + + def _accounts_open_or_create( + self, name: str, passwd: list[str] | None, password_hash: str | None + ) -> FixStepOutcomeDict: + if passwd is None: + failed = self._accounts_run(self._account_create(name, password_hash)) + done = f"account {name} created" + else: + locked = self._account_locked(name, passwd) + failed = self._accounts_run(self._account_open(name, password_hash, locked=locked)) + done = f"account {name} opened again" if locked else f"account {name} is there" + if failed is not None: + return {"ok": False, "output": _said(failed)} + return {"ok": True, "output": done + (", password set" if password_hash else "")} + + def _accounts_lock(self, name: str) -> FixStepOutcomeDict: + passwd = self._accounts_passwd(name) + if passwd is None: + return {"ok": False, "output": f"no account {name}"} + locked = self._account_locked(name, passwd) + failed = self._accounts_run(self._account_lock(name, locked=locked)) + if failed is not None: + return {"ok": False, "output": _said(failed)} + if not self._account_locked(name, passwd): + return {"ok": False, "output": f"{name} is still not locked"} + return {"ok": True, "output": f"{name} was locked already" if locked else f"{name} locked"} + + # -- sudo -------------------------------------------------------------------------- + + def _accounts_set_sudo( + self, name: str, *, admin: bool, locked: bool = False + ) -> FixStepOutcomeDict: + path = sudoers_rule_path(self.SUDOERS_DIR, name) + if admin: + return self._accounts_grant_sudo(name, path) + said: list[str] = [] + removed = self._accounts_root(["rm", "-f", "--", path]) + if removed.exit_code != 0: + return {"ok": False, "output": f"{path}: {_said(removed)}"} + groups = self.run_command(_command(["id", "-Gn", name]), timeout=30).stdout.split() + for group in self.ACCOUNT_ADMIN_GROUPS: + if group not in groups[1:]: + continue + left = self._accounts_root(self._account_leave_group(name, group, groups)) + if left.exit_code != 0: + return {"ok": False, "output": f"cannot take {name} out of {group}: {_said(left)}"} + groups.remove(group) + said.append(f"{name} left {group}") + if self._accounts_admin(name): + rest = f"another rule than {path} still lets {name} run everything as root" + if locked: + return {"ok": True, "output": f"{rest}; the account is locked, so it cannot use it"} + return {"ok": False, "output": rest} + said.append(f"{name} has no sudo") + return {"ok": True, "output": "\n".join(said)} + + def _accounts_grant_sudo(self, name: str, path: str) -> FixStepOutcomeDict: + staged = self._accounts_stage(sudoers_rule(name)) + try: + checked = self._accounts_root(["visudo", "-cf", staged]) + if checked.exit_code != 0: + return {"ok": False, "output": f"visudo refuses the rule: {_said(checked)}"} + installed = self._accounts_root( + ["install", "-m", "440", "-o", "root", "-g", self.ROOT_GROUP, "--", staged, path] + ) + if installed.exit_code != 0: + return {"ok": False, "output": f"{path}: {_said(installed)}"} + finally: + self._accounts_unstage(staged) + if not self._accounts_admin(name): + return { + "ok": False, + "output": f"{path} is written, but sudo does not read it: " + f"does sudoers include {self.SUDOERS_DIR}?", + } + return {"ok": True, "output": f"{name} may use sudo with its password ({path})"} + + # -- keys -------------------------------------------------------------------------- + + def _accounts_stage(self, content: str) -> str: + """*content* in a fresh file of the login user's; its path. + + :raises RuntimeError: when it cannot be staged. + """ + result = self.run_command(_STAGE, timeout=30, stdin=content.encode()) + path = result.stdout.strip().splitlines()[-1:] or [""] + if result.exit_code != 0 or not path[0].startswith("/"): + raise RuntimeError(f"cannot stage a file: {_said(result)}") + return path[0] + + def _accounts_unstage(self, path: str) -> None: + self.run_command(_command(["rm", "-f", "--", path]), timeout=30) + + def _accounts_home(self, name: str) -> str | None: + passwd = self._accounts_passwd(name) + return passwd[5] if passwd is not None else None + + def _accounts_add_key(self, name: str, public_key: str) -> FixStepOutcomeDict: + home = self._accounts_home(name) + if home is None: + return {"ok": False, "output": f"no account {name}"} + return self._account_add_key(name, home, public_key) + + def _accounts_remove_keys(self, name: str) -> FixStepOutcomeDict: + home = self._accounts_home(name) + if home is None: + return {"ok": False, "output": f"no account {name}"} + return self._account_remove_keys(name, home) + + def _account_add_key(self, name: str, home: str, public_key: str) -> FixStepOutcomeDict: + """Add *public_key* to *name*'s first key file, as *name*; the others stay. + + A driver whose host keeps keys elsewhere overrides this, with + :meth:`_account_read_keys` and :meth:`_account_remove_keys`. + """ + path = authorized_keys_paths(home)[0] + current = self._account_read_keys(name, home) + if current is None: + return {"ok": False, "output": f"cannot read the key files of {name}"} + blob = _key_blob(public_key) + if any(_key_blob(line) == blob for line in current): + return {"ok": True, "output": f"the key is already in {path}"} + 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()])) + try: + failed = self._accounts_run_as( + name, + [ + ["mkdir", "-p", "-m", "700", "--", f"{home}/.ssh"], + ["install", "-m", "600", "--", staged, path], + ], + ) + finally: + self._accounts_unstage(staged) + if failed is not None: + return {"ok": False, "output": f"{path}: {_said(failed)}"} + return {"ok": True, "output": f"key added to {path}"} + + def _accounts_key_file(self, name: str, path: str) -> list[str] | None: + there = self.run_command(_command(["test", "-e", path]), privileged=True, timeout=30) + if there.exit_code != 0: + return [] + result = self.run_command(_as(name, "cat", "--", path), privileged=True, timeout=30) + if result.exit_code != 0: + return None + return [line for line in result.stdout.splitlines() if line.strip()] + + def _accounts_run_as(self, name: str, commands: list[list[str]]) -> CommandResult | None: + for argv in commands: + result = self.run_command(_as(name, *argv), privileged=True, timeout=60) + if result.exit_code != 0: + return result + return None + + def _account_remove_keys(self, name: str, home: str) -> FixStepOutcomeDict: + """Remove *name*'s key files in *home*, as *name*; then no key may be left.""" + paths = authorized_keys_paths(home) + failed = self._accounts_run_as(name, [["rm", "-f", "--", *paths]]) + if failed is not None: + return {"ok": False, "output": f"cannot remove the keys of {name}: {_said(failed)}"} + if self._account_read_keys(name, home): + return {"ok": False, "output": f"{name} still has keys"} + return {"ok": True, "output": f"keys of {name} removed"} + + +def _joined(steps: list[FixStepDict]) -> FixResultDict: + return { + "success": bool(steps) and all(s["ok"] for s in steps), + "steps": steps, + "output": "\n".join(f"[{s['step']}] {s['output']}".rstrip() for s in steps), + } + + +__all__ = [ + "ACCOUNT_NAME_RE", + "PASSWORD_SCHEMES", + "SUDOERS_FILE_PREFIX", + "LocalAccountChangeDict", + "LocalAccountDict", + "LocalAccountsMixin", + "authorized_keys_paths", + "check_account_name", + "check_public_key", + "sudoers_rule", + "sudoers_rule_path", +] diff --git a/tests/test_local_accounts.py b/tests/test_local_accounts.py new file mode 100644 index 0000000..30f1363 --- /dev/null +++ b/tests/test_local_accounts.py @@ -0,0 +1,692 @@ +"""Personal accounts on a host: reading them, adding one, locking one again. + +The host is a fake that keeps accounts, groups, sudo rules and key files in +memory and answers the fixed commands the mixin and a driver send. A driver's +own commands (create, open, lock, leave a group) are stand-ins here; the real +ones are tested in the drivers. +""" + +from __future__ import annotations + +import shlex +from dataclasses import dataclass, field + +import pytest + +from napalm_device_types.channel import CommandResult +from napalm_device_types.local_accounts import ( + LocalAccountsMixin, + authorized_keys_paths, + sudoers_rule, + sudoers_rule_path, +) +from napalm_device_types.models import FixStepOutcomeDict + +ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@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. +SHELL_SYNTAX = (";", "&&", "||", "|", ">", "<", "$(", "`") + + +@dataclass +class _Account: + uid: int + home: str + shell: str = "/bin/sh" + groups: list[str] = field(default_factory=list) + locked: bool = False + password: str | None = None + + +class _Host: + """What the fake host holds, and the commands it ran.""" + + def __init__(self) -> None: + self.login = "netadmin" + self.accounts: dict[str, _Account] = { + "netadmin": _Account(1000, "/home/netadmin", groups=["netadmin", "wheel"]), + "daemon": _Account(1, "/usr/sbin"), + } + #: Path -> content, for the sudoers drop-ins and the key files. + self.files: dict[str, str] = {} + #: Users a rule outside the drop-in directory lets run everything. + self.other_rules: set[str] = set() + #: Whether sudo reads the drop-in directory at all. + self.includes_dropins = True + #: Commands that fail, by their first words ("as " for one run as + #: the person); and commands that succeed without doing anything. + self.failing: set[str] = set() + self.ignored: set[str] = set() + self.ran: list[tuple[str, bool]] = [] + self.staged = 0 + + 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) + + def run(self, command: str, privileged: bool, stdin: bytes | None) -> CommandResult: + self.ran.append((command, privileged)) + if stdin is not None: + assert not privileged, "a privileged command takes no stdin" + return self._stage(command, stdin) + words = shlex.split(command) + if " ".join(words[:2]) in self.failing or words[0] in self.failing: + return CommandResult("", f"{words[0]}: failed", 1) + if words[:3] == ["sudo", "-n", "-u"]: + assert privileged, "only root changes to another user" + return self._as_user(words[3], words[4:]) + handler = getattr(self, "_" + words[0].replace("-", "_"), None) + assert handler is not None, f"unexpected command: {command}" + return handler(words[1:], privileged) + + # -- staging, as the login user --------------------------------------------- + + def _stage(self, command: str, stdin: bytes) -> CommandResult: + assert "mktemp" in command + if "mktemp" in self.failing: + return CommandResult("", "mktemp: No space left on device", 1) + self.staged += 1 + path = f"/tmp/tmp.{self.staged}" + self.files[path] = stdin.decode() + return CommandResult(path, "", 0) + + def _rm(self, args: list[str], privileged: bool) -> CommandResult: + for path in args[args.index("--") + 1 :]: + if path.startswith("/tmp/"): + assert not privileged, "the staged file is the login user's" + self.files.pop(path, None) + return CommandResult("", "", 0) + + # -- the account database ------------------------------------------------------- + + def _getent(self, args: list[str], privileged: bool) -> CommandResult: + assert args[0] == "passwd" and not privileged + a = self.accounts.get(args[1]) + if a is None: + return CommandResult("", "", 2) + return CommandResult(f"{args[1]}:*:{a.uid}:{a.uid}::{a.home}:{a.shell}\n", "", 0) + + def _id(self, args: list[str], privileged: bool) -> CommandResult: + if args == ["-un"]: + return CommandResult(f"{self.login}\n", "", 0) + assert args[0] == "-Gn" and not privileged + a = self.accounts.get(args[1]) + if a is None: + return CommandResult("", f"id: {args[1]}: no such user", 1) + return CommandResult(" ".join(a.groups) + "\n", "", 0) + + def _sudo(self, args: list[str], privileged: bool) -> CommandResult: + assert args[:2] == ["-l", "-U"] and privileged + name = args[2] + if self.is_admin(name): + out = f"User {name} may run the following commands on host:\n (ALL) ALL\n" + else: + out = f"User {name} is not allowed to run sudo on host.\n" + return CommandResult(out, "", 0) + + def _visudo(self, args: list[str], privileged: bool) -> CommandResult: + assert args[0] == "-cf" and privileged + content = self.files[args[1]] + ok = content.endswith(" ALL=(ALL) ALL\n") and "\n" not in content[:-1] + return CommandResult("parsed OK" if ok else "syntax error", "", 0 if ok else 1) + + def _install(self, args: list[str], privileged: bool) -> CommandResult: + assert privileged + source, target = args[args.index("--") + 1 :] + assert target.startswith(_Driver.SUDOERS_DIR + "/"), "root installs only sudo rules" + assert args[:6] == ["-m", "440", "-o", "root", "-g", _Driver.ROOT_GROUP] + self.files[target] = self.files[source] + return CommandResult("", "", 0) + + def _test(self, args: list[str], privileged: bool) -> CommandResult: + assert args[0] == "-e" + return CommandResult("", "", 0 if args[1] in self.files else 1) + + # -- the person's own files, as that person ------------------------------------ + + def _as_user(self, name: str, words: list[str]) -> CommandResult: + a = self.accounts[name] + if a.locked: + return CommandResult("", "sudo: account expired", 1) + rest = words[words.index("--") + 1 :] if "--" in words else words[1:] + if f"as {words[0]}" in self.failing: + return CommandResult("", f"{words[0]}: Permission denied", 1) + if f"as {words[0]}" in self.ignored: + return CommandResult("", "", 0) + assert all(p.startswith(a.home + "/") or p.startswith("/tmp/") for p in rest) + if words[0] == "cat": + return CommandResult(self.files.get(rest[0], ""), "", 0) + if words[0] == "mkdir": + return CommandResult("", "", 0) + if words[0] == "install": + assert words[1:3] == ["-m", "600"] + self.files[rest[1]] = self.files[rest[0]] + return CommandResult("", "", 0) + if words[0] == "rm": + for path in rest: + self.files.pop(path, None) + return CommandResult("", "", 0) + raise AssertionError(f"unexpected command as {name}: {words}") + + # -- the driver's own commands (stand-ins) ------------------------------------- + + def _mkuser(self, args: list[str], privileged: bool) -> CommandResult: + assert privileged + name, password = args[0], (args[1] if len(args) > 1 else None) + uid = 1001 + len(self.accounts) + self.accounts[name] = _Account(uid, f"/home/{name}", groups=[name], password=password) + return CommandResult("", "", 0) + + def _openuser(self, args: list[str], privileged: bool) -> CommandResult: + assert privileged + a = self.accounts[args[0]] + a.locked = False + if len(args) > 1: + a.password = args[1] + return CommandResult("", "", 0) + + def _lockuser(self, args: list[str], privileged: bool) -> CommandResult: + assert privileged + self.accounts[args[0]].locked = "lockuser" not in self.ignored + return CommandResult("", "", 0) + + def _islocked(self, args: list[str], privileged: bool) -> CommandResult: + assert privileged + return CommandResult("yes\n" if self.accounts[args[0]].locked else "no\n", "", 0) + + def _leavegroup(self, args: list[str], privileged: bool) -> CommandResult: + assert privileged + self.accounts[args[0]].groups.remove(args[1]) + return CommandResult("", "", 0) + + +class _Driver(LocalAccountsMixin): + ACCOUNT_SHELL = "/bin/sh" + ACCOUNT_ADMIN_GROUPS = ("wheel", "sudo") + SUDOERS_DIR = "/etc/sudoers.d" + ROOT_GROUP = "wheel" + + def __init__(self, host: _Host) -> None: + self.host = host + + def run_command( + self, + command: str, + *, + privileged: bool = False, + timeout: float = 60, + stdin: bytes | None = None, + ) -> CommandResult: + return self.host.run(command, privileged, stdin) + + def _account_create(self, name: str, password_hash: str | None) -> list[list[str]]: + return [["mkuser", name, *([password_hash] if password_hash else [])]] + + def _account_open( + self, name: str, password_hash: str | None, *, locked: bool + ) -> list[list[str]]: + return [["openuser", name, *([password_hash] if password_hash else [])]] + + def _account_lock(self, name: str, *, locked: bool) -> list[list[str]]: + return [] if locked else [["lockuser", name]] + + def _account_locked(self, name: str, passwd: list[str]) -> bool: + result = self.run_command(shlex.join(["islocked", name]), privileged=True) + return result.stdout.strip() == "yes" + + def _account_leave_group(self, name: str, group: str, groups: list[str]) -> list[str]: + return ["leavegroup", name, group] + + +@pytest.fixture +def host() -> _Host: + return _Host() + + +@pytest.fixture +def driver(host: _Host) -> _Driver: + return _Driver(host) + + +def _root_commands(host: _Host) -> list[str]: + return [c for c, privileged in host.ran if privileged] + + +def _add_alice(host: _Host, *, locked: bool = False, keys: str = "") -> None: + host.accounts["alice"] = _Account( + 1001, "/home/alice", groups=["alice", "wheel"], locked=locked, password=HASH + ) + if keys: + host.files["/home/alice/.ssh/authorized_keys"] = keys + + +# -- the helpers --------------------------------------------------------------------- + + +def test_the_sudo_rule_names_the_account_and_asks_for_its_password() -> None: + assert sudoers_rule("alice") == "alice ALL=(ALL) ALL\n" + + +def test_the_rule_file_has_no_dot_sudo_would_skip() -> None: + # sudo ignores a file in an included directory whose name holds a dot. + path = sudoers_rule_path("/etc/sudoers.d", "a.lice") + assert path.startswith("/etc/sudoers.d/") + assert "." not in path.rsplit("/", 1)[1] + assert sudoers_rule_path("/etc/sudoers.d", "a.lice") != sudoers_rule_path( + "/etc/sudoers.d", "a_lice" + ) + + +def test_both_key_files_sshd_reads_by_default() -> None: + assert authorized_keys_paths("/home/alice") == ( + "/home/alice/.ssh/authorized_keys", + "/home/alice/.ssh/authorized_keys2", + ) + + +# -- reading -------------------------------------------------------------------------- + + +def test_an_account_is_read_with_its_groups_lock_sudo_and_keys( + host: _Host, driver: _Driver +) -> None: + _add_alice(host, keys=ALICE_KEY + "\n" + OWN_KEY + "\n") + host.other_rules.add("alice") + + [account] = driver.get_local_accounts(["alice"]) + + assert account == { + "name": "alice", + "uid": 1001, + "home": "/home/alice", + "shell": "/bin/sh", + "groups": ["alice", "wheel"], + "locked": False, + "admin": True, + "authorized_keys": [ALICE_KEY, OWN_KEY], + } + + +def test_an_account_that_is_not_there_is_left_out(driver: _Driver) -> None: + assert driver.get_local_accounts(["bob"]) == [] + + +def test_a_locked_accounts_keys_that_cannot_be_read_are_unknown( + host: _Host, driver: _Driver +) -> None: + _add_alice(host, locked=True, keys=ALICE_KEY + "\n") + + [account] = driver.get_local_accounts(["alice"]) + + assert account["locked"] is True + assert account["authorized_keys"] is None + + +def test_an_account_without_a_key_file_has_no_keys(host: _Host, driver: _Driver) -> None: + _add_alice(host) + + [account] = driver.get_local_accounts(["alice"]) + + assert account["authorized_keys"] == [] + + +def test_a_failing_read_raises_rather_than_report_nothing(host: _Host, driver: _Driver) -> None: + _add_alice(host) + host.failing.add("sudo -l") + + with pytest.raises(RuntimeError, match="alice"): + driver.get_local_accounts(["alice"]) + + +@pytest.mark.parametrize("name", ["", "Alice", "1alice", "al ice", "a;b", "-alice", "a" * 33]) +def test_a_name_no_guest_takes_is_refused(driver: _Driver, name: str) -> None: + with pytest.raises(ValueError, match="account name"): + driver.get_local_accounts([name]) + + +# -- adding --------------------------------------------------------------------------- + + +def test_a_new_account_gets_the_key_and_the_sudo_rule(host: _Host, driver: _Driver) -> None: + result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True) + + assert result["success"], result["output"] + assert [s["step"] for s in result["steps"]] == ["account", "sudo", "keys"] + assert host.accounts["alice"].password == HASH + assert host.files["/home/alice/.ssh/authorized_keys"] == ALICE_KEY + "\n" + assert host.files["/etc/sudoers.d/80-account-alice"] == "alice ALL=(ALL) ALL\n" + account = result["account"] + assert account is not None + assert account["admin"] is True and account["authorized_keys"] == [ALICE_KEY] + + +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.lock_local_account("alice") + + for command in _root_commands(host): + assert not any(s in command for s in SHELL_SYNTAX), command + + +def test_the_staged_files_are_removed_again(host: _Host, driver: _Driver) -> None: + driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True) + + assert host.staged == 2 + assert not [p for p in host.files if p.startswith("/tmp/")] + + +def test_an_existing_account_keeps_its_own_keys(host: _Host, driver: _Driver) -> None: + _add_alice(host, keys=OWN_KEY + "\n") + + result = driver.add_local_account("alice", ALICE_KEY) + + assert result["success"], result["output"] + assert host.files["/home/alice/.ssh/authorized_keys"] == f"{OWN_KEY}\n{ALICE_KEY}\n" + + +def test_a_line_without_a_key_is_kept_and_not_taken_for_one(host: _Host, driver: _Driver) -> None: + _add_alice(host, keys="# the laptop\n") + + result = driver.add_local_account("alice", ALICE_KEY) + + assert result["success"], result["output"] + assert host.files["/home/alice/.ssh/authorized_keys"] == f"# the laptop\n{ALICE_KEY}\n" + + +def test_a_key_already_there_is_not_written_again(host: _Host, driver: _Driver) -> None: + # The same key with options in front and another comment is the same key. + _add_alice(host, keys=f'from="10.0.0.0/8" {ALICE_KEY.rsplit(" ", 1)[0]} old\n') + + result = driver.add_local_account("alice", ALICE_KEY) + + assert result["success"], result["output"] + assert host.staged == 0 + assert "already" in result["steps"][-1]["output"] + + +def test_a_locked_account_is_opened_again(host: _Host, driver: _Driver) -> None: + _add_alice(host, locked=True) + + result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH) + + assert result["success"], result["output"] + assert host.accounts["alice"].locked is False + assert result["account"] is not None and result["account"]["locked"] is False + + +def test_without_sudo_the_rule_and_the_admin_groups_go(host: _Host, driver: _Driver) -> None: + _add_alice(host) + host.files["/etc/sudoers.d/80-account-alice"] = sudoers_rule("alice") + + result = driver.add_local_account("alice", ALICE_KEY, admin=False) + + assert result["success"], result["output"] + assert "/etc/sudoers.d/80-account-alice" not in host.files + assert host.accounts["alice"].groups == ["alice"] + + +def test_sudo_another_rule_still_grants_fails_the_step(host: _Host, driver: _Driver) -> None: + _add_alice(host) + host.other_rules.add("alice") + + result = driver.add_local_account("alice", ALICE_KEY, admin=False) + + assert not result["success"] + sudo = next(s for s in result["steps"] if s["step"] == "sudo") + assert not sudo["ok"] and "another rule" in sudo["output"] + # The key still went in: the steps after the account are independent. + assert host.files["/home/alice/.ssh/authorized_keys"] == ALICE_KEY + "\n" + + +def test_a_rule_sudo_does_not_read_fails_the_step(host: _Host, driver: _Driver) -> None: + host.includes_dropins = False + + result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True) + + sudo = next(s for s in result["steps"] if s["step"] == "sudo") + assert not sudo["ok"] and "/etc/sudoers.d" in sudo["output"] + + +def test_a_rule_visudo_rejects_is_not_installed(host: _Host, driver: _Driver) -> None: + host.failing.add("visudo") + + result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True) + + assert not result["success"] + assert "/etc/sudoers.d/80-account-alice" not in host.files + assert not [p for p in host.files if p.startswith("/tmp/")] + + +def test_a_failed_create_stops_before_sudo_and_keys(host: _Host, driver: _Driver) -> None: + host.failing.add("mkuser") + + result = driver.add_local_account("alice", ALICE_KEY, admin=True) + + assert not result["success"] + assert [s["step"] for s in result["steps"]] == ["account"] + assert result["account"] is None + + +@pytest.mark.parametrize( + "key", + ["", "not a key", ALICE_KEY + "\n" + OWN_KEY, "ssh-ed25519", "ssh-ed25519 AAAA;rm"], +) +def test_a_public_key_that_is_none_is_refused(driver: _Driver, key: str) -> None: + with pytest.raises(ValueError, match="public key"): + driver.add_local_account("alice", key) + + +@pytest.mark.parametrize("password_hash", ["secret", "$6$salt$ab cd", "$2b$10$" + "x" * 53]) +def test_a_password_hash_the_guest_does_not_take_is_refused( + driver: _Driver, password_hash: str +) -> None: + # This driver takes SHA-512 crypt: neither plain text nor bcrypt. + with pytest.raises(ValueError, match="password hash"): + driver.add_local_account("alice", ALICE_KEY, password_hash=password_hash) + + +def test_the_login_users_own_account_is_never_touched(host: _Host, driver: _Driver) -> None: + for change in ( + lambda: driver.add_local_account("netadmin", ALICE_KEY), + lambda: driver.lock_local_account("netadmin"), + ): + with pytest.raises(ValueError, match="logs in"): + change() + assert _root_commands(host) == [] + + +def test_nothing_changes_when_the_login_user_cannot_be_told(host: _Host, driver: _Driver) -> None: + _add_alice(host) + host.login = "" + + with pytest.raises(RuntimeError, match="logs in"): + driver.lock_local_account("alice") + assert _root_commands(host) == [] + + +def test_a_system_account_is_never_touched(host: _Host, driver: _Driver) -> None: + with pytest.raises(ValueError, match="system account"): + driver.lock_local_account("daemon") + assert _root_commands(host) == [] + + +# -- locking -------------------------------------------------------------------------- + + +def test_locking_takes_keys_sudo_and_login_away(host: _Host, driver: _Driver) -> None: + _add_alice(host, keys=ALICE_KEY + "\n" + OWN_KEY + "\n") + host.files["/home/alice/.ssh/authorized_keys2"] = OWN_KEY + "\n" + host.files["/etc/sudoers.d/80-account-alice"] = sudoers_rule("alice") + + result = driver.lock_local_account("alice") + + assert result["success"], result["output"] + assert [s["step"] for s in result["steps"]] == ["keys", "lock", "sudo"] + a = host.accounts["alice"] + assert a.locked and a.groups == ["alice"] and a.password == HASH + assert not [p for p in host.files if p.startswith("/home/alice/")] + assert "/etc/sudoers.d/80-account-alice" not in host.files + account = result["account"] + assert account is not None and account["locked"] and not account["admin"] + + +def test_a_rule_left_elsewhere_is_named_but_harmless_once_locked( + host: _Host, driver: _Driver +) -> None: + _add_alice(host) + host.other_rules.add("alice") + + result = driver.lock_local_account("alice") + + assert result["success"], result["output"] + sudo = next(s for s in result["steps"] if s["step"] == "sudo") + assert "another rule" in sudo["output"] and "locked" in sudo["output"] + + +def test_the_lock_comes_even_when_the_keys_could_not_go(host: _Host, driver: _Driver) -> None: + _add_alice(host, locked=True, keys=ALICE_KEY + "\n") + + result = driver.lock_local_account("alice") + + assert not result["success"] + keys = next(s for s in result["steps"] if s["step"] == "keys") + assert not keys["ok"] + assert next(s for s in result["steps"] if s["step"] == "lock")["ok"] + assert host.accounts["alice"].locked + + +def test_locking_an_account_that_is_not_there_fails(driver: _Driver) -> None: + result = driver.lock_local_account("bob") + + assert not result["success"] + assert "no account" in result["output"] + assert result["account"] is None + + +# -- what fails is said --------------------------------------------------------------- + + +@pytest.mark.parametrize("failing", ["getent", "id -Gn"]) +def test_an_account_that_cannot_be_read_raises(host: _Host, driver: _Driver, failing: str) -> None: + _add_alice(host) + host.failing.add(failing) + + with pytest.raises(RuntimeError, match="alice"): + driver.get_local_accounts(["alice"]) + + +@pytest.mark.parametrize( + ("failing", "step", "said"), + [ + ("rm -f", "sudo", "80-account-alice"), + ("leavegroup", "sudo", "out of wheel"), + ("as cat", "keys", "cannot read"), + ("as install", "keys", "authorized_keys"), + ("mktemp", "keys", "cannot stage"), + ], +) +def test_a_step_that_fails_says_why( + host: _Host, driver: _Driver, failing: str, step: str, said: str +) -> None: + _add_alice(host, keys=OWN_KEY + "\n") + host.failing.add(failing) + + result = driver.add_local_account("alice", ALICE_KEY) + + failed = next(s for s in result["steps"] if s["step"] == step) + assert not failed["ok"] and said in failed["output"] + assert not result["success"] + + +def test_a_rule_that_cannot_be_installed_fails_the_step(host: _Host, driver: _Driver) -> None: + host.failing.add("install -m") + + result = driver.add_local_account("alice", ALICE_KEY, password_hash=HASH, admin=True) + + sudo = next(s for s in result["steps"] if s["step"] == "sudo") + assert not sudo["ok"] and "80-account-alice" in sudo["output"] + assert not [p for p in host.files if p.startswith("/tmp/")] + + +@pytest.mark.parametrize( + ("failing", "ignored", "step", "said"), + [ + ({"lockuser"}, set(), "lock", "lockuser: failed"), + (set(), {"lockuser"}, "lock", "still not locked"), + ({"as rm"}, set(), "keys", "cannot remove"), + (set(), {"as rm"}, "keys", "still has keys"), + ], +) +def test_a_lock_that_did_not_take_says_so( + host: _Host, driver: _Driver, failing: set[str], ignored: set[str], step: str, said: str +) -> None: + _add_alice(host, keys=ALICE_KEY + "\n") + host.failing |= failing + host.ignored |= ignored + + result = driver.lock_local_account("alice") + + failed = next(s for s in result["steps"] if s["step"] == step) + assert not failed["ok"] and said in failed["output"] + assert not result["success"] + + +def test_an_account_that_cannot_be_read_back_is_said(host: _Host, driver: _Driver) -> None: + _add_alice(host) + host.failing.add("sudo -l") + + result = driver.lock_local_account("alice") + + assert result["account"] is None + assert "[read back] cannot ask sudo about alice" in result["output"] + + +# -- a key store of the driver's own --------------------------------------------------- + + +class _OwnKeyStore(_Driver): + """A driver whose host keeps keys in a place of its own.""" + + def __init__(self, host: _Host) -> None: + super().__init__(host) + self.store: dict[str, list[str]] = {} + + def _account_read_keys(self, name: str, home: str) -> list[str] | None: + return list(self.store.get(name, [])) + + def _account_add_key(self, name: str, home: str, public_key: str) -> FixStepOutcomeDict: + self.store.setdefault(name, []).append(f"{home} {public_key}") + return {"ok": True, "output": "stored"} + + def _account_remove_keys(self, name: str, home: str) -> FixStepOutcomeDict: + self.store.pop(name, None) + return {"ok": True, "output": "dropped"} + + +def test_a_driver_can_keep_the_keys_elsewhere(host: _Host) -> None: + driver = _OwnKeyStore(host) + + added = driver.add_local_account("alice", ALICE_KEY) + assert added["success"], added["output"] + assert driver.store == {"alice": [f"/home/alice {ALICE_KEY}"]} + assert added["account"] is not None + assert added["account"]["authorized_keys"] == [f"/home/alice {ALICE_KEY}"] + assert not [p for p in host.files if p.startswith("/home/")] + + locked = driver.lock_local_account("alice") + assert locked["success"], locked["output"] + assert driver.store == {} + + +def test_a_key_file_the_host_adds_is_read_too(host: _Host) -> None: + class _ExtraFile(_Driver): + def _account_key_files(self, name: str, home: str) -> tuple[str, ...]: + return (*super()._account_key_files(name, home), f"/home/{name}/extra") + + _add_alice(host, keys=OWN_KEY + "\n") + host.files["/home/alice/extra"] = ALICE_KEY + "\n" + + [account] = _ExtraFile(host).get_local_accounts(["alice"]) + + assert account["authorized_keys"] == [OWN_KEY, ALICE_KEY]