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(files): make the File Manager's "Web config" shortcut resolve, read-only
Juan Denisf927b1405ebf
diff --git a/backend/app/api/files.py b/backend/app/api/files.pyindex 7e151aa3..c2056878 100644--- a/backend/app/api/files.py+++ b/backend/app/api/files.py@@ -370,7 +370,9 @@ def upload_file():if not destination:return jsonify({'error': 'Destination path is required'}), 400- if not FileService.is_path_allowed(destination):+ # Upload writes straight to disk without going through FileService's+ # mutating methods, so it has to repeat the writable check itself.+ if not FileService.is_path_writable(destination):return jsonify({'error': 'Access denied'}), 403if file.filename == '':@@ -393,7 +395,7 @@ def upload_file():else:full_path = destination- if not FileService.is_path_allowed(full_path):+ if not FileService.is_path_writable(full_path):return jsonify({'error': 'Access denied'}), 403# Ensure parent directory existsdiff --git a/backend/app/services/file_service.py b/backend/app/services/file_service.pyindex 7a3977d2..dc7920df 100644--- a/backend/app/services/file_service.py+++ b/backend/app/services/file_service.py@@ -30,8 +30,24 @@ from app.utils.formatting import format_bytesclass FileService:"""Service for file system operations."""- # Allowed root directories for browsing (security)- ALLOWED_ROOTS = ['/home', '/var/www', '/opt', '/srv', '/var/log', paths.SERVERKIT_DIR]+ # Allowed root directories for browsing (security). Reachability is gated+ # here; mutation is gated again by READ_ONLY_ROOTS below, by the+ # files.write RBAC permission, and by the OS's own permissions.+ # /etc/nginx backs the File Manager's "Web config" shortcut; it is only+ # this subtree, not /etc — panel-internal paths stay blocked by+ # PROTECTED_ROOTS below regardless (GHSA-rm3m-9mvw-68fh).+ ALLOWED_ROOTS = ['/home', '/var/www', '/opt', '/srv', '/var/log', '/etc/nginx', paths.SERVERKIT_DIR]++ # Roots that may be browsed and read but never modified through the file+ # manager. Reading the effective nginx configuration is the point of the+ # "Web config" shortcut; hand-editing it from here is not. The panel+ # generates these vhosts itself, so a manual edit is overwritten without+ # warning on the next domain change, and an editable /etc/nginx would hand+ # anyone holding files.write a root-owned config that the panel itself+ # reloads. Config changes belong to the nginx/domain surfaces, which+ # regenerate and validate. Order matters: a read-only root only takes+ # effect while it is also inside ALLOWED_ROOTS.+ READ_ONLY_ROOTS = ['/etc/nginx']# Panel-internal directories that must NEVER be reachable through the file# manager, for any role. The backend .env (JWT_SECRET_KEY, encryption key,@@ -79,6 +95,38 @@ class FileService:except (ValueError, OSError):return False+ @classmethod+ def is_path_readonly(cls, path: str) -> bool:+ """True when *path* sits inside a browse-but-don't-touch root."""+ try:+ real_path = os.path.realpath(path)+ except (ValueError, OSError):+ return True+ return any(real_path == root or real_path.startswith(root + os.sep)+ for root in cls.READ_ONLY_ROOTS)++ @classmethod+ def is_path_writable(cls, path: str) -> bool:+ """Allowed *and* not read-only. Every mutating operation gates on this+ rather than on is_path_allowed, so adding a root to READ_ONLY_ROOTS is+ enough to make the whole write surface refuse it."""+ return cls.is_path_allowed(path) and not cls.is_path_readonly(path)++ # Denial reasons, kept identical in shape to the pre-existing messages so+ # the frontend's error rendering is unchanged.+ _DENIED = 'Access denied: path not in allowed directories'+ _READONLY = ('Access denied: this location is read-only in the file '+ 'manager — edit it through the panel surface that owns it')++ @classmethod+ def _write_denial(cls, path: str) -> Optional[str]:+ """Denial message for a mutating operation on *path*, or None."""+ if not cls.is_path_allowed(path):+ return cls._DENIED+ if cls.is_path_readonly(path):+ return cls._READONLY+ return None+@classmethoddef get_file_info(cls, path: str) -> Optional[Dict]:"""Get detailed information about a file or directory."""@@ -230,8 +278,9 @@ class FileService:@classmethoddef write_file(cls, path: str, content: str, create_backup: bool = True) -> Dict:"""Write content to file."""- if not cls.is_path_allowed(path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ denial = cls._write_denial(path)+ if denial:+ return {'success': False, 'error': denial}try:# Create backup if file exists@@ -256,8 +305,9 @@ class FileService:@classmethoddef create_file(cls, path: str, content: str = '') -> Dict:"""Create a new file."""- if not cls.is_path_allowed(path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ denial = cls._write_denial(path)+ if denial:+ return {'success': False, 'error': denial}if os.path.exists(path):return {'success': False, 'error': 'File already exists'}@@ -280,8 +330,9 @@ class FileService:@classmethoddef create_directory(cls, path: str) -> Dict:"""Create a new directory."""- if not cls.is_path_allowed(path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ denial = cls._write_denial(path)+ if denial:+ return {'success': False, 'error': denial}if os.path.exists(path):return {'success': False, 'error': 'Directory already exists'}@@ -297,8 +348,9 @@ class FileService:@classmethoddef delete(cls, path: str) -> Dict:"""Delete a file or directory."""- if not cls.is_path_allowed(path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ denial = cls._write_denial(path)+ if denial:+ return {'success': False, 'error': denial}if not os.path.exists(path):return {'success': False, 'error': 'Path not found'}@@ -317,8 +369,9 @@ class FileService:@classmethoddef rename(cls, old_path: str, new_name: str) -> Dict:"""Rename a file or directory."""- if not cls.is_path_allowed(old_path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ denial = cls._write_denial(old_path)+ if denial:+ return {'success': False, 'error': denial}if not os.path.exists(old_path):return {'success': False, 'error': 'Path not found'}@@ -330,7 +383,7 @@ class FileService:new_path = os.path.join(os.path.dirname(old_path), new_name)# Re-validate the constructed path- if not cls.is_path_allowed(new_path):+ if not cls.is_path_writable(new_path):return {'success': False, 'error': 'Access denied: target path not allowed'}if os.path.exists(new_path):@@ -347,8 +400,14 @@ class FileService:@classmethoddef copy(cls, src_path: str, dest_path: str) -> Dict:"""Copy a file or directory."""- if not cls.is_path_allowed(src_path) or not cls.is_path_allowed(dest_path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ # The source is only read, so copying *out* of a read-only root (e.g.+ # taking a vhost off /etc/nginx to keep) is allowed; the destination+ # is written, so it gets the full check.+ if not cls.is_path_allowed(src_path):+ return {'success': False, 'error': cls._DENIED}+ denial = cls._write_denial(dest_path)+ if denial:+ return {'success': False, 'error': denial}if not os.path.exists(src_path):return {'success': False, 'error': 'Source not found'}@@ -370,8 +429,11 @@ class FileService:@classmethoddef move(cls, src_path: str, dest_path: str) -> Dict:"""Move a file or directory."""- if not cls.is_path_allowed(src_path) or not cls.is_path_allowed(dest_path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ # A move removes the source, so unlike copy both ends must be writable.+ for candidate in (src_path, dest_path):+ denial = cls._write_denial(candidate)+ if denial:+ return {'success': False, 'error': denial}if not os.path.exists(src_path):return {'success': False, 'error': 'Source not found'}@@ -390,8 +452,9 @@ class FileService:@classmethoddef change_permissions(cls, path: str, mode: str) -> Dict:"""Change file/directory permissions."""- if not cls.is_path_allowed(path):- return {'success': False, 'error': 'Access denied: path not in allowed directories'}+ denial = cls._write_denial(path)+ if denial:+ return {'success': False, 'error': denial}if not os.path.exists(path):return {'success': False, 'error': 'Path not found'}diff --git a/backend/tests/test_files_readonly_roots.py b/backend/tests/test_files_readonly_roots.pynew file mode 100644index 00000000..1b7400c0--- /dev/null+++ b/backend/tests/test_files_readonly_roots.py@@ -0,0 +1,172 @@+"""Plan 73 item 3 — the File Manager's "Web config" quick-access shortcut.++The rail links the local target at /etc/nginx, but /etc was never in+ALLOWED_ROOTS, so the shortcut was a guaranteed 403 for every user — our own+regression, shipped after the review that flagged the surrounding SSL story.++/etc/nginx is now reachable, but read-only: the panel generates those vhosts+itself (a hand edit is silently overwritten on the next domain change) and an+editable /etc/nginx would hand anyone holding files.write a root-owned config+that the panel itself reloads.++Path behaviour is asserted against monkeypatched roots rather than the literal+/etc/nginx, because realpath('/etc/nginx') is C:\\etc\\nginx on a Windows dev+box; the literal constants get their own assertion below.+"""+import os++import pytest++from app.services.file_service import FileService+++def roots(tmp_path, monkeypatch):+ """An allowed root with a read-only subtree inside it.++ Mirrors the production shape: READ_ONLY_ROOTS only bites while the path is+ also inside ALLOWED_ROOTS.+ """+ ro = tmp_path / 'ro'+ rw = tmp_path / 'rw'+ ro.mkdir()+ rw.mkdir()+ (ro / 'nginx.conf').write_text('server { }\n', encoding='utf-8')+ monkeypatch.setattr(FileService, 'ALLOWED_ROOTS', [str(tmp_path)])+ monkeypatch.setattr(FileService, 'READ_ONLY_ROOTS', [str(ro)])+ return {'ro': ro, 'rw': rw, 'conf': ro / 'nginx.conf'}+++# --------------------------------------------------------------------------- #+# The shortcut resolves at all (the actual bug)+# --------------------------------------------------------------------------- #+def test_etc_nginx_is_allowed_but_read_only():+ """The literal constants behind the quick-access link. /etc itself stays+ shut — the shortcut needed one subtree, not the whole config tree."""+ assert '/etc/nginx' in FileService.ALLOWED_ROOTS+ assert '/etc/nginx' in FileService.READ_ONLY_ROOTS+ assert '/etc' not in FileService.ALLOWED_ROOTS+ assert not FileService.is_path_allowed('/etc/passwd')+ assert not FileService.is_path_allowed('/etc/shadow')+++def test_read_only_subtree_is_browsable(roots):+ assert FileService.is_path_allowed(str(roots['ro']))+ assert FileService.is_path_allowed(str(roots['conf']))+ assert FileService.is_path_readonly(str(roots['conf']))+ assert not FileService.is_path_writable(str(roots['conf']))+++def test_writable_root_is_unaffected(roots):+ target = roots['rw'] / 'index.html'+ assert FileService.is_path_allowed(str(target))+ assert not FileService.is_path_readonly(str(target))+ assert FileService.is_path_writable(str(target))+++def test_paths_outside_every_root_stay_denied(roots, tmp_path):+ outside = tmp_path.parent / 'elsewhere.txt'+ assert not FileService.is_path_allowed(str(outside))+ assert not FileService.is_path_writable(str(outside))+++# --------------------------------------------------------------------------- #+# Every mutating entry point refuses — and refuses before touching disk+# --------------------------------------------------------------------------- #+def test_write_file_refuses_and_leaves_content_untouched(roots):+ original = roots['conf'].read_text(encoding='utf-8')+ result = FileService.write_file(str(roots['conf']), 'server { evil; }')++ assert result['success'] is False+ assert 'read-only' in result['error']+ assert roots['conf'].read_text(encoding='utf-8') == original+ # ...and no .bak was dropped next to it either.+ assert not (roots['ro'] / 'nginx.conf.bak').exists()+++def test_create_file_refuses(roots):+ target = roots['ro'] / 'new.conf'+ result = FileService.create_file(str(target), 'x')++ assert result['success'] is False+ assert 'read-only' in result['error']+ assert not target.exists()+++def test_create_directory_refuses(roots):+ target = roots['ro'] / 'sites-enabled'+ result = FileService.create_directory(str(target))++ assert result['success'] is False+ assert 'read-only' in result['error']+ assert not target.exists()+++def test_delete_refuses(roots):+ result = FileService.delete(str(roots['conf']))++ assert result['success'] is False+ assert 'read-only' in result['error']+ assert roots['conf'].exists()+++def test_rename_refuses(roots):+ result = FileService.rename(str(roots['conf']), 'nginx.conf.disabled')++ assert result['success'] is False+ assert 'read-only' in result['error']+ assert roots['conf'].exists()+ assert not (roots['ro'] / 'nginx.conf.disabled').exists()+++def test_change_permissions_refuses(roots):+ result = FileService.change_permissions(str(roots['conf']), '777')++ assert result['success'] is False+ assert 'read-only' in result['error']+++def test_move_refuses_in_both_directions(roots):+ out = FileService.move(str(roots['conf']), str(roots['rw'] / 'nginx.conf'))+ assert out['success'] is False+ assert 'read-only' in out['error']+ assert roots['conf'].exists()++ donor = roots['rw'] / 'payload.conf'+ donor.write_text('x', encoding='utf-8')+ into = FileService.move(str(donor), str(roots['ro'] / 'payload.conf'))+ assert into['success'] is False+ assert 'read-only' in into['error']+ assert not (roots['ro'] / 'payload.conf').exists()+ assert donor.exists()+++def test_copy_out_is_allowed_but_copy_in_is_refused(roots):+ """Taking a vhost out to keep is reading; writing one in is not."""+ out = FileService.copy(str(roots['conf']), str(roots['rw'] / 'nginx.conf'))+ assert out['success'] is True+ assert (roots['rw'] / 'nginx.conf').exists()+ assert roots['conf'].exists()++ donor = roots['rw'] / 'payload.conf'+ donor.write_text('x', encoding='utf-8')+ into = FileService.copy(str(donor), str(roots['ro'] / 'payload.conf'))+ assert into['success'] is False+ assert 'read-only' in into['error']+ assert not (roots['ro'] / 'payload.conf').exists()+++# --------------------------------------------------------------------------- #+# A symlink out of a writable root must not launder a write into the read-only+# subtree — the check resolves before comparing.+# --------------------------------------------------------------------------- #[email protected](os.name == 'nt', reason='symlink creation needs privilege on Windows')+def test_symlink_into_read_only_root_does_not_launder_a_write(roots):+ link = roots['rw'] / 'sneaky.conf'+ link.symlink_to(roots['conf'])++ result = FileService.write_file(str(link), 'server { evil; }')++ assert result['success'] is False+ assert 'read-only' in result['error']+ assert roots['conf'].read_text(encoding='utf-8') == 'server { }\n'