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(nginx): one privileged-write door, one vhost lifecycle

Juan Denis6cd1950fc930
diff --git a/backend/app/services/environment_domain_service.py b/backend/app/services/environment_domain_service.py
index e6e268db..a2ee0b2f 100644
--- a/backend/app/services/environment_domain_service.py
+++ b/backend/app/services/environment_domain_service.py
@@ -11,14 +11,19 @@ import re
import subprocess
from typing import Dict
+from app.services.nginx_service import NginxService
from app.utils.slug import slugify as _slugify
+from app.utils.system import run_privileged, write_privileged_file
class EnvironmentDomainService:
"""Service for managing per-environment domains and Nginx configs."""
- SITES_AVAILABLE = '/etc/nginx/sites-available'
- SITES_ENABLED = '/etc/nginx/sites-enabled'
+ # Not redeclared: NginxService owns where vhosts live (plan 75 §G4). Four
+ # files used to hardcode these, so a test that redirected NginxService's
+ # paths left the other three writing to the real /etc/nginx.
+ SITES_AVAILABLE = NginxService.SITES_AVAILABLE
+ SITES_ENABLED = NginxService.SITES_ENABLED
# Nginx template for environment proxy (based on NginxService.DOCKER_SITE_TEMPLATE)
ENV_SITE_TEMPLATE = '''server {{
@@ -131,35 +136,18 @@ class EnvironmentDomainService:
robots_block=robots_block,
)
- # Write config file using sudo tee
- config_path = os.path.join(cls.SITES_AVAILABLE, site_name)
- process = subprocess.run(
- ['sudo', 'tee', config_path],
- input=config,
- capture_output=True,
- text=True
- )
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to write config: {process.stderr}'}
-
- # Enable the site (symlink to sites-enabled)
- enabled_path = os.path.join(cls.SITES_ENABLED, site_name)
- result = subprocess.run(
- ['sudo', 'ln', '-sf', config_path, enabled_path],
- capture_output=True,
- text=True
- )
- if result.returncode != 0:
- return {'success': False, 'error': f'Failed to enable site: {result.stderr}'}
-
- # Reload Nginx
- reload_result = cls._reload_nginx()
- if not reload_result.get('success'):
- return reload_result
+ # write + enable + nginx -t + rollback + reload, all owned by
+ # NginxService (plan 75 §G4). This block used to re-implement it
+ # with hardcoded `sudo`, which is the founding bug class of plan 75:
+ # it breaks on a panel running as root without sudo, and never
+ # rolled back a vhost that failed the config test.
+ result = NginxService.write_vhost(site_name, config)
+ if not result['success']:
+ return result
return {
'success': True,
- 'config_path': config_path,
+ 'config_path': result['path'],
'domain': domain,
}
@@ -177,25 +165,7 @@ class EnvironmentDomainService:
Dict with success status
"""
try:
- # Remove symlink from sites-enabled
- enabled_path = os.path.join(cls.SITES_ENABLED, site_name)
- subprocess.run(
- ['sudo', 'rm', '-f', enabled_path],
- capture_output=True,
- text=True
- )
-
- # Remove config from sites-available
- available_path = os.path.join(cls.SITES_AVAILABLE, site_name)
- subprocess.run(
- ['sudo', 'rm', '-f', available_path],
- capture_output=True,
- text=True
- )
-
- # Reload Nginx
- cls._reload_nginx()
-
+ NginxService.delete_site(site_name)
return {'success': True, 'message': f'Nginx config for {site_name} removed'}
except Exception as e:
@@ -221,10 +191,7 @@ class EnvironmentDomainService:
"""
try:
# Ensure htpasswd directory exists
- subprocess.run(
- ['sudo', 'mkdir', '-p', cls.HTPASSWD_DIR],
- capture_output=True, text=True
- )
+ run_privileged(['mkdir', '-p', cls.HTPASSWD_DIR])
# Generate password hash using openssl
hash_result = subprocess.run(
@@ -239,31 +206,16 @@ class EnvironmentDomainService:
# Write htpasswd file
htpasswd_path = os.path.join(cls.HTPASSWD_DIR, site_name)
- process = subprocess.run(
- ['sudo', 'tee', htpasswd_path],
- input=htpasswd_content,
- capture_output=True, text=True
- )
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to write htpasswd: {process.stderr}'}
-
- # Set correct permissions
- subprocess.run(
- ['sudo', 'chmod', '644', htpasswd_path],
- capture_output=True, text=True
- )
+ written = write_privileged_file(htpasswd_path, htpasswd_content, mode='644')
+ if not written['success']:
+ return {'success': False,
+ 'error': f"Failed to write htpasswd: {written['error']}"}
# Modify Nginx config to add auth_basic directives
- config_path = os.path.join(cls.SITES_AVAILABLE, site_name)
- read_result = subprocess.run(
- ['sudo', 'cat', config_path],
- capture_output=True, text=True
- )
- if read_result.returncode != 0:
+ config_content = NginxService.read_vhost(site_name)
+ if config_content is None:
return {'success': False, 'error': 'Failed to read Nginx config'}
- config_content = read_result.stdout
-
# Check if auth_basic already exists
if 'auth_basic' in config_content:
# Already has basic auth, just update htpasswd file
@@ -281,19 +233,10 @@ class EnvironmentDomainService:
count=1
)
- # Write updated config
- process = subprocess.run(
- ['sudo', 'tee', config_path],
- input=config_content,
- capture_output=True, text=True
- )
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to update Nginx config: {process.stderr}'}
-
- # Reload Nginx
- reload_result = cls._reload_nginx()
- if not reload_result.get('success'):
- return reload_result
+ # Write updated config (tested + rolled back by NginxService)
+ result = NginxService.write_vhost(site_name, config_content)
+ if not result['success']:
+ return result
return {
'success': True,
@@ -320,39 +263,21 @@ class EnvironmentDomainService:
try:
# Remove htpasswd file
htpasswd_path = os.path.join(cls.HTPASSWD_DIR, site_name)
- subprocess.run(
- ['sudo', 'rm', '-f', htpasswd_path],
- capture_output=True, text=True
- )
+ run_privileged(['rm', '-f', htpasswd_path])
# Remove auth_basic directives from Nginx config
- config_path = os.path.join(cls.SITES_AVAILABLE, site_name)
- read_result = subprocess.run(
- ['sudo', 'cat', config_path],
- capture_output=True, text=True
- )
- if read_result.returncode != 0:
+ config_content = NginxService.read_vhost(site_name)
+ if config_content is None:
return {'success': False, 'error': 'Failed to read Nginx config'}
- config_content = read_result.stdout
-
# Remove auth_basic lines
config_content = re.sub(r'\n\s*auth_basic\s+"[^"]*";\n', '\n', config_content)
config_content = re.sub(r'\s*auth_basic_user_file\s+[^;]+;\n', '', config_content)
- # Write updated config
- process = subprocess.run(
- ['sudo', 'tee', config_path],
- input=config_content,
- capture_output=True, text=True
- )
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to update Nginx config: {process.stderr}'}
-
- # Reload Nginx
- reload_result = cls._reload_nginx()
- if not reload_result.get('success'):
- return reload_result
+ # Write updated config (tested + rolled back by NginxService)
+ result = NginxService.write_vhost(site_name, config_content)
+ if not result['success']:
+ return result
return {'success': True, 'message': 'Basic Auth disabled'}
@@ -373,31 +298,11 @@ class EnvironmentDomainService:
@classmethod
def _reload_nginx(cls) -> Dict:
- """Test and reload Nginx configuration."""
- try:
- # Test config first
- test_result = subprocess.run(
- ['sudo', 'nginx', '-t'],
- capture_output=True,
- text=True,
- timeout=10
- )
- if test_result.returncode != 0:
- return {'success': False, 'error': f'Nginx config test failed: {test_result.stderr}'}
-
- # Reload
- result = subprocess.run(
- ['sudo', 'systemctl', 'reload', 'nginx'],
- capture_output=True,
- text=True,
- timeout=30
- )
- if result.returncode != 0:
- return {'success': False, 'error': f'Nginx reload failed: {result.stderr}'}
-
- return {'success': True}
+ """Test and reload Nginx — NginxService owns both (plan 75 §G4).
- except subprocess.TimeoutExpired:
- return {'success': False, 'error': 'Nginx reload timed out'}
- except Exception as e:
- return {'success': False, 'error': str(e)}
+ Kept as a thin alias so callers outside this module keep working; the
+ private re-implementation it replaced hardcoded ``sudo`` and called
+ ``nginx`` by bare name, which the panel's sbin-less unit PATH cannot
+ resolve.
+ """
+ return NginxService.reload()
diff --git a/backend/app/services/fail2ban_jail_service.py b/backend/app/services/fail2ban_jail_service.py
index ded484f3..4b25705c 100644
--- a/backend/app/services/fail2ban_jail_service.py
+++ b/backend/app/services/fail2ban_jail_service.py
@@ -29,7 +29,8 @@ import os
import re
import logging
-from app.utils.system import run_privileged, is_command_available, ServiceControl
+from app.utils.system import (ServiceControl, is_command_available,
+ run_privileged, write_privileged_file)
from app.services.nginx_service import NginxService
logger = logging.getLogger(__name__)
@@ -145,14 +146,8 @@ bantime = {bantime}
@staticmethod
def _write_file(path, content):
- """Write *content* to *path* with privilege (sudo tee), like NginxService."""
- try:
- proc = run_privileged(['tee', path], input=content)
- if proc.returncode != 0:
- return {'success': False, 'error': (proc.stderr or 'write failed').strip()}
- return {'success': True, 'path': path}
- except Exception as e:
- return {'success': False, 'error': str(e)}
+ """Write *content* to *path* with privilege — the shared door (plan 75 §G2)."""
+ return write_privileged_file(path, content)
@staticmethod
def _ensure_logpath(logpath):
diff --git a/backend/app/services/nginx_advanced_service.py b/backend/app/services/nginx_advanced_service.py
index 59f707f5..557eb4be 100644
--- a/backend/app/services/nginx_advanced_service.py
+++ b/backend/app/services/nginx_advanced_service.py
@@ -2,6 +2,7 @@ import os
import json
import logging
import re
+from app.services.nginx_service import NginxService
from app.utils.system import run_unprivileged, run_privileged
logger = logging.getLogger(__name__)
@@ -10,9 +11,12 @@ logger = logging.getLogger(__name__)
class NginxAdvancedService:
"""Advanced Nginx configuration: reverse proxy, load balancing, caching, rate limiting."""
- NGINX_CONF_DIR = '/etc/nginx'
- SITES_AVAILABLE = '/etc/nginx/sites-available'
- SITES_ENABLED = '/etc/nginx/sites-enabled'
+ # NginxService owns these (plan 75 §G4). Hardcoding them here meant an
+ # NGINX_CONF_DIR override — the env var NginxService honours, and what
+ # tests redirect — silently did not apply to this service.
+ NGINX_CONF_DIR = NginxService.NGINX_CONF_DIR
+ SITES_AVAILABLE = NginxService.SITES_AVAILABLE
+ SITES_ENABLED = NginxService.SITES_ENABLED
@staticmethod
def get_proxy_rules(domain):
@@ -123,28 +127,28 @@ class NginxAdvancedService:
config = '\n'.join(lines)
- # Write config
- conf_path = os.path.join(NginxAdvancedService.SITES_AVAILABLE, domain)
- with open(conf_path, 'w') as f:
- f.write(config)
+ # Write config through the shared vhost door (plan 75 §G4). This was a
+ # plain `open(conf_path, 'w')`: unprivileged, so it raises
+ # PermissionError against a root-owned /etc/nginx/sites-available, and
+ # it neither config-tested nor reloaded what it wrote.
+ result = NginxService.write_vhost(domain, config)
+ if not result['success']:
+ return {'error': result['error'], 'domain': domain}
- return {'domain': domain, 'config': config, 'path': conf_path}
+ return {'domain': domain, 'config': config, 'path': result['path']}
@staticmethod
def test_config():
- """Test nginx config syntax."""
- # 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.
- try:
- result = run_privileged(['nginx', '-t'])
- return {
- 'valid': result.returncode == 0,
- 'output': (result.stdout or '') + (result.stderr or ''),
- }
- except Exception as e:
- return {'valid': False, 'output': str(e)}
+ """Test nginx config syntax — NginxService owns the call (plan 75 §G4).
+
+ Kept as a distinct method because its result shape (``valid``/
+ ``output``) is what this service's API consumers read.
+ """
+ result = NginxService.test_config()
+ return {
+ 'valid': result['success'],
+ 'output': result.get('message') or result.get('error') or '',
+ }
@staticmethod
def preview_diff(domain, new_config):
@@ -166,15 +170,13 @@ class NginxAdvancedService:
@staticmethod
def reload_nginx():
- """Reload nginx configuration."""
- try:
- result = run_privileged(['nginx', '-s', 'reload'])
- if result.returncode != 0:
- return {'success': False,
- 'error': (result.stderr or 'nginx reload failed').strip()}
- return {'success': True}
- except Exception as e:
- return {'success': False, 'error': str(e)}
+ """Reload nginx — NginxService owns it (plan 75 §G4).
+
+ The private version ran `nginx -s reload` with no config test first, so
+ a broken vhost written by this same service reloaded straight into
+ production instead of being refused.
+ """
+ return NginxService.reload()
@staticmethod
def get_vhost_logs(domain, log_type='access', lines=100):
diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py
index 55d58274..3ac9edaa 100644
--- a/backend/app/services/nginx_service.py
+++ b/backend/app/services/nginx_service.py
@@ -4,7 +4,8 @@ import re
from typing import Dict, List, Optional
from pathlib import Path
-from app.utils.system import ServiceControl, run_privileged, is_command_available
+from app.utils.system import (ServiceControl, is_command_available,
+ run_privileged, write_privileged_file)
def _validate_domain(domain: str) -> bool:
@@ -643,9 +644,9 @@ location /p/ {{
run_privileged(['mkdir', '-p',
os.path.join(cls.MICROCACHE_DIR, 'proxy'),
os.path.join(cls.MICROCACHE_DIR, 'fastcgi')])
- process = run_privileged(['tee', conf_path], input=cls.MICROCACHE_ZONE_SNIPPET)
- if process.returncode != 0:
- return {'success': False, 'error': process.stderr}
+ written = write_privileged_file(conf_path, cls.MICROCACHE_ZONE_SNIPPET)
+ if not written['success']:
+ return {'success': False, 'error': written['error']}
return {'success': True, 'changed': True, 'path': conf_path,
'message': 'Micro-cache zone configured'}
except Exception as e:
@@ -709,13 +710,9 @@ location /p/ {{
# Write config file
config_path = os.path.join(cls.SITES_AVAILABLE, name)
try:
- # Use sudo to write
- process = run_privileged(
- ['tee', config_path],
- input=config,
- )
- if process.returncode != 0:
- return {'success': False, 'error': process.stderr}
+ written = write_privileged_file(config_path, config)
+ if not written['success']:
+ return {'success': False, 'error': written['error']}
return {'success': True, 'message': f'Site {name} created', 'path': config_path}
except Exception as e:
@@ -750,6 +747,86 @@ location /p/ {{
:meth:`site_access_log_path`)."""
return f'{cls.LOG_DIR}/{name}.error.log'
+ @classmethod
+ def read_vhost(cls, name: str) -> Optional[str]:
+ """The vhost's current content, or ``None`` if it cannot be read.
+
+ ``None`` means "could not determine", never "empty file" (§A). Callers
+ that need to distinguish a missing vhost from an unreadable one check
+ ``os.path.exists`` themselves.
+ """
+ try:
+ result = run_privileged(['cat', os.path.join(cls.SITES_AVAILABLE, name)])
+ except Exception: # noqa: BLE001 - no cat, no permission, timeout
+ return None
+ return result.stdout if result.returncode == 0 else None
+
+ @classmethod
+ def write_vhost(cls, name: str, content: str, *, enable: bool = True) -> Dict:
+ """Write, enable, config-test, roll back on failure, reload. One door (§G4).
+
+ ``environment_domain_service`` re-implemented this whole sequence with
+ raw ``sudo`` calls, and ``nginx_advanced_service`` wrote the file with a
+ plain unprivileged ``open()``. Both bypass every guard NginxService
+ already owns: the sudo-vs-root decision, argv[0] resolution for an
+ sbin-resident nginx, and the config test.
+
+ The rollback is the part a copy never has. Writing a broken vhost and
+ *then* discovering ``nginx -t`` fails leaves the file on disk and
+ symlinked; the next unrelated reload — a certificate renewal, another
+ site going live — picks it up and fails, and the blame lands on
+ whatever triggered that reload. Restoring the previous content (or
+ removing a file that did not exist before) keeps the failure local to
+ the caller that caused it.
+
+ Returns ``{'success', 'path'}`` or ``{'success': False, 'error'}``.
+ """
+ available_path = os.path.join(cls.SITES_AVAILABLE, name)
+ enabled_path = os.path.join(cls.SITES_ENABLED, name)
+ previous = cls.read_vhost(name)
+ was_enabled = os.path.exists(enabled_path)
+
+ written = write_privileged_file(available_path, content)
+ if not written['success']:
+ return {'success': False, 'error': written['error']}
+
+ if enable and not was_enabled:
+ link = run_privileged(['ln', '-sf', available_path, enabled_path])
+ if link.returncode != 0:
+ cls._restore_vhost(name, previous, was_enabled)
+ return {'success': False,
+ 'error': (link.stderr or f'failed to enable {name}').strip()}
+
+ test = cls.test_config()
+ if not test['success']:
+ cls._restore_vhost(name, previous, was_enabled)
+ return {'success': False,
+ 'error': f"Config test failed: {test.get('message') or test.get('error')}"}
+
+ reloaded = cls.reload()
+ if not reloaded['success']:
+ return reloaded
+ return {'success': True, 'path': available_path}
+
+ @classmethod
+ def _restore_vhost(cls, name: str, previous: Optional[str], was_enabled: bool) -> None:
+ """Undo a :meth:`write_vhost` that did not survive the config test.
+
+ Best-effort by nature — the write already failed, and a failure to
+ clean up must not mask the error the caller is about to be told about.
+ """
+ available_path = os.path.join(cls.SITES_AVAILABLE, name)
+ enabled_path = os.path.join(cls.SITES_ENABLED, name)
+ try:
+ if previous is None:
+ run_privileged(['rm', '-f', available_path])
+ else:
+ write_privileged_file(available_path, previous)
+ if not was_enabled:
+ run_privileged(['rm', '-f', enabled_path])
+ except Exception: # noqa: BLE001 - never mask the original failure
+ pass
+
@classmethod
def enable_site(cls, name: str) -> Dict:
"""Enable a site by creating symlink in sites-enabled."""
@@ -834,14 +911,10 @@ location /p/ {{
final_content = redirect_block + '\n' + new_content
# Write updated config
- process = run_privileged(
- ['tee', config_path],
- input=final_content,
- )
-
- if process.returncode == 0:
- return cls.reload()
- return {'success': False, 'error': process.stderr}
+ written = write_privileged_file(config_path, final_content)
+ if not written['success']:
+ return {'success': False, 'error': written['error']}
+ return cls.reload()
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -1080,9 +1153,9 @@ location /p/ {{
# Write location snippet to serverkit-locations dir
config_path = os.path.join(cls.LOCATIONS_DIR, f'{cls.PRIVATE_URL_CONFIG_NAME}.conf')
- process = run_privileged(['tee', config_path], input=config)
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to write config: {process.stderr}'}
+ written = write_privileged_file(config_path, config)
+ if not written['success']:
+ return {'success': False, 'error': f"Failed to write config: {written['error']}"}
# Clean up legacy separate server block if it exists
cls._remove_legacy_site(cls.PRIVATE_URL_CONFIG_NAME)
@@ -1164,9 +1237,9 @@ location /p/ {{
config_path = os.path.join(cls.LOCATIONS_DIR, f'{cls.GITEA_CONFIG_NAME}.conf')
# Write location snippet (no separate server block, no sites-enabled symlink)
- process = run_privileged(['tee', config_path], input=config)
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to write config: {process.stderr}'}
+ written = write_privileged_file(config_path, config)
+ if not written['success']:
+ return {'success': False, 'error': f"Failed to write config: {written['error']}"}
# Clean up legacy separate server block if it exists
cls._remove_legacy_site(cls.GITEA_CONFIG_NAME)
@@ -1239,9 +1312,9 @@ location /p/ {{
config_path = os.path.join(cls.LOCATIONS_DIR, f'{cls.WORDPRESS_CONFIG_NAME}.conf')
# Write location snippet (no separate server block, no sites-enabled symlink)
- process = run_privileged(['tee', config_path], input=config)
- if process.returncode != 0:
- return {'success': False, 'error': f'Failed to write config: {process.stderr}'}
+ written = write_privileged_file(config_path, config)
+ if not written['success']:
+ return {'success': False, 'error': f"Failed to write config: {written['error']}"}
# Clean up legacy separate server block if it exists
cls._remove_legacy_site(cls.WORDPRESS_CONFIG_NAME)
diff --git a/backend/app/services/php_service.py b/backend/app/services/php_service.py
index 15bebb5e..8d1f39e9 100644
--- a/backend/app/services/php_service.py
+++ b/backend/app/services/php_service.py
@@ -4,7 +4,8 @@ import re
from typing import Dict, List, Optional
from pathlib import Path
-from app.utils.system import PackageManager, ServiceControl, run_privileged, is_command_available
+from app.utils.system import (PackageManager, ServiceControl, is_command_available,
+ run_privileged, write_privileged_file)
class PHPService:
@@ -321,14 +322,13 @@ env[TEMP] = /tmp
run_privileged(['mkdir', '-p', '/var/log/php'])
# Write pool config
- process = run_privileged(['tee', pool_file], input=pool_content)
+ written = write_privileged_file(pool_file, pool_content)
+ if not written['success']:
+ return {'success': False, 'error': written['error']}
- if process.returncode == 0:
- # Restart FPM
- cls.restart_fpm(version)
- return {'success': True, 'message': f'Pool {pool_name} created', 'file': pool_file}
-
- return {'success': False, 'error': process.stderr}
+ # Restart FPM
+ cls.restart_fpm(version)
+ return {'success': True, 'message': f'Pool {pool_name} created', 'file': pool_file}
except Exception as e:
return {'success': False, 'error': str(e)}
diff --git a/backend/app/services/postfix_service.py b/backend/app/services/postfix_service.py
index 4bce68d5..92961ed8 100644
--- a/backend/app/services/postfix_service.py
+++ b/backend/app/services/postfix_service.py
@@ -4,7 +4,8 @@ import re
import subprocess
from typing import Dict
-from app.utils.system import PackageManager, ServiceControl, run_privileged
+from app.utils.system import (PackageManager, ServiceControl, run_privileged,
+ write_privileged_file)
from app import paths
@@ -186,12 +187,12 @@ mailbox_size_limit = 0
)
# Append to main.cf
- run_privileged(['tee', '-a', cls.POSTFIX_MAIN_CF], input=additions)
+ write_privileged_file(cls.POSTFIX_MAIN_CF, additions, append=True)
# Enable submission port in master.cf
result = run_privileged(['cat', cls.POSTFIX_MASTER_CF])
if 'submission' not in (result.stdout or ''):
- run_privileged(['tee', '-a', cls.POSTFIX_MASTER_CF], input=cls.SUBMISSION_CONF)
+ write_privileged_file(cls.POSTFIX_MASTER_CF, cls.SUBMISSION_CONF, append=True)
# Restart
ServiceControl.restart('postfix', timeout=30)
@@ -207,7 +208,7 @@ mailbox_size_limit = 0
result = run_privileged(['cat', cls.VIRTUAL_DOMAINS_FILE])
content = result.stdout or ''
if domain not in content:
- run_privileged(['tee', '-a', cls.VIRTUAL_DOMAINS_FILE], input=f'{domain} OK\n')
+ write_privileged_file(cls.VIRTUAL_DOMAINS_FILE, f'{domain} OK\n', append=True)
run_privileged(['postmap', cls.VIRTUAL_DOMAINS_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -220,19 +221,19 @@ mailbox_size_limit = 0
try:
result = run_privileged(['cat', cls.VIRTUAL_DOMAINS_FILE])
lines = [l for l in (result.stdout or '').splitlines() if not l.startswith(f'{domain} ')]
- run_privileged(['tee', cls.VIRTUAL_DOMAINS_FILE], input='\n'.join(lines) + '\n')
+ write_privileged_file(cls.VIRTUAL_DOMAINS_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_DOMAINS_FILE])
# Also remove mailboxes for this domain
result = run_privileged(['cat', cls.VIRTUAL_MAILBOXES_FILE])
lines = [l for l in (result.stdout or '').splitlines() if not l.endswith(f'@{domain}') and f'@{domain} ' not in l]
- run_privileged(['tee', cls.VIRTUAL_MAILBOXES_FILE], input='\n'.join(lines) + '\n')
+ write_privileged_file(cls.VIRTUAL_MAILBOXES_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_MAILBOXES_FILE])
# Remove aliases for this domain
result = run_privileged(['cat', cls.VIRTUAL_ALIASES_FILE])
lines = [l for l in (result.stdout or '').splitlines() if f'@{domain}' not in l]
- run_privileged(['tee', cls.VIRTUAL_ALIASES_FILE], input='\n'.join(lines) + '\n')
+ write_privileged_file(cls.VIRTUAL_ALIASES_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_ALIASES_FILE])
run_privileged(['postfix', 'reload'])
@@ -245,7 +246,7 @@ mailbox_size_limit = 0
"""Add a mailbox to the virtual mailbox map."""
try:
mailbox_path = f'{domain}/{username}/Maildir/'
- run_privileged(['tee', '-a', cls.VIRTUAL_MAILBOXES_FILE], input=f'{email} {mailbox_path}\n')
+ write_privileged_file(cls.VIRTUAL_MAILBOXES_FILE, f'{email} {mailbox_path}\n', append=True)
run_privileged(['postmap', cls.VIRTUAL_MAILBOXES_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -258,7 +259,7 @@ mailbox_size_limit = 0
try:
result = run_privileged(['cat', cls.VIRTUAL_MAILBOXES_FILE])
lines = [l for l in (result.stdout or '').splitlines() if not l.startswith(f'{email} ')]
- run_privileged(['tee', cls.VIRTUAL_MAILBOXES_FILE], input='\n'.join(lines) + '\n')
+ write_privileged_file(cls.VIRTUAL_MAILBOXES_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_MAILBOXES_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -269,7 +270,7 @@ mailbox_size_limit = 0
def add_alias(cls, source: str, destination: str) -> Dict:
"""Add a virtual alias."""
try:
- run_privileged(['tee', '-a', cls.VIRTUAL_ALIASES_FILE], input=f'{source} {destination}\n')
+ write_privileged_file(cls.VIRTUAL_ALIASES_FILE, f'{source} {destination}\n', append=True)
run_privileged(['postmap', cls.VIRTUAL_ALIASES_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -282,7 +283,7 @@ mailbox_size_limit = 0
try:
result = run_privileged(['cat', cls.VIRTUAL_ALIASES_FILE])
lines = [l for l in (result.stdout or '').splitlines() if not l.startswith(f'{source} ')]
- run_privileged(['tee', cls.VIRTUAL_ALIASES_FILE], input='\n'.join(lines) + '\n')
+ write_privileged_file(cls.VIRTUAL_ALIASES_FILE, '\n'.join(lines) + '\n')
run_privileged(['postmap', cls.VIRTUAL_ALIASES_FILE])
run_privileged(['postfix', 'reload'])
return {'success': True}
@@ -411,8 +412,8 @@ mailbox_size_limit = 0
run_privileged(['postconf', '-e', 'smtp_sasl_auth_enable=yes'])
run_privileged(['postconf', '-e', f'smtp_sasl_password_maps=hash:{cls.POSTFIX_SASL_PASSWD}'])
run_privileged(['postconf', '-e', 'smtp_sasl_security_options=noanonymous'])
- run_privileged(['tee', cls.POSTFIX_SASL_PASSWD], input=f'{relay} {username}:{password or ""}\n')
- run_privileged(['chmod', '600', cls.POSTFIX_SASL_PASSWD])
+ write_privileged_file(cls.POSTFIX_SASL_PASSWD,
+ f'{relay} {username}:{password or ""}\n', mode='600')
run_privileged(['postmap', cls.POSTFIX_SASL_PASSWD])
run_privileged(['postconf', '-e', f'smtp_tls_security_level={"encrypt" if use_tls else "may"}'])
run_privileged(['postfix', 'reload'])
diff --git a/backend/app/services/ssl_service.py b/backend/app/services/ssl_service.py
index 74da4db5..74039cd0 100644
--- a/backend/app/services/ssl_service.py
+++ b/backend/app/services/ssl_service.py
@@ -6,7 +6,8 @@ from datetime import datetime
from typing import Dict, List, Optional, Tuple
from pathlib import Path
-from app.utils.system import ServiceControl, run_privileged, PackageManager, is_command_available
+from app.utils.system import (PackageManager, ServiceControl, is_command_available,
+ run_privileged, write_privileged_file)
# Candidate locations for the certbot binary when it isn't on $PATH. Snap is
@@ -512,7 +513,7 @@ class SSLService:
cron_job = '0 0,12 * * * root certbot renew --quiet --post-hook "systemctl reload nginx"'
cron_file = '/etc/cron.d/certbot-renewal'
- run_privileged(['tee', cron_file], input=cron_job + '\n')
+ write_privileged_file(cron_file, cron_job + '\n')
return {'success': True, 'message': 'Auto-renewal configured via cron'}
diff --git a/backend/app/services/waf_service.py b/backend/app/services/waf_service.py
index d24921c5..4e2f7421 100644
--- a/backend/app/services/waf_service.py
+++ b/backend/app/services/waf_service.py
@@ -50,9 +50,13 @@ OWASP_CRS_PATH = os.environ.get(
# ``events`` or the SERVERKIT_MODSEC_AUDIT_LOG env var.
MODSEC_AUDIT_LOG = os.environ.get('SERVERKIT_MODSEC_AUDIT_LOG', '/var/log/modsec_audit.log')
-# Where managed app vhosts live (mirrors NginxService.SITES_AVAILABLE).
-NGINX_CONF_DIR = os.environ.get('NGINX_CONF_DIR', '/etc/nginx')
-SITES_AVAILABLE = os.path.join(NGINX_CONF_DIR, 'sites-available')
+# Where managed app vhosts live. Imported, not mirrored: "mirrors
+# NginxService.SITES_AVAILABLE" is a comment, and a comment is not a
+# constraint — the two drift the moment either side moves (plan 75 §G4).
+from app.services.nginx_service import NginxService # noqa: E402
+
+NGINX_CONF_DIR = NginxService.NGINX_CONF_DIR
+SITES_AVAILABLE = NginxService.SITES_AVAILABLE
# Sentinel marking our additive include so re-applies are idempotent.
_INCLUDE_MARKER = '# serverkit-waf'
@@ -280,12 +284,9 @@ class WafService:
@classmethod
def _write_file(cls, path: str, content: str) -> Dict:
- """Write *content* to *path* with privilege escalation (via tee)."""
- from app.utils.system import run_privileged
- result = run_privileged(['tee', path], input=content)
- if result.returncode != 0:
- return {'success': False, 'error': result.stderr or f'failed to write {path}'}
- return {'success': True, 'path': path}
+ """Write *content* to *path* with privilege — the shared door (plan 75 §G2)."""
+ from app.utils.system import write_privileged_file
+ return write_privileged_file(path, content)
@classmethod
def _nginx_test_and_reload(cls) -> Dict:
diff --git a/backend/app/utils/system.py b/backend/app/utils/system.py
index 903c5080..341937be 100644
--- a/backend/app/utils/system.py
+++ b/backend/app/utils/system.py
@@ -144,6 +144,65 @@ def run_unprivileged(cmd: Union[List[str], str], *, timeout: int = 60,
}
+def write_privileged_file(path: str, content: str, *, append: bool = False,
+ mode: Optional[str] = None,
+ owner: Optional[str] = None) -> dict:
+ """Write *content* to *path* with privilege escalation. One door (plan 75 §G2).
+
+ The write-a-root-owned-file sequence was pasted at 15+ call sites in **two
+ competing forms**: ``run_privileged(['tee', path], input=content)`` and a
+ raw ``subprocess.run(['sudo', 'tee', path], ...)``. The second form is the
+ drift this plan exists to remove — it hardcodes ``sudo`` instead of asking
+ :func:`_needs_sudo`, so it fails on a panel already running as root (no
+ sudo binary in a minimal container) exactly the way plan 74's outage did.
+
+ Returns a result dict rather than a ``CompletedProcess`` because every one
+ of those call sites immediately converted one into the other:
+
+ {'success': bool, 'path': str, 'error': str} # 'error' only on failure
+
+ ``success`` is never True on a write that did not demonstrably happen — a
+ ``FileNotFoundError`` (no ``tee``) or a timeout reports the failure instead
+ of being swallowed into a cheerful return (§A, probe honesty).
+
+ *mode* and *owner* are applied after the write (``chmod`` / ``chown``); a
+ failure there is reported, because a config written with the wrong
+ ownership is not a config that works.
+
+ Still ``tee`` under the hood, deliberately: this change is a collapse, not
+ a behaviour change. Having one door is what makes a later atomic write
+ (tmp + ``os.replace``) a single edit instead of fifteen.
+ """
+ argv = ['tee', '-a', path] if append else ['tee', path]
+ try:
+ result = run_privileged(argv, input=content)
+ except FileNotFoundError:
+ return {'success': False, 'path': path,
+ 'error': "'tee' not found - cannot write privileged file"}
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'path': path,
+ 'error': f'timed out writing {path}'}
+ except Exception as exc: # noqa: BLE001 - reported, never converted to success
+ return {'success': False, 'path': path, 'error': str(exc)}
+
+ if result.returncode != 0:
+ return {'success': False, 'path': path,
+ 'error': (result.stderr or f'failed to write {path}').strip()}
+
+ follow_ups = ([['chmod', mode, path]] if mode else []) + \
+ ([['chown', owner, path]] if owner else [])
+ for step_argv in follow_ups:
+ try:
+ step = run_privileged(step_argv)
+ except Exception as exc: # noqa: BLE001
+ return {'success': False, 'path': path, 'error': str(exc)}
+ if step.returncode != 0:
+ return {'success': False, 'path': path,
+ 'error': (step.stderr or f'{step_argv[0]} failed on {path}').strip()}
+
+ return {'success': True, 'path': path}
+
+
# Searched when ``$PATH`` does not resolve a command. Ordered the way a login
# shell would. ``/usr/sbin`` and ``/sbin`` matter most: the panel's systemd unit
# ships a PATH of venv:/usr/local/bin:/usr/bin:/bin, so every sbin-resident tool
@@ -154,6 +213,33 @@ _COMMAND_SEARCH_DIRS = ('/usr/local/sbin', '/usr/local/bin', '/usr/sbin',
'/usr/bin', '/sbin', '/bin', '/snap/bin')
+def unit_is_active(unit: str, *, timeout: int = 10) -> Optional[bool]:
+ """Tri-state systemd unit probe: ``True``, ``False``, or ``None`` (§G6).
+
+ ``None`` means *could not determine* — no systemctl, no systemd, a probe
+ that timed out — and is deliberately not ``False``. The five hand-rolled
+ copies of this ``systemctl is-active`` call all collapsed those cases into
+ "not running", which is how a working service gets reported as down on a
+ host the panel simply could not ask (plan 74's outage, one layer up).
+
+ Callers that genuinely want two states write ``unit_is_active(u) is True``
+ and are then saying so out loud.
+ """
+ try:
+ result = subprocess.run(
+ ['systemctl', 'is-active', unit],
+ capture_output=True, text=True, timeout=timeout,
+ )
+ except (FileNotFoundError, subprocess.TimeoutExpired, OSError):
+ return None
+ # systemctl prints one word: active / inactive / failed / unknown. An empty
+ # stdout means it answered nothing useful, which is not the same as "no".
+ answer = (result.stdout or '').strip()
+ if not answer:
+ return None
+ return answer == 'active'
+
+
def resolve_command(cmd: str) -> Optional[str]:
"""Absolute path to *cmd*, or None when it cannot be found anywhere.
diff --git a/backend/tests/test_fail2ban_jail_service.py b/backend/tests/test_fail2ban_jail_service.py
index e6f4720c..570fe582 100644
--- a/backend/tests/test_fail2ban_jail_service.py
+++ b/backend/tests/test_fail2ban_jail_service.py
@@ -101,19 +101,19 @@ def test_enable_requires_app_name():
# ---------- lifecycle (mocked privileged calls) ----------
-def test_enable_writes_filter_and_jail_then_reloads():
- writes = {}
-
- def fake_run(cmd, **kwargs):
- if cmd[:1] == ['tee'] and 'input' in kwargs:
- writes[cmd[1]] = kwargs['input']
- return _ok()
+def test_enable_writes_filter_and_jail_then_reloads(fake_subprocess):
+ # Scripted through the shared seam (plan 75 §G7): the config write now goes
+ # through write_privileged_file, so a stub pinned to this module's imported
+ # `run_privileged` would quietly stop seeing it.
+ for cmd in (['tee'], ['touch'], ['fail2ban-client']):
+ fake_subprocess.script(cmd)
with patch.object(F2B, 'available', return_value=True), \
- patch.object(F2B, '_read_text', return_value=None), \
- patch('app.services.fail2ban_jail_service.run_privileged', side_effect=fake_run) as rp:
+ patch.object(F2B, '_read_text', return_value=None):
res = F2B.enable_wp_jail(_app('myblog'))
+ writes = fake_subprocess.writes()
+
assert res['success'] is True and res['enabled'] is True
assert res['jail'] == 'serverkit-myblog'
@@ -124,7 +124,7 @@ def test_enable_writes_filter_and_jail_then_reloads():
assert 'logpath = /var/log/nginx/myblog.access.log' in writes[jail_path]
# the logpath was touched, and fail2ban was reloaded (not restarted)
- cmds = [c.args[0] for c in rp.call_args_list]
+ cmds = fake_subprocess.commands()
assert ['touch', '/var/log/nginx/myblog.access.log'] in cmds
assert ['fail2ban-client', 'reload'] in cmds
@@ -172,26 +172,22 @@ def test_get_status_shape_when_jail_absent():
# ---------- generic jail engine (plan 52 — reusable beyond WordPress) ----------
-def test_enable_jail_generic_writes_custom_filter_jail_and_port():
+def test_enable_jail_generic_writes_custom_filter_jail_and_port(fake_subprocess):
"""The generic engine any vertical can use (e.g. a game-server login jail):
an arbitrary serverkit-* filter, a custom logpath, and a non-web port."""
- writes = {}
-
- def fake_run(cmd, **kwargs):
- if cmd[:1] == ['tee'] and 'input' in kwargs:
- writes[cmd[1]] = kwargs['input']
- return _ok()
+ for cmd in (['tee'], ['touch'], ['fail2ban-client']):
+ fake_subprocess.script(cmd)
custom_filter = ('# ServerKit game-server login filter.\n[Definition]\n'
'failregex = ^.*Failed login from <HOST>\nignoreregex =\n')
with patch.object(F2B, 'available', return_value=True), \
- patch.object(F2B, '_read_text', return_value=None), \
- patch('app.services.fail2ban_jail_service.run_privileged', side_effect=fake_run):
+ patch.object(F2B, '_read_text', return_value=None):
res = F2B.enable_jail(
'mc survival', filter_name='serverkit-mc-login',
filter_content=custom_filter, logpath='/var/log/mc/console.log',
maxretry=4, findtime=300, bantime=1800, port='25565', site_label='MC Survival')
+ writes = fake_subprocess.writes()
assert res['success'] is True and res['enabled'] is True
# key is sanitized + prefixed like any jail
assert res['jail'] == 'serverkit-mc-survival'
diff --git a/backend/tests/test_micro_cache.py b/backend/tests/test_micro_cache.py
index a56d097b..4d8091fd 100644
--- a/backend/tests/test_micro_cache.py
+++ b/backend/tests/test_micro_cache.py
@@ -16,20 +16,14 @@ Proving points:
save-only note when not; POST .../purge wipes the shared cache dir
(Linux-guarded); both require auth
"""
-from types import SimpleNamespace
-
import pytest
from app import db
from app.models import Application, User
from app.models.domain import Domain
-from app.services import nginx_service
from app.services.nginx_service import NginxService
from app.services.site_domain_service import SiteDomainService
-
-
-def _proc(returncode=0, stdout='', stderr=''):
- return SimpleNamespace(returncode=returncode, stdout=stdout, stderr=stderr)
+from subprocess_stub import FakeProc
BYPASS_MARKERS = [
@@ -134,56 +128,57 @@ def test_zone_snippet_declares_shared_zones():
assert snippet.count('/var/cache/nginx/serverkit-microcache') == 2
-def test_ensure_cache_zone_writes_once_and_is_idempotent(tmp_path, monkeypatch):
+def _tee_to_disk(fake):
+ """Make the scripted `tee` actually write, so idempotence is observable.
+
+ Scripted through the shared seam (plan 75 §G7) rather than by patching
+ `nginx_service.run_privileged`: the write now goes through
+ `write_privileged_file`, and a stub pinned to one module's imported name
+ would silently stop intercepting it — which is exactly how a test keeps a
+ bypass route alive.
+ """
import os as _os
- conf_dir = tmp_path / 'nginx'
- monkeypatch.setattr(NginxService, 'NGINX_CONF_DIR', str(conf_dir))
- calls = []
+ def write(argv, kwargs):
+ path = argv[2] if argv[1] == '-a' else argv[1]
+ _os.makedirs(_os.path.dirname(path), exist_ok=True)
+ with open(path, 'a' if argv[1] == '-a' else 'w') as fh:
+ fh.write(kwargs.get('input', ''))
+ return FakeProc()
- def fake_run(cmd, **kw):
- calls.append(list(cmd))
- if cmd[0] == 'tee':
- path = cmd[1]
- _os.makedirs(_os.path.dirname(path), exist_ok=True)
- with open(path, 'w') as f:
- f.write(kw.get('input', ''))
- return _proc()
+ fake.when(['tee'], write)
+ return fake
- monkeypatch.setattr(nginx_service, 'run_privileged', fake_run)
+
+def test_ensure_cache_zone_writes_once_and_is_idempotent(tmp_path, fake_subprocess, monkeypatch):
+ conf_dir = tmp_path / 'nginx'
+ monkeypatch.setattr(NginxService, 'NGINX_CONF_DIR', str(conf_dir))
+ fake_subprocess.script(['mkdir'])
+ _tee_to_disk(fake_subprocess)
first = NginxService.ensure_cache_zone()
assert first['success'] is True and first['changed'] is True
conf_path = conf_dir / 'conf.d' / 'serverkit-microcache.conf'
assert conf_path.read_text() == NginxService.MICROCACHE_ZONE_SNIPPET
- tees = [c for c in calls if c[0] == 'tee']
- assert len(tees) == 1
+ assert len([c for c in fake_subprocess.commands() if c[0] == 'tee']) == 1
second = NginxService.ensure_cache_zone()
assert second['success'] is True and second['changed'] is False
- assert len([c for c in calls if c[0] == 'tee']) == 1 # no rewrite
+ assert len([c for c in fake_subprocess.commands() if c[0] == 'tee']) == 1 # no rewrite
-def test_create_site_ensures_zone_when_enabled(tmp_path, monkeypatch):
+def test_create_site_ensures_zone_when_enabled(tmp_path, fake_subprocess, monkeypatch):
monkeypatch.setattr(NginxService, 'SITES_AVAILABLE', str(tmp_path))
ensured = []
monkeypatch.setattr(NginxService, 'ensure_cache_zone',
classmethod(lambda cls: ensured.append(True) or {'success': True}))
- written = {}
-
- def fake_run(cmd, **kw):
- if cmd[0] == 'tee':
- written['path'] = cmd[1]
- written['content'] = kw.get('input', '')
- return _proc()
-
- monkeypatch.setattr(nginx_service, 'run_privileged', fake_run)
+ fake_subprocess.script(['tee'])
res = NginxService.create_site('shop', 'docker', ['shop.lvh.me'],
root_path=None, port=8300, micro_cache=True)
assert res['success'] is True
assert ensured == [True]
- assert 'proxy_cache serverkit_microcache;' in written['content']
+ assert 'proxy_cache serverkit_microcache;' in fake_subprocess.kwargs_for(['tee'])['input']
# Disabled writes never touch the zone.
NginxService.create_site('shop', 'docker', ['shop.lvh.me'],
@@ -365,27 +360,26 @@ def test_api_purge_failure_is_500_with_error(client, auth_headers, app, monkeypa
# ── purge service ────────────────────────────────────────────────────────────
-def test_purge_wipes_and_recreates_cache_dirs(monkeypatch):
+def test_purge_wipes_and_recreates_cache_dirs(fake_subprocess, monkeypatch):
import os as _os
monkeypatch.setattr(_os, 'name', 'posix') # force the Linux branch
- calls = []
- monkeypatch.setattr(nginx_service, 'run_privileged',
- lambda cmd, **kw: calls.append(list(cmd)) or _proc())
+ fake_subprocess.script(['rm'])
+ fake_subprocess.script(['mkdir'])
res = NginxService.purge_micro_cache()
assert res['success'] is True
assert 'shared' in res['note'] # documents the full-zone tradeoff
- rm, mkdir = calls
+ rm, mkdir = fake_subprocess.commands()
assert rm[:2] == ['rm', '-rf']
assert f'{NginxService.MICROCACHE_DIR}/proxy'.replace('/', _os.sep) in [p.replace('/', _os.sep) for p in rm]
assert mkdir[:2] == ['mkdir', '-p']
-def test_purge_is_linux_guarded(monkeypatch):
+def test_purge_is_linux_guarded(fake_subprocess, monkeypatch):
import os as _os
monkeypatch.setattr(_os, 'name', 'nt')
- monkeypatch.setattr(nginx_service, 'run_privileged',
- lambda *a, **kw: (_ for _ in ()).throw(AssertionError('must not run')))
+ # Nothing is scripted: any exec at all would raise UnscriptedCommand.
res = NginxService.purge_micro_cache()
assert res['success'] is False
assert 'Linux' in res['error']
+ assert fake_subprocess.commands() == []
diff --git a/backend/tests/test_nginx_write_vhost.py b/backend/tests/test_nginx_write_vhost.py
new file mode 100644
index 00000000..d4624fff
--- /dev/null
+++ b/backend/tests/test_nginx_write_vhost.py
@@ -0,0 +1,189 @@
+"""The one nginx vhost lifecycle (plan 75 §G4).
+
+`environment_domain_service` re-implemented write → symlink → `nginx -t` →
+reload with raw `sudo` calls, and `nginx_advanced_service` wrote the file with
+a plain unprivileged `open()`. Both are gone; what they each half-did is
+asserted here once.
+
+The rollback has no precedent in any of the copies, so it gets the most
+attention: a vhost that fails `nginx -t` and stays on disk turns the *next*
+unrelated reload — a cert renewal, another site going live — into the failure,
+and the blame lands on whatever triggered it.
+"""
+
+import os
+
+import pytest
+
+from app.services.nginx_service import NginxService
+
+pytestmark = pytest.mark.usefixtures('fake_subprocess')
+
+
+def nginx(tmp_path, monkeypatch, fake_subprocess):
+ """NginxService pointed at a temp tree, with every exec scripted."""
+ available = tmp_path / 'sites-available'
+ enabled = tmp_path / 'sites-enabled'
+ available.mkdir()
+ enabled.mkdir()
+ monkeypatch.setattr(NginxService, 'SITES_AVAILABLE', str(available))
+ monkeypatch.setattr(NginxService, 'SITES_ENABLED', str(enabled))
+ monkeypatch.setattr('app.services.nginx_service.is_command_available',
+ lambda *a, **k: True)
+
+ from subprocess_stub import FakeProc
+
+ def tee(argv, kwargs):
+ path = argv[2] if argv[1] == '-a' else argv[1]
+ with open(path, 'a' if argv[1] == '-a' else 'w') as fh:
+ fh.write(kwargs.get('input', ''))
+ return FakeProc()
+
+ def cat(argv, kwargs):
+ try:
+ with open(argv[1]) as fh:
+ return FakeProc(stdout=fh.read())
+ except OSError:
+ return FakeProc(returncode=1, stderr='No such file')
+
+ def ln(argv, kwargs):
+ target, link = argv[-2], argv[-1]
+ if not os.path.exists(link):
+ with open(link, 'w') as fh: # a plain file stands in for the symlink
+ fh.write(target)
+ return FakeProc()
+
+ def rm(argv, kwargs):
+ for path in argv[1:]:
+ if not path.startswith('-') and os.path.exists(path):
+ os.remove(path)
+ return FakeProc()
+
+ fake_subprocess.when(['tee'], tee)
+ fake_subprocess.when(['cat'], cat)
+ fake_subprocess.when(['ln'], ln)
+ fake_subprocess.when(['rm'], rm)
+ fake_subprocess.script(['nginx', '-t']) # valid by default
+ fake_subprocess.script(['systemctl']) # reload
+ return fake_subprocess
+
+
+def _paths(name='shop'):
+ return (os.path.join(NginxService.SITES_AVAILABLE, name),
+ os.path.join(NginxService.SITES_ENABLED, name))
+
+
+class TestHappyPath:
+ def test_writes_enables_tests_and_reloads(self, nginx):
+ res = NginxService.write_vhost('shop', 'server { listen 80; }')
+ assert res['success'] is True
+
+ available, enabled = _paths()
+ assert open(available).read() == 'server { listen 80; }'
+ assert os.path.exists(enabled)
+
+ cmds = nginx.commands()
+ assert ['nginx', '-t'] in cmds
+ assert any(c[:2] == ['systemctl', 'reload'] for c in cmds)
+
+ def test_config_test_runs_before_the_reload(self, nginx):
+ NginxService.write_vhost('shop', 'server {}')
+ cmds = nginx.commands()
+ test_at = cmds.index(['nginx', '-t'])
+ reload_at = next(i for i, c in enumerate(cmds) if c[:2] == ['systemctl', 'reload'])
+ assert test_at < reload_at
+
+ def test_enable_false_writes_without_symlinking(self, nginx):
+ NginxService.write_vhost('shop', 'server {}', enable=False)
+ available, enabled = _paths()
+ assert os.path.exists(available)
+ assert not os.path.exists(enabled)
+
+
+class TestRollback:
+ """What none of the hand-rolled copies did."""
+
+ def test_a_new_vhost_that_fails_the_test_is_removed(self, nginx):
+ nginx.script(['nginx', '-t'], returncode=1, stderr='invalid directive')
+
+ res = NginxService.write_vhost('shop', 'server { bogus; }')
+
+ assert res['success'] is False
+ assert 'invalid directive' in res['error']
+ available, enabled = _paths()
+ assert not os.path.exists(available), 'broken vhost left on disk'
+ assert not os.path.exists(enabled), 'broken vhost left enabled'
+
+ def test_an_existing_vhost_is_restored_byte_for_byte(self, nginx):
+ good = 'server { listen 80; server_name a.test; }'
+ assert NginxService.write_vhost('shop', good)['success'] is True
+
+ nginx.script(['nginx', '-t'], returncode=1, stderr='invalid directive')
+ res = NginxService.write_vhost('shop', 'server { bogus; }')
+
+ assert res['success'] is False
+ available, _ = _paths()
+ assert open(available).read() == good
+
+ def test_an_already_enabled_vhost_stays_enabled_after_a_rollback(self, nginx):
+ NginxService.write_vhost('shop', 'server {}')
+ nginx.script(['nginx', '-t'], returncode=1, stderr='nope')
+
+ NginxService.write_vhost('shop', 'server { bogus; }')
+
+ _, enabled = _paths()
+ assert os.path.exists(enabled), 'rollback disabled a site it did not enable'
+
+ def test_no_reload_happens_when_the_test_fails(self, nginx):
+ """The point of testing first: a broken config never reaches nginx."""
+ nginx.script(['nginx', '-t'], returncode=1, stderr='nope')
+ NginxService.write_vhost('shop', 'server { bogus; }')
+ assert not any(c[:2] == ['systemctl', 'reload'] for c in nginx.commands())
+
+
+class TestFailedWrite:
+ def test_a_failed_write_is_reported_and_nothing_is_enabled(self, nginx):
+ nginx.script(['tee'], returncode=1, stderr='Permission denied')
+
+ res = NginxService.write_vhost('shop', 'server {}')
+
+ assert res['success'] is False
+ assert 'Permission denied' in res['error']
+ _, enabled = _paths()
+ assert not os.path.exists(enabled)
+
+ def test_a_missing_tee_does_not_report_success(self, nginx):
+ """§A: a write that could not run must never render as one that did."""
+ nginx.script(['tee'], raises=FileNotFoundError)
+ assert NginxService.write_vhost('shop', 'server {}')['success'] is False
+
+
+class TestReadVhost:
+ def test_returns_the_content(self, nginx):
+ NginxService.write_vhost('shop', 'server { listen 80; }')
+ assert NginxService.read_vhost('shop') == 'server { listen 80; }'
+
+ def test_unreadable_is_none_never_empty_string(self, nginx):
+ """None means "could not determine"; '' would read as an empty vhost."""
+ assert NginxService.read_vhost('does-not-exist') is None
+
+ def test_a_broken_cat_is_none_not_an_exception(self, nginx):
+ nginx.script(['cat'], raises=FileNotFoundError)
+ assert NginxService.read_vhost('shop') is None
+
+
+class TestOneDeclarationOfThePaths:
+ """Four files used to hardcode these; a test redirecting one left the other
+ three writing to the real /etc/nginx."""
+
+ def test_every_service_reads_nginxservice_paths(self, monkeypatch):
+ from app.services import waf_service
+ from app.services.environment_domain_service import EnvironmentDomainService
+ from app.services.nginx_advanced_service import NginxAdvancedService
+
+ assert EnvironmentDomainService.SITES_AVAILABLE == NginxService.SITES_AVAILABLE
+ assert EnvironmentDomainService.SITES_ENABLED == NginxService.SITES_ENABLED
+ assert NginxAdvancedService.SITES_AVAILABLE == NginxService.SITES_AVAILABLE
+ assert NginxAdvancedService.SITES_ENABLED == NginxService.SITES_ENABLED
+ assert waf_service.SITES_AVAILABLE == NginxService.SITES_AVAILABLE
diff --git a/backend/tests/test_utils_system.py b/backend/tests/test_utils_system.py
index bbd69d80..c97a8711 100644
--- a/backend/tests/test_utils_system.py
+++ b/backend/tests/test_utils_system.py
@@ -41,6 +41,8 @@ privileged_cmd = _module.privileged_cmd
is_command_available = _module.is_command_available
PackageManager = _module.PackageManager
ServiceControl = _module.ServiceControl
+write_privileged_file = _module.write_privileged_file
+unit_is_active = _module.unit_is_active
# ---------------------------------------------------------------------------
@@ -454,3 +456,153 @@ class TestResultDict:
proc = subprocess.CompletedProcess([], 1, stdout='', stderr='')
assert ServiceControl.result_dict(proc, 'ok', fallback='Restart failed') == {
'success': False, 'error': 'Restart failed'}
+
+
+# ---------------------------------------------------------------------------
+# write_privileged_file
+# ---------------------------------------------------------------------------
+class TestWritePrivilegedFile:
+ """The one privileged-write door (plan 75 §G2).
+
+ Fifteen call sites in two competing forms collapsed into this, so the
+ properties they each hand-rolled are asserted once, here.
+ """
+
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_writes_via_tee_with_content_on_stdin(self, _euid, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')
+ assert write_privileged_file('/etc/nginx/sites-available/x', 'server {}') == {
+ 'success': True, 'path': '/etc/nginx/sites-available/x'}
+ argv, kwargs = mock_run.call_args[0][0], mock_run.call_args[1]
+ assert argv == ['tee', '/etc/nginx/sites-available/x']
+ # content never lands on the argv
+ assert kwargs['input'] == 'server {}'
+
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_append_uses_tee_dash_a(self, _euid, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')
+ write_privileged_file('/etc/postfix/main.cf', 'x=1\n', append=True)
+ assert mock_run.call_args[0][0] == ['tee', '-a', '/etc/postfix/main.cf']
+
+ @patch('app.utils.system.os.name', 'posix')
+ @patch('app.utils.system.shutil.which', return_value='/usr/bin/sudo')
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=1000, create=True)
+ def test_sudo_is_decided_by_needs_sudo_not_hardcoded(self, _euid, mock_run, *_):
+ """The drift this helper exists to remove.
+
+ environment_domain_service hardcoded ``['sudo', 'tee', path]``, which
+ fails on a panel already running as root in a container with no sudo
+ binary — plan 74's outage shape. Going through run_privileged means the
+ decision is made once, by _needs_sudo().
+ """
+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')
+ write_privileged_file('/etc/x', 'c')
+ assert mock_run.call_args[0][0] == ['sudo', '-n', 'tee', '/etc/x']
+
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_nonzero_exit_reports_stderr(self, _euid, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 1, stdout='', stderr='Permission denied\n')
+ result = write_privileged_file('/etc/x', 'c')
+ assert result['success'] is False
+ assert result['error'] == 'Permission denied'
+
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_empty_stderr_still_yields_an_error_string(self, _euid, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 1, stdout='', stderr='')
+ result = write_privileged_file('/etc/x', 'c')
+ assert result['success'] is False
+ assert '/etc/x' in result['error']
+
+ @patch('app.utils.system.subprocess.run', side_effect=FileNotFoundError())
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_missing_tee_is_a_failure_not_a_silent_success(self, _euid, _run):
+ """§A: a write that could not run must never report as one that did."""
+ result = write_privileged_file('/etc/x', 'c')
+ assert result['success'] is False
+ assert 'tee' in result['error']
+
+ @patch('app.utils.system.subprocess.run',
+ side_effect=subprocess.TimeoutExpired('tee', 300))
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_timeout_is_a_failure_not_a_silent_success(self, _euid, _run):
+ result = write_privileged_file('/etc/x', 'c')
+ assert result['success'] is False
+ assert 'timed out' in result['error']
+
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_mode_and_owner_are_applied_after_the_write(self, _euid, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='', stderr='')
+ write_privileged_file('/etc/postfix/sasl_passwd', 'x', mode='600', owner='root:root')
+ assert [c[0][0] for c in mock_run.call_args_list] == [
+ ['tee', '/etc/postfix/sasl_passwd'],
+ ['chmod', '600', '/etc/postfix/sasl_passwd'],
+ ['chown', 'root:root', '/etc/postfix/sasl_passwd'],
+ ]
+
+ @patch('app.utils.system.subprocess.run')
+ @patch('app.utils.system.os.geteuid', return_value=0, create=True)
+ def test_a_failed_chmod_fails_the_write(self, _euid, mock_run):
+ """A secrets file written world-readable is not a successful write."""
+ mock_run.side_effect = [
+ subprocess.CompletedProcess([], 0, stdout='', stderr=''),
+ subprocess.CompletedProcess([], 1, stdout='', stderr='chmod: no such file'),
+ ]
+ result = write_privileged_file('/etc/x', 'c', mode='600')
+ assert result['success'] is False
+ assert 'chmod' in result['error']
+
+
+# ---------------------------------------------------------------------------
+# unit_is_active
+# ---------------------------------------------------------------------------
+class TestUnitIsActive:
+ """Tri-state systemd probe (plan 75 §G6).
+
+ Five services re-inlined `systemctl is-active` and every one of them
+ collapsed "could not ask" into "not running". None means could-not-tell.
+ """
+
+ @patch('app.utils.system.subprocess.run')
+ def test_active(self, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='active\n', stderr='')
+ assert unit_is_active('nginx') is True
+
+ @patch('app.utils.system.subprocess.run')
+ def test_inactive_is_false_not_none(self, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 3, stdout='inactive\n', stderr='')
+ assert unit_is_active('nginx') is False
+
+ @patch('app.utils.system.subprocess.run')
+ def test_failed_unit_is_false(self, mock_run):
+ mock_run.return_value = subprocess.CompletedProcess([], 3, stdout='failed\n', stderr='')
+ assert unit_is_active('nginx') is False
+
+ @patch('app.utils.system.subprocess.run', side_effect=FileNotFoundError())
+ def test_no_systemctl_is_none_never_false(self, _run):
+ """A host without systemd has not told us the service is down."""
+ assert unit_is_active('nginx') is None
+
+ @patch('app.utils.system.subprocess.run',
+ side_effect=subprocess.TimeoutExpired('systemctl', 10))
+ def test_timeout_is_none(self, _run):
+ assert unit_is_active('nginx') is None
+
+ @patch('app.utils.system.subprocess.run')
+ def test_empty_answer_is_none(self, mock_run):
+ """systemctl answering nothing is not systemctl answering "no"."""
+ mock_run.return_value = subprocess.CompletedProcess([], 1, stdout='', stderr='')
+ assert unit_is_active('nginx') is None
+
+ @patch('app.utils.system.subprocess.run')
+ def test_probe_is_not_privileged(self, mock_run):
+ """is-active needs no root; adding sudo would make it fail where the
+ sudoers policy is tight, for no benefit."""
+ mock_run.return_value = subprocess.CompletedProcess([], 0, stdout='active', stderr='')
+ unit_is_active('nginx')
+ assert mock_run.call_args[0][0] == ['systemctl', 'is-active', 'nginx']