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.

fix(security): harden nginx write path and certbot issuance trust bugs

Juan Denis76c57c19d68e
diff --git a/backend/app/api/nginx_advanced.py b/backend/app/api/nginx_advanced.py
index 48d92a8d..eaeeeff9 100644
--- a/backend/app/api/nginx_advanced.py
+++ b/backend/app/api/nginx_advanced.py
@@ -27,6 +27,8 @@ def create_proxy():
return jsonify({'error': 'domain required'}), 400
result = NginxAdvancedService.create_reverse_proxy(data)
+ if 'error' in result:
+ return jsonify(result), 400
return jsonify(result), 201
diff --git a/backend/app/services/advanced_ssl_service.py b/backend/app/services/advanced_ssl_service.py
index 7d599705..ff802534 100644
--- a/backend/app/services/advanced_ssl_service.py
+++ b/backend/app/services/advanced_ssl_service.py
@@ -1,8 +1,10 @@
import json
import logging
import subprocess
+import tempfile
from datetime import datetime
-from app.utils.system import run_unprivileged
+from app.utils.system import run_privileged, run_unprivileged
+from app.services.nginx_service import _validate_domain
from app.services.ssl_service import resolve_certbot_bin
@@ -52,6 +54,13 @@ class AdvancedSSLService:
import os
from app.utils.system import PackageManager
+ if dns_provider not in ('cloudflare', 'route53'):
+ return {'success': False, 'error': f'Unsupported DNS provider: {dns_provider}'}
+ # The domain becomes certbot argv below — reject anything that is not a
+ # plain domain so a crafted value cannot be parsed as certbot flags.
+ if not _validate_domain(domain):
+ return {'success': False, 'error': f'Invalid domain: {domain}'}
+
wildcard = f'*.{domain}'
cmd = [_certbot_bin(), 'certonly', '--non-interactive', '--agree-tos',
'--dns-' + dns_provider, '-d', domain, '-d', wildcard]
@@ -64,30 +73,49 @@ class AdvancedSSLService:
except Exception:
pass # certbot reports a clear error below if the plugin is truly missing
- run_kwargs = {}
+ # certbot writes /etc/letsencrypt as root, so it runs through
+ # run_privileged — and the credentials must survive sudo. cloudflare
+ # gets an unpredictable root-readable file that is always deleted
+ # afterwards; route53 goes through `sudo env A=B …` because sudo's
+ # env_reset would silently strip a plain env= kwarg.
+ cred_file = None
if dns_provider == 'cloudflare':
- cred_file = f'/tmp/certbot-{dns_provider}.ini'
- with open(cred_file, 'w') as f:
+ fd, cred_file = tempfile.mkstemp(prefix='certbot-cloudflare-', suffix='.ini')
+ with os.fdopen(fd, 'w') as f:
f.write(f"dns_cloudflare_api_token = {credentials.get('api_token', '')}\n")
- os.chmod(cred_file, 0o600)
+ if os.name != 'nt':
+ os.chmod(cred_file, 0o600)
cmd.extend(['--dns-cloudflare-credentials', cred_file])
elif dns_provider == 'route53':
- run_kwargs['env'] = {
- **os.environ,
- 'AWS_ACCESS_KEY_ID': credentials.get('api_key', ''),
- 'AWS_SECRET_ACCESS_KEY': credentials.get('api_secret', ''),
- }
+ cmd = ['env',
+ f"AWS_ACCESS_KEY_ID={credentials.get('api_key', '')}",
+ f"AWS_SECRET_ACCESS_KEY={credentials.get('api_secret', '')}",
+ ] + cmd
try:
- result = run_unprivileged(cmd, **run_kwargs)
+ result = run_privileged(cmd, timeout=600)
+ if result.returncode != 0:
+ # A failed certbot run is a failure, full stop — never report
+ # the not-issued cert paths as if issuance had succeeded.
+ return {'success': False,
+ 'error': (result.stderr or result.stdout
+ or 'certbot failed').strip()}
return {
'success': True, 'domain': domain, 'type': 'wildcard',
'certificate_path': f'/etc/letsencrypt/live/{domain}/fullchain.pem',
'private_key_path': f'/etc/letsencrypt/live/{domain}/privkey.pem',
- 'output': result.get('stdout', ''),
+ 'output': result.stdout or '',
}
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Certificate request timed out'}
except Exception as e:
return {'success': False, 'error': str(e)}
+ finally:
+ if cred_file:
+ try:
+ os.remove(cred_file)
+ except OSError:
+ pass
@staticmethod
def issue_san_cert(domains):
@@ -95,14 +123,27 @@ class AdvancedSSLService:
if not domains or len(domains) < 1:
raise ValueError('At least one domain required')
+ invalid = [d for d in domains if not isinstance(d, str)
+ or not _validate_domain(d)]
+ if invalid:
+ return {'success': False,
+ 'error': f'Invalid domain(s): {", ".join(map(str, invalid))}'}
+
cmd = [_certbot_bin(), 'certonly', '--non-interactive', '--agree-tos',
'--webroot', '-w', '/var/www/html']
for d in domains:
cmd.extend(['-d', d])
try:
- result = run_unprivileged(cmd)
- return {'success': True, 'domains': domains, 'type': 'san', 'output': result.get('stdout', '')}
+ result = run_privileged(cmd, timeout=600)
+ if result.returncode != 0:
+ return {'success': False,
+ 'error': (result.stderr or result.stdout
+ or 'certbot failed').strip()}
+ return {'success': True, 'domains': domains, 'type': 'san',
+ 'output': result.stdout or ''}
+ except subprocess.TimeoutExpired:
+ return {'success': False, 'error': 'Certificate request timed out'}
except Exception as e:
return {'success': False, 'error': str(e)}
@@ -110,6 +151,11 @@ class AdvancedSSLService:
def upload_custom_cert(domain, cert_pem, key_pem, chain_pem=None):
"""Upload custom certificate files."""
import os
+ # The domain is joined into the cert directory path below — refuse
+ # anything that is not a plain domain so it cannot traverse out of
+ # /etc/ssl/serverkit.
+ if not _validate_domain(domain):
+ raise ValueError(f'Invalid domain: {domain}')
cert_dir = f'/etc/ssl/serverkit/{domain}'
os.makedirs(cert_dir, exist_ok=True)
diff --git a/backend/app/services/nginx_advanced_service.py b/backend/app/services/nginx_advanced_service.py
index 570f7bdc..6101343a 100644
--- a/backend/app/services/nginx_advanced_service.py
+++ b/backend/app/services/nginx_advanced_service.py
@@ -2,11 +2,96 @@ import os
import json
import logging
import re
-from app.services.nginx_service import NginxService
+from app.services.nginx_service import NginxService, _validate_domain
from app.utils.system import run_unprivileged
logger = logging.getLogger(__name__)
+# Characters that would break out of the nginx directive being generated and
+# inject arbitrary configuration. Everything interpolated into the generated
+# config is checked against these (or a stricter pattern) before the build.
+_CONFIG_BREAKOUT = ('{', '}', ';', '\n', '\r')
+
+_UPSTREAM_ADDR_RE = re.compile(r'^(?:[a-zA-Z0-9._\-]+:\d{1,5}|unix:[a-zA-Z0-9/_.\-]+)$')
+_HEADER_NAME_RE = re.compile(r'^[A-Za-z0-9\-]+$')
+_SIZE_RE = re.compile(r'^\d+[kmgKMG]$')
+_TTL_RE = re.compile(r'^\d+[smhdSMHD]$')
+
+
+def _has_breakout(value):
+ return any(c in value for c in _CONFIG_BREAKOUT)
+
+
+def _validate_proxy_input(data):
+ """Validate reverse-proxy input before it becomes nginx config.
+
+ Every value the builder interpolates is a potential config-injection
+ vector — a ``;`` or ``}`` in a header value, upstream address or location
+ path closes the directive being generated and starts an attacker-chosen
+ one. Returns an error string, or ``None`` when the input is clean.
+ """
+ domain = data.get('domain')
+ if not isinstance(domain, str) or not _validate_domain(domain):
+ return f'invalid domain: {domain}'
+
+ if data.get('lb_method', 'round_robin') not in (
+ 'round_robin', 'least_conn', 'ip_hash'):
+ return f"invalid lb_method: {data.get('lb_method')}"
+
+ for u in data.get('upstreams', []):
+ address = u.get('address', '')
+ if not isinstance(address, str) or not _UPSTREAM_ADDR_RE.match(address):
+ return f'invalid upstream address: {address}'
+ weight = u.get('weight')
+ if weight is not None and (not isinstance(weight, int)
+ or isinstance(weight, bool)
+ or not 1 <= weight <= 100):
+ return f'invalid upstream weight: {weight}'
+
+ rate_limit = data.get('rate_limit', {})
+ if rate_limit.get('enabled'):
+ rps = rate_limit.get('requests_per_second', 10)
+ burst = rate_limit.get('burst', 20)
+ if not isinstance(rps, (int, float)) or isinstance(rps, bool) or rps <= 0:
+ return f'invalid requests_per_second: {rps}'
+ if not isinstance(burst, int) or isinstance(burst, bool) or burst <= 0:
+ return f'invalid burst: {burst}'
+
+ cache = data.get('cache', {})
+ if cache.get('enabled'):
+ if not _SIZE_RE.match(str(cache.get('size', '100m'))):
+ return f"invalid cache size: {cache.get('size')}"
+ if not _TTL_RE.match(str(cache.get('ttl', '60m'))):
+ return f"invalid cache ttl: {cache.get('ttl')}"
+ for bypass in cache.get('bypass_rules', []):
+ if not isinstance(bypass, str) or _has_breakout(bypass):
+ return f'invalid cache bypass rule: {bypass}'
+
+ headers = data.get('headers', {})
+ for name, value in headers.get('add', {}).items():
+ if not _HEADER_NAME_RE.match(str(name)):
+ return f'invalid header name: {name}'
+ # Header values are emitted inside double quotes — a quote or newline
+ # breaks out of them.
+ if any(c in str(value) for c in ('"', '\n', '\r')):
+ return f'invalid value for header {name}'
+ for name in headers.get('remove', []):
+ if not _HEADER_NAME_RE.match(str(name)):
+ return f'invalid header name: {name}'
+
+ for loc in data.get('locations', []):
+ path = loc.get('path', '')
+ if not isinstance(path, str) or not path.strip() or _has_breakout(path):
+ return f'invalid location path: {path}'
+ proxy_pass = loc.get('proxy_pass')
+ if proxy_pass is not None:
+ if (not isinstance(proxy_pass, str)
+ or not proxy_pass.startswith(('http://', 'https://'))
+ or any(c in proxy_pass for c in (' ', '\t', '{', '}', ';', '\n', '\r'))):
+ return f'invalid proxy_pass: {proxy_pass}'
+
+ return None
+
class NginxAdvancedService:
"""Advanced Nginx configuration: reverse proxy, load balancing, caching, rate limiting."""
@@ -34,6 +119,10 @@ class NginxAdvancedService:
@staticmethod
def create_reverse_proxy(data):
"""Create a reverse proxy configuration."""
+ invalid = _validate_proxy_input(data)
+ if invalid:
+ return {'error': invalid}
+
domain = data['domain']
upstreams = data.get('upstreams', [])
lb_method = data.get('lb_method', 'round_robin')
diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py
index 8992b298..48782ce3 100644
--- a/backend/app/services/nginx_service.py
+++ b/backend/app/services/nginx_service.py
@@ -896,6 +896,13 @@ location /p/ {{
Returns ``{'success', 'path'}`` or ``{'success': False, 'error'}``.
"""
+ # `name` becomes a filesystem path below — refuse anything that is not
+ # a plain filename so a caller-controlled name cannot traverse out of
+ # sites-available (preview_diff applies the same rule for reads).
+ if (not name or os.path.basename(name) != name
+ or name in ('.', '..') or '\x00' in name):
+ return {'success': False, 'error': f'Invalid site name: {name!r}'}
+
available_path = os.path.join(cls.SITES_AVAILABLE, name)
enabled_path = os.path.join(cls.SITES_ENABLED, name)
previous = cls.read_vhost(name)
@@ -921,6 +928,10 @@ location /p/ {{
reloaded = cls.reload()
if not reloaded['success']:
+ # A failed reload means nginx is still serving the previous config
+ # (reload fails safe) — restore the file so on-disk state matches
+ # what nginx actually runs, exactly like the config-test rollback.
+ cls._restore_vhost(name, previous, was_enabled)
return reloaded
return {'success': True, 'path': available_path}
diff --git a/backend/tests/test_advanced_ssl_hardening.py b/backend/tests/test_advanced_ssl_hardening.py
new file mode 100644
index 00000000..65a2f75d
--- /dev/null
+++ b/backend/tests/test_advanced_ssl_hardening.py
@@ -0,0 +1,161 @@
+"""Trust bugs in the wildcard/SAN certbot path.
+
+The advanced SSL service ran certbot unprivileged (it cannot write
+/etc/letsencrypt that way) and returned ``success: True`` without looking at
+the result, so a failed issuance reported the would-be cert paths as if they
+existed. Cloudflare credentials went to a predictable ``/tmp`` path and were
+never deleted. Both issuance entry points are asserted here against the
+``run_privileged`` seam, plus the domain validation that keeps crafted
+domains from being parsed as certbot flags.
+"""
+
+import os
+import stat
+
+import pytest
+
+import app.services.advanced_ssl_service as mod
+from app.services.advanced_ssl_service import AdvancedSSLService
+from subprocess_stub import FakeProc
+
+
+def _must_not_run_unprivileged(cmd, **kw):
+ raise AssertionError(
+ f'certbot must run through run_privileged, got run_unprivileged({cmd!r})')
+
+
+def certbot(monkeypatch):
+ """run_privileged seam captured; PackageManager and the unprivileged door
+ are both taken out — certbot has no business running unprivileged."""
+ from app.utils.system import PackageManager
+
+ monkeypatch.setattr(PackageManager, 'is_available', staticmethod(lambda: False))
+ monkeypatch.setattr(mod, 'run_unprivileged', _must_not_run_unprivileged)
+
+ captured = {}
+
+ def fake_run(cmd, **kw):
+ captured['cmd'] = list(cmd)
+ captured['kw'] = kw
+ return captured['proc']
+
+ monkeypatch.setattr(mod, 'run_privileged', fake_run)
+ return captured
+
+
+class TestWildcardIssuance:
+ def test_a_failed_certbot_is_a_failure_never_cert_paths(self, certbot):
+ certbot['proc'] = FakeProc(returncode=1, stderr='DNS problem: NXDOMAIN')
+
+ res = AdvancedSSLService.issue_wildcard_cert(
+ 'example.com', 'cloudflare', {'api_token': 'tok'})
+
+ assert res['success'] is False
+ assert 'NXDOMAIN' in res['error']
+ assert 'certificate_path' not in res, 'a failed issuance reported cert paths'
+
+ def test_a_successful_certbot_reports_the_cert_paths(self, certbot):
+ certbot['proc'] = FakeProc(stdout='Congratulations!')
+
+ res = AdvancedSSLService.issue_wildcard_cert(
+ 'example.com', 'cloudflare', {'api_token': 'tok'})
+
+ assert res['success'] is True
+ assert res['certificate_path'] == '/etc/letsencrypt/live/example.com/fullchain.pem'
+ assert res['private_key_path'] == '/etc/letsencrypt/live/example.com/privkey.pem'
+
+ def test_an_unsupported_provider_is_refused(self, certbot):
+ res = AdvancedSSLService.issue_wildcard_cert(
+ 'example.com', 'digitalocean', {'api_token': 'tok'})
+ assert res['success'] is False
+ assert 'cmd' not in certbot, 'certbot ran for an unsupported provider'
+
+
+class TestCloudflareCredentialsFile:
+ """The API token sits on disk while certbot runs: the file must be
+ unpredictable, owner-only, and gone afterwards — whatever the outcome."""
+
+ def _run_with_creds_probe(self, monkeypatch, proc):
+ """Replace the fixture responder with one that inspects the
+ credentials file mid-run (the fixture only sees argv afterwards)."""
+ seen = {}
+
+ def fake_run(cmd, **kw):
+ path = cmd[cmd.index('--dns-cloudflare-credentials') + 1]
+ seen['path'] = path
+ seen['existed_during_run'] = os.path.isfile(path)
+ if os.name != 'nt':
+ seen['mode'] = stat.S_IMODE(os.stat(path).st_mode)
+ return proc
+
+ monkeypatch.setattr(mod, 'run_privileged', fake_run)
+ return seen
+
+ def test_credentials_file_lifecycle(self, certbot, monkeypatch):
+ seen = self._run_with_creds_probe(monkeypatch, FakeProc(stdout='Congratulations!'))
+
+ res = AdvancedSSLService.issue_wildcard_cert(
+ 'example.com', 'cloudflare', {'api_token': 'tok'})
+
+ assert res['success'] is True
+ assert seen['path'] != '/tmp/certbot-cloudflare.ini', 'predictable path'
+ assert seen['existed_during_run'] is True
+ if os.name != 'nt':
+ assert seen['mode'] == 0o600
+ assert not os.path.exists(seen['path']), 'credentials file left behind'
+
+ def test_credentials_file_is_deleted_even_when_certbot_fails(self, certbot, monkeypatch):
+ seen = self._run_with_creds_probe(monkeypatch, FakeProc(returncode=1, stderr='boom'))
+
+ res = AdvancedSSLService.issue_wildcard_cert(
+ 'example.com', 'cloudflare', {'api_token': 'tok'})
+
+ assert res['success'] is False
+ assert not os.path.exists(seen['path']), 'failed run left credentials behind'
+
+
+class TestSanIssuance:
+ def test_a_failed_certbot_is_a_failure(self, certbot):
+ certbot['proc'] = FakeProc(returncode=1, stderr='webroot unreachable')
+
+ res = AdvancedSSLService.issue_san_cert(['a.example.com', 'b.example.com'])
+
+ assert res['success'] is False
+ assert 'webroot unreachable' in res['error']
+
+ def test_a_successful_certbot_reports_the_domains(self, certbot):
+ certbot['proc'] = FakeProc(stdout='Congratulations!')
+
+ res = AdvancedSSLService.issue_san_cert(['a.example.com', 'b.example.com'])
+
+ assert res['success'] is True
+ assert res['domains'] == ['a.example.com', 'b.example.com']
+ for d in ('a.example.com', 'b.example.com'):
+ assert d in certbot['cmd']
+
+
+class TestDomainValidation:
+ """A crafted domain must not survive into certbot argv, where a leading
+ dash would be parsed as a flag, nor into the custom-cert file path."""
+
+ def test_wildcard_rejects_a_flag_like_domain(self, certbot):
+ res = AdvancedSSLService.issue_wildcard_cert(
+ '--cert-name=evil', 'cloudflare', {'api_token': 'tok'})
+ assert res['success'] is False
+ assert 'cmd' not in certbot, 'certbot ran for an invalid domain'
+
+ def test_wildcard_rejects_shell_metacharacters(self, certbot):
+ res = AdvancedSSLService.issue_wildcard_cert(
+ 'example.com; rm -rf /', 'cloudflare', {'api_token': 'tok'})
+ assert res['success'] is False
+ assert 'cmd' not in certbot
+
+ def test_san_rejects_one_bad_domain_out_of_many(self, certbot):
+ res = AdvancedSSLService.issue_san_cert(['good.example.com', '--expand'])
+ assert res['success'] is False
+ assert 'cmd' not in certbot
+
+ def test_upload_custom_cert_rejects_traversal(self):
+ with pytest.raises(ValueError):
+ AdvancedSSLService.upload_custom_cert('../../etc/cron.d', 'cert', 'key')
diff --git a/backend/tests/test_nginx_advanced_hardening.py b/backend/tests/test_nginx_advanced_hardening.py
new file mode 100644
index 00000000..8da88207
--- /dev/null
+++ b/backend/tests/test_nginx_advanced_hardening.py
@@ -0,0 +1,110 @@
+"""Config-injection validation in the advanced nginx builder.
+
+``create_reverse_proxy`` interpolates domains, upstreams, headers and
+locations straight into a generated vhost. A ``;`` or ``}`` in any of them
+closes the directive being written and starts an attacker-chosen one — and
+the builder writes through ``write_vhost``, which config-tests and reloads,
+so an injected-but-valid fragment would go live. Every interpolated value is
+now validated first; these tests pin both the rejections and the clean path.
+"""
+
+import pytest
+
+from app.services.nginx_advanced_service import NginxAdvancedService
+from app.services.nginx_service import NginxService
+
+
+def written(monkeypatch):
+ """write_vhost seam: captures what the builder tried to write."""
+ captured = {}
+
+ def fake_write(name, content, *, enable=True):
+ captured['name'] = name
+ captured['content'] = content
+ return {'success': True, 'path': f'/etc/nginx/sites-available/{name}'}
+
+ monkeypatch.setattr(NginxService, 'write_vhost', staticmethod(fake_write))
+ return captured
+
+
+def _clean_payload():
+ return {
+ 'domain': 'shop.example.com',
+ 'upstreams': [{'address': '127.0.0.1:8001', 'weight': 2}],
+ 'lb_method': 'least_conn',
+ 'rate_limit': {'enabled': True, 'requests_per_second': 5, 'burst': 10},
+ 'cache': {'enabled': True, 'size': '100m', 'ttl': '60m',
+ 'bypass_rules': ['$http_authorization']},
+ 'headers': {'add': {'X-Frame-Options': 'DENY'},
+ 'remove': ['X-Powered-By']},
+ 'locations': [{'path': '/api', 'proxy_pass': 'http://127.0.0.1:9000'}],
+ }
+
+
+class TestCleanPayload:
+ def test_a_clean_payload_builds_and_writes(self, written):
+ res = NginxAdvancedService.create_reverse_proxy(_clean_payload())
+
+ assert 'error' not in res
+ assert written['name'] == 'shop.example.com'
+ config = written['content']
+ assert 'upstream shop_example_com {' in config
+ assert 'least_conn;' in config
+ assert 'server 127.0.0.1:8001 weight=2;' in config
+ assert 'server_name shop.example.com;' in config
+ assert 'add_header X-Frame-Options "DENY";' in config
+ assert 'proxy_hide_header X-Powered-By;' in config
+ assert 'location /api {' in config
+ assert 'proxy_pass http://127.0.0.1:9000;' in config
+
+ def test_a_unix_socket_upstream_is_accepted(self, written):
+ payload = _clean_payload()
+ payload['upstreams'] = [{'address': 'unix:/run/app.sock'}]
+ res = NginxAdvancedService.create_reverse_proxy(payload)
+ assert 'error' not in res
+ assert 'server unix:/run/app.sock;' in written['content']
+
+ def test_a_regex_location_is_accepted(self, written):
+ payload = _clean_payload()
+ payload['locations'] = [{'path': '~ \\.php$', 'proxy_pass': 'http://127.0.0.1:9000'}]
+ res = NginxAdvancedService.create_reverse_proxy(payload)
+ assert 'error' not in res
+
+
+class TestInjectionIsRefused:
+ """Each payload has exactly one poisoned value; the builder must refuse
+ it and write nothing."""
+
+ @pytest.mark.parametrize('mutate,fragment', [
+ (lambda p: p.update(domain='example.com; } server {'), 'domain'),
+ (lambda p: p.update(domain='--bogus'), 'domain'),
+ (lambda p: p.update(lb_method='least_conn; }'), 'lb_method'),
+ (lambda p: p['upstreams'][0].update(address='127.0.0.1:8001; } server {'), 'upstream'),
+ (lambda p: p['upstreams'][0].update(address='not-a-socket'), 'upstream'),
+ (lambda p: p['upstreams'][0].update(weight='2; drop'), 'weight'),
+ (lambda p: p['upstreams'][0].update(weight=0), 'weight'),
+ (lambda p: p['rate_limit'].update(requests_per_second='5; x'), 'requests_per_second'),
+ (lambda p: p['rate_limit'].update(burst=-1), 'burst'),
+ (lambda p: p['cache'].update(size='100m; }'), 'size'),
+ (lambda p: p['cache'].update(ttl='60m 0'), 'ttl'),
+ (lambda p: p['cache'].update(bypass_rules=['$http_x; }']), 'bypass'),
+ (lambda p: p['headers']['add'].update({'X-Test"; add_header X-Evil "1': 'v'}), 'header name'),
+ (lambda p: p['headers']['add'].update(
+ {'X-Frame-Options': 'DENY"; add_header X-Evil "1'}), 'header value'),
+ (lambda p: p['headers']['add'].update({'X-Frame-Options': 'line1\nline2'}), 'header newline'),
+ (lambda p: p['headers'].update(remove=['X-Powered-By;']), 'remove header'),
+ (lambda p: p['locations'][0].update(path='/api; return 200;'), 'location path'),
+ (lambda p: p['locations'][0].update(path='/api { deny all; }'), 'location brace'),
+ (lambda p: p['locations'][0].update(proxy_pass='http://127.0.0.1:9000; return 200'), 'proxy_pass'),
+ (lambda p: p['locations'][0].update(proxy_pass='file:///etc/passwd'), 'proxy_pass scheme'),
+ ])
+ def test_a_poisoned_value_is_refused_and_nothing_is_written(
+ self, written, mutate, fragment):
+ payload = _clean_payload()
+ mutate(payload)
+
+ res = NginxAdvancedService.create_reverse_proxy(payload)
+
+ assert 'error' in res, f'{fragment} injection was accepted'
+ assert written == {}, f'{fragment} injection still reached write_vhost'
diff --git a/backend/tests/test_nginx_write_vhost.py b/backend/tests/test_nginx_write_vhost.py
index 82471d77..8e5c837b 100644
--- a/backend/tests/test_nginx_write_vhost.py
+++ b/backend/tests/test_nginx_write_vhost.py
@@ -142,6 +142,53 @@ class TestRollback:
assert not any(c[:2] == ['systemctl', 'reload'] for c in nginx.commands())
+class TestReloadFailureRollback:
+ """A config that passes `nginx -t` can still fail the reload itself
+ (systemd unit error, raced restart). The write must not be left behind:
+ nginx keeps serving the previous config after a failed reload, so the
+ on-disk file is put back to match it."""
+
+ def test_a_failed_reload_restores_the_previous_vhost(self, nginx):
+ good = 'server { listen 80; server_name a.test; }'
+ assert NginxService.write_vhost('shop', good)['success'] is True
+
+ nginx.script(['systemctl'], returncode=1, stderr='reload exploded')
+ res = NginxService.write_vhost('shop', 'server { listen 81; }')
+
+ assert res['success'] is False
+ available, enabled = _paths()
+ assert open(available).read() == good
+ assert os.path.exists(enabled), 'reload rollback disabled an existing site'
+
+ def test_a_failed_reload_removes_a_new_vhost(self, nginx):
+ nginx.script(['systemctl'], returncode=1, stderr='reload exploded')
+
+ res = NginxService.write_vhost('shop', 'server {}')
+
+ assert res['success'] is False
+ available, enabled = _paths()
+ assert not os.path.exists(available), 'unreloadable vhost left on disk'
+ assert not os.path.exists(enabled), 'unreloadable vhost left enabled'
+
+
+class TestSiteNameValidation:
+ """`name` is joined straight onto SITES_AVAILABLE — a caller-controlled
+ name must not become a path."""
+
+ def test_a_traversing_name_is_refused(self, nginx):
+ res = NginxService.write_vhost('../evil', 'server {}')
+ assert res['success'] is False
+ assert nginx.commands() == [], 'a refused name still ran commands'
+
+ def test_an_absolute_name_is_refused(self, nginx):
+ res = NginxService.write_vhost('/tmp/evil', 'server {}')
+ assert res['success'] is False
+ assert nginx.commands() == []
+
+ def test_dotdot_itself_is_refused(self, nginx):
+ assert NginxService.write_vhost('..', 'server {}')['success'] is False
+
+
class TestConsolidatedCallers:
"""The high-traffic renderers must inherit the lifecycle door's rollback."""
diff --git a/backend/tests/test_sites_https.py b/backend/tests/test_sites_https.py
index a17f4458..a64a9055 100644
--- a/backend/tests/test_sites_https.py
+++ b/backend/tests/test_sites_https.py
@@ -82,12 +82,19 @@ def test_issue_wildcard_cert_route53(monkeypatch):
monkeypatch.setattr(PackageManager, 'is_available', staticmethod(lambda: False))
captured = {}
+ class FakeProc:
+ returncode = 0
+ stdout = 'Congratulations'
+ stderr = ''
+
def fake_run(cmd, **kw):
captured['cmd'] = list(cmd)
captured['kw'] = kw
- return {'stdout': 'Congratulations'}
+ return FakeProc()
- monkeypatch.setattr(mod, 'run_unprivileged', fake_run)
+ # certbot writes /etc/letsencrypt as root — the privileged door is the
+ # contract, and its returncode decides success.
+ monkeypatch.setattr(mod, 'run_privileged', fake_run)
res = AdvancedSSLService.issue_wildcard_cert('example.com', 'route53',
{'api_key': 'AK', 'api_secret': 'SK'},
@@ -98,8 +105,12 @@ def test_issue_wildcard_cert_route53(monkeypatch):
assert '--dns-route53' in cmd
assert 'example.com' in cmd and '*.example.com' in cmd
assert '--email' in cmd and '[email protected]' in cmd
- assert captured['kw']['env']['AWS_ACCESS_KEY_ID'] == 'AK'
- assert captured['kw']['env']['AWS_SECRET_ACCESS_KEY'] == 'SK'
+ # sudo's env_reset would strip a plain env= kwarg, so the AWS credentials
+ # travel as `env A=B` argv entries in front of certbot instead.
+ assert cmd[0] == 'env'
+ assert 'AWS_ACCESS_KEY_ID=AK' in cmd
+ assert 'AWS_SECRET_ACCESS_KEY=SK' in cmd
+ assert 'env' not in captured['kw']
# ── setup orchestration ─────────────────────────────────────────────────────