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.

Keep host paths and site names out of user hands

Juan Denis12f6dff4303f
diff --git a/backend/app/api/apps.py b/backend/app/api/apps.py
index c318baf7..40a6338c 100644
--- a/backend/app/api/apps.py
+++ b/backend/app/api/apps.py
@@ -910,6 +910,11 @@ def create_app_from_repository():
return unexpected_response(exc)
+# Fields that point the row at host paths and units root-run code acts on
+# (docker compose up, nginx site files, systemctl) — admin-only, as /manual.
+_HOST_BINDING_FIELDS = ('root_path', 'compose_file', 'systemd_unit', 'managed_by')
+
+
@apps_bp.route('', methods=['POST'])
@jwt_required()
def create_app():
@@ -919,7 +924,12 @@ def create_app():
if not data:
return jsonify({'error': 'No data provided'}), 400
- name = data.get('name')
+ host_fields = [f for f in _HOST_BINDING_FIELDS if data.get(f)]
+ if host_fields and not User.query.get(current_user_id).is_admin:
+ return jsonify({'error': f"Only an admin can set {', '.join(host_fields)}"}), 403
+
+ # The name becomes the nginx vhost name and its file path.
+ name = _service_slug(data.get('name'))
app_type = data.get('app_type')
if not all([name, app_type]):
@@ -929,6 +939,10 @@ def create_app():
if app_type not in valid_types:
return jsonify({'error': f'Invalid app_type. Must be one of: {", ".join(valid_types)}'}), 400
+ clash = app_name_clash_error(Application.query.filter_by(name=name).first(), name)
+ if clash:
+ return jsonify({'error': clash}), 400
+
# Stamp the workspace (#33): the requested one (membership-checked) or the default.
from app.services.workspace_service import WorkspaceService
user = User.query.get(current_user_id)
@@ -1307,10 +1321,20 @@ def update_app(app_id):
if not _can_edit_app(user, app):
raise permission_denied()
- data = request.get_json()
+ data = request.get_json() or {}
# Validate before anything is assigned, so a bad setting leaves the app
# untouched rather than half-updated in the session.
+ host_fields = [f for f in _HOST_BINDING_FIELDS if f in data]
+ if host_fields and not user.is_admin:
+ return jsonify({'error': f"Only an admin can change {', '.join(host_fields)}"}), 403
+ if 'name' in data and data['name'] != app.name:
+ if not data['name'] or _service_slug(data['name']) != data['name']:
+ return jsonify({'error': 'Service name must be lowercase letters, digits and hyphens'}), 400
+ clash = app_name_clash_error(
+ Application.query.filter_by(name=data['name']).first(), data['name'])
+ if clash:
+ return jsonify({'error': clash}), 400
if 'deploy_settings' in data:
from app.exceptions import ValidationError
from app.services import deploy_settings
diff --git a/backend/app/services/nginx_service.py b/backend/app/services/nginx_service.py
index 87b49cf5..c4298ec2 100644
--- a/backend/app/services/nginx_service.py
+++ b/backend/app/services/nginx_service.py
@@ -1128,6 +1128,19 @@ location /p/ {{
return None
return result.stdout if result.returncode == 0 else None
+ @staticmethod
+ def _invalid_site_name(name) -> Optional[Dict]:
+ """The error for a site name that is not a plain filename, else None.
+
+ Every site method joins `name` onto sites-available/sites-enabled and
+ acts on the result as root, so a caller-controlled name must not
+ traverse out (preview_diff applies the same rule for reads).
+ """
+ if (not name or not isinstance(name, str) or os.path.basename(name) != name
+ or name in ('.', '..') or '\x00' in name):
+ return {'success': False, 'error': f'Invalid site name: {name!r}'}
+ return 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).
@@ -1148,12 +1161,9 @@ 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}'}
+ invalid = cls._invalid_site_name(name)
+ if invalid:
+ return invalid
# A vhost naming the timed format fails `nginx -t` until the
# http-level log_format exists — declare it first.
@@ -1223,6 +1233,9 @@ location /p/ {{
@classmethod
def enable_site(cls, name: str) -> Dict:
"""Enable a site by creating symlink in sites-enabled."""
+ invalid = cls._invalid_site_name(name)
+ if invalid:
+ return invalid
available_path = os.path.join(cls.SITES_AVAILABLE, name)
enabled_path = os.path.join(cls.SITES_ENABLED, name)
@@ -1246,6 +1259,9 @@ location /p/ {{
@classmethod
def disable_site(cls, name: str) -> Dict:
"""Disable a site by removing symlink from sites-enabled."""
+ invalid = cls._invalid_site_name(name)
+ if invalid:
+ return invalid
enabled_path = os.path.join(cls.SITES_ENABLED, name)
_auto_capture_vhost(name, 'disable_site')
@@ -1263,6 +1279,9 @@ location /p/ {{
@classmethod
def delete_site(cls, name: str) -> Dict:
"""Delete a site configuration."""
+ invalid = cls._invalid_site_name(name)
+ if invalid:
+ return invalid
_auto_capture_vhost(name, 'delete_site')
# First disable it
from app.services.restore_point_service import suppress_auto_capture
diff --git a/backend/tests/test_app_host_binding_fields.py b/backend/tests/test_app_host_binding_fields.py
new file mode 100644
index 00000000..afe2f9cc
--- /dev/null
+++ b/backend/tests/test_app_host_binding_fields.py
@@ -0,0 +1,103 @@
+"""Non-admins must not point an app at host paths/units, and an app name must
+stay a plain slug: root-run code turns these into compose invocations, nginx
+site files and `rm -f` targets."""
+from unittest.mock import patch
+
+import pytest
+
+
+def _mk_user(db, username, role):
+ from app.models import User
+ from werkzeug.security import generate_password_hash
+ u = User(email=f'{username}@t.local', username=username,
+ password_hash=generate_password_hash('x'), role=role, is_active=True)
+ db.session.add(u)
+ db.session.commit()
+ return u
+
+
+def _token(user_id):
+ from flask_jwt_extended import create_access_token
+ return {'Authorization': f'Bearer {create_access_token(identity=user_id)}'}
+
+
+def users(app):
+ from app import db
+ return {'dev': _mk_user(db, 'hb_dev', 'developer').id,
+ 'admin': _mk_user(db, 'hb_admin', 'admin').id}
+
+
[email protected]('field,value', [
+ ('root_path', '/'),
+ ('compose_file', '../../etc/evil.yml'),
+ ('systemd_unit', 'ssh.service'),
+ ('managed_by', 'systemd'),
+])
+def test_developer_cannot_create_with_host_fields(client, users, field, value):
+ from app.models import Application
+ resp = client.post('/api/v1/apps', headers=_token(users['dev']),
+ json={'name': f'hb-{field}', 'app_type': 'docker', field: value})
+ assert resp.status_code == 403
+ assert Application.query.filter_by(name=f'hb-{field}').first() is None
+
+
+def test_create_slugs_the_name(client, users):
+ resp = client.post('/api/v1/apps', headers=_token(users['dev']),
+ json={'name': 'My App; }\nserver {', 'app_type': 'php'})
+ assert resp.status_code == 201
+ assert resp.get_json()['app']['name'] == 'my-app-server'
+
+
+def test_create_refuses_a_taken_name(client, users):
+ body = {'name': 'hb-taken', 'app_type': 'php'}
+ assert client.post('/api/v1/apps', headers=_token(users['dev']), json=body).status_code == 201
+ assert client.post('/api/v1/apps', headers=_token(users['dev']), json=body).status_code == 400
+
+
+def dev_app(client, users):
+ resp = client.post('/api/v1/apps', headers=_token(users['dev']),
+ json={'name': 'hb-own', 'app_type': 'docker'})
+ return resp.get_json()['app']['id']
+
+
+def test_owner_cannot_repoint_host_fields(client, users, dev_app):
+ from app.models import Application
+ resp = client.put(f'/api/v1/apps/{dev_app}', headers=_token(users['dev']),
+ json={'root_path': '/', 'compose_file': 'x.yml'})
+ assert resp.status_code == 403
+ app = Application.query.get(dev_app)
+ assert app.root_path is None and app.compose_file is None
+
+
+def test_admin_can_set_host_fields(client, users, dev_app):
+ resp = client.put(f'/api/v1/apps/{dev_app}', headers=_token(users['admin']),
+ json={'root_path': '/srv/hb-own'})
+ assert resp.status_code == 200
+ assert resp.get_json()['app']['root_path'] == '/srv/hb-own'
+
+
[email protected]('name', ['../../etc/passwd', 'Has Space', 'x;y', ''])
+def test_rename_must_be_a_slug(client, users, dev_app, name):
+ resp = client.put(f'/api/v1/apps/{dev_app}', headers=_token(users['dev']),
+ json={'name': name})
+ assert resp.status_code == 400
+
+
+def test_owner_can_still_update_safe_fields(client, users, dev_app):
+ resp = client.put(f'/api/v1/apps/{dev_app}', headers=_token(users['dev']),
+ json={'name': 'hb-renamed', 'port': 8123})
+ assert resp.status_code == 200
+ assert resp.get_json()['app']['name'] == 'hb-renamed'
+
+
[email protected]('method', ['enable_site', 'disable_site', 'delete_site'])
[email protected]('name', ['../../etc/passwd', 'a/b', '..', ''])
+def test_nginx_site_methods_refuse_paths(method, name):
+ from app.services.nginx_service import NginxService
+ with patch('app.services.nginx_service.run_privileged') as run:
+ result = getattr(NginxService, method)(name)
+ assert result['success'] is False
+ assert 'Invalid site name' in result['error']
+ run.assert_not_called()