feat: a fixed uid for netOrk's own account (NetOrk/netork#1817)
driver / standard (pull_request) Successful in 16s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Successful in 1m8s
driver / test (3.13) (pull_request) Successful in 1m2s
driver / lowest (pull_request) Successful in 31s
driver / security (pull_request) Successful in 1m3s
driver / build (pull_request) Successful in 26s
driver / test (3.12) (pull_request) Successful in 1m10s
CI / driver (pull_request) Successful in 1m10s
driver / publish (pull_request) Skipped

add_service_account(uid=) makes a new account with that uid once no other
account has it, through the driver's _account_create_with_uid; an account that
is there keeps its own, as a uid is never changed under files that carry it.
The infrastructure's build standard wants the same uid on every host.
This commit is contained in:
christianmanivong committed 2026-11-01 12:42:30 +01:00
1 parent 666be091e3
commit 3f59023f46
3 files changed
+137 -4

No files matched your search

+3 -1
View File
@@ -19,7 +19,9 @@ recorded here; their history is the git log.
password, and a rule of its own in `85-service-<name>` 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
+51 -3
View File
@@ -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):
+83
View File
@@ -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"]