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
fix(waf): keep the include through drift detection and repair
Juan Denis67aa5291972e
diff --git a/backend/app/services/drift_service.py b/backend/app/services/drift_service.pyindex 8e5f0ffa..e8a3ea3b 100644--- a/backend/app/services/drift_service.py+++ b/backend/app/services/drift_service.py@@ -362,8 +362,30 @@ def _nginx_render_expected(app_id):rendered = NginxService.render_site_config(**kwargs)if not rendered.get('success'):raise RuntimeError(rendered.get('error') or 'vhost render failed')+ config = rendered['config']++ # Feature blocks live in the vhost but not in the template: an app with+ # an enforcing WAF policy has its include wired post-render+ # (WafService.apply). Render the expected file through the SAME injector,+ # or every WAF'd app reads as permanently drifted and one "repair" click+ # regenerates the vhost without the include — silently unprotecting the+ # site while the DB still says enforcing (plan 82 §F.1).+ config = _with_expected_waf(app.id, config)+path = os.path.join(NginxService.SITES_AVAILABLE, app.name)- return {path: rendered['config']}+ return {path: config}+++def _with_expected_waf(app_id, config):+ from app.models.waf_policy import WafPolicy+ from app.services.waf_service import WafService++ policy = WafPolicy.query.filter_by(application_id=app_id).first()+ if policy is None or policy.mode not in ('block', 'detect'):+ return config+ injected = WafService.inject_include_text(+ config, WafService.include_path_for(app_id))+ return injected if injected is not None else configdef _nginx_repair(app_id):@@ -377,6 +399,16 @@ def _nginx_repair(app_id):res = SiteDomainService.write_app_vhost(app)if res.get('warning') and not (res.get('nginx') or {}).get('success'):return {'success': False, 'error': res['warning']}++ # write_app_vhost regenerates from the template, which drops the WAF+ # include; re-wire it for apps with an enforcing policy so a repair+ # never strips protection the DB still records (plan 82 §F.1).+ from app.models.waf_policy import WafPolicy+ policy = WafPolicy.query.filter_by(application_id=app_id).first()+ if policy is not None and policy.mode in ('block', 'detect'):+ from app.services.waf_service import WafService+ WafService.apply(app_id)+reload_res = NginxService.reload()return {'success': True,diff --git a/backend/app/services/waf_service.py b/backend/app/services/waf_service.pyindex 909f7461..e1d13ad1 100644--- a/backend/app/services/waf_service.py+++ b/backend/app/services/waf_service.py@@ -344,19 +344,19 @@ class WafService:return None@classmethod- def _inject_include(cls, vhost_path: str, include_path: str) -> Dict:- """Idempotently add ``include <include_path>;`` into the first server block.+ def include_path_for(cls, application_id: int) -> str:+ """The nginx include file wired into this app's vhost."""+ return os.path.join(WAF_RULES_DIR, f'app-{application_id}.include.conf')- Guarded by ``_INCLUDE_MARKER`` so repeated applies don't duplicate the- line, and we replace any prior serverkit-waf include for this app rather- than stacking. Never touches anything outside the inserted line.- """- try:- with open(vhost_path, 'r') as fh:- content = fh.read()- except OSError as e:- return {'success': False, 'error': f'cannot read vhost: {e}'}+ @classmethod+ def inject_include_text(cls, content: str, include_path: str) -> Optional[str]:+ """``content`` with ``include <include_path>;`` idempotently wired into+ the serving server block, or None when no server block exists.+ Text-level so the live wiring (_inject_include) and drift's expected+ render (drift_service._nginx_render_expected) share one injector — two+ copies is how the expected file and the real file learn to disagree.+ """include_line = f' {_INCLUDE_MARKER}\n include {include_path};'# Drop any existing serverkit-waf include line(s) first (idempotent).@@ -373,7 +373,7 @@ class WafService:# redirect-only blocks (a 301 return and nothing served).starts = list(re.finditer(r'server\s*\{', cleaned))if not starts:- return {'success': False, 'error': 'no server block found in vhost'}+ return Noneidx = Nonefor pos, match in enumerate(starts):end = starts[pos + 1].start() if pos + 1 < len(starts) else len(cleaned)@@ -385,7 +385,21 @@ class WafService:breakif idx is None:idx = starts[0].end()- new_content = cleaned[:idx] + '\n' + include_line + cleaned[idx:]+ return cleaned[:idx] + '\n' + include_line + cleaned[idx:]++ @classmethod+ def _inject_include(cls, vhost_path: str, include_path: str) -> Dict:+ """Idempotently add ``include <include_path>;`` into the serving+ server block of the vhost file at ``vhost_path``."""+ try:+ with open(vhost_path, 'r') as fh:+ content = fh.read()+ except OSError as e:+ return {'success': False, 'error': f'cannot read vhost: {e}'}++ new_content = cls.inject_include_text(content, include_path)+ if new_content is None:+ return {'success': False, 'error': 'no server block found in vhost'}return cls._write_file(vhost_path, new_content)@@ -411,7 +425,7 @@ class WafService:policy = cls.get_or_create_policy(application_id)rules_path = os.path.join(WAF_RULES_DIR, f'app-{application_id}.conf')- include_path = os.path.join(WAF_RULES_DIR, f'app-{application_id}.include.conf')+ include_path = cls.include_path_for(application_id)rules = cls.render_rules(policy)snippet = cls.nginx_snippet(policy, rules_path)diff --git a/backend/tests/test_waf_vhost_injection.py b/backend/tests/test_waf_vhost_injection.pyindex 9798d39f..95c2b8df 100644--- a/backend/tests/test_waf_vhost_injection.py+++ b/backend/tests/test_waf_vhost_injection.py@@ -94,6 +94,78 @@ def test_reapply_is_idempotent_and_stays_in_https_block(tmp_path, plain_write):assert 'waf' not in redirect_block+def test_drift_expected_render_includes_waf_for_enforcing_policy(app, monkeypatch):+ """An enforcing WAF policy's include must appear in drift's EXPECTED+ render — byte-comparing the wired vhost against the bare template read+ every WAF'd app as permanently drifted, and one repair click then+ regenerated the vhost without the include: silently unprotected while+ the DB still said enforcing (plan 82 §F.1)."""+ from app import db+ from app.services import drift_service+ from app.services.nginx_service import NginxService+ from app.services.site_domain_service import SiteDomainService+ from app.services.waf_service import WafService+ from factories import make_application++ a = make_application(db, name='waf-drift-app')+ policy = WafService.get_or_create_policy(a.id)+ policy.mode = 'block'+ db.session.commit()++ monkeypatch.setattr(SiteDomainService, 'app_vhost_kwargs',+ classmethod(lambda cls, app_, force_type=None:+ ({'name': app_.name}, None)))+ monkeypatch.setattr(NginxService, 'render_site_config',+ classmethod(lambda cls, **kw:+ {'success': True, 'config': PLAIN_VHOST}))++ expected = drift_service._nginx_render_expected(a.id)+ (content,) = expected.values()+ assert f'include {WafService.include_path_for(a.id)};' in content++ # Without a policy (or with mode off) the template is expected as-is.+ policy.mode = 'off'+ db.session.commit()+ (content,) = drift_service._nginx_render_expected(a.id).values()+ assert 'include /etc/nginx' not in content+++def test_drift_repair_rewires_waf(app, monkeypatch):+ """Repair regenerates the vhost from the template; for an enforcing+ policy it must re-run WafService.apply so the include comes back."""+ from app import db+ from app.services import drift_service+ from app.services.nginx_service import NginxService+ from app.services.site_domain_service import SiteDomainService+ from app.services.waf_service import WafService+ from factories import make_application++ a = make_application(db, name='waf-repair-app')+ policy = WafService.get_or_create_policy(a.id)+ policy.mode = 'detect'+ db.session.commit()++ applied = []+ monkeypatch.setattr(SiteDomainService, 'write_app_vhost',+ classmethod(lambda cls, app_, force_type=None:+ {'nginx': {'success': True}, 'warning': None}))+ monkeypatch.setattr(NginxService, 'reload',+ classmethod(lambda cls: {'success': True}))+ monkeypatch.setattr(WafService, 'apply',+ classmethod(lambda cls, app_id: applied.append(app_id)+ or {'success': True}))++ result = drift_service._nginx_repair(a.id)+ assert result['success']+ assert applied == [a.id]++ # No policy -> no apply call.+ applied.clear()+ b = make_application(db, name='no-waf-app')+ assert drift_service._nginx_repair(b.id)['success']+ assert applied == []++def test_app_block_with_location_level_redirect_still_selected(tmp_path, plain_write):# A serving block that happens to contain a 301 inside a location must# not be mistaken for the redirect-only wrapper.