Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
89 changes: 52 additions & 37 deletions ruoyi-fastapi-backend/middlewares/demo_mode_middleware.py
Original file line number Diff line number Diff line change
@@ -1,11 +1,48 @@
import re

from fastapi import FastAPI, Request
from starlette._utils import get_route_path
from starlette.middleware.base import BaseHTTPMiddleware, RequestResponseEndpoint
from starlette.responses import Response

from utils.client_ip_util import ClientIPUtil
from utils.log_util import logger
from utils.response_util import ResponseUtil

_GET_ONLY_PREFIXES = (
'/system/user',
'/system/role',
'/system/menu',
'/system/dept',
'/system/post',
'/system/dict',
'/system/config',
'/system/notice',
'/system/file',
'/system/plugin',
'/system/oauth',
'/monitor/operlog',
'/monitor/logininfor',
'/monitor/online',
'/monitor/job',
'/monitor/jobLog',
'/monitor/cache',
'/monitor/oauth/audit',
'/tool/gen',
'/ai/model',
'/ai/chat',
)
_BLOCKED_PREFIXES = (
'/common',
'/register',
'/system/file/download',
'/monitor/logininfor/unlock',
'/tool/gen/createTable',
'/tool/gen/genCode',
'/tool/gen/synchDb',
)
_INTERACTION_PASSWORD_PATH = re.compile(r'/auth/interaction/[^/]+/change-password/?')


class DemoModeMiddleware(BaseHTTPMiddleware):
"""演示模式中间件。"""
Expand All @@ -18,44 +55,22 @@ async def dispatch(self, request: Request, call_next: RequestResponseEndpoint) -
:param call_next: 调用下一层请求处理器的异步回调
:return: 演示限制提示或下游响应
"""
url_path = str(request.url)
method = request.method.lower()
intercept_url_list = [
'system/user',
'system/role',
'system/menu',
'system/dept',
'system/post',
'system/dict',
'system/config',
'system/notice',
'system/file',
'system/plugin',
'monitor/operlog',
'monitor/logininfor',
'monitor/online',
'monitor/job',
'monitor/jobLog',
'monitor/cache',
'ai/model',
'ai/chat',
]
path = get_route_path(request.scope)
method = request.method
prefixes = _BLOCKED_PREFIXES if method == 'GET' else _BLOCKED_PREFIXES + _GET_ONLY_PREFIXES

for item in intercept_url_list:
if (url_path.startswith(f'{request.base_url!s}{item}') and method != 'get') or url_path.startswith(
(
f'{request.base_url!s}common',
f'{request.base_url!s}register',
f'{request.base_url!s}tool/gen/createTable',
)
):
operate_ip = ClientIPUtil.get_client_ip(request)
logger.warning(
'请求IP:{}||请求API:{}||请求方法:{}||请求结果:演示模式,不允许操作!', operate_ip, url_path, method
)
return ResponseUtil.failure(msg_key='common.demoReadOnly')
response = await call_next(request)
return response
blocked_path = any(path == prefix or path.startswith(f'{prefix}/') for prefix in prefixes)
plugin_write = path.startswith('/apps/') and method not in {'GET', 'HEAD', 'OPTIONS'}
password_change = method == 'POST' and _INTERACTION_PASSWORD_PATH.fullmatch(path) is not None
if blocked_path or plugin_write or password_change:
logger.warning(
'请求IP:{}||请求API:{}||请求方法:{}||请求结果:演示模式,不允许操作!',
ClientIPUtil.get_client_ip(request),
path,
method,
)
return ResponseUtil.failure(msg_key='common.demoReadOnly')
return await call_next(request)


def add_demo_mode_middleware(app: FastAPI) -> None:
Expand Down
Original file line number Diff line number Diff line change
@@ -0,0 +1,65 @@
import pytest
from fastapi import FastAPI, Response, status
from fastapi.testclient import TestClient

from middlewares.demo_mode_middleware import add_demo_mode_middleware


@pytest.fixture
def client() -> TestClient:
"""
创建部署在网关前缀下的测试应用。

:return: 放行请求时返回 204 的测试客户端
"""
app = FastAPI()
add_demo_mode_middleware(app)
app.mount('/', Response(status_code=status.HTTP_204_NO_CONTENT))
return TestClient(app, root_path='/gateway')


@pytest.mark.parametrize(
('method', 'path'),
[
('POST', '/gateway/system/oauth/client/1/secret'),
('POST', '/monitor/oauth/audit/export'),
('PUT', '/tool/gen'),
('GET', '/tool/gen/synchDb/sys_user?dataSourceName=default'),
('GET', '/tool/gen/genCode/sys_user'),
('GET', '/monitor/logininfor/unlock/demo'),
('GET', '/system/file/download/123/report.pdf'),
('POST', '/auth/interaction/abc/change-password'),
('PATCH', '/apps/demo/api/items/1'),
('GET', '/common/download'),
('POST', '/register'),
('POST', '/tool/gen/createTable'),
],
)
def test_demo_blocks_operation(client: TestClient, method: str, path: str) -> None:
"""受限请求返回演示模式的业务错误。"""
response = client.request(method, path)

assert response.status_code == status.HTTP_200_OK
assert response.json()['msgKey'] == 'common.demoReadOnly'


@pytest.mark.parametrize(
('method', 'path'),
[
('GET', '/gateway/system/oauth/client/list'),
('GET', '/monitor/oauth/audit/list'),
('GET', '/tool/gen/preview/1'),
('GET', '/apps/demo/ui/'),
('HEAD', '/apps/demo/ui/assets/app.js'),
('POST', '/auth/interaction/abc/login?next=/auth/interaction/abc/change-password'),
('POST', '/auth/interaction/abc/change-password-preview'),
('POST', '/oauth2/token'),
('POST', '/system/oauth2'),
('GET', '/community'),
],
)
def test_demo_allows_request(client: TestClient, method: str, path: str) -> None:
"""查询、认证交互与仅路径相似的请求继续到达下游。"""
response = client.request(method, path)

assert response.status_code == status.HTTP_204_NO_CONTENT
Loading