Skip to content

ServerKit is a lightweight, modern server control panel for managing web applications, databases, and services on your VPS or dedicated server. Built with Python/Flask backend and React frontend.

refactor(utils): rename run_command -> run_unprivileged

Juan Denis8c8161717990
diff --git a/backend/app/services/advanced_ssl_service.py b/backend/app/services/advanced_ssl_service.py
index 93bd9b48..cbc83207 100644
--- a/backend/app/services/advanced_ssl_service.py
+++ b/backend/app/services/advanced_ssl_service.py
@@ -2,7 +2,7 @@ import json
import logging
import subprocess
from datetime import datetime
-from app.utils.system import run_command
+from app.utils.system import run_unprivileged
from app.services.ssl_service import resolve_certbot_bin
@@ -79,7 +79,7 @@ class AdvancedSSLService:
}
try:
- result = run_command(cmd, **run_kwargs)
+ result = run_unprivileged(cmd, **run_kwargs)
return {
'success': True, 'domain': domain, 'type': 'wildcard',
'certificate_path': f'/etc/letsencrypt/live/{domain}/fullchain.pem',
@@ -101,7 +101,7 @@ class AdvancedSSLService:
cmd.extend(['-d', d])
try:
- result = run_command(cmd)
+ result = run_unprivileged(cmd)
return {'success': True, 'domains': domains, 'type': 'san', 'output': result.get('stdout', '')}
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -206,7 +206,7 @@ class AdvancedSSLService:
for cert_path in cert_paths:
try:
domain = os.path.basename(os.path.dirname(cert_path))
- result = run_command(['openssl', 'x509', '-enddate', '-noout', '-in', cert_path])
+ result = run_unprivileged(['openssl', 'x509', '-enddate', '-noout', '-in', cert_path])
stdout = result.get('stdout', '')
if 'notAfter=' in stdout:
date_str = stdout.split('notAfter=')[1].strip()
diff --git a/backend/app/services/dns_zone_service.py b/backend/app/services/dns_zone_service.py
index 352d800d..c2eeb1a0 100644
--- a/backend/app/services/dns_zone_service.py
+++ b/backend/app/services/dns_zone_service.py
@@ -539,8 +539,8 @@ class DNSZoneService:
results = []
for ns_name, ns_ip in nameservers:
try:
- from app.utils.system import run_command
- result = run_command(['dig', f'@{ns_ip}', domain, record_type, '+short'], timeout=5)
+ from app.utils.system import run_unprivileged
+ result = run_unprivileged(['dig', f'@{ns_ip}', domain, record_type, '+short'], timeout=5)
stdout = result.get('stdout', '').strip()
results.append({
'nameserver': ns_name,
diff --git a/backend/app/services/monitor_service.py b/backend/app/services/monitor_service.py
index 1a839b41..405073a1 100644
--- a/backend/app/services/monitor_service.py
+++ b/backend/app/services/monitor_service.py
@@ -407,13 +407,13 @@ class MonitorService:
def _ping(monitor):
"""One ICMP echo. The previous implementation ignored the return code
entirely, so a ping check could only ever report 'up'."""
- from app.utils.system import run_command
+ from app.utils.system import run_unprivileged
timeout = monitor.check_timeout or 10
if os.name == 'nt':
cmd = ['ping', '-n', '1', '-w', str(int(timeout) * 1000), monitor.check_target]
else:
cmd = ['ping', '-c', '1', '-W', str(int(timeout)), monitor.check_target]
- res = run_command(cmd, timeout=timeout + 5)
+ res = run_unprivileged(cmd, timeout=timeout + 5)
if res.get('returncode') == 0:
return {'status': 'up'}
return {
diff --git a/backend/app/services/nginx_advanced_service.py b/backend/app/services/nginx_advanced_service.py
index f4ac6341..59f707f5 100644
--- a/backend/app/services/nginx_advanced_service.py
+++ b/backend/app/services/nginx_advanced_service.py
@@ -2,7 +2,7 @@ import os
import json
import logging
import re
-from app.utils.system import run_command, run_privileged
+from app.utils.system import run_unprivileged, run_privileged
logger = logging.getLogger(__name__)
@@ -133,7 +133,7 @@ class NginxAdvancedService:
@staticmethod
def test_config():
"""Test nginx config syntax."""
- # run_privileged, not run_command: `nginx -t` reads root-owned config
+ # run_privileged, not run_unprivileged: `nginx -t` reads root-owned config
# and nginx lives in /usr/sbin, which the panel's unit PATH omits. The
# unprivileged bare-name call raised FileNotFoundError and this method
# reported every config as INVALID.
@@ -193,7 +193,7 @@ class NginxAdvancedService:
return {'lines': [], 'error': 'Log file not found'}
try:
- result = run_command(['tail', '-n', str(lines), log_file])
+ result = run_unprivileged(['tail', '-n', str(lines), log_file])
log_lines = result.get('stdout', '').strip().split('\n')
return {'lines': log_lines, 'file': log_file}
except Exception as e:
diff --git a/backend/app/utils/system.py b/backend/app/utils/system.py
index b9f9bbd9..9233e422 100644
--- a/backend/app/utils/system.py
+++ b/backend/app/utils/system.py
@@ -104,18 +104,29 @@ def run_privileged(cmd: Union[List[str], str], *, user: Optional[str] = None, **
return subprocess.run(cmd, **kwargs)
-def run_command(cmd: Union[List[str], str], *, timeout: int = 60,
- capture_stderr: bool = False, **kwargs) -> dict:
- """Run a shell command and return a dict with stdout/stderr/returncode.
-
- This is a convenience wrapper used by services that need simple dict results
- rather than a raw ``CompletedProcess`` object.
+def run_unprivileged(cmd: Union[List[str], str], *, timeout: int = 60,
+ capture_stderr: bool = False, **kwargs) -> dict:
+ """Run a command WITHOUT privilege escalation; dict with stdout/stderr/rc.
+
+ Named for what it does not do. It was called ``run_command`` — a name that
+ described nothing and sat one autocomplete away from
+ :func:`run_privileged`, so ``nginx -t`` went through it and could neither
+ read root-owned config nor find /usr/sbin/nginx. The caller reported every
+ config as invalid. ``run_unprivileged(['nginx', '-t'])`` reads as obviously
+ wrong; ``run_command(['nginx', '-t'])`` did not.
+
+ The old name was also ambiguous across the codebase: ``PythonService`` has
+ an unrelated method of the same name.
+
+ Use :func:`run_privileged` unless the command genuinely must not gain root.
+ That is the common case — this helper has a handful of callers and they are
+ all reads that work fine as the invoking user.
"""
# Same argv[0] resolution as privileged_cmd: this helper does no privilege
# escalation, so nothing else would find a command outside $PATH. Without
- # it `run_command(['nginx', '-t'])` raised FileNotFoundError on every root
- # install (nginx is /usr/sbin/nginx) and the caller reported the config as
- # invalid. Only applied when $PATH genuinely misses the command.
+ # it `run_unprivileged(['nginx', '-t'])` raised FileNotFoundError on every
+ # root install (nginx is /usr/sbin/nginx). Only applied when $PATH
+ # genuinely misses the command.
if isinstance(cmd, (list, tuple)):
cmd = list(cmd)
if cmd and cmd[0] != 'sudo' and not os.path.isabs(cmd[0]) and not shutil.which(cmd[0]):
diff --git a/backend/tests/test_monitor_service.py b/backend/tests/test_monitor_service.py
index 569f9b86..82558851 100644
--- a/backend/tests/test_monitor_service.py
+++ b/backend/tests/test_monitor_service.py
@@ -184,7 +184,7 @@ def test_probe_never_raises_on_transport_error(app):
def test_ping_failure_is_down_not_up(app):
monitor = _monitor(check_type='ping', check_target='10.255.255.1')
- with patch('app.utils.system.run_command',
+ with patch('app.utils.system.run_unprivileged',
return_value={'returncode': 1, 'stdout': '', 'stderr': '100% packet loss'}):
result = MonitorService._perform_check(monitor)
assert result['status'] == 'down'
@@ -193,14 +193,14 @@ def test_ping_failure_is_down_not_up(app):
def test_ping_success_is_up(app):
monitor = _monitor(check_type='ping', check_target='127.0.0.1')
- with patch('app.utils.system.run_command',
+ with patch('app.utils.system.run_unprivileged',
return_value={'returncode': 0, 'stdout': '1 received', 'stderr': ''}):
assert MonitorService._perform_check(monitor)['status'] == 'up'
def test_ping_uses_platform_appropriate_flags(app):
monitor = _monitor(check_type='ping', check_target='127.0.0.1', check_timeout=3)
- with patch('app.utils.system.run_command',
+ with patch('app.utils.system.run_unprivileged',
return_value={'returncode': 0, 'stdout': '', 'stderr': ''}) as run:
with patch('app.services.monitor_service.os.name', 'nt'):
MonitorService._perform_check(monitor)
diff --git a/backend/tests/test_sbin_command_guard.py b/backend/tests/test_sbin_command_guard.py
index 729f9d6f..152a246c 100644
--- a/backend/tests/test_sbin_command_guard.py
+++ b/backend/tests/test_sbin_command_guard.py
@@ -18,7 +18,7 @@ is exactly why the failure looked feature-specific instead of systemic.
Two layers keep it dead:
- 1. `privileged_cmd` and `run_command` resolve argv[0] to an absolute path
+ 1. `privileged_cmd` and `run_unprivileged` resolve argv[0] to an absolute path
when $PATH cannot (verified below against a PATH with no sbin).
2. this static scan, so a NEW raw `subprocess` call cannot reintroduce it by
bypassing both helpers.
@@ -32,7 +32,7 @@ from unittest.mock import patch
import pytest
-from app.utils.system import privileged_cmd, resolve_command, run_command
+from app.utils.system import privileged_cmd, resolve_command, run_unprivileged
APP_ROOT = Path(__file__).resolve().parent.parent / 'app'
@@ -71,7 +71,7 @@ def _first_arg_command(node):
def _is_raw_subprocess(node):
- """`subprocess.<fn>(...)` — not run_privileged / run_command."""
+ """`subprocess.<fn>(...)` — not run_privileged / run_unprivileged."""
func = node.func
return (isinstance(func, ast.Attribute)
and func.attr in RAW_SUBPROCESS_FUNCS
@@ -110,7 +110,7 @@ def test_no_bare_sbin_command_in_raw_subprocess_calls():
'These commands live in /usr/sbin or /sbin, which the panel unit\'s '
'PATH may omit — subprocess would raise FileNotFoundError:\n '
+ '\n '.join(found)
- + '\n\nUse run_privileged() (or run_command() when no root is needed); '
+ + '\n\nUse run_privileged() (or run_unprivileged() when no root is needed); '
'both resolve argv[0] to an absolute path when $PATH cannot.'
)
@@ -141,22 +141,39 @@ def test_helpers_resolve_every_sbin_command_without_sbin_on_path(command):
@patch('app.utils.system.subprocess.run')
@patch('app.utils.system.os.path.exists')
@patch('app.utils.system.shutil.which', return_value=None)
-def test_run_command_resolves_too(_which, exists, mock_run):
+def test_run_unprivileged_resolves_too(_which, exists, mock_run):
"""The sibling helper had the same gap — `nginx -t` went through it."""
exists.side_effect = lambda p: p == '/usr/sbin/nginx'
mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')
- run_command(['nginx', '-t'])
+ run_unprivileged(['nginx', '-t'])
assert mock_run.call_args[0][0] == ['/usr/sbin/nginx', '-t']
@patch('app.utils.system.subprocess.run')
@patch('app.utils.system.shutil.which', return_value='/usr/bin/git')
-def test_run_command_leaves_resolvable_commands_alone(_which, mock_run):
+def test_run_unprivileged_leaves_resolvable_commands_alone(_which, mock_run):
"""A working $PATH must not have its argv rewritten underneath callers."""
mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')
- run_command(['git', 'status'])
+ run_unprivileged(['git', 'status'])
assert mock_run.call_args[0][0] == ['git', 'status']
+
+
+def test_the_ambiguous_name_stays_gone():
+ """`run_command` said nothing about privilege and sat one autocomplete from
+ `run_privileged`. `nginx -t` went through it and reported every config
+ invalid. Re-adding the name re-adds the second door this rename closed.
+
+ (`PythonService.run_command` is unrelated and keeps its name — the collision
+ is part of why the utils one had to change.)
+ """
+ import app.utils.system as system
+
+ assert not hasattr(system, 'run_command'), (
+ 'app.utils.system.run_command is back. Use run_privileged() or the '
+ 'explicit run_unprivileged() — a name that does not say whether it '
+ 'escalates is how nginx -t ended up unprivileged.'
+ )
diff --git a/backend/tests/test_sites_https.py b/backend/tests/test_sites_https.py
index 8ae306af..a17f4458 100644
--- a/backend/tests/test_sites_https.py
+++ b/backend/tests/test_sites_https.py
@@ -87,7 +87,7 @@ def test_issue_wildcard_cert_route53(monkeypatch):
captured['kw'] = kw
return {'stdout': 'Congratulations'}
- monkeypatch.setattr(mod, 'run_command', fake_run)
+ monkeypatch.setattr(mod, 'run_unprivileged', fake_run)
res = AdvancedSSLService.issue_wildcard_cert('example.com', 'route53',
{'api_key': 'AK', 'api_secret': 'SK'},