fix(安全培训): 修复安全培训文件预览报错不bug
This commit is contained in:
1 parent
e62e4961d4
commit
31182a83d7
2 files changed
+119
-2
No files matched your search
@@ -2,13 +2,14 @@
|
||||
api/chat/preview_support.py
|
||||
|
||||
用途:提供聊天文件预览所需的来源校验、文件获取和格式转换操作。
|
||||
依赖:chat.shared、requests、LibreOffice、openpyxl、共享盘配置。
|
||||
逻辑:由 previews 路由调用,限制可访问路径与 URL,并将 Office/Excel 内容转换为可预览格式。
|
||||
依赖:chat.shared、知识库 document_service、requests、LibreOffice、openpyxl、共享盘配置。
|
||||
逻辑:由 previews 路由调用,优先直读受保护的培训知识库文件;其余来源按原有 URL/共享盘策略获取并转换为预览内容。
|
||||
"""
|
||||
from __future__ import annotations
|
||||
|
||||
from .shared import * # noqa: F403
|
||||
from urllib.parse import urljoin
|
||||
from app.services.kb import document_service
|
||||
|
||||
|
||||
def _normalize_allowed_share_path(path_value: str) -> tuple[str, str]:
|
||||
@@ -88,6 +89,52 @@ def _resolve_internal_preview_url(target_url: str) -> str:
|
||||
return raw
|
||||
return urljoin(request.host_url, raw)
|
||||
|
||||
def _resolve_training_preview_version_id(target_url: str) -> int | None:
|
||||
"""
|
||||
从员工培训知识库预览地址提取文档版本 ID。
|
||||
|
||||
用途:识别培训资料专用的站内 URL,使预览代理能直接读取共享存储而非通过 HTTP 回调本站。
|
||||
核心逻辑:仅接受精确的 `/api/kb/document-versions/<正整数>/training-preview-file` 路径,拒绝带额外路径的地址。
|
||||
参数与返回约束:target_url 可以是相对或绝对 URL;非培训预览地址返回 None,不影响其他 Chat、知识库或外部文件预览流程。
|
||||
"""
|
||||
import re
|
||||
|
||||
path = urlparse(str(target_url or '').strip()).path
|
||||
matched = re.fullmatch(r'/api/kb/document-versions/(\d+)/training-preview-file', path)
|
||||
if not matched:
|
||||
return None
|
||||
return int(matched.group(1))
|
||||
|
||||
def _read_training_preview_bytes(version_id: int, max_size: int | None):
|
||||
"""
|
||||
读取培训知识库资料的二进制内容。
|
||||
|
||||
用途:为 Chat 通用预览代理提供培训资料内容,避免容器经前端端口回调自身引发 502。
|
||||
核心逻辑:复用 document_service 的原件/清洗预览回退路径,校验体积后读取文件并推断 MIME 类型。
|
||||
参数与返回约束:version_id 必须来自受限路由匹配;返回 `(content, content_type, error_tuple)`,错误契约保持与其他预览来源一致。
|
||||
"""
|
||||
try:
|
||||
preview_path, _filename = document_service.resolve_training_preview_file_path(version_id)
|
||||
except NotFoundError:
|
||||
return (None, None, ('source file not found', 404))
|
||||
except Exception as exc:
|
||||
current_app.logger.warning('[file-preview] failed to resolve training preview version=%s: %s', version_id, exc)
|
||||
return (None, None, ('failed to read source file', 502))
|
||||
|
||||
try:
|
||||
file_size = preview_path.stat().st_size
|
||||
if max_size is not None and file_size > max_size:
|
||||
return (None, None, ('file too large for online preview', 413))
|
||||
content = preview_path.read_bytes()
|
||||
except OSError as exc:
|
||||
current_app.logger.warning('[file-preview] failed to read training preview version=%s path=%s: %s', version_id, preview_path, exc)
|
||||
return (None, None, ('failed to read source file', 502))
|
||||
|
||||
content_type = (mimetypes.guess_type(preview_path.name)[0] or '').strip().lower()
|
||||
if _extract_placeholder_text(content):
|
||||
content_type = 'text/plain; charset=utf-8'
|
||||
return (content, content_type, None)
|
||||
|
||||
def _is_allowed_preview_url(target_url: str) -> bool:
|
||||
"""
|
||||
预览代理 URL 白名单校验。
|
||||
@@ -142,6 +189,9 @@ def _fetch_preview_source_bytes(file_url: str, max_size: int | None=15 * 1024 *
|
||||
import time
|
||||
import sqlalchemy as sa
|
||||
from urllib.parse import parse_qs
|
||||
training_version_id = _resolve_training_preview_version_id(file_url)
|
||||
if training_version_id is not None:
|
||||
return _read_training_preview_bytes(training_version_id, max_size)
|
||||
file_url = _resolve_internal_preview_url(file_url)
|
||||
if _is_allowed_share_path(file_url):
|
||||
_path_kind, normalized_path = _normalize_allowed_share_path(file_url)
|
||||
|
||||
@@ -10,6 +10,7 @@ from __future__ import annotations
|
||||
|
||||
from datetime import date, datetime
|
||||
from io import BytesIO
|
||||
from pathlib import Path
|
||||
|
||||
from openpyxl import load_workbook
|
||||
import pytest
|
||||
@@ -19,6 +20,7 @@ from app.core.errors import ValidationError
|
||||
from app.models import Agent, TrainingRecord, User
|
||||
from app.services import training_service
|
||||
from app.services.training_service import _grade_answer_details, _normalize_question_bank
|
||||
from app.api.chat import preview_support
|
||||
|
||||
|
||||
def _create_user(
|
||||
@@ -521,6 +523,71 @@ def test_training_admin_list_stats_and_export_share_one_fact_source(client, app)
|
||||
assert {rows[1][7], rows[2][7]} == {"passed", "failed"}
|
||||
|
||||
|
||||
def test_training_preview_proxy_reads_kb_storage_without_http_callback(monkeypatch, tmp_path, app):
|
||||
"""
|
||||
培训资料预览必须直接复用知识库存储解析,不能回调前端 Nginx。
|
||||
|
||||
关键断言:匹配培训资料路径时,预览代理返回原始 PDF 内容,且不会调用 requests.get,
|
||||
防止测试环境容器经宿主机端口回环时再次出现 502。
|
||||
"""
|
||||
preview_file = tmp_path / "safety-training.pdf"
|
||||
preview_file.write_bytes(b"%PDF-training-preview")
|
||||
requested_version_ids: list[int] = []
|
||||
|
||||
def resolve_preview_path(version_id: int):
|
||||
requested_version_ids.append(version_id)
|
||||
return Path(preview_file), preview_file.name
|
||||
|
||||
def reject_http_callback(*_args, **_kwargs):
|
||||
raise AssertionError("training preview must not call requests.get")
|
||||
|
||||
monkeypatch.setattr(
|
||||
preview_support.document_service,
|
||||
"resolve_training_preview_file_path",
|
||||
resolve_preview_path,
|
||||
)
|
||||
monkeypatch.setattr(preview_support.requests, "get", reject_http_callback)
|
||||
|
||||
with app.app_context():
|
||||
content, content_type, error = preview_support._fetch_preview_source_bytes(
|
||||
"/api/kb/document-versions/1231/training-preview-file",
|
||||
)
|
||||
|
||||
assert requested_version_ids == [1231]
|
||||
assert content == b"%PDF-training-preview"
|
||||
assert content_type == "application/pdf"
|
||||
assert error is None
|
||||
|
||||
|
||||
def test_non_training_preview_url_keeps_existing_http_fetch_path(monkeypatch):
|
||||
"""
|
||||
非培训来源必须继续走原有通用预览取流逻辑。
|
||||
|
||||
关键断言:普通内网 URL 不会触发知识库培训文件解析,避免影响既有 Chat 来源文件预览。
|
||||
"""
|
||||
class FakeResponse:
|
||||
status_code = 200
|
||||
content = b"%PDF-chat-source"
|
||||
headers = {"content-type": "application/pdf"}
|
||||
|
||||
def reject_training_resolver(_version_id: int):
|
||||
raise AssertionError("non-training URL must not resolve training preview")
|
||||
|
||||
monkeypatch.setattr(
|
||||
preview_support.document_service,
|
||||
"resolve_training_preview_file_path",
|
||||
reject_training_resolver,
|
||||
)
|
||||
monkeypatch.setattr(preview_support.requests, "get", lambda *_args, **_kwargs: FakeResponse())
|
||||
|
||||
content, content_type, error = preview_support._fetch_preview_source_bytes(
|
||||
"http://192.168.100.192:9000/chat-source.pdf",
|
||||
)
|
||||
|
||||
assert content == b"%PDF-chat-source"
|
||||
assert content_type == "application/pdf"
|
||||
assert error is None
|
||||
|
||||
def test_training_admin_permission_can_be_granted_by_feature_permission(client, app):
|
||||
"""培训 HR 管理能力应支持通过功能权限显式授予普通用户。"""
|
||||
with app.app_context():
|
||||
|
||||
Reference in new issue
Block a user