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.
Python astracloudflarecontrol-panelcyberpaneldnsfablehosting-control-panelhosting-panelkimi-k3server-managementserverkitubuntu-web-panelwebserver
refactor(nginx): consolidate vhost writes
Juan Denisded7d5403908
diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.pyindex 3ac9edaa..d6d6ad5d 100644--- a/backend/app/services/nginx_service.py+++ b/backend/app/services/nginx_service.py@@ -707,14 +707,11 @@ location /p/ {{return {'success': False,'error': f"micro-cache zone setup failed: {zone.get('error')}"}- # Write config file- config_path = os.path.join(cls.SITES_AVAILABLE, name)try:- 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}+ result = cls.write_vhost(name, config)+ if result.get('success'):+ result['message'] = f'Site {name} created'+ return resultexcept Exception as e:return {'success': False, 'error': str(e)}@@ -888,8 +885,9 @@ location /p/ {{return {'success': False, 'error': f'Site {name} not found'}try:- with open(config_path, 'r') as f:- content = f.read()+ content = cls.read_vhost(name)+ if content is None:+ return {'success': False, 'error': f'Could not read site {name}'}# Extract domains for redirectmatch = re.search(r'server_name\s+([^;]+);', content)@@ -910,11 +908,7 @@ location /p/ {{# Prepend redirect blockfinal_content = redirect_block + '\n' + new_content- # Write updated config- written = write_privileged_file(config_path, final_content)- if not written['success']:- return {'success': False, 'error': written['error']}- return cls.reload()+ return cls.write_vhost(name, final_content)except Exception as e:return {'success': False, 'error': str(e)}diff --git a/backend/tests/test_micro_cache.py b/backend/tests/test_micro_cache.pyindex 4d8091fd..eed9808e 100644--- a/backend/tests/test_micro_cache.py+++ b/backend/tests/test_micro_cache.py@@ -167,23 +167,32 @@ def test_ensure_cache_zone_writes_once_and_is_idempotent(tmp_path, fake_subproceassert 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, fake_subprocess, monkeypatch):- monkeypatch.setattr(NginxService, 'SITES_AVAILABLE', str(tmp_path))+def test_create_site_ensures_zone_when_enabled(monkeypatch):ensured = []+ writes = []monkeypatch.setattr(NginxService, 'ensure_cache_zone',classmethod(lambda cls: ensured.append(True) or {'success': True}))- fake_subprocess.script(['tee'])+ monkeypatch.setattr(+ NginxService,+ 'write_vhost',+ classmethod(lambda cls, name, content: writes.append((name, content)) or {+ 'success': True,+ 'path': f'/etc/nginx/sites-available/{name}',+ }),+ )res = NginxService.create_site('shop', 'docker', ['shop.lvh.me'],root_path=None, port=8300, micro_cache=True)assert res['success'] is Trueassert ensured == [True]- assert 'proxy_cache serverkit_microcache;' in fake_subprocess.kwargs_for(['tee'])['input']+ assert writes[0][0] == 'shop'+ assert 'proxy_cache serverkit_microcache;' in writes[0][1]# Disabled writes never touch the zone.NginxService.create_site('shop', 'docker', ['shop.lvh.me'],root_path=None, port=8300)assert ensured == [True]+ assert len(writes) == 2# ── kwargs plumbing / drift consistency ──────────────────────────────────────diff --git a/backend/tests/test_nginx_write_vhost.py b/backend/tests/test_nginx_write_vhost.pyindex d4624fff..82471d77 100644--- a/backend/tests/test_nginx_write_vhost.py+++ b/backend/tests/test_nginx_write_vhost.py@@ -142,6 +142,40 @@ class TestRollback:assert not any(c[:2] == ['systemctl', 'reload'] for c in nginx.commands())+class TestConsolidatedCallers:+ """The high-traffic renderers must inherit the lifecycle door's rollback."""++ def test_create_site_removes_a_new_vhost_when_config_test_fails(self, nginx):+ nginx.script(['nginx', '-t'], returncode=1, stderr='rendered config is invalid')++ res = NginxService.create_site(+ 'shop', 'docker', ['shop.example.com'], port=8080)++ assert res['success'] is False+ assert 'rendered config is invalid' in res['error']+ available, enabled = _paths()+ assert not os.path.exists(available), 'create_site bypassed write_vhost rollback'+ assert not os.path.exists(enabled), 'create_site left a broken vhost enabled'++ def test_add_ssl_restores_the_previous_vhost_when_config_test_fails(self, nginx):+ original = '''server {+ listen 80;+ server_name shop.example.com;+}+'''+ assert NginxService.write_vhost('shop', original)['success'] is True+ nginx.script(['nginx', '-t'], returncode=1, stderr='bad certificate config')++ res = NginxService.add_ssl_to_site(+ 'shop', '/certs/fullchain.pem', '/certs/privkey.pem')++ assert res['success'] is False+ assert 'bad certificate config' in res['error']+ available, enabled = _paths()+ assert open(available).read() == original+ assert os.path.exists(enabled), 'SSL rollback disabled an existing site'++class TestFailedWrite:def test_a_failed_write_is_reported_and_nothing_is_enabled(self, nginx):nginx.script(['tee'], returncode=1, stderr='Permission denied')