"""``set_hostname`` renames the host itself, not only what netOrk calls it (#45). The static and runtime hostname take the short name; ``/etc/hosts`` follows, so the host still resolves its own name; and a cloud-init host is told to keep the name, or its next boot puts the image's name back. Every file root writes is staged without privilege first, as ``_install_file_as_root`` does for the fixes. """ from __future__ import annotations import shlex from types import SimpleNamespace from unittest.mock import MagicMock import pytest from napalm_linux import LinuxDriver from napalm_linux._hostname import _rename_in_hosts, _split_hostname _PW = "pw-45" _STAGED = "/tmp/netork-stage.Xy34Zw" _HOSTS = "127.0.0.1\tlocalhost\n127.0.1.1\told.example.net old\n\n::1 localhost ip6-localhost\n" class Host: """The host's exec channels: every line, its stdin, and whether it ran as root.""" def __init__(self, *, hosts=_HOSTS, cloud_init=False, rename_status=0, hosts_status=0): self.runs: list[SimpleNamespace] = [] self.hosts = hosts self.cloud_init = cloud_init self.rename_status = rename_status self.hosts_status = hosts_status def open_session(self): return _Channel(self) def answer(self, command: str, script: str) -> tuple[str, int]: if command.startswith("sudo -n "): return "sudo: a password is required\n", 1 if script == "hostname": return "old\n", 0 if script.startswith("hostname -f"): return "old.example.net\n", 0 if script == "cat /etc/hosts": return self.hosts, 0 if script.startswith("test -d /etc/cloud"): return "", 0 if self.cloud_init else 1 if "mktemp" in script: return _STAGED, 0 if "hostnamectl" in script: return ( "hostname: you must be root\n" if self.rename_status else "" ), self.rename_status if "/etc/hosts" in script and "install" in script: return ("install: cannot create\n" if self.hosts_status else ""), self.hosts_status return "", 0 @property def root_scripts(self) -> list[str]: return [run.script for run in self.runs if run.root] def staged(self) -> list[bytes]: return [run.stdin for run in self.runs if "mktemp" in run.script] class _Channel: def __init__(self, host: Host): self._host = host self._run: SimpleNamespace | None = None self._out = b"" self._status = 0 def exec_command(self, command): assert _PW not in command root = command.startswith(("sudo ", "sh -c ")) parts = shlex.split(command) script = parts[parts.index("-c") + 1] if root else command script = script.removeprefix("exec LinuxDriver: optional_args = {"sudo_password": sudo_password} if sudo_password else {} driver = LinuxDriver("h", "admin", "p", optional_args=optional_args) driver._device = MagicMock() driver._device.remote_conn_pre = SimpleNamespace(get_transport=lambda: host) driver._root = False driver._pkg_manager = "apt" return driver def _hosts_written(host: Host) -> str: """What was staged for /etc/hosts, or "" when it was left alone.""" staged = b"" for run in host.runs: if "mktemp" in run.script: staged = run.stdin elif run.root and "/etc/hosts" in run.script: return staged.decode() return "" class TestSplitHostname: @pytest.mark.parametrize( "name, expected", [ ("web-01", ("web-01", None)), ("web-01.example.net", ("web-01", "web-01.example.net")), ("A1", ("A1", None)), ("a" * 63, ("a" * 63, None)), ], ) def test_valid(self, name, expected): assert _split_hostname(name) == expected @pytest.mark.parametrize( "name", [ "", "web_01", "-web", "web-", "a" * 64, ".".join(["a" * 60] * 5), "web 01", "web;reboot", "web.", ".web", "web..example", "$(id)", ], ) def test_invalid(self, name): with pytest.raises(ValueError): _split_hostname(name) class TestRenameInHosts: def test_old_names_replaced_on_every_line_they_appear(self): content = "127.0.0.1 localhost old\n10.0.0.5 old.example.net old # me\n" assert _rename_in_hosts(content, {"old", "old.example.net"}, "new", "new.example.net") == ( "127.0.0.1\tlocalhost new.example.net new\n10.0.0.5\tnew.example.net new # me\n" ) def test_other_aliases_and_lines_kept(self): content = "# static\n127.0.1.1 old mail\n::1 localhost\n" assert _rename_in_hosts(content, {"old"}, "new", None) == ( "# static\n127.0.1.1\tnew mail\n::1 localhost\n" ) def test_names_compared_without_case(self): assert _rename_in_hosts("127.0.1.1 OLD\n", {"old"}, "new", None) == "127.0.1.1\tnew\n" def test_no_old_name_but_a_127_0_1_1_line_takes_the_new_name(self): content = "127.0.0.1 localhost\n127.0.1.1 ubuntu\n" assert _rename_in_hosts(content, {"old"}, "new", "new.example.net") == ( "127.0.0.1 localhost\n127.0.1.1\tnew.example.net new\n" ) def test_neither_leaves_the_file_alone(self): content = "127.0.0.1 localhost localhost.localdomain\n::1 localhost\n" assert _rename_in_hosts(content, {"old"}, "new", None) == content def test_localhost_is_never_renamed(self): content = "127.0.0.1 localhost\n" assert _rename_in_hosts(content, {"localhost"}, "new", None) == content class TestSetHostname: def test_short_name_set_as_root(self): host = Host() _driver(host).set_hostname("new") rename = host.root_scripts[0] assert "hostnamectl set-hostname new" in rename assert "/etc/hostname" in rename and "hostname new" in rename def test_fqdn_sets_the_short_name_and_both_in_hosts(self): host = Host() _driver(host).set_hostname("new.example.net") assert "hostnamectl set-hostname new " in host.root_scripts[0] assert "example" not in host.root_scripts[0] assert _hosts_written(host) == ( "127.0.0.1\tlocalhost\n127.0.1.1\tnew.example.net new\n\n::1 localhost ip6-localhost\n" ) def test_hosts_installed_from_a_staged_file_never_privileged_stdin(self): host = Host() _driver(host).set_hostname("new") hosts_install = [s for s in host.root_scripts if "/etc/hosts" in s] assert len(hosts_install) == 1 assert f"install -m 644 -o root -g root -- {_STAGED}" in hosts_install[0] for run in host.runs: if run.root: assert run.stdin == f"{_PW}\n".encode() def test_unchanged_hosts_not_rewritten(self): host = Host(hosts="127.0.0.1 localhost\n") _driver(host).set_hostname("new") assert not any("/etc/hosts" in s for s in host.root_scripts) def test_cloud_init_host_keeps_the_name(self): host = Host(cloud_init=True) _driver(host).set_hostname("new") assert any( "/etc/cloud/cloud.cfg.d/99-preserve-hostname.cfg" in s for s in host.root_scripts ) assert any(b"preserve_hostname: true" in staged for staged in host.staged()) def test_no_cloud_init_no_drop_in(self): host = Host() _driver(host).set_hostname("new") assert not any("cloud.cfg.d" in s for s in host.root_scripts) def test_invalid_name_runs_nothing(self): host = Host() driver = _driver(host) with pytest.raises(ValueError): driver.set_hostname("new;reboot") assert host.runs == [] driver._device.send_command.assert_not_called() def test_failed_rename_raises_and_writes_nothing(self): host = Host(rename_status=1) with pytest.raises(RuntimeError): _driver(host).set_hostname("new") assert not any("/etc/hosts" in s for s in host.root_scripts) def test_sudo_without_password_says_what_to_do(self): host = Host() with pytest.raises(RuntimeError, match="no sudo password was given"): _driver(host, sudo_password=None).set_hostname("new") def test_failed_hosts_write_raises(self): host = Host(hosts_status=1) with pytest.raises(RuntimeError, match="/etc/hosts"): _driver(host).set_hostname("new")