diff --git a/CHANGELOG.md b/CHANGELOG.md index 6f1c27e..d6a8ea8 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -19,7 +19,9 @@ recorded here; their history is the git log. password, and a rule of its own in `85-service-` lets it run everything as root without a password (`NOPASSWD: ALL`, checked with `visudo` and `sudo -l`). An account that is there is opened again and keeps its other keys; root is refused - (NetOrk/netork#1817). + (NetOrk/netork#1817). With `uid=`, a new account gets that uid once no other account + has it; one that is there keeps its own. A driver supplies + `_account_create_with_uid`. - `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 diff --git a/napalm_device_types/local_accounts.py b/napalm_device_types/local_accounts.py index 9cde5c3..fae3d6e 100644 --- a/napalm_device_types/local_accounts.py +++ b/napalm_device_types/local_accounts.py @@ -254,6 +254,14 @@ class LocalAccountsMixin: """The command that takes *name* out of *group*; *groups* are all of its own.""" raise NotImplementedError + def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]: + """The commands that create *name* as :meth:`_account_create` does, without a + password, and with the uid *uid*. + + Only netOrk's own account asks for one (``add_service_account(uid=)``). + """ + raise NotImplementedError + # -- reading --------------------------------------------------------------------- def get_local_accounts(self, names: Iterable[str]) -> list[LocalAccountDict]: @@ -383,7 +391,9 @@ class LocalAccountsMixin: ] return self._accounts_result(name, parts) - def add_service_account(self, name: str, public_key: str) -> LocalAccountChangeDict: + def add_service_account( + self, name: str, public_key: str, *, uid: int | None = None + ) -> LocalAccountChangeDict: """Make *name* netOrk's own account: it logs in with *public_key*, and gains root without a password. @@ -392,14 +402,20 @@ class LocalAccountsMixin: again with the account the driver already logs in with, it only adds what is missing. + A new account gets *uid* when one is given -- the same on every host -- + once no other account has it; an account that is there keeps its own, + as a uid is never changed under files that carry it. + Steps as in :meth:`add_local_account`: ``account``, then ``sudo`` and ``keys``. The new login itself is for the caller to try. - :raises ValueError: for a name or key no host takes, or root. + :raises ValueError: for a name or key no host takes, root, or a uid of 0 or less. :raises RuntimeError: when the login user cannot be told. """ check_account_name(name) check_public_key(public_key) + if uid is not None and uid <= 0: + raise ValueError(f"not a uid for netOrk's own account: {uid}") login = self._accounts_login() existing = self._accounts_passwd(name) if existing is not None and int(existing[2]) == 0: @@ -413,7 +429,7 @@ class LocalAccountsMixin: first: FixResultDict = _joined([step]) else: first = run_fix_steps( - [("account", lambda: self._accounts_open_or_create(name, existing, None))] + [("account", lambda: self._accounts_service_account(name, existing, uid))] ) parts = [first] if first["success"]: @@ -423,6 +439,38 @@ class LocalAccountsMixin: ] return self._accounts_result(name, parts) + def _accounts_service_account( + self, name: str, passwd: list[str] | None, uid: int | None + ) -> FixStepOutcomeDict: + """netOrk's own account opened or made, a new one with *uid* when given.""" + if uid is None: + return self._accounts_open_or_create(name, passwd, None) + if passwd is not None: + outcome = self._accounts_open_or_create(name, passwd, None) + if outcome["ok"] and int(passwd[2]) != uid: + outcome["output"] += f"; it keeps its uid {passwd[2]}, not {uid}" + return outcome + owner = self._accounts_passwd_of_uid(uid) + if owner is not None: + return {"ok": False, "output": f"uid {uid} is the account {owner}'s"} + try: + create = self._account_create_with_uid(name, uid) + except NotImplementedError: + return {"ok": False, "output": f"this driver cannot give an account the uid {uid}"} + failed = self._accounts_run(create) + if failed is not None: + return {"ok": False, "output": _said(failed)} + return {"ok": True, "output": f"account {name} created, uid {uid}"} + + def _accounts_passwd_of_uid(self, uid: int) -> str | None: + """The name of the account with *uid*, or None.""" + result = self.run_command(_command(["getent", "passwd", str(uid)]), timeout=30) + if result.exit_code == 2: + return None + if result.exit_code != 0: + raise RuntimeError(f"cannot ask who has uid {uid}: {_said(result)}") + return result.stdout.split(":", 1)[0].strip() or None + 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): diff --git a/tests/test_service_account.py b/tests/test_service_account.py index 0c53bb7..d9d4169 100644 --- a/tests/test_service_account.py +++ b/tests/test_service_account.py @@ -197,3 +197,86 @@ def test_a_personal_account_of_the_same_name_keeps_its_own_rule_apart( assert [shlex.split(c)[-1] for c in rules] == [ service_sudoers_rule_path(_Driver.SUDOERS_DIR, "netork") ] + + +# -- a fixed uid (infrastructure BAUSTANDARD A) ------------------------------------------ + + +class _UidDriver(_Driver): + def _account_create_with_uid(self, name: str, uid: int) -> list[list[str]]: + return [["mkuseruid", name, str(uid)]] + + +def _mkuseruid(host: _ServiceHost): + def handler(args: list[str], privileged: bool) -> CommandResult: + assert privileged + name, uid = args[0], int(args[1]) + host.accounts[name] = _Account(uid, f"/home/{name}", groups=[name]) + return CommandResult("", "", 0) + + return handler + + +def _getent_uid(host: _ServiceHost, original): + def handler(args: list[str], privileged: bool) -> CommandResult: + if args[1].isdigit(): + owner = next((n for n, a in host.accounts.items() if a.uid == int(args[1])), None) + if owner is None: + return CommandResult("", "", 2) + a = host.accounts[owner] + return CommandResult(f"{owner}:*:{a.uid}:{a.uid}::{a.home}:{a.shell}\n", "", 0) + return original(args, privileged) + + return handler + + +@pytest.fixture +def uid_driver(host: _ServiceHost) -> _UidDriver: + host._mkuseruid = _mkuseruid(host) # type: ignore[attr-defined] + host._getent = _getent_uid(host, host._getent) # type: ignore[method-assign] + return _UidDriver(host) + + +def test_a_new_account_gets_the_uid_asked_for(host: _ServiceHost, uid_driver: _UidDriver) -> None: + result = uid_driver.add_service_account("netork", NETORK_KEY, uid=900) + + assert result["success"], result["output"] + assert host.accounts["netork"].uid == 900 + account = result["account"] + assert account is not None and account["uid"] == 900 + + +def test_a_uid_another_account_has_stops_before_anything_is_made( + host: _ServiceHost, uid_driver: _UidDriver +) -> None: + host.accounts["fwupd-refresh"] = _Account(900, "/run/fwupd") + + result = uid_driver.add_service_account("netork", NETORK_KEY, uid=900) + + assert not result["success"] + assert "fwupd-refresh" in result["output"] + assert "netork" not in host.accounts + + +def test_an_existing_account_keeps_its_uid_and_says_so( + host: _ServiceHost, uid_driver: _UidDriver +) -> None: + host.accounts["netork"] = _Account(1001, "/home/netork", groups=["netork"]) + + result = uid_driver.add_service_account("netork", NETORK_KEY, uid=900) + + assert result["success"], result["output"] + assert host.accounts["netork"].uid == 1001 + assert "uid 1001" in result["output"] + + +def test_a_uid_root_has_is_refused(uid_driver: _UidDriver) -> None: + with pytest.raises(ValueError): + uid_driver.add_service_account("netork", NETORK_KEY, uid=0) + + +def test_a_driver_that_cannot_set_a_uid_says_so(host: _ServiceHost, driver: _Driver) -> None: + result = driver.add_service_account("netork", NETORK_KEY, uid=900) + + assert not result["success"] + assert "uid" in result["output"]