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
Keep panel secrets out of build and deploy scripts
Juan Denisacb4f4745c3e
diff --git a/backend/app/services/build_service.py b/backend/app/services/build_service.pyindex 2e2d4af6..69121697 100644--- a/backend/app/services/build_service.py+++ b/backend/app/services/build_service.py@@ -13,7 +13,7 @@ Supports:import osimport subprocess-from app.utils.system import run_checked+from app.utils.system import app_process_env, run_checkedimport jsonimport shutilimport hashlib@@ -546,9 +546,7 @@ class BuildService:}try:- env = os.environ.copy()- if env_vars:- env.update(env_vars)+ env = app_process_env(env_vars)process = subprocess.Popen(['bash', '-c', build_cmd],diff --git a/backend/app/services/git_deploy_service.py b/backend/app/services/git_deploy_service.pyindex 5aa6d8a0..c1afdb67 100644--- a/backend/app/services/git_deploy_service.py+++ b/backend/app/services/git_deploy_service.py@@ -8,7 +8,7 @@ import loggingfrom datetime import datetimefrom typing import Dict, Optional-from app.utils.system import run_checked+from app.utils.system import app_process_env, run_checkedfrom app.utils.git_security import git_argv, git_env, validate_ref_namefrom app.services.deploy_lock import with_deploy_lock@@ -450,7 +450,7 @@ class GitDeployService:"""Run a deployment script."""try:result = run_checked(['bash', '-c', script], cwd=cwd, timeout=300,- env={**os.environ, 'DEPLOY_DIR': cwd})+ env=app_process_env({'DEPLOY_DIR': cwd}))return {'success': result['success'],diff --git a/backend/app/services/python_service.py b/backend/app/services/python_service.pyindex e8f0c57b..393bc4ce 100644--- a/backend/app/services/python_service.py+++ b/backend/app/services/python_service.py@@ -4,7 +4,7 @@ import jsonimport secretsfrom pathlib import Path-from app.utils.system import ServiceControl, run_checked+from app.utils.system import ServiceControl, app_process_env, run_checkedclass PythonService:@@ -524,7 +524,7 @@ application = get_wsgi_application()try:# Prepare environment- env = os.environ.copy()+ env = app_process_env()env['PATH'] = f"{os.path.join(venv_path, 'bin')}:{env.get('PATH', '')}"env['VIRTUAL_ENV'] = venv_pathdiff --git a/backend/app/services/template_service.py b/backend/app/services/template_service.pyindex 96489911..dd5537d7 100644--- a/backend/app/services/template_service.py+++ b/backend/app/services/template_service.py@@ -28,7 +28,7 @@ from pathlib import Pathimport requestsfrom app import paths-from app.utils.system import run_checked+from app.utils.system import app_process_env, run_checkedfrom app.services.deploy_lock import with_deploy_lock@@ -2208,8 +2208,7 @@ class TemplateService:try:script = cls.substitute_variables(script, variables)- env = os.environ.copy()- env.update(variables)+ env = app_process_env(variables)result = run_checked(['bash', '-c', script], cwd=cwd, env=env, timeout=300)diff --git a/backend/app/utils/system.py b/backend/app/utils/system.pyindex ecfa0f09..5664150c 100644--- a/backend/app/utils/system.py+++ b/backend/app/utils/system.py@@ -271,6 +271,29 @@ def _never_ran(error: str) -> dict:'returncode': None, 'error': error}+_PANEL_SECRET_ENV = frozenset({+ 'SECRET_KEY', 'JWT_SECRET_KEY', 'DATABASE_URL', 'TEST_DATABASE_URL',+ 'PROMETHEUS_TOKEN',+})+++def app_process_env(extra: Optional[dict] = None) -> dict:+ """The environment for code the panel runs on an app's behalf — build+ commands, deploy and template scripts — without the panel's own secrets.++ Those scripts come from repositories and registries, not from the panel,+ and ``os.environ.copy()`` handed them the JWT signing key, the session+ key, the database URL and every SERVERKIT_* credential.+ """+ env = {k: v for k, v in os.environ.items()+ if k not in _PANEL_SECRET_ENV+ and not k.startswith('SERVERKIT_')+ and not k.endswith('_CLIENT_SECRET')}+ if extra:+ env.update(extra)+ return env++_CHUNK = 1024 * 1024diff --git a/backend/tests/test_app_process_env.py b/backend/tests/test_app_process_env.pynew file mode 100644index 00000000..b6a25c65--- /dev/null+++ b/backend/tests/test_app_process_env.py@@ -0,0 +1,89 @@+"""Build commands and deploy/template scripts come from repositories and+registries; they must not inherit the panel's own secrets."""+import pytest++from app.utils.system import app_process_env++SECRETS = {+ 'SECRET_KEY': 'flask-session-key',+ 'JWT_SECRET_KEY': 'jwt-signing-key',+ 'DATABASE_URL': 'postgresql://panel:pw@db/serverkit',+ 'SERVERKIT_ENCRYPTION_KEY': 'fernet-key',+ 'SERVERKIT_GITHUB_TOKEN': 'ghp_x',+ 'SOURCE_GITHUB_CLIENT_SECRET': 'oauth-secret',+}+++def panel_env(monkeypatch):+ for key, value in SECRETS.items():+ monkeypatch.setenv(key, value)+ monkeypatch.setenv('SOURCE_DATE_EPOCH', '1700000000') # a build var, not a secret+++def _assert_clean(env):+ leaked = sorted(k for k in SECRETS if k in env)+ assert leaked == [], f'panel secrets reached the script: {leaked}'+ assert 'PATH' in env+++def test_helper_drops_panel_secrets_and_keeps_the_rest(panel_env):+ env = app_process_env({'NODE_ENV': 'production'})+ _assert_clean(env)+ assert env['SOURCE_DATE_EPOCH'] == '1700000000'+ assert env['NODE_ENV'] == 'production'+++def test_extra_vars_are_the_apps_to_set(panel_env):+ # An app may define its own DATABASE_URL; that is its value, not ours.+ assert app_process_env({'DATABASE_URL': 'mysql://app'})['DATABASE_URL'] == 'mysql://app'+++def _capture_run_checked(monkeypatch, module):+ seen = {}++ def fake(cmd, **kwargs):+ seen['env'] = kwargs.get('env')+ return {'success': True, 'output': '', 'stderr': '', 'error': None, 'returncode': 0}+ monkeypatch.setattr(f'{module}.run_checked', fake)+ return seen+++def test_template_scripts(panel_env, monkeypatch, tmp_path):+ from app.services.template_service import TemplateService+ seen = _capture_run_checked(monkeypatch, 'app.services.template_service')+ TemplateService._run_script('echo hi', str(tmp_path), {'APP_PORT': '8080'})+ _assert_clean(seen['env'])+ assert seen['env']['APP_PORT'] == '8080'+++def test_git_deploy_scripts(panel_env, monkeypatch, tmp_path):+ from app.services.git_deploy_service import GitDeployService+ seen = _capture_run_checked(monkeypatch, 'app.services.git_deploy_service')+ GitDeployService._run_script('echo hi', str(tmp_path))+ _assert_clean(seen['env'])+ assert seen['env']['DEPLOY_DIR'] == str(tmp_path)+++def test_python_app_commands(panel_env, monkeypatch, tmp_path):+ from app.services.python_service import PythonService+ (tmp_path / 'venv' / 'bin').mkdir(parents=True)+ (tmp_path / 'venv' / 'bin' / 'python').write_text('')+ monkeypatch.setattr(PythonService, 'get_env_vars', staticmethod(lambda path: {}))+ seen = _capture_run_checked(monkeypatch, 'app.services.python_service')+ PythonService.run_command(str(tmp_path), 'manage.py migrate')+ _assert_clean(seen['env'])+++def test_custom_build_commands(panel_env, monkeypatch, tmp_path):+ from app.services import build_service+ seen = {}++ def popen(cmd, **kwargs):+ seen['env'] = kwargs['env']+ raise OSError('stop here')+ monkeypatch.setattr(build_service.subprocess, 'Popen', popen)+ build_service.BuildService.build_with_custom_command(+ 1, str(tmp_path), 'npm run build', env_vars={'NODE_ENV': 'production'})+ _assert_clean(seen['env'])+ assert seen['env']['NODE_ENV'] == 'production'