runspec-linux-core 0.2.0__tar.gz → 0.3.0__tar.gz

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (24) hide show
  1. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/CHANGELOG.md +20 -0
  2. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/PKG-INFO +1 -1
  3. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/pyproject.toml +1 -1
  4. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/__init__.py +3 -0
  5. runspec_linux_core-0.3.0/runspec_linux_core/sudoers.py +129 -0
  6. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/tests/test_preconditions.py +6 -0
  7. runspec_linux_core-0.3.0/tests/test_sudoers.py +147 -0
  8. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/.gitignore +0 -0
  9. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/containers.py +0 -0
  10. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/errors.py +0 -0
  11. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/files.py +0 -0
  12. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/logs.py +0 -0
  13. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/nc.py +0 -0
  14. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/network.py +0 -0
  15. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/packages.py +0 -0
  16. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/power.py +0 -0
  17. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/security.py +0 -0
  18. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/services.py +0 -0
  19. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/runspec_linux_core/system.py +0 -0
  20. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/tests/__init__.py +0 -0
  21. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/tests/test_nc_send.py +0 -0
  22. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/tests/test_network.py +0 -0
  23. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/tests/test_packages.py +0 -0
  24. {runspec_linux_core-0.2.0 → runspec_linux_core-0.3.0}/tests/test_power.py +0 -0
@@ -1,5 +1,25 @@
1
1
  # runspec-linux-core Changelog
2
2
 
3
+ ## [0.3.0] — 2026-06-20
4
+
5
+ Add `enable_passwordless_sudo()` (new `sudoers.py`) — the one-time bootstrap that
6
+ makes the `run_as = "root"` package/power runnables work without a password.
7
+
8
+ - Installs a validated drop-in at `/etc/sudoers.d/runspec`. Two scopes:
9
+ `"scoped"` → `NOPASSWD` for the runspec venv's runnable scripts only
10
+ (`{venv_bin}/`); `"all"` → `NOPASSWD: ALL`.
11
+ - The sudo password is read from **stdin via `sudo -S`** — never on argv, in the
12
+ process table, shell history, or the audit log.
13
+ - Validates with `visudo -cf` before install *and* `visudo -c` after; rolls the
14
+ drop-in back if the post-install check fails, so a typo can't lock sudo out.
15
+ - The target user name is validated against a strict pattern before it reaches
16
+ the file (no rule injection); idempotent when an identical drop-in exists.
17
+ - Raises `ValueError` (bad scope/user), `ToolNotFoundError` (no `sudo`/`visudo`),
18
+ or `CommandError` (auth failure / validation failure).
19
+
20
+ Note: the console's *agent* path wraps the command in `env(1)`, so a `"scoped"`
21
+ grant covers manual/CLI runs; agent-driven runs need `"all"`.
22
+
3
23
  ## [0.2.0] — 2026-06-20
4
24
 
5
25
  Add package-manager and host-power helpers so a fleet can be patched and
@@ -1,6 +1,6 @@
1
1
  Metadata-Version: 2.4
2
2
  Name: runspec-linux-core
3
- Version: 0.2.0
3
+ Version: 0.3.0
4
4
  Summary: Pure-Python Linux system-admin helpers — the importable core behind runspec-linux (no runspec dependency, no runnables)
5
5
  Requires-Python: >=3.10
6
6
  Provides-Extra: dev
@@ -4,7 +4,7 @@ build-backend = "hatchling.build"
4
4
 
5
5
  [project]
6
6
  name = "runspec-linux-core"
7
- version = "0.2.0"
7
+ version = "0.3.0"
8
8
  requires-python = ">=3.10"
9
9
  description = "Pure-Python Linux system-admin helpers — the importable core behind runspec-linux (no runspec dependency, no runnables)"
10
10
  dependencies = []
@@ -30,6 +30,7 @@ from runspec_linux_core.packages import (
30
30
  from runspec_linux_core.power import reboot_host
31
31
  from runspec_linux_core.security import last_logins, who
32
32
  from runspec_linux_core.services import check_service, list_services, restart_service
33
+ from runspec_linux_core.sudoers import enable_passwordless_sudo
33
34
  from runspec_linux_core.system import check_memory, disk_usage, list_processes, system_info
34
35
 
35
36
  __all__ = [
@@ -73,6 +74,8 @@ __all__ = [
73
74
  "remove_package",
74
75
  # power
75
76
  "reboot_host",
77
+ # sudoers
78
+ "enable_passwordless_sudo",
76
79
  # tcp
77
80
  "nc_send",
78
81
  ]
@@ -0,0 +1,129 @@
1
+ """Bootstrap passwordless sudo so the console's ``run_as = "root"`` path works.
2
+
3
+ This is the one-time, interactive complement to ``run_as``: the operator supplies
4
+ their sudo password (delivered out of band by the caller — never on argv) and we
5
+ install a **validated** drop-in under ``/etc/sudoers.d`` so subsequent
6
+ ``run_as = "root"`` invocations escalate without a password.
7
+
8
+ The password is read from stdin via ``sudo -S`` — it never appears in argv, the
9
+ process table, shell history, or the audit log. The drop-in is validated with
10
+ ``visudo`` before *and* after install, and rolled back if the post-install check
11
+ fails, so a typo can't lock the operator out of sudo.
12
+
13
+ Two grant scopes:
14
+
15
+ - ``"scoped"`` — ``NOPASSWD`` only for the runspec venv's runnable scripts
16
+ (``{venv_bin}/``). Least privilege, and enough for **manual** console runs and
17
+ direct CLI/cron. Note: the console's *agent* path wraps the command in
18
+ ``env(1)`` to carry ``RUNSPEC_AGENT`` through sudo, so under the agent the
19
+ command sudo sees is ``/usr/bin/env …`` — which this scope does **not** match.
20
+ Agent-driven fleet management therefore needs ``"all"``.
21
+ - ``"all"`` — ``NOPASSWD: ALL``. Works for every path (manual *and* agent).
22
+ """
23
+
24
+ import getpass
25
+ import os
26
+ import re
27
+ import shutil
28
+ import subprocess
29
+ import sys
30
+ import tempfile
31
+
32
+ from runspec_linux_core.errors import CommandError, ToolNotFoundError
33
+
34
+ _DROP_IN = "/etc/sudoers.d/runspec"
35
+ _MANAGED_HEADER = "# Managed by runspec-linux enable-passwordless-sudo\n"
36
+
37
+ # POSIX-ish user/group name: starts with a letter or underscore, then letters,
38
+ # digits, _, -, . and an optional trailing $ (machine accounts). Validated before
39
+ # interpolation into the sudoers file so a crafted name can't inject extra rules.
40
+ _USER_RE = re.compile(r"^[a-z_][a-z0-9_.-]*\$?$")
41
+
42
+
43
+ def _runspec_bin_dir() -> str:
44
+ """The venv bin directory holding the runspec runnable scripts.
45
+
46
+ The console invokes a runnable as ``{bin_dir}/{runnable}``; on a standard
47
+ venv install that is the directory of the running interpreter (kept as the
48
+ venv path, not resolved through symlinks).
49
+ """
50
+ return os.path.dirname(sys.executable)
51
+
52
+
53
+ def _sudoers_content(user: str, scope: str, bin_dir: str) -> str:
54
+ # scoped: a trailing slash matches any command in the runspec venv bin dir.
55
+ rule = f"{user} ALL=(ALL) NOPASSWD: ALL" if scope == "all" else f"{user} ALL=(root) NOPASSWD: {bin_dir}/"
56
+ return f"{_MANAGED_HEADER}{rule}\n"
57
+
58
+
59
+ def _sudo(password: str, argv: list[str]) -> subprocess.CompletedProcess:
60
+ """Run ``sudo -S -p '' argv``, feeding ``password`` on stdin (never on argv)."""
61
+ return subprocess.run(
62
+ ["sudo", "-S", "-p", "", *argv],
63
+ input=password + "\n",
64
+ capture_output=True,
65
+ text=True,
66
+ )
67
+
68
+
69
+ def _auth_hint(result: subprocess.CompletedProcess) -> str:
70
+ err = result.stderr.strip()
71
+ low = err.lower()
72
+ if "incorrect password" in low or "try again" in low or "authentication failure" in low:
73
+ return "sudo authentication failed — check the password"
74
+ return err or "sudo command failed"
75
+
76
+
77
+ def enable_passwordless_sudo(password: str, user: str | None = None, scope: str = "scoped") -> dict:
78
+ """Install a validated ``/etc/sudoers.d/runspec`` granting passwordless sudo.
79
+
80
+ ``user`` defaults to the current login user. ``scope`` is ``"scoped"`` (the
81
+ runspec venv runnables only) or ``"all"`` (``NOPASSWD: ALL``). Returns
82
+ ``{user, scope, path, installed: True, already_configured}``.
83
+
84
+ Raises ValueError on a bad scope/user, ToolNotFoundError if sudo/visudo are
85
+ missing, or CommandError on a sudo auth failure or a sudoers validation
86
+ failure (in which case the drop-in is rolled back).
87
+ """
88
+ if scope not in ("scoped", "all"):
89
+ raise ValueError(f"invalid scope: {scope!r} (expected 'scoped' or 'all')")
90
+ user = user or getpass.getuser()
91
+ if not _USER_RE.match(user):
92
+ raise ValueError(f"invalid user name: {user!r}")
93
+ if not shutil.which("sudo"):
94
+ raise ToolNotFoundError("sudo is not installed")
95
+ if not shutil.which("visudo"):
96
+ raise ToolNotFoundError("visudo is not installed (needed to validate the sudoers file)")
97
+
98
+ content = _sudoers_content(user, scope, _runspec_bin_dir())
99
+
100
+ with tempfile.NamedTemporaryFile("w", suffix=".sudoers", delete=False) as tf:
101
+ tf.write(content)
102
+ tmp_path = tf.name
103
+ try:
104
+ # 1) Validate the generated syntax locally before touching the system.
105
+ check = subprocess.run(["visudo", "-cf", tmp_path], capture_output=True, text=True)
106
+ if check.returncode != 0:
107
+ detail = check.stdout.strip() or check.stderr.strip()
108
+ raise CommandError(f"generated sudoers failed validation: {detail}")
109
+
110
+ # 2) Idempotent: identical drop-in already present? (reading it needs root)
111
+ existing = _sudo(password, ["cat", _DROP_IN])
112
+ if existing.returncode == 0 and existing.stdout == content:
113
+ return {"user": user, "scope": scope, "path": _DROP_IN, "installed": True, "already_configured": True}
114
+
115
+ # 3) Install atomically as root, 0440 root:root.
116
+ install = _sudo(password, ["install", "-m", "0440", "-o", "root", "-g", "root", tmp_path, _DROP_IN])
117
+ if install.returncode != 0:
118
+ raise CommandError(_auth_hint(install))
119
+
120
+ # 4) Re-validate the whole sudoers tree; roll our drop-in back if broken.
121
+ verify = _sudo(password, ["visudo", "-c"])
122
+ if verify.returncode != 0:
123
+ _sudo(password, ["rm", "-f", _DROP_IN])
124
+ detail = verify.stdout.strip() or verify.stderr.strip()
125
+ raise CommandError(f"sudoers validation failed after install — rolled back: {detail}")
126
+
127
+ return {"user": user, "scope": scope, "path": _DROP_IN, "installed": True, "already_configured": False}
128
+ finally:
129
+ os.unlink(tmp_path)
@@ -104,3 +104,9 @@ def test_reboot_host_requires_a_tool(monkeypatch: pytest.MonkeyPatch) -> None:
104
104
  monkeypatch.setattr("runspec_linux_core.power.shutil.which", lambda _: None)
105
105
  with pytest.raises(ToolNotFoundError):
106
106
  core.reboot_host()
107
+
108
+
109
+ def test_enable_passwordless_sudo_requires_sudo(monkeypatch: pytest.MonkeyPatch) -> None:
110
+ monkeypatch.setattr("runspec_linux_core.sudoers.shutil.which", lambda _: None)
111
+ with pytest.raises(ToolNotFoundError):
112
+ core.enable_passwordless_sudo("pw", "alice", "scoped")
@@ -0,0 +1,147 @@
1
+ """enable_passwordless_sudo: content generation, validation, install + rollback.
2
+
3
+ No real sudo/visudo is invoked — the subprocess layer is stubbed so the control
4
+ flow (pre-validate, idempotency, install, post-validate, rollback) is exercised
5
+ deterministically. The password is asserted to travel via stdin, never argv.
6
+ """
7
+
8
+ import subprocess
9
+
10
+ import pytest
11
+
12
+ from runspec_linux_core import sudoers
13
+ from runspec_linux_core.errors import CommandError, ToolNotFoundError
14
+
15
+
16
+ def _ok(stdout: str = "", returncode: int = 0, stderr: str = "") -> subprocess.CompletedProcess:
17
+ return subprocess.CompletedProcess(args=[], returncode=returncode, stdout=stdout, stderr=stderr)
18
+
19
+
20
+ @pytest.fixture(autouse=True)
21
+ def _tools_present(monkeypatch: pytest.MonkeyPatch) -> None:
22
+ monkeypatch.setattr("runspec_linux_core.sudoers.shutil.which", lambda name: f"/usr/sbin/{name}")
23
+ monkeypatch.setattr("runspec_linux_core.sudoers._runspec_bin_dir", lambda: "/opt/rs/bin")
24
+
25
+
26
+ # ── content ───────────────────────────────────────────────────────────────────
27
+
28
+
29
+ def test_scoped_content_targets_venv_bin() -> None:
30
+ out = sudoers._sudoers_content("alice", "scoped", "/opt/rs/bin")
31
+ assert "alice ALL=(root) NOPASSWD: /opt/rs/bin/\n" in out
32
+ assert out.startswith("# Managed by runspec-linux")
33
+
34
+
35
+ def test_all_content_is_nopasswd_all() -> None:
36
+ out = sudoers._sudoers_content("alice", "all", "/opt/rs/bin")
37
+ assert "alice ALL=(ALL) NOPASSWD: ALL\n" in out
38
+
39
+
40
+ # ── input validation ──────────────────────────────────────────────────────────
41
+
42
+
43
+ def test_rejects_bad_scope() -> None:
44
+ with pytest.raises(ValueError):
45
+ sudoers.enable_passwordless_sudo("pw", "alice", "everything")
46
+
47
+
48
+ @pytest.mark.parametrize("bad", ["root\nbad ALL=(ALL) NOPASSWD: ALL", "al ice", "-x", "a;b"])
49
+ def test_rejects_injection_in_user(bad: str) -> None:
50
+ with pytest.raises(ValueError):
51
+ sudoers.enable_passwordless_sudo("pw", bad, "scoped")
52
+
53
+
54
+ # ── install flow ──────────────────────────────────────────────────────────────
55
+
56
+
57
+ def test_install_happy_path_pipes_password_via_stdin(monkeypatch: pytest.MonkeyPatch) -> None:
58
+ calls: list[dict] = []
59
+
60
+ def fake_run(cmd, **kw):
61
+ calls.append({"cmd": cmd, "input": kw.get("input")})
62
+ if cmd[:2] == ["visudo", "-cf"]: # local pre-validate
63
+ return _ok()
64
+ if cmd[:4] == ["sudo", "-S", "-p", ""]:
65
+ sub = cmd[4:] # args after the `sudo -S -p ''` prefix
66
+ if sub[0] == "cat": # idempotency probe: not yet installed
67
+ return _ok(returncode=1, stderr="No such file")
68
+ if sub[0] == "install":
69
+ return _ok()
70
+ if sub[0] == "visudo": # post-validate
71
+ return _ok()
72
+ raise AssertionError(f"unexpected command: {cmd}")
73
+
74
+ monkeypatch.setattr("runspec_linux_core.sudoers.subprocess.run", fake_run)
75
+
76
+ result = sudoers.enable_passwordless_sudo("s3cret", "alice", "all")
77
+ assert result == {
78
+ "user": "alice",
79
+ "scope": "all",
80
+ "path": "/etc/sudoers.d/runspec",
81
+ "installed": True,
82
+ "already_configured": False,
83
+ }
84
+ # Password rides stdin on every sudo call — never appears in any argv.
85
+ sudo_calls = [c for c in calls if c["cmd"][:1] == ["sudo"]]
86
+ assert sudo_calls and all(c["input"] == "s3cret\n" for c in sudo_calls)
87
+ assert not any("s3cret" in " ".join(c["cmd"]) for c in calls)
88
+
89
+
90
+ def test_idempotent_when_identical_drop_in_exists(monkeypatch: pytest.MonkeyPatch) -> None:
91
+ content = sudoers._sudoers_content("alice", "all", "/opt/rs/bin")
92
+
93
+ def fake_run(cmd, **kw):
94
+ if cmd[:2] == ["visudo", "-cf"]:
95
+ return _ok()
96
+ if cmd[4:5] == ["cat"]:
97
+ return _ok(stdout=content) # already present, identical
98
+ raise AssertionError(f"should not install: {cmd}")
99
+
100
+ monkeypatch.setattr("runspec_linux_core.sudoers.subprocess.run", fake_run)
101
+ result = sudoers.enable_passwordless_sudo("pw", "alice", "all")
102
+ assert result["already_configured"] is True
103
+
104
+
105
+ def test_wrong_password_raises_command_error(monkeypatch: pytest.MonkeyPatch) -> None:
106
+ def fake_run(cmd, **kw):
107
+ if cmd[:2] == ["visudo", "-cf"]:
108
+ return _ok()
109
+ if cmd[4:5] == ["cat"]:
110
+ return _ok(returncode=1)
111
+ if cmd[4:5] == ["install"]:
112
+ return _ok(returncode=1, stderr="sudo: 1 incorrect password attempt")
113
+ raise AssertionError(f"unexpected: {cmd}")
114
+
115
+ monkeypatch.setattr("runspec_linux_core.sudoers.subprocess.run", fake_run)
116
+ with pytest.raises(CommandError, match="authentication failed"):
117
+ sudoers.enable_passwordless_sudo("wrong", "alice", "all")
118
+
119
+
120
+ def test_post_validate_failure_rolls_back(monkeypatch: pytest.MonkeyPatch) -> None:
121
+ removed: list[list[str]] = []
122
+
123
+ def fake_run(cmd, **kw):
124
+ if cmd[:2] == ["visudo", "-cf"]:
125
+ return _ok()
126
+ sub = cmd[4:] if cmd[:4] == ["sudo", "-S", "-p", ""] else []
127
+ if sub[:1] == ["cat"]:
128
+ return _ok(returncode=1)
129
+ if sub[:1] == ["install"]:
130
+ return _ok()
131
+ if sub[:1] == ["visudo"]: # whole-tree check fails
132
+ return _ok(returncode=1, stderr=">>> syntax error")
133
+ if sub[:1] == ["rm"]:
134
+ removed.append(sub)
135
+ return _ok()
136
+ raise AssertionError(f"unexpected: {cmd}")
137
+
138
+ monkeypatch.setattr("runspec_linux_core.sudoers.subprocess.run", fake_run)
139
+ with pytest.raises(CommandError, match="rolled back"):
140
+ sudoers.enable_passwordless_sudo("pw", "alice", "scoped")
141
+ assert removed and removed[0] == ["rm", "-f", "/etc/sudoers.d/runspec"]
142
+
143
+
144
+ def test_requires_visudo(monkeypatch: pytest.MonkeyPatch) -> None:
145
+ monkeypatch.setattr("runspec_linux_core.sudoers.shutil.which", lambda name: None if name == "visudo" else "/usr/bin/sudo")
146
+ with pytest.raises(ToolNotFoundError, match="visudo"):
147
+ sudoers.enable_passwordless_sudo("pw", "alice", "scoped")