MCP calls introduce resource group restrictions.
This commit is contained in:
1 parent
f416f4c278
commit
2dcd42a546
5 files changed
+194
-13
No files matched your search
@@ -8,12 +8,13 @@ from services.admin_service.repositories.mcp_service_repository import McpServic
|
||||
from services.admin_service.repositories.sys_config_repository import SysConfigRepository
|
||||
from services.admin_service.constants.sys_config_key import KEY_DEFAULT_RESOURCE_GROUP
|
||||
from services.common.models.mcp_service import ChargeType
|
||||
|
||||
from services.common.redis import redis_client
|
||||
|
||||
|
||||
class ResourceGroupService:
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
self.redis = redis_client
|
||||
self.group_repo = ResourceGroupRepository(db)
|
||||
self.map_repo = ResourceGroupServiceMapRepository(db)
|
||||
self.mcp_repo = McpServiceRepository(db)
|
||||
@@ -80,6 +81,8 @@ class ResourceGroupService:
|
||||
deleted = self.group_repo.delete(gid, commit=False)
|
||||
if deleted is None:
|
||||
raise ValueError("Resource group not found")
|
||||
cache_key = f"xpack:resource_group:id:{gid}"
|
||||
self.redis.delete(cache_key)
|
||||
self.db.commit()
|
||||
return True
|
||||
except Exception:
|
||||
@@ -181,11 +184,17 @@ class ResourceGroupService:
|
||||
|
||||
def bind_groups(self, service_id: str, group_ids: List[str]) -> int:
|
||||
created = self.map_repo.bind_group(service_id, group_ids, commit=False)
|
||||
for gid in group_ids:
|
||||
cache_key = f"xpack:resource_group:id:{gid}"
|
||||
self.redis.delete(cache_key)
|
||||
self.db.commit()
|
||||
return created
|
||||
|
||||
def unbind_groups(self, service_id: str, group_ids: List[str]) -> int:
|
||||
count = self.map_repo.unbind_group(service_id, group_ids, commit=False)
|
||||
for gid in group_ids:
|
||||
cache_key = f"xpack:resource_group:id:{gid}"
|
||||
self.redis.delete(cache_key)
|
||||
self.db.commit()
|
||||
return count
|
||||
|
||||
@@ -200,12 +209,27 @@ class ResourceGroupService:
|
||||
valid_ids.append(sid)
|
||||
try:
|
||||
created = self.map_repo.bind_services(gid, valid_ids, commit=False)
|
||||
cache_key = f"xpack:resource_group:id:{gid}"
|
||||
self.redis.delete(cache_key)
|
||||
self.db.commit()
|
||||
return created
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
def unbind_service(self, gid: str, sids: List[str]) -> int:
|
||||
try:
|
||||
for sid in sids:
|
||||
self.map_repo.unbind_service(gid, sid, commit=False)
|
||||
cache_key = f"xpack:resource_group:id:{gid}"
|
||||
self.redis.delete(cache_key)
|
||||
self.db.commit()
|
||||
return len(sids)
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
|
||||
|
||||
def get_bind_groups(self, sid: str, page: int = 1, page_size: int = 10, keyword: Optional[str] = None) -> Tuple[List[dict], int]:
|
||||
groups = self.group_repo.get_all(keyword=keyword)
|
||||
if not groups:
|
||||
@@ -274,7 +298,6 @@ class ResourceGroupService:
|
||||
for s in services
|
||||
],total
|
||||
if keyword:
|
||||
|
||||
services = self.mcp_repo.get_all(keyword=keyword)
|
||||
if not services:
|
||||
return [],0
|
||||
@@ -353,12 +376,3 @@ class ResourceGroupService:
|
||||
for g in groups
|
||||
]
|
||||
|
||||
def unbind_service(self, gid: str, sids: List[str]) -> int:
|
||||
try:
|
||||
for sid in sids:
|
||||
self.map_repo.unbind_service(gid, sid, commit=False)
|
||||
self.db.commit()
|
||||
return len(sids)
|
||||
except Exception:
|
||||
self.db.rollback()
|
||||
raise
|
||||
@@ -5,6 +5,11 @@ from services.common.database import SessionLocal
|
||||
|
||||
from services.admin_service.repositories.user_repository import UserRepository
|
||||
from services.admin_service.repositories.user_wallet_repository import UserWalletRepository
|
||||
from services.common.redis_keys import RedisKeys
|
||||
from services.common.utils.cache import get_model_cache, set_model_cache, delete_cache
|
||||
import logging
|
||||
|
||||
logger = logging.getLogger(__name__)
|
||||
|
||||
|
||||
class UserService:
|
||||
@@ -46,4 +51,12 @@ class UserService:
|
||||
|
||||
def update_resource_group(self, user_id: str, group_id: str) -> Optional[User]:
|
||||
"""Update user resource group"""
|
||||
return self.user_repository.update_resource_group(user_id=user_id, group_id=group_id)
|
||||
try:
|
||||
user = self.user_repository.update_resource_group(user_id=user_id, group_id=group_id)
|
||||
cache_key = RedisKeys.user_key(user_id)
|
||||
set_model_cache(cache_key, user)
|
||||
return self.get_by_id(user_id)
|
||||
except Exception as e:
|
||||
logger.error(f"Failed to update user resource group for user_id {user_id}: {e}", exc_info=True)
|
||||
return None
|
||||
|
||||
@@ -5,6 +5,7 @@ Supports both service_id (UUID) and slug_name service identifiers
|
||||
|
||||
from typing import Optional
|
||||
from datetime import datetime, timezone
|
||||
from sqlalchemy import false
|
||||
from starlette.requests import Request
|
||||
from starlette.responses import Response
|
||||
import asyncio
|
||||
@@ -17,6 +18,9 @@ from mcp.server.lowlevel import Server
|
||||
from services.api_service.services.mcp_server_factory import McpServerFactory
|
||||
from services.common.logging_config import get_logger
|
||||
from services.api_service.repositories.user_apikey_repository import UserApiKeyRepository
|
||||
from services.api_service.repositories.user_repository import UserRepository
|
||||
from services.api_service.repositories.resource_group_repository import ResourceGroupMapRepository
|
||||
|
||||
from services.api_service.utils.connection_manager import connection_manager
|
||||
from services.common.database import get_db
|
||||
from services.common.config import Config
|
||||
@@ -177,6 +181,20 @@ class McpController:
|
||||
return
|
||||
|
||||
user_id, apikey_id = user_info
|
||||
|
||||
# Check invoke permission
|
||||
if not self._check_invoke_permission(user_id, service_id):
|
||||
response_body = b"Invoke permission denied"
|
||||
await send({
|
||||
'type': 'http.response.start',
|
||||
'status': 403,
|
||||
'headers': [
|
||||
[b'content-type', b'text/plain'],
|
||||
[b'content-length', str(len(response_body)).encode()],
|
||||
],
|
||||
})
|
||||
await send({'type': 'http.response.body', 'body': response_body})
|
||||
return
|
||||
|
||||
# Create MCP server instance (pass user_id and apikey_id for billing and logging)
|
||||
mcp_server = await self.server_factory.create_server(service_id, user_id, apikey_id)
|
||||
@@ -347,8 +365,19 @@ class McpController:
|
||||
})
|
||||
await send({'type': 'http.response.body', 'body': response_body})
|
||||
return
|
||||
|
||||
user_id, apikey_id = user_info
|
||||
if not self._check_invoke_permission(user_id, service_id):
|
||||
response_body = b"Invoke permission denied"
|
||||
await send({
|
||||
'type': 'http.response.start',
|
||||
'status': 403,
|
||||
'headers': [
|
||||
[b'content-type', b'text/plain'],
|
||||
[b'content-length', str(len(response_body)).encode()],
|
||||
],
|
||||
})
|
||||
await send({'type': 'http.response.body', 'body': response_body})
|
||||
return
|
||||
raw_client_id = req.headers.get('x-client-instance-id') or req.headers.get('x-client-id')
|
||||
client_instance_id = (re.sub(r'[^a-zA-Z0-9._-]', '', raw_client_id)[:32]) if raw_client_id else None
|
||||
ua = user_agent or ""
|
||||
@@ -611,6 +640,43 @@ class McpController:
|
||||
finally:
|
||||
if db is not None:
|
||||
db.close()
|
||||
def _check_invoke_permission(self, user_id: str, service_id: str) -> bool:
|
||||
db = None
|
||||
try:
|
||||
# Create database session
|
||||
db = next(get_db())
|
||||
user_repo = UserRepository(db)
|
||||
# Query user info by apikey
|
||||
user = user_repo.get_by_id(user_id)
|
||||
if not user:
|
||||
logger.warning(f"User not found in database: {user_id[:10]}...")
|
||||
return False
|
||||
logger.debug(f"Found user record - User ID: {user.id}, group id is: {user.group_id}")
|
||||
if user.group_id == "allow-all":
|
||||
return True
|
||||
elif user.group_id == "deny-all":
|
||||
return False
|
||||
|
||||
resource_group_map_repo = ResourceGroupMapRepository(db)
|
||||
resource_groups = resource_group_map_repo.get_by_id(user.group_id)
|
||||
if not resource_groups:
|
||||
logger.warning(f"Resource group not found for user: {user_id[:10]}...")
|
||||
return False
|
||||
|
||||
# Check if service_id is in resource_groups
|
||||
if service_id not in resource_groups:
|
||||
logger.warning(f"Service {service_id} not found in user's resource groups: {user_id[:10]}...")
|
||||
return False
|
||||
|
||||
return True
|
||||
|
||||
except Exception as e:
|
||||
logger.error(f"Error occurred while querying user apikey: {str(e)}", exc_info=True)
|
||||
return False
|
||||
finally:
|
||||
if db is not None:
|
||||
db.close()
|
||||
|
||||
|
||||
def _extract_user_info(self, request: Request) -> Optional[tuple[str, str]]:
|
||||
"""Extract user ID and apikey ID from request by validating apikey parameter."""
|
||||
@@ -650,6 +716,7 @@ class McpController:
|
||||
logger.warning(f"Apikey has expired: {apikey[:10]}..., expiry time: {user_apikey.expire_at}")
|
||||
return None
|
||||
|
||||
|
||||
logger.info(f"Apikey validation successful - User ID: {user_apikey.user_id}, API Key ID: {user_apikey.id}")
|
||||
return (user_apikey.user_id, user_apikey.id)
|
||||
|
||||
|
||||
@@ -0,0 +1,43 @@
|
||||
"""
|
||||
Resource group service map repository class - used in API service
|
||||
"""
|
||||
from typing import List
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.resource_group import ResourceGroupServiceMap
|
||||
from services.common.utils.cache_utils import CacheUtils
|
||||
|
||||
|
||||
class ResourceGroupMapRepository:
|
||||
"""Resource group service map repository class"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_by_id(self, group_id: str, force_update: bool = False) -> List[str]:
|
||||
"""
|
||||
Get resource group service map by ID
|
||||
|
||||
Args:
|
||||
group_id: Resource group ID
|
||||
|
||||
Returns:
|
||||
List[str]: Resource group service map instance, returns None if not exists
|
||||
"""
|
||||
"""
|
||||
Get resource group service map by ID
|
||||
"""
|
||||
cache_key = f"xpack:resource_group:id:{group_id}"
|
||||
if not force_update:
|
||||
# Try to get from cache using SQLAlchemy-specific method
|
||||
cached_model = CacheUtils.get_sqlalchemy_cache(cache_key, List[str])
|
||||
if cached_model:
|
||||
return cached_model
|
||||
|
||||
# Query from database if not in cache
|
||||
service_ids = [item.service_id for item in self.db.query(ResourceGroupServiceMap).filter(ResourceGroupServiceMap.group_id == group_id).all()]
|
||||
if service_ids:
|
||||
# Cache the result for 10 minutes
|
||||
CacheUtils.set_sqlalchemy_cache(cache_key, service_ids, 600)
|
||||
return service_ids
|
||||
|
||||
return []
|
||||
@@ -0,0 +1,44 @@
|
||||
"""
|
||||
User repository class - used in API service
|
||||
"""
|
||||
from typing import Optional
|
||||
from sqlalchemy.orm import Session
|
||||
from services.common.models.user import User
|
||||
from services.common.utils.cache_utils import CacheUtils
|
||||
from services.common.redis_keys import RedisKeys
|
||||
|
||||
|
||||
class UserRepository:
|
||||
"""User repository class"""
|
||||
|
||||
def __init__(self, db: Session):
|
||||
self.db = db
|
||||
|
||||
def get_by_id(self, user_id: str, force_update: bool = False) -> Optional[User]:
|
||||
"""
|
||||
Get user by ID
|
||||
|
||||
Args:
|
||||
user_id: User ID
|
||||
|
||||
Returns:
|
||||
User: User instance, returns None if not exists
|
||||
"""
|
||||
"""
|
||||
Get user by ID
|
||||
"""
|
||||
cache_key = RedisKeys.user_key(user_id)
|
||||
if not force_update:
|
||||
# Try to get from cache using SQLAlchemy-specific method
|
||||
cached_model = CacheUtils.get_sqlalchemy_cache(cache_key, User)
|
||||
if cached_model:
|
||||
return cached_model
|
||||
|
||||
# Query from database if not in cache
|
||||
user = self.db.query(User).filter(User.id == user_id).first()
|
||||
if user:
|
||||
# Cache the result for 10 minutes
|
||||
CacheUtils.set_sqlalchemy_cache(cache_key, user, 600)
|
||||
return user
|
||||
|
||||
return None
|
||||
Reference in new issue
Block a user