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.

fix(ai): enforce resource access and bounded protected chat

Juan Denis6bf34903459a
diff --git a/backend/app/api/ai.py b/backend/app/api/ai.py
index a99375bc..a15f51e0 100644
--- a/backend/app/api/ai.py
+++ b/backend/app/api/ai.py
@@ -28,7 +28,8 @@ import queue
import threading
from flask import Blueprint, Response, current_app, jsonify, request, stream_with_context
-from flask_jwt_extended import jwt_required
+from flask_jwt_extended import get_jwt, jwt_required
+from werkzeug.exceptions import RequestEntityTooLarge, TooManyRequests
from app import db
from app.middleware.rbac import admin_required, get_current_user
@@ -40,11 +41,52 @@ from app.services.ai_attachment_registry import (
)
from app.services.ai_tool_registry import ai_tool_registry
from app.error_reporting import unexpected_response
+from app.exceptions import DependencyUnavailableError, ValidationError
logger = logging.getLogger(__name__)
ai_bp = Blueprint('ai', __name__)
HEARTBEAT_SECONDS = 15
+MAX_CHAT_BODY_BYTES = 128 * 1024
+MAX_MESSAGE_CHARS = 16000
+MAX_CONTEXT_CHARS = 16000
+MAX_ACTIVE_TURNS = 8
+_turn_lock = threading.Lock()
+_active_turns = set()
+
+
+@ai_bp.before_request
+def _bound_chat_body():
+ if request.endpoint in ('ai.chat', 'ai.chat_stream'):
+ if request.content_length and request.content_length > MAX_CHAT_BODY_BYTES:
+ raise RequestEntityTooLarge('AI request is too large')
+ # Bound chunked bodies too, before JSON parsing allocates the payload.
+ request.max_content_length = MAX_CHAT_BODY_BYTES
+
+
+def _claim_turn(user_id):
+ with _turn_lock:
+ if user_id in _active_turns or len(_active_turns) >= MAX_ACTIVE_TURNS:
+ return False
+ _active_turns.add(user_id)
+ return True
+
+
+def _release_turn(user_id):
+ with _turn_lock:
+ _active_turns.discard(user_id)
+
+
+def _validate_chat_data(data):
+ if not isinstance(data, dict) or not isinstance(data.get('message'), str):
+ return 'message must be a string'
+ if len(data['message']) > MAX_MESSAGE_CHARS:
+ return 'message is too long'
+ context = data.get('page_context') or {}
+ if not isinstance(context, dict) or len(json.dumps(context)) > MAX_CONTEXT_CHARS:
+ return 'page_context must be a small object'
+ if data.get('mode', 'assistant') not in ('assistant', 'simple'):
+ return 'Invalid assistant mode'
# ---------------------------------------------------------------------------
@@ -203,6 +245,7 @@ def tools():
'qualified_name': d.qualified_name, 'name': d.name, 'description': d.description,
'plugin_slug': d.plugin_slug, 'rbac_feature': d.rbac_feature,
'rbac_level': d.rbac_level, 'is_write': d.is_write,
+ 'admin_only': d.admin_only,
}
for d in ai_tool_registry.all_descriptors()
]})
@@ -287,6 +330,9 @@ def chat():
if not ai_service.is_configured():
return jsonify({'error': 'AI assistant is not configured'}), 503
data = request.get_json(silent=True) or {}
+ invalid = _validate_chat_data(data)
+ if invalid:
+ raise ValidationError(invalid)
message = (data.get('message') or '').strip()
if not message:
return jsonify({'error': 'message is required'}), 400
@@ -300,12 +346,24 @@ def chat():
if row is None:
return jsonify({'error': 'Conversation not found'}), 404
- if ai_service.injection_flagged(message):
- return jsonify({'error': 'Your message was flagged by the prompt-injection guardrail.'}), 400
+ try:
+ if ai_service.injection_flagged(message):
+ raise ValidationError('Your message was flagged by the prompt-injection guardrail.')
+ safe_message = ai_service.redact_input(message)
+ except ai_service.AIProtectionError as exc:
+ raise DependencyUnavailableError(str(exc)) from exc
+
+ if not _claim_turn(user.id):
+ raise TooManyRequests('AI is busy. Wait for the current turn to finish.')
+ try:
+ return _run_chat(row, user, mode, page_context, attachment_refs, message, safe_message)
+ finally:
+ _release_turn(user.id)
+
+def _run_chat(row, user, mode, page_context, attachment_refs, message, safe_message):
attachment_result = resolve_attachments(user, attachment_refs)
_persist_user_message(row, message, attachments=attachment_result['manifest'])
- safe_message = ai_service.redact_input(message)
try:
# gate=None: write tools refuse (no interactive confirmation in this mode).
conv = ai_service.build_conversation(
@@ -313,6 +371,8 @@ def chat():
attachment_context=attachment_result['context'],
)
reply = conv.ask(safe_message)
+ except ai_service.AIProtectionError as exc:
+ raise DependencyUnavailableError(str(exc)) from exc
except Exception as exc: # noqa: BLE001 - reported, not swallowed
return unexpected_response(exc)
@@ -337,6 +397,9 @@ def chat_stream():
if not ai_service.is_configured():
return jsonify({'error': 'AI assistant is not configured'}), 503
data = request.get_json(silent=True) or {}
+ invalid = _validate_chat_data(data)
+ if invalid:
+ raise ValidationError(invalid)
message = (data.get('message') or '').strip()
if not message:
return jsonify({'error': 'message is required'}), 400
@@ -361,21 +424,35 @@ def chat_stream():
attachment_result = resolve_attachments(user, attachment_refs)
_persist_user_message(row, message, attachments=attachment_result['manifest'])
- flagged = ai_service.injection_flagged(message)
- safe_message = ai_service.redact_input(message)
+ try:
+ flagged = ai_service.injection_flagged(message)
+ safe_message = ai_service.redact_input(message)
+ except ai_service.AIProtectionError as exc:
+ raise DependencyUnavailableError(str(exc)) from exc
+ if not _claim_turn(user_id):
+ raise TooManyRequests('AI is busy. Wait for the current turn to finish.')
+ claims = dict(get_jwt())
q: "queue.Queue" = queue.Queue(maxsize=512)
cancel_event = threading.Event()
def emit(event_name: str, payload: dict) -> None:
- q.put(('frame', (event_name, payload)))
+ enqueue(('frame', (event_name, payload)))
+
+ def enqueue(item):
+ while not cancel_event.is_set():
+ try:
+ q.put(item, timeout=0.25)
+ return
+ except queue.Full:
+ continue
gate = ai_service.ConfirmationGate(conversation_id, user_id, emit, cancel_event, ttl)
+ gate.session_claims = claims
ai_service.register_gate(conversation_id, gate)
def producer():
with app.app_context():
- from app.models.user import User
acc_text: list[str] = []
tool_calls: dict[str, dict] = {}
tool_order: list[str] = []
@@ -387,7 +464,11 @@ def chat_stream():
return
conv_row = db.session.get(AiConversation, conversation_id)
- conv_user = db.session.get(User, user_id)
+ from app.middleware.session_auth import validate_session_claims
+ conv_user = validate_session_claims(claims)
+ if conv_user is None or conv_row is None:
+ emit('error', {'message': 'Your session is no longer authorized.'})
+ return
conv = ai_service.build_conversation(
conv_row, conv_user, mode, page_context, gate,
attachment_context=attachment_result['context'],
@@ -423,9 +504,10 @@ def chat_stream():
emit(name, payload)
except Exception as exc:
logger.exception("AI stream worker failed")
- emit('error', {'message': str(exc)})
+ emit('error', {'message': str(exc) if isinstance(exc, ai_service.AIProtectionError)
+ else 'AI request failed. Please try again.'})
finally:
- ai_service.unregister_gate(conversation_id)
+ ai_service.unregister_gate(conversation_id, gate)
try:
text = ''.join(acc_text)
if text or tool_order:
@@ -440,18 +522,25 @@ def chat_stream():
ai_service.persist_conversation(conv_row, conv, page_context=page_context)
except Exception:
logger.warning("Failed to persist assistant turn", exc_info=True)
- q.put(('frame', ('done', {'conversation_id': conversation_id, 'usage': last_usage})))
- q.put(('end', None))
+ emit('done', {'conversation_id': conversation_id, 'usage': last_usage})
+ enqueue(('end', None))
+ _release_turn(user_id)
- threading.Thread(target=producer, daemon=True).start()
+ try:
+ threading.Thread(target=producer, daemon=True).start()
+ except Exception:
+ gate.cancel_all()
+ ai_service.unregister_gate(conversation_id, gate)
+ _release_turn(user_id)
+ raise
@stream_with_context
def gen():
- yield _sse('open', {'conversation_id': conversation_id})
- for warning in attachment_result['warnings']:
- yield _sse('attachment_warning', warning)
try:
- while True:
+ yield _sse('open', {'conversation_id': conversation_id})
+ for warning in attachment_result['warnings']:
+ yield _sse('attachment_warning', warning)
+ while not cancel_event.is_set():
try:
kind, payload = q.get(timeout=HEARTBEAT_SECONDS)
except queue.Empty:
@@ -464,7 +553,7 @@ def chat_stream():
finally:
cancel_event.set()
gate.cancel_all()
- ai_service.unregister_gate(conversation_id)
+ ai_service.unregister_gate(conversation_id, gate)
return Response(gen(), mimetype='text/event-stream', headers={
'Cache-Control': 'no-cache',
@@ -487,7 +576,7 @@ def chat_confirm():
return jsonify({'error': 'Conversation not found'}), 404
# Validate the pending action belongs to this user and is still actionable.
pending = db.session.get(AiPendingAction, token)
- if pending is None or pending.user_id != user.id:
+ if pending is None or pending.user_id != user.id or pending.conversation_id != conversation_id:
return jsonify({'error': 'Pending action not found'}), 404
if pending.status != AiPendingAction.STATUS_PENDING or pending.is_expired():
return jsonify({'error': 'Pending action is no longer actionable'}), 409
diff --git a/backend/app/services/ai_service.py b/backend/app/services/ai_service.py
index c12f9075..b5881752 100644
--- a/backend/app/services/ai_service.py
+++ b/backend/app/services/ai_service.py
@@ -22,6 +22,7 @@ from __future__ import annotations
import dataclasses
import json
import logging
+import re
import secrets
import threading
from typing import TYPE_CHECKING, Any, Callable, Iterator, Optional
@@ -289,8 +290,27 @@ def injection_flagged(text: str) -> bool:
return False
try:
return bool(_get_injection_detector().is_injection(text))
- except Exception:
- return False
+ except Exception as exc:
+ raise AIProtectionError('AI injection protection is unavailable. Please try again later.') from exc
+
+
+class AIProtectionError(RuntimeError):
+ """Enabled protection failed; never send the original data as a fallback."""
+
+
+def _filter_secrets(text: str) -> str:
+ """Deterministic credential filtering, independent of optional PII detection."""
+ text = re.sub(r'-----BEGIN [^-]*PRIVATE KEY-----.*?-----END [^-]*PRIVATE KEY-----',
+ '[redacted]', text, flags=re.DOTALL)
+ text = re.sub(r'(?i)\b(Bearer|Basic)\s+[A-Za-z0-9_./+=-]+', r'\1 [redacted]', text)
+ text = re.sub(r'(?i)([a-z][a-z0-9+.-]*://)[^\s/@:]+:[^\s/@]+@',
+ r'\1[redacted]@', text)
+ # Handle assignments in log lines, pasted config, URLs and serialized JSON.
+ from app.utils.sensitive_data_filter import SENSITIVE_KEY_PARTS
+ parts = '|'.join(re.escape(part) for part in SENSITIVE_KEY_PARTS)
+ pattern = (r'(?i)([\w.-]*(?:' + parts + r')[\w.-]*["\x27]?\s*[:=]\s*)'
+ r'(?:"[^"\n]*"|\x27[^\x27\n]*\x27|[^\s,;&}\]]+)')
+ return re.sub(pattern, r'\1[redacted]', text)
def _pii_enabled() -> bool:
@@ -298,21 +318,30 @@ def _pii_enabled() -> bool:
def redact_input(text: str) -> str:
+ text = _filter_secrets(text)
if not _pii_enabled():
return text
try:
return _get_pii_redactor().redact(text).text
- except Exception:
- return text
+ except Exception as exc:
+ raise AIProtectionError('AI privacy protection is unavailable. Please try again later.') from exc
def _maybe_redact_result(result: Any) -> Any:
- if not _pii_enabled() or not isinstance(result, str):
- return result
- try:
- return _get_pii_redactor().redact(result).text
- except Exception:
- return result
+ from app.utils.sensitive_data_filter import mask_payload
+
+ def walk(value):
+ if isinstance(value, dict):
+ return {redact_input(str(k)): walk(v) for k, v in value.items()}
+ if isinstance(value, (list, tuple)):
+ return [walk(item) for item in value]
+ if isinstance(value, str):
+ return redact_input(value)
+ if value is None or isinstance(value, (bool, int, float)):
+ return value
+ return redact_input(str(value))
+
+ return walk(mask_payload(result))
# ===========================================================================
@@ -356,7 +385,7 @@ def build_system_prompt(user, mode: str, page_context: Optional[dict],
f"\nThe operator's role is '{role}'. Do not offer or attempt actions they "
"lack permission for; tools you cannot see are unavailable to this user."
)
- return "".join(parts)
+ return redact_input("".join(parts))
# ===========================================================================
@@ -370,24 +399,70 @@ def build_tool_registry(user, mode: str, gate: Optional["ConfirmationGate"]) ->
reg = ToolRegistry()
for d in descriptors:
- fn = _make_write_wrapper(d, user, gate) if d.is_write else _make_read_wrapper(d, user)
+ fn = (_make_write_wrapper(d, user, gate) if d.is_write else
+ _make_read_wrapper(d, user, session_claims=getattr(gate, 'session_claims', None)))
reg.add(ToolDefinition(name=d.qualified_name, description=d.description,
parameters=d.parameters, function=fn))
return reg
-def _make_read_wrapper(descriptor, user) -> Callable[..., Any]:
+def _caller_validator(user, claims=None):
+ """Capture authentication before a long model/confirmation wait."""
+ from flask import has_request_context
+ from flask_jwt_extended import get_jwt
+ uid = getattr(user, 'id', None)
+ version = getattr(user, 'auth_version', None)
+ if claims is None and has_request_context():
+ try:
+ claims = get_jwt()
+ except RuntimeError:
+ claims = None # In-process plugin callers may have no JWT.
+
+ def validate():
+ if claims:
+ from app.middleware.session_auth import validate_session_claims
+ return validate_session_claims(claims)
+ from app.models.user import User
+ fresh = db.session.get(User, uid, populate_existing=True) if uid is not None else None
+ if fresh is None or not fresh.is_active or getattr(fresh, 'auth_version', None) != version:
+ return None
+ return fresh
+ return validate
+
+
+def _invoke_tool(descriptor, user, kwargs):
+ from app.services.ai_tools_builtin import tool_caller
+ token = tool_caller.set(user)
+ try:
+ return descriptor.func(**kwargs)
+ finally:
+ tool_caller.reset(token)
+
+
+def _make_read_wrapper(descriptor, user, session_claims=None) -> Callable[..., Any]:
+ validate = _caller_validator(user, session_claims)
def wrapper(**kwargs):
- if not descriptor.allowed_for(user):
+ caller = validate()
+ if caller is None or not descriptor.allowed_for(caller):
return f"Permission denied: you lack {descriptor.rbac_feature} {descriptor.rbac_level} access."
- result = descriptor.func(**kwargs)
- return _maybe_redact_result(result)
+ try:
+ result = _invoke_tool(descriptor, caller, kwargs)
+ return _maybe_redact_result(result)
+ except AIProtectionError:
+ raise
+ except Exception:
+ # Provider SDKs commonly turn exception text into tool output.
+ # Service exception messages can contain credentials/connection URLs.
+ logger.warning('AI read tool %s failed', descriptor.qualified_name)
+ return 'The tool failed to retrieve data.'
return wrapper
def _make_write_wrapper(descriptor, user, gate: Optional["ConfirmationGate"]) -> Callable[..., Any]:
+ validate = _caller_validator(user, getattr(gate, 'session_claims', None))
def wrapper(**kwargs):
- if not descriptor.allowed_for(user):
+ caller = validate()
+ if caller is None or not descriptor.allowed_for(caller):
return f"Permission denied: you lack {descriptor.rbac_feature} write access."
if gate is None:
return ("This is a state-changing action and needs explicit confirmation. "
@@ -395,15 +470,25 @@ def _make_write_wrapper(descriptor, user, gate: Optional["ConfirmationGate"]) ->
decision, token = gate.request_confirmation(descriptor, kwargs)
if decision != "approve":
return f"The user declined to run '{descriptor.name}'."
+ caller = validate()
+ if gate.is_cancelled() or caller is None or not descriptor.allowed_for(caller):
+ gate.mark_failed(token, 'Authorization changed or the stream was cancelled.')
+ return 'Permission denied: authorization changed or the stream was cancelled.'
try:
- result = descriptor.func(**kwargs)
+ result = _maybe_redact_result(_invoke_tool(descriptor, caller, kwargs))
+ if isinstance(result, dict) and (result.get('success') is False or result.get('ok') is False):
+ gate.mark_failed(token, 'The service reported that the action failed.')
+ _audit_tool_execute(descriptor, kwargs, caller, ok=False, error='Service action failed')
+ return result
gate.mark_executed(token, result)
_audit_tool_execute(descriptor, kwargs, user, ok=True)
return result
except Exception as exc:
- gate.mark_failed(token, str(exc))
- _audit_tool_execute(descriptor, kwargs, user, ok=False, error=str(exc))
- return f"Action '{descriptor.name}' failed: {exc}"
+ error = ('AI privacy protection failed after execution; the action may have completed.'
+ if isinstance(exc, AIProtectionError) else 'The action failed.')
+ gate.mark_failed(token, error)
+ _audit_tool_execute(descriptor, kwargs, caller, ok=False, error=error)
+ return error
return wrapper
@@ -444,7 +529,7 @@ def build_conversation(row, user, mode: str, page_context: Optional[dict],
)
export = row.export
if export:
- conv = Conversation.from_export(export, tools=registry)
+ conv = Conversation.from_export(_maybe_redact_result(export), tools=registry)
conv.system_prompt = system # refresh page context each turn
return conv
return Conversation(
@@ -558,11 +643,15 @@ class ConfirmationGate:
self._ttl = ttl_seconds
self._pending: dict[str, dict] = {}
self._lock = threading.Lock()
+ self.session_claims = None
def request_confirmation(self, descriptor, params: dict) -> tuple[str, str]:
"""Block until the user approves/denies. Returns ('approve'|'deny', token)."""
from app.models.ai import AiPendingAction
+ if self._cancel.is_set():
+ return 'deny', ''
+
token = secrets.token_urlsafe(16)
summary = summarize_action(descriptor, params)
row = AiPendingAction(
@@ -578,6 +667,7 @@ class ConfirmationGate:
except Exception:
db.session.rollback()
logger.warning("Failed to persist pending action", exc_info=True)
+ return 'deny', token
ev = threading.Event()
with self._lock:
@@ -616,6 +706,9 @@ class ConfirmationGate:
with self._lock:
return bool(self._pending)
+ def is_cancelled(self) -> bool:
+ return self._cancel.is_set()
+
def cancel_all(self) -> None:
"""Deny and unblock every confirmation when a stream disconnects."""
self._cancel.set()
@@ -657,9 +750,10 @@ def register_gate(conversation_id: str, gate: ConfirmationGate) -> None:
_active_gates[conversation_id] = gate
-def unregister_gate(conversation_id: str) -> None:
+def unregister_gate(conversation_id: str, gate: Optional[ConfirmationGate] = None) -> None:
with _gates_lock:
- _active_gates.pop(conversation_id, None)
+ if gate is None or _active_gates.get(conversation_id) is gate:
+ _active_gates.pop(conversation_id, None)
def resolve_pending(conversation_id: str, token: str, decision: str) -> bool:
diff --git a/backend/app/services/ai_tool_registry.py b/backend/app/services/ai_tool_registry.py
index 3ded15d5..71fa8597 100644
--- a/backend/app/services/ai_tool_registry.py
+++ b/backend/app/services/ai_tool_registry.py
@@ -48,9 +48,14 @@ class ToolDescriptor:
rbac_feature: Optional[str] = None # e.g. 'docker'; None => any authenticated user
rbac_level: str = "read" # 'read' | 'write'
is_write: bool = False # write tools go through the confirmation handshake
+ admin_only: bool = False # raw host operations mirror REST's admin gate
def allowed_for(self, user) -> bool:
"""True if *user* may use this tool given its RBAC tagging."""
+ if user is None or not getattr(user, 'is_active', True):
+ return False
+ if self.admin_only and not getattr(user, 'is_admin', False):
+ return False
if self.rbac_feature is None:
return True
try:
@@ -104,6 +109,7 @@ class AiToolRegistry:
rbac_feature: Optional[str] = None,
rbac_level: str = "read",
is_write: bool = False,
+ admin_only: bool = False,
) -> ToolDescriptor:
"""Register a tool callable. Idempotent per qualified name (re-register overwrites)."""
prefix = plugin_slug or CORE_PREFIX
@@ -125,6 +131,7 @@ class AiToolRegistry:
rbac_feature=rbac_feature,
rbac_level=("write" if is_write else rbac_level),
is_write=is_write,
+ admin_only=admin_only,
)
with self._mutex:
self._tools[qualified] = descriptor
diff --git a/backend/app/services/ai_tools_builtin.py b/backend/app/services/ai_tools_builtin.py
index e6f75f31..336138bf 100644
--- a/backend/app/services/ai_tools_builtin.py
+++ b/backend/app/services/ai_tools_builtin.py
@@ -16,12 +16,25 @@ Flask app context, so DB/service calls work normally.
from __future__ import annotations
import logging
+from contextvars import ContextVar
from app.services.ai_tool_registry import ai_tool_registry
logger = logging.getLogger(__name__)
_REGISTERED = False
+tool_caller = ContextVar('ai_tool_caller', default=None)
+
+
+def _caller(*, admin=False):
+ user = tool_caller.get()
+ if user is None or not user.is_active or (admin and not user.is_admin):
+ raise PermissionError('Permission denied for this AI tool.')
+ return user
+
+
+def _summary(row, fields):
+ return {field: getattr(row, field, None) for field in fields}
# ---------------------------------------------------------------------------
@@ -44,42 +57,54 @@ def list_docker_containers(include_stopped: bool = True) -> list:
include_stopped: If true, include stopped containers; otherwise only running ones.
"""
from app.services.docker_service import DockerService
- return DockerService.list_containers(all_containers=include_stopped)
+ _caller()
+ rows = DockerService.list_containers(all_containers=include_stopped)
+ fields = ('id', 'name', 'image', 'status', 'state', 'ports', 'protected')
+ return [{key: row.get(key) for key in fields if key in row} for row in rows]
def get_docker_info() -> dict:
"""Get Docker engine status and summary info (version, container/image counts)."""
from app.services.docker_service import DockerService
- return DockerService.get_docker_info()
+ _caller()
+ info = DockerService.get_docker_info() or {}
+ fields = ('ServerVersion', 'Containers', 'ContainersRunning', 'ContainersPaused',
+ 'ContainersStopped', 'Images', 'NCPU', 'MemTotal', 'OperatingSystem',
+ 'version', 'containers', 'images', 'running')
+ return {key: info[key] for key in fields if key in info}
-def list_applications() -> list:
+def list_applications(workspace_id: int = None) -> list:
"""List the web applications managed by this ServerKit panel.
Returns:
A list of apps with name, status, type, and port.
"""
from app.models.application import Application
+ from app.services.workspace_service import WorkspaceService
+ user = _caller()
+ ws_id = WorkspaceService.resolve_workspace_id(user, workspace_id)
# The assistant answers questions about what is RUNNING; a deleted app in
# its context would be reported as though it still existed.
- return [a.to_dict() for a in Application.query_active().all()]
+ query = WorkspaceService.scope_query(
+ Application.query_active(), Application, user, workspace_id=ws_id,
+ owner_attr='user_id', grant_resource_type='application',
+ )
+ return [_summary(a, ('id', 'name', 'status', 'app_type', 'port')) for a in query.all()]
-def list_servers() -> list:
+def list_servers(workspace_id: int = None) -> list:
"""List the servers in this ServerKit fleet (the panel host plus paired agents).
Returns:
A list of servers with name, status, and address.
"""
from app.models.server import Server
- out = []
- for s in Server.query.all():
- if hasattr(s, "to_dict"):
- out.append(s.to_dict())
- else:
- out.append({"id": getattr(s, "id", None), "name": getattr(s, "name", None),
- "status": getattr(s, "status", None)})
- return out
+ from app.services.workspace_service import WorkspaceService
+ user = _caller()
+ ws_id = WorkspaceService.resolve_workspace_id(user, workspace_id)
+ query = WorkspaceService.scope_query(Server.query, Server, user, workspace_id=ws_id)
+ return [_summary(s, ('id', 'name', 'status', 'hostname')) for s in query.all()]
def list_databases() -> dict:
@@ -89,14 +114,15 @@ def list_databases() -> dict:
A dict with the database list, or a message if MySQL is not available.
"""
from app.services.database_service import DatabaseService
+ _caller(admin=True)
try:
if not DatabaseService.mysql_is_installed():
return {"available": False, "message": "MySQL/MariaDB is not installed on this host."}
if not DatabaseService.mysql_is_running():
return {"available": False, "message": "MySQL/MariaDB is installed but not running."}
return {"available": True, "databases": DatabaseService.mysql_list_databases()}
- except Exception as exc: # pragma: no cover - environment dependent
- return {"available": False, "message": f"Could not list databases: {exc}"}
+ except Exception: # pragma: no cover - environment dependent
+ return {"available": False, "message": "Could not list databases on this host."}
# ---------------------------------------------------------------------------
@@ -109,8 +135,10 @@ def restart_docker_container(container_id: str) -> dict:
container_id: The container id or name to restart.
"""
from app.services.docker_service import DockerService
- DockerService.restart_container(container_id)
- return {"ok": True, "action": "restart", "container": container_id}
+ _caller(admin=True)
+ if DockerService.is_protected_container(container_id):
+ raise PermissionError('ServerKit system containers cannot be controlled here.')
+ return DockerService.restart_container(container_id)
def stop_docker_container(container_id: str) -> dict:
@@ -120,8 +148,10 @@ def stop_docker_container(container_id: str) -> dict:
container_id: The container id or name to stop.
"""
from app.services.docker_service import DockerService
- DockerService.stop_container(container_id)
- return {"ok": True, "action": "stop", "container": container_id}
+ _caller(admin=True)
+ if DockerService.is_protected_container(container_id):
+ raise PermissionError('ServerKit system containers cannot be controlled here.')
+ return DockerService.stop_container(container_id)
def register_builtin_tools() -> None:
@@ -152,16 +182,16 @@ def register_builtin_tools() -> None:
)
ai_tool_registry.register(
name="list_databases", func=list_databases,
- rbac_feature="databases", rbac_level="read",
+ rbac_feature="databases", rbac_level="read", admin_only=True,
)
# --- guarded write tools ---
ai_tool_registry.register(
name="restart_docker_container", func=restart_docker_container,
- rbac_feature="docker", is_write=True,
+ rbac_feature="docker", is_write=True, admin_only=True,
)
ai_tool_registry.register(
name="stop_docker_container", func=stop_docker_container,
- rbac_feature="docker", is_write=True,
+ rbac_feature="docker", is_write=True, admin_only=True,
)
_REGISTERED = True
diff --git a/backend/tests/test_ai_security_boundaries.py b/backend/tests/test_ai_security_boundaries.py
new file mode 100644
index 00000000..5911ab93
--- /dev/null
+++ b/backend/tests/test_ai_security_boundaries.py
@@ -0,0 +1,335 @@
+"""Offline regressions for AI authorization and provider-boundary protection."""
+import json
+import threading
+from types import SimpleNamespace
+
+import pytest
+
+from app import db
+from app.services import ai_service
+from app.services.ai_tool_registry import ToolDescriptor, ai_tool_registry
+from app.services.ai_tools_builtin import register_builtin_tools, tool_caller
+from factories import headers_for, make_application, make_server, make_user, make_workspace
+
+
+def no_pii(monkeypatch):
+ monkeypatch.setattr(ai_service, '_pii_enabled', lambda: False)
+
+
+def descriptor(func, *, write=False):
+ return ToolDescriptor('probe', 'probe__probe', func, 'Security probe', {},
+ plugin_slug='probe', is_write=write)
+
+
+def test_ai_app_list_matches_rest_visibility_and_omits_config(app, client, no_pii):
+ from app.services.resource_grant_service import ResourceGrantService
+ with app.app_context():
+ viewer = make_user(db, role='viewer')
+ owner = make_user(db)
+ admin = make_user(db, role='admin')
+ own = make_application(db, name='own', user_id=viewer.id)
+ shared = make_application(db, name='shared', user_id=owner.id)
+ foreign = make_application(db, name='foreign', user_id=owner.id)
+ deleted = make_application(db, name='deleted', user_id=viewer.id)
+ from datetime import datetime
+ deleted.deleted_at = datetime.utcnow()
+ db.session.commit()
+ ResourceGrantService.grant(viewer.id, 'application', shared.id, role='viewer')
+ register_builtin_tools()
+ d = ai_tool_registry.get('core__list_applications')
+ result = ai_service._make_read_wrapper(d, viewer)()
+ assert {r['id'] for r in result} == {own.id, shared.id}
+ assert all(set(r) == {'id', 'name', 'status', 'app_type', 'port'} for r in result)
+ assert client.get(f'/api/v1/apps/{foreign.id}', headers=headers_for(viewer)).status_code == 403
+ assert client.get(f'/api/v1/apps/{shared.id}', headers=headers_for(viewer)).status_code == 200
+ assert {r['id'] for r in ai_service._make_read_wrapper(d, admin)()} == {
+ own.id, shared.id, foreign.id,
+ }
+ assert tool_caller.get() is None
+
+
+def test_workspace_membership_does_not_grant_foreign_apps(app, no_pii):
+ from app.models.workspace import WorkspaceMember
+ with app.app_context():
+ viewer = make_user(db, role='viewer')
+ owner = make_user(db)
+ ws = make_workspace(db, created_by=owner.id)
+ db.session.add(WorkspaceMember(workspace_id=ws.id, user_id=viewer.id, role='member'))
+ db.session.commit()
+ mine = make_application(db, user_id=viewer.id, workspace_id=ws.id)
+ make_application(db, user_id=owner.id, workspace_id=ws.id)
+ other = make_application(db, user_id=viewer.id)
+ register_builtin_tools()
+ wrapper = ai_service._make_read_wrapper(ai_tool_registry.get('core__list_applications'), viewer)
+ assert {r['id'] for r in wrapper(workspace_id=ws.id)} == {mine.id}
+ assert {r['id'] for r in wrapper()} == {mine.id, other.id}
+
+
+def test_ai_server_list_uses_workspace_scope_and_summary(app, no_pii):
+ with app.app_context():
+ user = make_user(db, role='admin')
+ ws = make_workspace(db, created_by=user.id)
+ selected = make_server(db, name='selected', workspace_id=ws.id)
+ make_server(db, name='other')
+ register_builtin_tools()
+ result = ai_service._make_read_wrapper(ai_tool_registry.get('core__list_servers'), user)(workspace_id=ws.id)
+ assert [r['id'] for r in result] == [selected.id]
+ assert set(result[0]) == {'id', 'name', 'status', 'hostname'}
+
+
+def test_raw_host_database_and_docker_write_tools_require_admin(app):
+ with app.app_context():
+ developer = make_user(db)
+ register_builtin_tools()
+ for name in ('list_databases', 'stop_docker_container', 'restart_docker_container'):
+ d = ai_tool_registry.get('core__' + name)
+ assert not d.allowed_for(developer)
+ assert 'core__stop_docker_container' not in {
+ d.qualified_name for d in ai_tool_registry.list_for(developer, 'assistant')
+ }
+
+
+class ApprovingGate:
+ def __init__(self, on_approval=lambda: None, cancelled=False):
+ self.on_approval = on_approval
+ self.cancelled = cancelled
+ self.result = None
+ self.failed = False
+
+ def request_confirmation(self, d, params):
+ self.on_approval()
+ return 'approve', 'test-token'
+
+ def is_cancelled(self):
+ return self.cancelled
+
+ def mark_executed(self, token, result):
+ self.result = result
+
+ def mark_failed(self, token, error):
+ self.failed = True
+
+
[email protected]('change', ['disable', 'role', 'session', 'cancel'])
+def test_write_rechecks_caller_after_confirmation(app, no_pii, change):
+ with app.app_context():
+ user = make_user(db, role='admin')
+ called = []
+ d = descriptor(lambda: called.append(True), write=True)
+ d.admin_only = True
+
+ def change_access():
+ if change == 'disable':
+ user.is_active = False
+ elif change == 'role':
+ user.role = 'viewer'
+ elif change == 'session':
+ user.auth_version = 'revoked'
+ db.session.commit()
+
+ gate = ApprovingGate(change_access, cancelled=change == 'cancel')
+ result = ai_service._make_write_wrapper(d, user, gate)()
+ assert not called
+ assert 'Permission denied' in result
+ assert gate.failed
+
+
+def test_protected_docker_container_never_restarts(app, monkeypatch, no_pii):
+ from app.services.docker_service import DockerService
+ with app.app_context():
+ user = make_user(db, role='admin')
+ called = []
+ monkeypatch.setattr(DockerService, 'is_protected_container', lambda cid: True)
+ monkeypatch.setattr(DockerService, 'restart_container', lambda cid: called.append(cid))
+ register_builtin_tools()
+ gate = ApprovingGate()
+ ai_service._make_write_wrapper(ai_tool_registry.get('core__restart_docker_container'), user, gate)(container_id='panel')
+ assert not called
+ assert gate.failed
+
+
+def test_nested_results_redact_secrets_and_pii(monkeypatch):
+ monkeypatch.setattr(ai_service, '_pii_enabled', lambda: True)
+ monkeypatch.setattr(ai_service, '_get_pii_redactor', lambda: SimpleNamespace(
+ redact=lambda value: SimpleNamespace(text=value.replace('[email protected]', '[email]'))))
+ data = {'rows': [{'password': {'value': 'never-send'}, 'email': '[email protected]',
+ 'log': 'password=hidden Authorization: Bearer abcdef'}]}
+ result = ai_service._maybe_redact_result(data)
+ rendered = json.dumps(result)
+ assert all(secret not in rendered for secret in ('never-send', '[email protected]', 'hidden', 'abcdef'))
+ assert data['rows'][0]['password']['value'] == 'never-send'
+
+
+def test_secret_filter_runs_with_pii_disabled(no_pii):
+ for text in ('password=hunter2', 'Authorization: Bearer abcdef',
+ 'mysql://root:dbpass@host/db',
+ '-----BEGIN RSA PRIVATE KEY-----\nsecret\n-----END RSA PRIVATE KEY-----'):
+ safe = ai_service.redact_input(text)
+ assert '[redacted]' in safe
+ assert all(secret not in safe for secret in ('hunter2', 'abcdef', 'dbpass', '\nsecret\n'))
+
+
+def test_read_and_write_result_share_protection(app, no_pii):
+ with app.app_context():
+ user = make_user(db)
+ data = {'items': [{'api_key': 'never-send'}]}
+ read = ai_service._make_read_wrapper(descriptor(lambda: data), user)()
+ gate = ApprovingGate()
+ write = ai_service._make_write_wrapper(descriptor(lambda: data, write=True), user, gate)()
+ assert read == write == gate.result == {'items': [{'api_key': '[redacted]'}]}
+
+
+def test_enabled_protection_failure_never_returns_original(monkeypatch):
+ monkeypatch.setattr(ai_service, '_pii_enabled', lambda: True)
+ def broken():
+ raise RuntimeError('offline')
+ monkeypatch.setattr(ai_service, '_get_pii_redactor', broken)
+ with pytest.raises(ai_service.AIProtectionError):
+ ai_service.redact_input('[email protected]')
+ with pytest.raises(ai_service.AIProtectionError):
+ ai_service._maybe_redact_result({'email': '[email protected]'})
+ monkeypatch.setattr(ai_service, '_setting', lambda key, default=None: True)
+ monkeypatch.setattr(ai_service, '_get_injection_detector', broken)
+ with pytest.raises(ai_service.AIProtectionError):
+ ai_service.injection_flagged('message')
+
+
[email protected]('route', ['/chat', '/chat/stream'])
+def test_chat_bounds_and_visible_protection_failure(client, auth_headers, monkeypatch, route):
+ monkeypatch.setattr(ai_service, 'ensure_initialized', lambda: None)
+ monkeypatch.setattr(ai_service, 'is_configured', lambda: True)
+ path = '/api/v1/ai' + route
+ invalid = client.post(path, headers=auth_headers, json={'message': 42})
+ assert invalid.status_code == 400 and invalid.json['code'] == 'validation_error'
+ assert client.post(path, headers=auth_headers, json={'message': 'x' * 16001}).status_code == 400
+ oversized = client.post(path, headers=auth_headers, json={'message': 'x' * 140000})
+ assert oversized.status_code == 413 and oversized.json['code'] == 'request_entity_too_large'
+ def broken(text):
+ raise ai_service.AIProtectionError('AI privacy protection is unavailable.')
+ monkeypatch.setattr(ai_service, 'injection_flagged', broken)
+ response = client.post(path, headers=auth_headers, json={'message': 'hello'})
+ assert response.status_code == 503
+ assert response.json['code'] == 'dependency_unavailable'
+ assert 'protection is unavailable' in response.json['error']
+
+
[email protected]('route', ['/chat', '/chat/stream'])
+def test_chat_busy_uses_typed_http_error(client, auth_headers, monkeypatch, route):
+ from app.api import ai
+ monkeypatch.setattr(ai_service, 'ensure_initialized', lambda: None)
+ monkeypatch.setattr(ai_service, 'is_configured', lambda: True)
+ monkeypatch.setattr(ai_service, 'injection_flagged', lambda text: False)
+ monkeypatch.setattr(ai_service, 'redact_input', lambda text: text)
+ monkeypatch.setattr(ai, '_claim_turn', lambda uid: False)
+ response = client.post('/api/v1/ai' + route, headers=auth_headers, json={'message': 'hello'})
+ assert response.status_code == 429
+ assert response.json['code'] == 'too_many_requests'
+ assert response.json['error'] == 'AI is busy. Wait for the current turn to finish.'
+ assert response.json['request_id']
+
+
+def test_turn_limits_bound_users_and_panel():
+ from app.api import ai
+ try:
+ for uid in range(ai.MAX_ACTIVE_TURNS):
+ assert ai._claim_turn(uid)
+ assert not ai._claim_turn(0)
+ assert not ai._claim_turn(999)
+ ai._release_turn(0)
+ assert ai._claim_turn(999)
+ finally:
+ for uid in (*range(ai.MAX_ACTIVE_TURNS), 999):
+ ai._release_turn(uid)
+
+
+def test_cancelled_confirmation_does_not_create_pending_action(app):
+ from app.models.ai import AiPendingAction
+ with app.app_context():
+ cancelled = threading.Event()
+ cancelled.set()
+ gate = ai_service.ConfirmationGate('unused', 1, lambda *args: None, cancelled, 5)
+ assert gate.request_confirmation(descriptor(lambda: None), {}) == ('deny', '')
+ assert AiPendingAction.query.count() == 0
+
+
+def test_stream_tool_rejects_logged_out_session_after_approval(app, no_pii):
+ from flask_jwt_extended import create_access_token, decode_token
+ from app.models import RevokedSession
+ with app.app_context():
+ user = make_user(db, role='admin')
+ claims = decode_token(create_access_token(identity=user.id))
+ called = []
+
+ def logout():
+ db.session.add(RevokedSession(session_id=claims['session_id'], user_id=user.id))
+ db.session.commit()
+
+ gate = ApprovingGate(logout)
+ gate.session_claims = claims
+ wrapper = ai_service._make_write_wrapper(descriptor(lambda: called.append(True), write=True), user, gate)
+ assert 'Permission denied' in wrapper()
+ assert not called
+ assert 'Permission denied' in ai_service._make_read_wrapper(
+ descriptor(lambda: called.append(True)), user, session_claims=claims)()
+ assert not called
+
+
+def test_service_failure_is_not_recorded_as_success(app, no_pii):
+ with app.app_context():
+ user = make_user(db)
+ gate = ApprovingGate()
+ output = {'success': False, 'error': 'Service could not restart'}
+ result = ai_service._make_write_wrapper(descriptor(lambda: output, write=True), user, gate)()
+ assert result == output
+ assert gate.failed and gate.result is None
+
+
+def test_disconnecting_at_open_cancels_stream_and_releases_slot(client, auth_headers, monkeypatch):
+ from app.api import ai
+ from prompture.agents.live_events import TextDelta
+ released = threading.Event()
+ original_release = ai._release_turn
+
+ def release(uid):
+ original_release(uid)
+ released.set()
+
+ class FakeConversation:
+ def ask_live(self, message):
+ for _ in range(2000):
+ yield TextDelta(text='x')
+
+ monkeypatch.setattr(ai, '_release_turn', release)
+ monkeypatch.setattr(ai_service, 'ensure_initialized', lambda: None)
+ monkeypatch.setattr(ai_service, 'is_configured', lambda: True)
+ monkeypatch.setattr(ai_service, 'injection_flagged', lambda message: False)
+ monkeypatch.setattr(ai_service, 'redact_input', lambda message: message)
+ monkeypatch.setattr(ai_service, 'build_conversation', lambda *args, **kwargs: FakeConversation())
+ response = client.post('/api/v1/ai/chat/stream', headers=auth_headers,
+ json={'message': 'hello'}, buffered=False)
+ assert response.status_code == 200
+ assert 'event: open' in next(iter(response.response)).decode()
+ response.close()
+ assert released.wait(5), 'Disconnected worker retained a concurrency slot'
+
+
+def test_old_stream_cleanup_does_not_unregister_new_gate():
+ first = ai_service.ConfirmationGate('same-conversation', 1, lambda *args: None, threading.Event(), 5)
+ second = ai_service.ConfirmationGate('same-conversation', 1, lambda *args: None, threading.Event(), 5)
+ try:
+ ai_service.register_gate('same-conversation', first)
+ ai_service.register_gate('same-conversation', second)
+ ai_service.unregister_gate('same-conversation', first)
+ assert ai_service._active_gates['same-conversation'] is second
+ finally:
+ ai_service.unregister_gate('same-conversation', second)
+
+
+def test_read_exception_does_not_leak_credentials_to_model(app, no_pii):
+ with app.app_context():
+ user = make_user(db)
+ def broken():
+ raise RuntimeError('Cannot connect to mysql://root:secret@host/db')
+ result = ai_service._make_read_wrapper(descriptor(broken), user)()
+ assert result == 'The tool failed to retrieve data.'