mirror of
https://github.com/jhd3197/ServerKit.git
synced 2026-11-09 05:24:49 +09:00
backend/app/services/plugin_service.py: - Zip Slip defense: new _safe_extract_path() validates every archive member against the destination root (rejects absolute paths, ../ segments, and entries that resolve outside backend/frontend dest). All zip extract paths route through it. - Plugin requirements.txt no longer auto-installs. Running pip on an untrusted plugin gives setup.py hooks code-exec at the backend's privilege level. Operators must opt in with SERVERKIT_ALLOW_PLUGIN_PIP=1; otherwise the file is saved to the plugin dir for manual review. - New _attach_status_guard() registers a per-blueprint before_request that returns 503 if the plugin's DB status is not 'active'. Flask can't unregister blueprints from a running app, so the in-DB status is now authoritative at request time — disabling a plugin actually stops serving its routes. - New _update_plugin_metadata() syncs all mutable manifest fields (display_name, description, author, homepage, repository, license, category) on reinstall. Previously these went stale after the first install. backend/app/api/plugins.py: - /install endpoints no longer echo raw exception strings to clients (could leak paths, lib versions, SQL fragments). Log full traceback server-side with a short correlation ref returned to the client. Co-Authored-By: Claude Opus 4.7 (1M context) <noreply@anthropic.com>
433 lines
16 KiB
Python
433 lines
16 KiB
Python
"""
|
|
Plugins API - Install, manage, and uninstall ServerKit plugins.
|
|
|
|
Supports installing plugins from:
|
|
- GitHub repo URLs (resolves latest release automatically)
|
|
- GitHub release URLs (specific version)
|
|
- Direct zip download URLs
|
|
"""
|
|
from flask import Blueprint, request, jsonify
|
|
from flask_jwt_extended import jwt_required
|
|
from app.services.audit_service import AuditService
|
|
from app.models.audit_log import AuditLog
|
|
|
|
plugins_bp = Blueprint('plugins', __name__)
|
|
|
|
|
|
def get_current_user():
|
|
from flask_jwt_extended import get_jwt_identity
|
|
from app.models.user import User
|
|
return User.query.get(get_jwt_identity())
|
|
|
|
|
|
@plugins_bp.route('', methods=['GET'])
|
|
@plugins_bp.route('/', methods=['GET'])
|
|
@jwt_required()
|
|
def list_plugins():
|
|
"""List all installed plugins."""
|
|
from app.services.plugin_service import list_plugins
|
|
status = request.args.get('status')
|
|
plugins = list_plugins(status=status)
|
|
return jsonify({'plugins': [p.to_dict() for p in plugins]})
|
|
|
|
|
|
@plugins_bp.route('/<int:plugin_id>', methods=['GET'])
|
|
@jwt_required()
|
|
def get_plugin(plugin_id):
|
|
"""Get details of an installed plugin."""
|
|
from app.services.plugin_service import get_plugin
|
|
plugin = get_plugin(plugin_id)
|
|
if not plugin:
|
|
return jsonify({'error': 'Plugin not found'}), 404
|
|
return jsonify(plugin.to_dict())
|
|
|
|
|
|
@plugins_bp.route('/install', methods=['POST'])
|
|
@jwt_required()
|
|
def install_plugin():
|
|
"""Install a plugin from a URL.
|
|
|
|
Body: { "url": "https://github.com/user/repo" }
|
|
|
|
Accepts:
|
|
- GitHub repo URL (downloads latest release)
|
|
- GitHub release URL (specific version)
|
|
- Direct .zip URL
|
|
"""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
data = request.get_json()
|
|
if not data or 'url' not in data:
|
|
return jsonify({'error': 'url required'}), 400
|
|
|
|
url = data['url'].strip()
|
|
if not url:
|
|
return jsonify({'error': 'url cannot be empty'}), 400
|
|
|
|
from app.services.plugin_service import install_from_url
|
|
try:
|
|
plugin = install_from_url(url, user_id=user.id)
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_CREATE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin.id,
|
|
details={'name': plugin.name, 'version': plugin.version, 'url': url}
|
|
)
|
|
return jsonify(plugin.to_dict()), 201
|
|
except ValueError as e:
|
|
return jsonify({'error': str(e)}), 400
|
|
except Exception:
|
|
# Log full traceback server-side; details go to the InstalledPlugin
|
|
# row's error_message field. Don't echo raw exceptions to the
|
|
# client — they can leak filesystem paths, library versions, or
|
|
# SQL fragments.
|
|
import logging, uuid
|
|
ref = uuid.uuid4().hex[:8]
|
|
logging.getLogger(__name__).exception(
|
|
'Plugin install failed (ref=%s)', ref
|
|
)
|
|
return jsonify({
|
|
'error': 'Installation failed. Check server logs.',
|
|
'ref': ref,
|
|
}), 500
|
|
|
|
|
|
@plugins_bp.route('/install-local', methods=['POST'])
|
|
@jwt_required()
|
|
def install_plugin_local():
|
|
"""Install a plugin from a local directory on the panel host.
|
|
|
|
Body: { "path": "/abs/path/to/plugin-folder" }
|
|
|
|
Intended for plugin development: point at the working tree, install,
|
|
iterate. The path must exist on the panel host's filesystem and
|
|
contain a plugin.json. The folder is zipped in memory and run
|
|
through the same install pipeline as URL/upload installs, so
|
|
behavior matches.
|
|
"""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
data = request.get_json() or {}
|
|
path = (data.get('path') or '').strip()
|
|
if not path:
|
|
return jsonify({'error': 'path required'}), 400
|
|
|
|
from app.services.plugin_service import install_from_path
|
|
try:
|
|
plugin = install_from_path(path, user_id=user.id)
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_CREATE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin.id,
|
|
details={'name': plugin.name, 'version': plugin.version, 'path': path, 'source': 'local'}
|
|
)
|
|
return jsonify(plugin.to_dict()), 201
|
|
except ValueError as e:
|
|
return jsonify({'error': str(e)}), 400
|
|
except Exception:
|
|
# Log full traceback server-side; details go to the InstalledPlugin
|
|
# row's error_message field. Don't echo raw exceptions to the
|
|
# client — they can leak filesystem paths, library versions, or
|
|
# SQL fragments.
|
|
import logging, uuid
|
|
ref = uuid.uuid4().hex[:8]
|
|
logging.getLogger(__name__).exception(
|
|
'Plugin install failed (ref=%s)', ref
|
|
)
|
|
return jsonify({
|
|
'error': 'Installation failed. Check server logs.',
|
|
'ref': ref,
|
|
}), 500
|
|
|
|
|
|
@plugins_bp.route('/install-upload', methods=['POST'])
|
|
@jwt_required()
|
|
def install_plugin_upload():
|
|
"""Install a plugin from an uploaded zip file.
|
|
|
|
Multipart: file=<plugin.zip>
|
|
|
|
Cap at 50 MB. Anything that needs to be bigger probably belongs in
|
|
a release artifact installed via /install instead.
|
|
"""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
if 'file' not in request.files:
|
|
return jsonify({'error': 'No file uploaded (use multipart field "file")'}), 400
|
|
|
|
f = request.files['file']
|
|
if not f or not f.filename:
|
|
return jsonify({'error': 'No file uploaded'}), 400
|
|
|
|
raw = f.read()
|
|
max_bytes = 50 * 1024 * 1024
|
|
if len(raw) > max_bytes:
|
|
return jsonify({'error': f'Upload exceeds {max_bytes // (1024 * 1024)} MB cap'}), 413
|
|
|
|
from app.services.plugin_service import install_from_zip
|
|
try:
|
|
plugin = install_from_zip(raw, user_id=user.id, source_name=f.filename)
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_CREATE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin.id,
|
|
details={
|
|
'name': plugin.name, 'version': plugin.version,
|
|
'filename': f.filename, 'source': 'upload',
|
|
}
|
|
)
|
|
return jsonify(plugin.to_dict()), 201
|
|
except ValueError as e:
|
|
return jsonify({'error': str(e)}), 400
|
|
except Exception:
|
|
# Log full traceback server-side; details go to the InstalledPlugin
|
|
# row's error_message field. Don't echo raw exceptions to the
|
|
# client — they can leak filesystem paths, library versions, or
|
|
# SQL fragments.
|
|
import logging, uuid
|
|
ref = uuid.uuid4().hex[:8]
|
|
logging.getLogger(__name__).exception(
|
|
'Plugin install failed (ref=%s)', ref
|
|
)
|
|
return jsonify({
|
|
'error': 'Installation failed. Check server logs.',
|
|
'ref': ref,
|
|
}), 500
|
|
|
|
|
|
@plugins_bp.route('/<int:plugin_id>', methods=['DELETE'])
|
|
@jwt_required()
|
|
def uninstall_plugin(plugin_id):
|
|
"""Uninstall a plugin (removes files and DB record)."""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
from app.services.plugin_service import uninstall_plugin, get_plugin
|
|
plugin = get_plugin(plugin_id)
|
|
if not plugin:
|
|
return jsonify({'error': 'Plugin not found'}), 404
|
|
|
|
plugin_name = plugin.name
|
|
uninstall_plugin(plugin_id)
|
|
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_DELETE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin_id,
|
|
details={'name': plugin_name}
|
|
)
|
|
return jsonify({'message': f'Plugin {plugin_name} uninstalled. Restart to fully unload backend routes.'})
|
|
|
|
|
|
@plugins_bp.route('/<int:plugin_id>/enable', methods=['POST'])
|
|
@jwt_required()
|
|
def enable_plugin(plugin_id):
|
|
"""Enable a disabled plugin."""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
from app.services.plugin_service import enable_plugin
|
|
plugin = enable_plugin(plugin_id)
|
|
if not plugin:
|
|
return jsonify({'error': 'Plugin not found'}), 404
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_ENABLE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin.id,
|
|
details={'name': plugin.name, 'version': plugin.version},
|
|
)
|
|
return jsonify(plugin.to_dict())
|
|
|
|
|
|
@plugins_bp.route('/<int:plugin_id>/disable', methods=['POST'])
|
|
@jwt_required()
|
|
def disable_plugin(plugin_id):
|
|
"""Disable a plugin without removing it."""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
from app.services.plugin_service import disable_plugin
|
|
plugin = disable_plugin(plugin_id)
|
|
if not plugin:
|
|
return jsonify({'error': 'Plugin not found'}), 404
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_DISABLE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin.id,
|
|
details={'name': plugin.name, 'version': plugin.version},
|
|
)
|
|
return jsonify(plugin.to_dict())
|
|
|
|
|
|
@plugins_bp.route('/builtin', methods=['GET'])
|
|
@jwt_required()
|
|
def list_builtin():
|
|
"""Enumerate bundled extensions in BUILTIN_EXTENSIONS_DIR.
|
|
|
|
Used by the Marketplace UI to show one-click installs for plugins
|
|
that ship with the repo (e.g. the Git extension) without making the
|
|
user paste an absolute path.
|
|
"""
|
|
from app.services.plugin_service import list_builtin_extensions
|
|
return jsonify({'builtin': list_builtin_extensions()})
|
|
|
|
|
|
@plugins_bp.route('/builtin/<slug>/install', methods=['POST'])
|
|
@jwt_required()
|
|
def install_builtin(slug):
|
|
"""Install a bundled extension by slug.
|
|
|
|
Mirror of /plugins/install — admin-only, since this writes to disk
|
|
and may execute lifecycle hooks.
|
|
"""
|
|
user = get_current_user()
|
|
if not user or not user.is_admin:
|
|
return jsonify({'error': 'Admin access required'}), 403
|
|
|
|
from app.services.plugin_service import install_builtin_extension
|
|
try:
|
|
plugin = install_builtin_extension(slug, user_id=user.id)
|
|
AuditService.log(
|
|
action=AuditLog.ACTION_RESOURCE_CREATE,
|
|
user_id=user.id,
|
|
target_type='plugin',
|
|
target_id=plugin.id,
|
|
details={'name': plugin.name, 'version': plugin.version, 'source': 'builtin'},
|
|
)
|
|
return jsonify(plugin.to_dict()), 201
|
|
except ValueError as e:
|
|
return jsonify({'error': str(e)}), 400
|
|
except Exception:
|
|
# Log full traceback server-side; details go to the InstalledPlugin
|
|
# row's error_message field. Don't echo raw exceptions to the
|
|
# client — they can leak filesystem paths, library versions, or
|
|
# SQL fragments.
|
|
import logging, uuid
|
|
ref = uuid.uuid4().hex[:8]
|
|
logging.getLogger(__name__).exception(
|
|
'Plugin install failed (ref=%s)', ref
|
|
)
|
|
return jsonify({
|
|
'error': 'Installation failed. Check server logs.',
|
|
'ref': ref,
|
|
}), 500
|
|
|
|
|
|
@plugins_bp.route('/manifest-spec', methods=['GET'])
|
|
@jwt_required()
|
|
def get_manifest_spec():
|
|
"""Return the documented plugin.json contract.
|
|
|
|
Used by SDK tooling, marketplace submissions, and the in-panel
|
|
plugin developer UI to validate a manifest before install. The
|
|
spec mirrors what `plugin_service` actually consumes — keep them
|
|
in sync when extending the contract.
|
|
"""
|
|
return jsonify({
|
|
'schema_version': '1.0',
|
|
'required': ['name', 'display_name', 'version'],
|
|
'fields': {
|
|
'name': {'type': 'string', 'pattern': '^[a-zA-Z0-9_-]+$',
|
|
'description': 'Filesystem-safe slug; also used as URL prefix default.'},
|
|
'display_name': {'type': 'string'},
|
|
'slug': {'type': 'string', 'description': 'Optional; defaults to `name`.'},
|
|
'version': {'type': 'string', 'description': 'Semver recommended.'},
|
|
'description': {'type': 'string'},
|
|
'author': {'type': 'string'},
|
|
'homepage': {'type': 'string'},
|
|
'repository': {'type': 'string'},
|
|
'license': {'type': 'string'},
|
|
'category': {'type': 'string',
|
|
'description': "monitoring|security|deployment|integration|ui|utility"},
|
|
'entry_point': {'type': 'string',
|
|
'description': "Backend blueprint ref, format 'module:bp_var'."},
|
|
'url_prefix': {'type': 'string',
|
|
'description': 'Defaults to /api/v1/<slug>.'},
|
|
'frontend_entry': {'type': 'string',
|
|
'description': 'Optional path within the frontend bundle (informational).'},
|
|
'permissions': {'type': 'array', 'items': {'type': 'string'},
|
|
'description': 'Declared host permissions (docker, shell, filesystem, network, db). Informational; surfaced to admins on install.'},
|
|
'templates': {'type': 'array',
|
|
'description': 'App-template ids to install on plugin install. String or {id, app_name?, variables?}.'},
|
|
'lifecycle': {'type': 'object',
|
|
'properties': {
|
|
'install': {'type': 'string', 'description': "module:func — runs after install."},
|
|
'uninstall': {'type': 'string', 'description': "module:func — runs before uninstall."},
|
|
}},
|
|
'contributions': {
|
|
'type': 'object',
|
|
'properties': {
|
|
'nav': {'type': 'array', 'description': 'Sidebar items: {id, label, route, category, icon}.'},
|
|
'routes': {'type': 'array',
|
|
'description': 'SPA routes: {path, component, layout?}. component matches a named export of the plugin index module. layout: padded (default) | full | bare | <custom-layout-id>.'},
|
|
'page_titles': {'type': 'object', 'description': 'Map of route path → document title.'},
|
|
'command_palette': {'type': 'array', 'description': '{label, path, category, keywords}.'},
|
|
'widgets': {'type': 'array', 'description': '{slot, component}. slot=global renders globally inside DashboardLayout.'},
|
|
'layouts': {'type': 'array',
|
|
'description': 'Custom layout components: {id, component}. The component must render <Outlet/> somewhere; it wraps every route that references its id. Built-in layouts (padded, full, bare) are reserved.'},
|
|
},
|
|
},
|
|
},
|
|
'example': {
|
|
'name': 'serverkit-git',
|
|
'display_name': 'Git Server',
|
|
'version': '1.0.0',
|
|
'entry_point': 'blueprint:git_bp',
|
|
'url_prefix': '/api/v1/git',
|
|
'permissions': ['docker', 'filesystem'],
|
|
'templates': ['gitea'],
|
|
'lifecycle': {'install': 'lifecycle:on_install'},
|
|
'contributions': {
|
|
'nav': [{'id': 'git', 'label': 'Git', 'route': '/git',
|
|
'category': 'infrastructure',
|
|
'icon': '<circle cx="18" cy="18" r="3"/>'}],
|
|
'routes': [
|
|
{'path': 'git', 'component': 'GitPage'},
|
|
{'path': 'git/:tab', 'component': 'GitPage'},
|
|
],
|
|
'page_titles': {'/git': 'Git Repositories'},
|
|
'command_palette': [
|
|
{'label': 'Git', 'path': '/git', 'category': 'Pages',
|
|
'keywords': 'repos deploy'},
|
|
],
|
|
},
|
|
},
|
|
})
|
|
|
|
|
|
@plugins_bp.route('/contributions', methods=['GET'])
|
|
@jwt_required()
|
|
def get_contributions():
|
|
"""Return merged UI contributions from all active plugins.
|
|
|
|
Shape:
|
|
{
|
|
"nav": [...],
|
|
"routes": [...],
|
|
"page_titles": {...},
|
|
"command_palette": [...],
|
|
"widgets": [...]
|
|
}
|
|
|
|
Each item in the lists carries a `plugin` field with the source slug
|
|
so the frontend can resolve component references against the correct
|
|
plugin module.
|
|
"""
|
|
from app.services.contribution_service import get_active_contributions
|
|
return jsonify(get_active_contributions())
|