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.

refactor(files): file manager onto the typed-error contract (C reference)

Juan Denisdee7c334868a
diff --git a/backend/app/api/files.py b/backend/app/api/files.py
index 70e38c2b..eabefd5d 100644
--- a/backend/app/api/files.py
+++ b/backend/app/api/files.py
@@ -2,6 +2,7 @@
from flask import Blueprint, request, jsonify, send_file
from app.error_reporting import unexpected_response
+from app.exceptions import NotFoundError, PermissionDeniedError, ValidationError
from ..middleware.rbac import permission_required
from ..services.file_service import FileService
from ..services.storage_provider_service import StorageProviderService
@@ -20,9 +21,7 @@ def browse_directory():
result = FileService.list_directory(path, show_hidden=show_hidden)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/info', methods=['GET'])
@@ -32,18 +31,16 @@ def get_file_info():
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
if not FileService.is_path_allowed(path):
- return jsonify({'error': 'Access denied'}), 403
+ raise PermissionDeniedError('Access denied')
info = FileService.get_file_info(path)
- if info and 'error' not in info:
- return jsonify({'success': True, 'file': info}), 200
-
- error = info.get('error', 'File not found') if info else 'File not found'
- return jsonify({'error': error}), 404
+ if not info or 'error' in info:
+ raise NotFoundError(info.get('error', 'File not found') if info else 'File not found')
+ return jsonify({'success': True, 'file': info}), 200
@files_bp.route('/read', methods=['GET'])
@@ -53,15 +50,11 @@ def read_file():
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = FileService.read_file(path)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/write', methods=['POST'])
@@ -71,25 +64,21 @@ def write_file():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
path = data.get('path')
content = data.get('content')
create_backup = data.get('create_backup', True)
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
if content is None:
- return jsonify({'error': 'Content is required'}), 400
+ raise ValidationError('Content is required')
result = FileService.write_file(path, content, create_backup=create_backup)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/create', methods=['POST'])
@@ -99,21 +88,17 @@ def create_file():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
path = data.get('path')
content = data.get('content', '')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = FileService.create_file(path, content)
- if result.get('success'):
- return jsonify(result), 201
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 201
@files_bp.route('/mkdir', methods=['POST'])
@@ -123,20 +108,16 @@ def create_directory():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
path = data.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = FileService.create_directory(path)
- if result.get('success'):
- return jsonify(result), 201
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 201
@files_bp.route('/delete', methods=['DELETE'])
@@ -146,15 +127,11 @@ def delete_path():
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = FileService.delete(path)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/rename', methods=['POST'])
@@ -164,21 +141,17 @@ def rename_path():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
path = data.get('path')
new_name = data.get('new_name')
if not path or not new_name:
- return jsonify({'error': 'Path and new_name are required'}), 400
+ raise ValidationError('Path and new_name are required')
result = FileService.rename(path, new_name)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/copy', methods=['POST'])
@@ -188,21 +161,17 @@ def copy_path():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
src = data.get('src')
dest = data.get('dest')
if not src or not dest:
- return jsonify({'error': 'Source and destination paths are required'}), 400
+ raise ValidationError('Source and destination paths are required')
result = FileService.copy(src, dest)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/move', methods=['POST'])
@@ -212,21 +181,17 @@ def move_path():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
src = data.get('src')
dest = data.get('dest')
if not src or not dest:
- return jsonify({'error': 'Source and destination paths are required'}), 400
+ raise ValidationError('Source and destination paths are required')
result = FileService.move(src, dest)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/chmod', methods=['POST'])
@@ -236,21 +201,17 @@ def change_permissions():
data = request.get_json()
if not data:
- return jsonify({'error': 'Request body is required'}), 400
+ raise ValidationError('Request body is required')
path = data.get('path')
mode = data.get('mode')
if not path or not mode:
- return jsonify({'error': 'Path and mode are required'}), 400
+ raise ValidationError('Path and mode are required')
result = FileService.change_permissions(path, mode)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/search', methods=['GET'])
@@ -262,15 +223,11 @@ def search_files():
max_results = request.args.get('max_results', 100, type=int)
if not pattern:
- return jsonify({'error': 'Search pattern is required'}), 400
+ raise ValidationError('Search pattern is required')
result = FileService.search(directory, pattern, max_results=max_results)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/disk-usage', methods=['GET'])
@@ -281,9 +238,7 @@ def get_disk_usage():
result = FileService.get_disk_usage(path)
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/disk-mounts', methods=['GET'])
@@ -292,9 +247,7 @@ def get_disk_mounts():
"""Get disk usage for all mount points."""
result = FileService.get_all_disk_mounts()
- if result.get('success'):
- return jsonify(result), 200
- return jsonify(result), 400
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/analyze', methods=['GET'])
@@ -307,11 +260,7 @@ def analyze_directory():
result = FileService.analyze_directory_sizes(path, depth=depth, limit=limit)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/type-breakdown', methods=['GET'])
@@ -323,11 +272,7 @@ def get_type_breakdown():
result = FileService.get_file_type_breakdown(path, max_depth=max_depth)
- if result.get('success'):
- return jsonify(result), 200
-
- status = 403 if 'denied' in result.get('error', '').lower() else 400
- return jsonify(result), status
+ return jsonify({'success': True, **result}), 200
@files_bp.route('/download', methods=['GET'])
@@ -337,7 +282,7 @@ def download_file():
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
if not FileService.is_path_allowed(path):
return jsonify({'error': 'Access denied'}), 403
@@ -369,7 +314,7 @@ def upload_file():
destination = request.form.get('destination')
if not destination:
- return jsonify({'error': 'Destination path is required'}), 400
+ raise ValidationError('Destination path is required')
# Upload writes straight to disk without going through FileService's
# mutating methods, so it has to repeat the writable check itself.
@@ -436,7 +381,7 @@ def s3_read():
"""Read a text object for in-app editing."""
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = StorageProviderService.s3_read(path)
return jsonify(result), 200 if result.get('success') else 400
@@ -449,9 +394,9 @@ def s3_write():
path = data.get('path')
content = data.get('content')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
if content is None:
- return jsonify({'error': 'Content is required'}), 400
+ raise ValidationError('Content is required')
result = StorageProviderService.s3_write(path, content)
return jsonify(result), 200 if result.get('success') else 400
@@ -462,7 +407,7 @@ def s3_delete():
"""Delete an object (or every object beneath a prefix)."""
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = StorageProviderService.s3_delete(path)
return jsonify(result), 200 if result.get('success') else 400
@@ -473,7 +418,7 @@ def s3_download_url():
"""Return a short-lived presigned URL the browser can download directly."""
path = request.args.get('path')
if not path:
- return jsonify({'error': 'Path is required'}), 400
+ raise ValidationError('Path is required')
result = StorageProviderService.s3_presigned_get(path)
return jsonify(result), 200 if result.get('success') else 400
diff --git a/backend/app/services/file_service.py b/backend/app/services/file_service.py
index dc7920df..d24bae9a 100644
--- a/backend/app/services/file_service.py
+++ b/backend/app/services/file_service.py
@@ -24,6 +24,12 @@ else:
grp = None
from app import paths
+from app.exceptions import (
+ ConflictError,
+ NotFoundError,
+ PermissionDeniedError,
+ ValidationError,
+)
from app.utils.formatting import format_bytes
@@ -119,13 +125,17 @@ class FileService:
'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."""
+ def _require_allowed(cls, path: str) -> None:
+ """Raise unless *path* is inside an allowed root."""
if not cls.is_path_allowed(path):
- return cls._DENIED
+ raise PermissionDeniedError(cls._DENIED)
+
+ @classmethod
+ def _require_writable(cls, path: str) -> None:
+ """Raise unless a mutating operation may touch *path*."""
+ cls._require_allowed(path)
if cls.is_path_readonly(path):
- return cls._READONLY
- return None
+ raise PermissionDeniedError(cls._READONLY)
@classmethod
def get_file_info(cls, path: str) -> Optional[Dict]:
@@ -191,13 +201,13 @@ class FileService:
def list_directory(cls, path: str, show_hidden: bool = False) -> Dict:
"""List contents of a directory."""
if not cls.is_path_allowed(path):
- return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+ raise PermissionDeniedError(cls._DENIED)
if not os.path.exists(path):
- return {'success': False, 'error': 'Directory not found'}
+ raise NotFoundError('Directory not found')
if not os.path.isdir(path):
- return {'success': False, 'error': 'Not a directory'}
+ raise ValidationError('Not a directory')
try:
entries = []
@@ -219,68 +229,59 @@ class FileService:
parent = None
return {
- 'success': True,
'path': path,
'parent': parent,
'entries': entries,
'total': len(entries)
}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def read_file(cls, path: str) -> Dict:
"""Read file contents."""
if not cls.is_path_allowed(path):
- return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+ raise PermissionDeniedError(cls._DENIED)
if not os.path.exists(path):
- return {'success': False, 'error': 'File not found'}
+ raise NotFoundError('File not found')
if os.path.isdir(path):
- return {'success': False, 'error': 'Cannot read directory'}
+ raise ValidationError('Cannot read directory')
try:
size = os.path.getsize(path)
if size > cls.MAX_EDIT_SIZE:
- return {
- 'success': False,
- 'error': f'File too large to edit ({cls._format_size(size)}). Maximum is {cls._format_size(cls.MAX_EDIT_SIZE)}'
- }
+ raise ValidationError(
+ f'File too large to edit ({cls._format_size(size)}). '
+ f'Maximum is {cls._format_size(cls.MAX_EDIT_SIZE)}')
# Try to read as text
try:
with open(path, 'r', encoding='utf-8') as f:
content = f.read()
return {
- 'success': True,
'path': path,
'content': content,
'encoding': 'utf-8',
'size': size,
'is_binary': False
}
- except UnicodeDecodeError:
- # File is binary
- return {
- 'success': False,
- 'error': 'Binary file cannot be edited',
- 'is_binary': True
- }
+ except UnicodeDecodeError as e:
+ raise ValidationError('Binary file cannot be edited',
+ details={'is_binary': True}) from e
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def write_file(cls, path: str, content: str, create_backup: bool = True) -> Dict:
"""Write content to file."""
- denial = cls._write_denial(path)
- if denial:
- return {'success': False, 'error': denial}
+ cls._require_writable(path)
try:
# Create backup if file exists
@@ -293,24 +294,21 @@ class FileService:
f.write(content)
return {
- 'success': True,
'path': path,
'size': len(content.encode('utf-8'))
}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def create_file(cls, path: str, content: str = '') -> Dict:
"""Create a new file."""
- denial = cls._write_denial(path)
- if denial:
- return {'success': False, 'error': denial}
+ cls._require_writable(path)
if os.path.exists(path):
- return {'success': False, 'error': 'File already exists'}
+ raise ConflictError('File already exists')
try:
# Ensure parent directory exists
@@ -321,81 +319,75 @@ class FileService:
with open(path, 'w', encoding='utf-8') as f:
f.write(content)
- return {'success': True, 'path': path}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'path': path}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def create_directory(cls, path: str) -> Dict:
"""Create a new directory."""
- denial = cls._write_denial(path)
- if denial:
- return {'success': False, 'error': denial}
+ cls._require_writable(path)
if os.path.exists(path):
- return {'success': False, 'error': 'Directory already exists'}
+ raise ConflictError('Directory already exists')
try:
os.makedirs(path)
- return {'success': True, 'path': path}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'path': path}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def delete(cls, path: str) -> Dict:
"""Delete a file or directory."""
- denial = cls._write_denial(path)
- if denial:
- return {'success': False, 'error': denial}
+ cls._require_writable(path)
if not os.path.exists(path):
- return {'success': False, 'error': 'Path not found'}
+ raise NotFoundError('Path not found')
try:
if os.path.isdir(path):
shutil.rmtree(path)
else:
os.remove(path)
- return {'success': True, 'path': path}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'path': path}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def rename(cls, old_path: str, new_name: str) -> Dict:
"""Rename a file or directory."""
- denial = cls._write_denial(old_path)
- if denial:
- return {'success': False, 'error': denial}
+ cls._require_writable(old_path)
if not os.path.exists(old_path):
- return {'success': False, 'error': 'Path not found'}
+ raise NotFoundError('Path not found')
# Validate new_name has no path separators
if '/' in new_name or '\\' in new_name or '..' in new_name:
- return {'success': False, 'error': 'Invalid filename: path separators not allowed'}
+ raise ValidationError('Invalid filename: path separators not allowed')
new_path = os.path.join(os.path.dirname(old_path), new_name)
# Re-validate the constructed path
if not cls.is_path_writable(new_path):
- return {'success': False, 'error': 'Access denied: target path not allowed'}
+ raise PermissionDeniedError('Access denied: target path not allowed')
if os.path.exists(new_path):
- return {'success': False, 'error': 'Target already exists'}
+ raise ConflictError('Target already exists')
try:
os.rename(old_path, new_path)
- return {'success': True, 'old_path': old_path, 'new_path': new_path}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'old_path': old_path, 'new_path': new_path}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def copy(cls, src_path: str, dest_path: str) -> Dict:
@@ -404,84 +396,80 @@ class FileService:
# 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}
+ raise PermissionDeniedError(cls._DENIED)
+ cls._require_writable(dest_path)
if not os.path.exists(src_path):
- return {'success': False, 'error': 'Source not found'}
+ raise NotFoundError('Source not found')
if os.path.exists(dest_path):
- return {'success': False, 'error': 'Destination already exists'}
+ raise ConflictError('Destination already exists')
try:
if os.path.isdir(src_path):
shutil.copytree(src_path, dest_path)
else:
shutil.copy2(src_path, dest_path)
- return {'success': True, 'src': src_path, 'dest': dest_path}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'src': src_path, 'dest': dest_path}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def move(cls, src_path: str, dest_path: str) -> Dict:
"""Move a file or directory."""
# 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}
+ cls._require_writable(candidate)
if not os.path.exists(src_path):
- return {'success': False, 'error': 'Source not found'}
+ raise NotFoundError('Source not found')
if os.path.exists(dest_path):
- return {'success': False, 'error': 'Destination already exists'}
+ raise ConflictError('Destination already exists')
try:
shutil.move(src_path, dest_path)
- return {'success': True, 'src': src_path, 'dest': dest_path}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'src': src_path, 'dest': dest_path}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def change_permissions(cls, path: str, mode: str) -> Dict:
"""Change file/directory permissions."""
- denial = cls._write_denial(path)
- if denial:
- return {'success': False, 'error': denial}
+ cls._require_writable(path)
if not os.path.exists(path):
- return {'success': False, 'error': 'Path not found'}
+ raise NotFoundError('Path not found')
+ # Convert octal string to int (parsed outside the chmod try so a
+ # ValidationError below is never re-caught as a generic ValueError).
try:
- # Convert octal string to int
mode_int = int(mode, 8)
- # Validate permission mode
- if mode_int < 0o000 or mode_int > 0o777:
- return {'success': False, 'error': 'Invalid permission mode. Must be between 000 and 777.'}
+ except ValueError as e:
+ raise ValidationError('Invalid permission mode') from e
+ if mode_int < 0o000 or mode_int > 0o777:
+ raise ValidationError('Invalid permission mode. Must be between 000 and 777.')
+
+ try:
os.chmod(path, mode_int)
- return {'success': True, 'path': path, 'mode': mode}
- except ValueError:
- return {'success': False, 'error': 'Invalid permission mode'}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'path': path, 'mode': mode}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def search(cls, directory: str, pattern: str, max_results: int = 100) -> Dict:
"""Search for files matching pattern."""
if not cls.is_path_allowed(directory):
- return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+ raise PermissionDeniedError(cls._DENIED)
if not os.path.isdir(directory):
- return {'success': False, 'error': 'Directory not found'}
+ raise NotFoundError('Directory not found')
try:
results = []
@@ -500,16 +488,15 @@ class FileService:
results.append(info)
if len(results) >= max_results:
return {
- 'success': True,
'results': results,
'truncated': True
}
- return {'success': True, 'results': results, 'truncated': False}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ return {'results': results, 'truncated': False}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def get_disk_usage(cls, path: str) -> Dict:
@@ -517,11 +504,10 @@ class FileService:
try:
# Validate path exists
if not os.path.exists(path):
- return {'success': False, 'error': 'Path not found'}
+ raise NotFoundError('Path not found')
usage = shutil.disk_usage(path)
return {
- 'success': True,
'path': path,
'total': usage.total,
'used': usage.used,
@@ -531,10 +517,10 @@ class FileService:
'used_human': cls._format_size(usage.used),
'free_human': cls._format_size(usage.free)
}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
- except (OSError, Exception) as e:
- return {'success': False, 'error': str(e)}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
+ except OSError as e:
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def _is_editable(cls, path: str) -> bool:
@@ -623,21 +609,21 @@ class FileService:
# Skip mounts we can't access
continue
- return {'success': True, 'mounts': mounts}
- except Exception as e:
- return {'success': False, 'error': str(e)}
+ return {'mounts': mounts}
+ except (PermissionError, OSError) as e:
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def analyze_directory_sizes(cls, path: str, depth: int = 1, limit: int = 20) -> Dict:
"""Analyze directory to get sizes of subdirectories and large files."""
if not cls.is_path_allowed(path):
- return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+ raise PermissionDeniedError(cls._DENIED)
if not os.path.exists(path):
- return {'success': False, 'error': 'Path not found'}
+ raise NotFoundError('Path not found')
if not os.path.isdir(path):
- return {'success': False, 'error': 'Path is not a directory'}
+ raise ValidationError('Path is not a directory')
try:
entries = []
@@ -682,17 +668,16 @@ class FileService:
files = [e for e in entries if not e['is_dir']][:limit]
return {
- 'success': True,
'path': path,
'total_size': total_size,
'total_size_human': cls._format_size(total_size),
'directories': directories,
'largest_files': files
}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def _get_dir_size_recursive(cls, path: str, max_depth: int = 2, current_depth: int = 0) -> int:
@@ -721,13 +706,13 @@ class FileService:
def get_file_type_breakdown(cls, path: str, max_depth: int = 3) -> Dict:
"""Get breakdown of file sizes by type category."""
if not cls.is_path_allowed(path):
- return {'success': False, 'error': 'Access denied: path not in allowed directories'}
+ raise PermissionDeniedError(cls._DENIED)
if not os.path.exists(path):
- return {'success': False, 'error': 'Path not found'}
+ raise NotFoundError('Path not found')
if not os.path.isdir(path):
- return {'success': False, 'error': 'Path is not a directory'}
+ raise ValidationError('Path is not a directory')
# File type categories with extensions
categories = {
@@ -804,16 +789,15 @@ class FileService:
breakdown.sort(key=lambda x: x['size'], reverse=True)
return {
- 'success': True,
'path': path,
'total_size': total_size,
'total_size_human': cls._format_size(total_size),
'breakdown': breakdown
}
- except PermissionError:
- return {'success': False, 'error': 'Permission denied'}
+ except PermissionError as e:
+ raise PermissionDeniedError('Permission denied') from e
except OSError as e:
- return {'success': False, 'error': str(e)}
+ raise ValidationError(str(e), code='filesystem_error') from e
@classmethod
def _categorize_files_recursive(cls, path: str, categories: Dict, max_depth: int, current_depth: int) -> None:
diff --git a/backend/tests/STATUS_SNIFFING_CEILING b/backend/tests/STATUS_SNIFFING_CEILING
index 40994076..b4de3947 100644
--- a/backend/tests/STATUS_SNIFFING_CEILING
+++ b/backend/tests/STATUS_SNIFFING_CEILING
@@ -1 +1 @@
-23
+11
diff --git a/backend/tests/test_files_rbac.py b/backend/tests/test_files_rbac.py
index e5c7eb93..fe273913 100644
--- a/backend/tests/test_files_rbac.py
+++ b/backend/tests/test_files_rbac.py
@@ -87,11 +87,22 @@ def test_developer_passes_files_write_gate(client, role_headers, monkeypatch,
assert resp.status_code != 403
-def test_viewer_can_still_browse(client, role_headers):
- """Read endpoints stay reachable for viewers (files.read=True)."""
+def test_viewer_can_still_browse(client, role_headers, monkeypatch):
+ """Read endpoints stay reachable for viewers (files.read=True).
+
+ The service is stubbed: /tmp is not an allowed root, and since the typed
+ error contract the path denial is itself a 403, which would be
+ indistinguishable from the RBAC gate this test is about.
+ """
+ from app.services.file_service import FileService
+ monkeypatch.setattr(
+ FileService, 'list_directory',
+ staticmethod(lambda *a, **k: {'path': '/tmp', 'parent': None,
+ 'entries': [], 'total': 0}))
resp = client.get('/api/v1/files/browse?path=/tmp',
headers=role_headers[User.ROLE_VIEWER])
- assert resp.status_code != 403
+ assert resp.status_code == 200
+ assert resp.get_json()['success'] is True
# --------------------------------------------------------------------------- #
diff --git a/backend/tests/test_files_readonly_roots.py b/backend/tests/test_files_readonly_roots.py
index 1b7400c0..b177dd6e 100644
--- a/backend/tests/test_files_readonly_roots.py
+++ b/backend/tests/test_files_readonly_roots.py
@@ -17,6 +17,7 @@ import os
import pytest
+from app.exceptions import PermissionDeniedError
from app.services.file_service import FileService
@@ -75,10 +76,9 @@ def test_paths_outside_every_root_stay_denied(roots, tmp_path):
# --------------------------------------------------------------------------- #
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; }')
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ 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()
@@ -86,57 +86,49 @@ def test_write_file_refuses_and_leaves_content_untouched(roots):
def test_create_file_refuses(roots):
target = roots['ro'] / 'new.conf'
- result = FileService.create_file(str(target), 'x')
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ 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))
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ 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']))
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ 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')
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ 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']
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ FileService.change_permissions(str(roots['conf']), '777')
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']
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ FileService.move(str(roots['conf']), str(roots['rw'] / 'nginx.conf'))
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']
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ FileService.move(str(donor), str(roots['ro'] / 'payload.conf'))
assert not (roots['ro'] / 'payload.conf').exists()
assert donor.exists()
@@ -144,15 +136,14 @@ def test_move_refuses_in_both_directions(roots):
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 out == {'src': str(roots['conf']), 'dest': str(roots['rw'] / 'nginx.conf')}
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']
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ FileService.copy(str(donor), str(roots['ro'] / 'payload.conf'))
assert not (roots['ro'] / 'payload.conf').exists()
@@ -165,8 +156,7 @@ 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; }')
+ with pytest.raises(PermissionDeniedError, match='read-only'):
+ 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'
diff --git a/backend/tests/test_files_typed_errors.py b/backend/tests/test_files_typed_errors.py
new file mode 100644
index 00000000..5e9a8f82
--- /dev/null
+++ b/backend/tests/test_files_typed_errors.py
@@ -0,0 +1,141 @@
+"""Files API on the typed-error contract (plan 76, C envelopes reference).
+
+The file manager is the reference conversion for milestone C's envelope
+decision: **services raise typed errors; routes return data.** Before this,
+``FileService`` returned ``{'success': False, 'error': <prose>}`` and
+``files.py`` chose status codes by sniffing the prose
+(``403 if 'denied' in error else 400``) — rephrasing a message silently
+changed the status code.
+
+These tests pin the visible consequences end to end through the real routes
+and the global ``ApplicationError`` handler:
+
+ * denials are 403 regardless of wording,
+ * missing paths are 404 (previously a sniffed 400),
+ * already-exists is 409 (previously 400),
+ * bad input is 400 with the ``error`` key the frontend reads,
+ * success bodies keep their compatibility ``success: True`` key.
+
+Everything runs against monkeypatched tmp roots so it works on any OS.
+"""
+import pytest
+
+from app.services.file_service import FileService
+
+
+def roots(tmp_path, monkeypatch):
+ ro = tmp_path / 'ro'
+ rw = tmp_path / 'rw'
+ ro.mkdir()
+ rw.mkdir()
+ (ro / 'nginx.conf').write_text('server { }\n', encoding='utf-8')
+ (rw / 'app.conf').write_text('x = 1\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', 'file': rw / 'app.conf'}
+
+
+def _get(client, auth_headers, url):
+ return client.get(url, headers=auth_headers)
+
+
+def _post(client, auth_headers, url, body):
+ return client.post(url, json=body, headers=auth_headers)
+
+
+# ---------------------------------------------------------------- statuses #
+
+def test_denied_path_is_403_not_a_sniffed_400(client, auth_headers, tmp_path):
+ """Outside every allowed root → PermissionDeniedError → 403."""
+ resp = _get(client, auth_headers,
+ f'/api/v1/files/read?path={tmp_path.parent / "elsewhere.txt"}')
+ assert resp.status_code == 403
+ body = resp.get_json()
+ assert body['code'] == 'permission_denied'
+ assert 'error' in body
+
+
+def test_missing_file_is_404(client, auth_headers, roots):
+ resp = _get(client, auth_headers,
+ f'/api/v1/files/read?path={roots["rw"] / "nope.txt"}')
+ assert resp.status_code == 404
+ assert resp.get_json()['code'] == 'not_found'
+
+
+def test_create_over_existing_file_is_409(client, auth_headers, roots):
+ resp = _post(client, auth_headers, '/api/v1/files/create',
+ {'path': str(roots['file'])})
+ assert resp.status_code == 409
+ assert resp.get_json()['code'] == 'conflict'
+
+
+def test_write_into_readonly_root_is_403_and_writes_nothing(client, auth_headers, roots):
+ resp = _post(client, auth_headers, '/api/v1/files/write',
+ {'path': str(roots['conf']), 'content': 'server { evil; }'})
+ assert resp.status_code == 403
+ assert 'read-only' in resp.get_json()['error']
+ assert roots['conf'].read_text(encoding='utf-8') == 'server { }\n'
+
+
+def test_missing_required_field_is_400_with_error_key(client, auth_headers):
+ resp = _get(client, auth_headers, '/api/v1/files/read')
+ assert resp.status_code == 400
+ assert resp.get_json()['error'] == 'Path is required'
+
+
+def test_browse_of_a_file_is_400(client, auth_headers, roots):
+ resp = _get(client, auth_headers,
+ f'/api/v1/files/browse?path={roots["file"]}')
+ assert resp.status_code == 400
+ assert resp.get_json()['error'] == 'Not a directory'
+
+
+# ----------------------------------------------------------- success shape #
+
+def test_success_bodies_keep_the_compat_envelope(client, auth_headers, roots):
+ """The wire shape existing consumers read: success key + data keys."""
+ resp = _get(client, auth_headers,
+ f'/api/v1/files/browse?path={roots["rw"]}')
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body['success'] is True
+ assert body['path'] == str(roots['rw'])
+ assert isinstance(body['entries'], list)
+
+ resp = _get(client, auth_headers,
+ f'/api/v1/files/read?path={roots["file"]}')
+ assert resp.status_code == 200
+ body = resp.get_json()
+ assert body['success'] is True
+ assert body['content'] == 'x = 1\n'
+
+
+def test_create_still_answers_201(client, auth_headers, roots):
+ target = roots['rw'] / 'fresh.txt'
+ resp = _post(client, auth_headers, '/api/v1/files/create',
+ {'path': str(target), 'content': 'hi'})
+ assert resp.status_code == 201
+ assert resp.get_json()['success'] is True
+ assert target.read_text(encoding='utf-8') == 'hi'
+
+
+# ----------------------------------------------------- service-level raises #
+
+def test_service_conflict_and_notfound_are_typed(roots):
+ from app.exceptions import ConflictError, NotFoundError
+
+ with pytest.raises(ConflictError):
+ FileService.create_file(str(roots['file']), 'x')
+ with pytest.raises(NotFoundError):
+ FileService.delete(str(roots['rw'] / 'ghost.txt'))
+
+
+def test_binary_read_carries_is_binary_detail(roots):
+ from app.exceptions import ValidationError
+
+ blob = roots['rw'] / 'blob.bin'
+ blob.write_bytes(b'\x00\xff\x00\xff')
+ with pytest.raises(ValidationError) as exc:
+ FileService.read_file(str(blob))
+ assert exc.value.details == {'is_binary': True}