Merge branch 'test' into prod

This commit is contained in:
sophie committed 2026-07-21 14:22:17 +08:00
commit 88fcf3c70b
14 files changed
+194 -35

No files matched your search

+81 -3
View File
@@ -6,7 +6,9 @@ backend/app/api/agents.py
逻辑:按当前用户 RBAC 返回可访问 Agent;列表统一 serialize_agent_for_user_list(结构化列为准)。
"""
import os
from flask import Blueprint, jsonify, send_from_directory
import mimetypes
import re
from flask import Blueprint, Response, jsonify, request, send_from_directory, stream_with_context
from app import db
from app.core.auth.jwt import get_current_user
@@ -115,8 +117,84 @@ def list_public_agents():
visible_agent_ids = {agent.id for agent in agents}
return jsonify([_serialize_agent_row(agent, visible_agent_ids=visible_agent_ids) for agent in sort_agent_rows(agents)])
# 为了兼容本地无MinIO的环境,暴露一个静态文件读取接口
def _parse_byte_range(range_header: str, file_size: int) -> tuple[int, int] | None:
"""
解析浏览器单段字节范围请求。
用途:iOS Safari/企业微信播放 MP4 时依赖 Range 请求,本函数将请求转换为闭区间。
参数约束:仅接受单个 bytes 范围;无效或越界范围返回 None。
"""
match = re.fullmatch(r'bytes=(\d*)-(\d*)', range_header.strip())
if not match or file_size <= 0:
return None
start_text, end_text = match.groups()
if not start_text and not end_text:
return None
if start_text:
start = int(start_text)
end = int(end_text) if end_text else file_size - 1
else:
suffix_length = int(end_text)
if suffix_length <= 0:
return None
start = max(file_size - suffix_length, 0)
end = file_size - 1
if start >= file_size or end < start:
return None
return start, min(end, file_size - 1)
def _stream_minio_guide_file(filename: str) -> Response:
"""
以同源流式响应返回 MinIO 指南文件。
用途:消除生产 HTTPS 页面加载 HTTP MinIO 地址的混合内容问题,并支持 iOS 所需的 206 响应。
参数约束:filename 为系统生成的 MinIO 对象名;响应流结束后必须释放连接。
"""
stat = minio_service.stat_file(filename)
file_size = int(stat.size)
content_type = stat.content_type or mimetypes.guess_type(filename)[0] or 'application/octet-stream'
requested_range = request.headers.get('Range', '').strip()
byte_range = _parse_byte_range(requested_range, file_size) if requested_range else None
if requested_range and byte_range is None:
return Response(status=416, headers={'Content-Range': f'bytes */{file_size}'})
start, end = byte_range or (0, file_size - 1)
content_length = end - start + 1
source = minio_service.open_file_stream(filename, offset=start, length=content_length)
def generate():
try:
while True:
chunk = source.read(64 * 1024)
if not chunk:
break
yield chunk
finally:
source.close()
source.release_conn()
headers = {
'Accept-Ranges': 'bytes',
'Content-Length': str(content_length),
'Cache-Control': 'private, max-age=3600',
}
status = 206 if byte_range else 200
if byte_range:
headers['Content-Range'] = f'bytes {start}-{end}/{file_size}'
return Response(stream_with_context(generate()), status=status, headers=headers, content_type=content_type)
@agents_bp.route('/guides/files/<path:filename>', methods=['GET'])
def serve_guide_file(filename):
return send_from_directory(os.path.join(os.getcwd(), 'data', 'agent-guides'), filename)
"""
返回本地或 MinIO 中的指南文件。
用途:为 PDF、图片和培训视频提供统一同源地址;本地文件沿用 Flask 条件响应,MinIO 文件支持 Range。
参数约束:filename 仅用于系统指南存储目录或 MinIO 指南桶,不接受任意外部路径。
"""
local_directory = os.path.join(os.getcwd(), 'data', 'agent-guides')
if os.path.isfile(os.path.join(local_directory, filename)):
return send_from_directory(local_directory, filename, conditional=True)
return _stream_minio_guide_file(filename)
+12 -14
View File
@@ -83,12 +83,6 @@ def _decode_jwt(token: str) -> dict:
header = jwt.get_unverified_header(token)
kid = header.get('kid')
current_app.logger.info(
'[auth_jwt] decode start kid=%s alg=%s token=%s',
kid,
header.get('alg'),
_token_brief(token),
)
if not kid:
if not bool(current_app.config.get('AUTH_ALLOW_LOCAL_JWT', True)):
raise ValueError('JWT header missing kid')
@@ -260,24 +254,28 @@ def get_current_user() -> Optional[User]:
try:
claims = _decode_jwt(token)
user = _resolve_user_from_claims(claims)
current_app.logger.info(
'[auth_jwt] decode ok sub=%s username=%s resolved_user=%s',
claims.get('sub'),
claims.get('preferred_username') or claims.get('username') or claims.get('name'),
getattr(user, 'username', None),
)
except Exception:
# Decode metadata is diagnostic-only: do not emit it for successful requests.
try:
header = jwt.get_unverified_header(token)
except Exception:
header = {}
unverified = _extract_unverified_claims(token)
expected_issuer = (current_app.config.get('AUTH_JWT_ISSUER') or '').strip()
expected_audience = (current_app.config.get('AUTH_JWT_AUDIENCE') or '').strip()
current_app.logger.error(
'[auth_jwt] decode context token_iss=%s token_aud=%s expected_iss=%s expected_aud=%s',
'[auth_jwt] decode context kid=%s alg=%s token=%s token_iss=%s token_aud=%s '
'expected_iss=%s expected_aud=%s path=%s',
header.get('kid'),
header.get('alg'),
_token_brief(token),
unverified.get('iss'),
unverified.get('aud'),
expected_issuer,
expected_audience,
request.path,
)
current_app.logger.exception('[auth_jwt] decode failed token=%s path=%s', _token_brief(token), request.path)
current_app.logger.exception('[auth_jwt] decode failed')
user = None
claims = None
if user:
+28 -9
View File
@@ -77,16 +77,35 @@ class MinioService:
def get_public_url(self, object_name: str) -> str:
"""
Returns the public URL for the given object name.
"""
if os.path.exists(os.path.join('data/agent-guides', object_name)):
# It's a local fallback file
# the backend needs a static route to serve this, we'll assume /api/agents/guides/files/<object_name>
# but since we want it public without auth:
return f"/api/agents/guides/files/{object_name}"
返回同源的指南文件代理地址。
base_url = cfg.MINIO_PUBLIC_BASE_URL.rstrip('/')
return f"{base_url}/{self.bucket_name}/{object_name}"
用途:避免 HTTPS 页面直接加载 HTTP MinIO 对象时被移动端浏览器拦截。
参数约束:object_name 必须是系统生成的对象名;返回地址由指南文件接口提供 Range 响应。
"""
return f"/api/agents/guides/files/{object_name}"
def open_file_stream(self, object_name: str, *, offset: int = 0, length: int | None = None):
"""
按指定字节范围打开 MinIO 指南对象流。
用途:供同源指南文件接口透传视频数据,满足 iOS 媒体播放器的 Range/206 请求。
参数约束:offset 从 0 开始,length 为本次最多读取字节数;调用方必须关闭返回流。
"""
return self.client.get_object(
self.bucket_name,
object_name,
offset=offset,
length=length,
)
def stat_file(self, object_name: str):
"""
获取 MinIO 指南对象元数据。
用途:在返回视频前确定文件大小和 MIME 类型,以生成 iOS 可识别的媒体响应头。
参数约束:object_name 必须是系统保存的对象名;对象不存在时由 MinIO 异常上抛。
"""
return self.client.stat_object(self.bucket_name, object_name)
def get_file_bytes(self, object_name: str) -> bytes:
"""
@@ -0,0 +1,51 @@
"""
用途:验证 Agent 指南视频同源代理的字节范围响应。
依赖:Flask 请求上下文、agents API 的 Range 解析与 MinIO 流式响应函数。
逻辑:使用内存对象模拟 MinIO,断言 iOS 媒体请求得到 206、Content-Range 和正确数据。
"""
from io import BytesIO
from types import SimpleNamespace
from flask import Flask
from app.api import agents as agents_api
class _FakeObjectStream(BytesIO):
"""模拟 MinIO 响应流,并提供连接释放接口。"""
def release_conn(self) -> None:
"""模拟 MinIO SDK 的连接释放操作。"""
def test_parse_byte_range_supports_ios_media_requests():
"""验证普通、开放结尾和后缀三种媒体字节范围均可正确解析。"""
assert agents_api._parse_byte_range('bytes=0-3', 10) == (0, 3)
assert agents_api._parse_byte_range('bytes=4-', 10) == (4, 9)
assert agents_api._parse_byte_range('bytes=-3', 10) == (7, 9)
assert agents_api._parse_byte_range('bytes=10-', 10) is None
def test_stream_minio_guide_file_returns_partial_content(monkeypatch):
"""验证视频代理响应 iOS Range 请求时返回 206 和完整范围响应头。"""
payload = b'0123456789'
monkeypatch.setattr(
agents_api.minio_service,
'stat_file',
lambda _filename: SimpleNamespace(size=len(payload), content_type='video/mp4'),
)
monkeypatch.setattr(
agents_api.minio_service,
'open_file_stream',
lambda _filename, offset, length: _FakeObjectStream(payload[offset:offset + length]),
)
app = Flask(__name__)
with app.test_request_context(headers={'Range': 'bytes=2-5'}):
response = agents_api._stream_minio_guide_file('training.mp4')
assert response.status_code == 206
assert response.headers['Accept-Ranges'] == 'bytes'
assert response.headers['Content-Range'] == 'bytes 2-5/10'
assert response.headers['Content-Length'] == '4'
assert response.content_type == 'video/mp4'
assert b''.join(response.response) == b'2345'