Files
napalm-openmediavault/tests/test_local_accounts.py
T
Christian Manivong d477fb1a76
driver / standard (pull_request) Failing after 14s
driver / lint (pull_request) Successful in 14s
driver / types (pull_request) Failing after 1m13s
driver / test (3.13) (pull_request) Failing after 1m6s
driver / test (3.12) (pull_request) Failing after 1m17s
driver / lowest (pull_request) Failing after 29s
driver / build (pull_request) Successful in 28s
driver / security (pull_request) Successful in 1m5s
CI / driver (pull_request) Failing after 2m25s
driver / publish (pull_request) Skipped
feat: personal accounts the way OMV's web UI makes them (NetOrk/netork#1793)
napalm-linux adds and locks accounts with shadow-utils and keys in ~/.ssh.
OMV's sshd lets in only root and _ssh, and OMV keeps a user's keys in its
own database, deploying them to /var/lib/openmediavault/ssh/authorized_keys.
So a new account is made by UserMgmt.setUser in _ssh, one made outside OMV
joins _ssh when it is opened, and keys go through setUser. Each call applies
the modules it made dirty (postfix, ssh) and leaves what was pending in the
web UI pending. setUser takes a plain password, netOrk only the hash, so the
hash is set with usermod -p. The lock stays napalm-linux's expiry.

Checked on a fresh OMV 8 (Debian 13) with the real driver over SSH and
sudo -S: a new account logs in with its key and uses sudo, is refused
after locking with OMV's keys emptied, logs in again after reopening; an
account made outside OMV is let in once it joined _ssh; a module left
dirty before stays dirty.
2026-10-31 23:43:43 +01:00

248 lines
9.4 KiB
Python

"""Personal accounts on OpenMediaVault, the way its web UI makes them (NetOrk/netork#1793).
napalm-linux adds and locks accounts with shadow-utils and keys in ``~/.ssh``.
On OMV that is not enough: sshd lets in only ``root`` and the ``_ssh`` group,
and a user's keys live in OMV's database, which the ``ssh`` module deploys to
``/var/lib/openmediavault/ssh/authorized_keys/<user>``. So the account is made
through ``UserMgmt.setUser``, the keys go through it as well, and only the
modules that change made dirty are applied.
"""
from __future__ import annotations
import json
import shlex
import pytest
from napalm_device_types import CommandResult
from napalm_openmediavault._local_accounts import OMV_KEYS_DIR, rfc4716_blob
from napalm_openmediavault.openmediavault import OpenMediaVaultDriver
ALICE_KEY = "ssh-ed25519 AAAAC3NzaC1lZDI1NTE5AAAAIAlice alice@laptop"
OWN_KEY = "ssh-rsa AAAAB3NzaC1yc2EAAAADAQABAAABAQOwn own@desktop"
HASH = "$6$salt$" + "x" * 86
def _rfc4716(key: str) -> str:
"""*key* as OMV stores it."""
kind, blob, comment = key.split(" ", 2)
lines = [blob[i : i + 70] for i in range(0, len(blob), 70)]
return "\n".join(
[
"---- BEGIN SSH2 PUBLIC KEY ----",
f'Comment: "{comment}"',
*lines,
"---- END SSH2 PUBLIC KEY ----",
]
)
class Omv:
"""omv-rpc and the dirty-modules file, as ``_sudo_status`` sees them."""
def __init__(self, *, dirty=("apt",), deploys=True):
self.users: dict[str, dict] = {
"alice": {
"name": "alice",
"groups": ["users", "_ssh"],
"email": "alice@example.net",
"disallowusermod": False,
"comment": "Alice",
"shell": "/bin/bash",
"sshpubkeys": [_rfc4716(OWN_KEY)],
}
}
#: What the ssh module last wrote, per user: OpenSSH lines.
self.deployed: dict[str, list[str]] = {"alice": [OWN_KEY]}
self.dirty = list(dirty)
self.deploys = deploys
self.calls: list[tuple[str, object]] = []
def __call__(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
if command.startswith("cat /var/lib/openmediavault/dirtymodules.json"):
return json.dumps(self.dirty), 0
argv = shlex.split(command)
assert argv[:3] == ["omv-rpc", "-u", "admin"], command
method = f"{argv[3]}.{argv[4]}"
params = json.loads(argv[5]) if len(argv) > 5 else None
self.calls.append((method, params))
if method == "UserMgmt.getUser":
return json.dumps(self.users[params["name"]]), 0
if method == "UserMgmt.setUser":
assert params["password"] == "", "OMV takes the plain password: none is sent"
self.users[params["name"]] = {
**params,
"sshpubkeys": [
k if k.startswith("----") else _rfc4716(k) for k in params["sshpubkeys"]
],
}
# As OMV 8 does: the user's mail alias and keys are to be deployed.
self.dirty += [m for m in ("postfix", "ssh") if m not in self.dirty]
return json.dumps(params), 0
if method == "Config.applyChanges":
if "ssh" in params["modules"] and self.deploys:
for name, user in self.users.items():
self.deployed[name] = [_openssh(k) for k in user["sshpubkeys"]]
self.dirty = [m for m in self.dirty if m not in params["modules"]]
return "null", 0
raise AssertionError(command)
def params(self, method: str) -> list:
return [p for m, p in self.calls if m == method]
def _openssh(rfc: str) -> str:
blob = rfc4716_blob(rfc)
kind = "ssh-ed25519" if "ZDI1NTE5" in (blob or "") else "ssh-rsa"
return f"{kind} {blob}"
class _Driver(OpenMediaVaultDriver):
"""OMV's own calls go to *omv*; the key files sshd reads come from it too."""
def __init__(self, omv: Omv, home_keys: list[str] | None = None) -> None:
super().__init__("nas", "netadmin", "p")
self.omv = omv
self.home_keys = home_keys if home_keys is not None else []
self.ran: list[tuple[str, bool]] = []
def _sudo_status(self, command: str, read_timeout: float = 100) -> tuple[str, int | None]:
return self.omv(command, read_timeout)
def run_command(self, command, *, privileged=False, timeout=60, stdin=None):
self.ran.append((command, privileged))
argv = shlex.split(command)
if argv[:2] == ["test", "-e"]:
path = argv[2]
there = path.startswith(OMV_KEYS_DIR) and path.rsplit("/", 1)[1] in self.omv.deployed
there = there or (path.endswith("/.ssh/authorized_keys") and bool(self.home_keys))
return CommandResult("", "", 0 if there else 1)
if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "cat":
path = argv[-1]
if path.startswith(OMV_KEYS_DIR):
lines = self.omv.deployed[path.rsplit("/", 1)[1]]
else:
lines = self.home_keys
return CommandResult("".join(f"{line}\n" for line in lines), "", 0)
if argv[:3] == ["sudo", "-n", "-u"] and argv[4] == "rm":
self.home_keys = []
return CommandResult("", "", 0)
raise AssertionError(command)
def test_omv_offers_personal_accounts_of_its_own() -> None:
assert callable(getattr(OpenMediaVaultDriver, "add_local_account", None))
assert callable(getattr(OpenMediaVaultDriver, "lock_local_account", None))
assert callable(getattr(OpenMediaVaultDriver, "get_local_accounts", None))
def test_the_key_file_omv_deploys_is_read_too() -> None:
files = _Driver(Omv())._account_key_files("alice", "/home/alice")
assert files[-1] == f"{OMV_KEYS_DIR}/alice"
assert "/home/alice/.ssh/authorized_keys" in files
def test_a_new_account_is_made_by_omv_in_its_ssh_group() -> None:
omv = Omv()
commands = _Driver(omv)._account_create("bob", HASH)
[params] = omv.params("UserMgmt.setUser")
assert params["name"] == "bob" and params["groups"] == ["_ssh"]
# OMV hashes a plain password itself; netOrk has the hash only.
assert params["password"] == "" and params["sshpubkeys"] == []
assert commands == [["usermod", "-p", HASH, "bob"]]
def test_making_an_account_applies_what_it_made_dirty_and_nothing_else() -> None:
omv = Omv()
_Driver(omv)._account_create("bob", None)
assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}]
assert omv.dirty == ["apt"]
def test_without_a_hash_no_password_is_set() -> None:
assert _Driver(Omv())._account_create("bob", None) == []
def test_opening_again_puts_the_account_back_into_ssh() -> None:
commands = _Driver(Omv())._account_open("alice", HASH, locked=True)
assert commands[-1] == ["gpasswd", "-a", "alice", "_ssh"]
assert ["usermod", "-e", "", "-p", HASH, "alice"] in commands
def test_a_key_goes_into_omvs_database_and_is_deployed() -> None:
omv = Omv()
outcome = _Driver(omv)._account_add_key("alice", "/home/alice", ALICE_KEY)
assert outcome["ok"], outcome["output"]
[params] = omv.params("UserMgmt.setUser")
assert params["sshpubkeys"] == [_rfc4716(OWN_KEY), ALICE_KEY]
# Everything else the user had stays as it was.
assert params["email"] == "alice@example.net" and params["groups"] == ["users", "_ssh"]
assert params["comment"] == "Alice" and params["shell"] == "/bin/bash"
# Only what the change made dirty is applied: the pending apt change stays.
assert omv.params("Config.applyChanges") == [{"modules": ["postfix", "ssh"], "force": False}]
assert omv.dirty == ["apt"]
assert any("AAAAC3NzaC1lZDI1NTE5AAAAIAlice" in k for k in omv.deployed["alice"])
def test_a_key_already_there_is_not_added_again() -> None:
omv = Omv()
outcome = _Driver(omv)._account_add_key("alice", "/home/alice", OWN_KEY)
assert outcome["ok"] and "already" in outcome["output"]
assert omv.params("UserMgmt.setUser") == []
def test_a_key_omv_does_not_deploy_fails_the_step() -> None:
outcome = _Driver(Omv(deploys=False))._account_add_key("alice", "/home/alice", ALICE_KEY)
assert not outcome["ok"]
assert "not deployed" in outcome["output"]
def test_locking_empties_omvs_keys_and_the_home_ones() -> None:
omv = Omv()
driver = _Driver(omv, home_keys=[ALICE_KEY])
outcome = driver._account_remove_keys("alice", "/home/alice")
assert outcome["ok"], outcome["output"]
[params] = omv.params("UserMgmt.setUser")
assert params["sshpubkeys"] == []
assert omv.deployed["alice"] == [] and driver.home_keys == []
def test_an_account_omv_holds_no_key_for_is_not_written() -> None:
omv = Omv()
omv.users["alice"]["sshpubkeys"] = []
omv.deployed["alice"] = []
outcome = _Driver(omv, home_keys=[ALICE_KEY])._account_remove_keys("alice", "/home/alice")
assert outcome["ok"], outcome["output"]
assert omv.params("UserMgmt.setUser") == []
@pytest.mark.parametrize(
("text", "blob"),
[
(_rfc4716(ALICE_KEY), "AAAAC3NzaC1lZDI1NTE5AAAAIAlice"),
(
'---- BEGIN SSH2 PUBLIC KEY ----\nComment: "a long \\\ncomment"\nAAAA\nBBBB\n'
"---- END SSH2 PUBLIC KEY ----",
"AAAABBBB",
),
(ALICE_KEY, "AAAAC3NzaC1lZDI1NTE5AAAAIAlice"),
("nonsense", None),
],
)
def test_the_key_omv_stores_is_read_back_as_its_base64(text: str, blob: str | None) -> None:
assert rfc4716_blob(text) == blob