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
13 changes: 4 additions & 9 deletions backend/apps/chat/api/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -14,7 +14,7 @@
list_chats, get_chat_with_records, create_chat, get_chat_chart_data, get_chat_predict_data, \
get_chat_with_records_with_data, get_chat_record_by_id, \
format_json_data, format_json_list_data, get_chart_config, list_recent_questions, rename_chat_with_user, \
get_chat_log_history, get_chart_data_with_user_live
get_chat_log_history, get_chart_data_with_user_live, get_chat_record_for_user
from apps.chat.models.chat_model import CreateChat, ChatRecord, RenameChat, ChatQuestion, AxisObj, QuickCommand, \
ChatInfo, Chat, ChatFinishStep, ChatQuestionBase, SimpleChat, ChatItem
from apps.chat.task.llm import LLMService
Expand Down Expand Up @@ -477,16 +477,11 @@ def _err(_e: Exception):
@router.get("/record/{chat_record_id}/excel/export/{chat_id}", summary=f"{PLACEHOLDER_PREFIX}export_chart_data")
@system_log(LogConfig(operation_type=OperationType.EXPORT, module=OperationModules.CHAT, resource_id_expr="chat_id", ))
async def export_excel(session: SessionDep, current_user: CurrentUser, chat_record_id: int, chat_id: int, trans: Trans):
chat_record = session.get(ChatRecord, chat_record_id)
if not chat_record:
chat_record = get_chat_record_for_user(session, current_user, chat_record_id)
if chat_record is None:
raise HTTPException(
status_code=500,
detail=f"ChatRecord with id {chat_record_id} not found"
)
if chat_record.create_by != current_user.id:
raise HTTPException(
status_code=500,
detail=f"ChatRecord with id {chat_record_id} not Owned by the current user"
detail=trans('i18n_permission.permission_resource_limit')
)
is_predict_data = chat_record.predict_record_id is not None

Expand Down
48 changes: 33 additions & 15 deletions backend/apps/chat/curd/chat.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,7 +4,7 @@

import orjson
import sqlparse
from sqlalchemy import and_, select, update
from sqlalchemy import Select, and_, select, update
from sqlalchemy import desc, func
from sqlalchemy.orm import aliased

Expand All @@ -17,7 +17,8 @@
from apps.db.db import exec_sql
from apps.system.crud.assistant import AssistantOutDs, AssistantOutDsFactory
from apps.system.schemas.system_schema import AssistantOutDsSchema
from common.core.deps import CurrentAssistant, SessionDep, CurrentUser, Trans
from common.core.deps import CurrentAssistant, SessionDep, CurrentUser, Trans, i18n
from common.error import SingleMessageError
from common.utils.data_format import DataFormat
from common.utils.utils import extract_nested_json, SQLBotLogUtil

Expand All @@ -35,6 +36,24 @@ def get_chat_record_by_id(session: SessionDep, record_id: int):
return record


def _select_chat_record_for_user(current_user: CurrentUser, chat_record_id: int) -> Select[tuple[ChatRecord]]:
return (
select(ChatRecord)
.join(Chat, Chat.id == ChatRecord.chat_id)
.where(
ChatRecord.id == chat_record_id,
ChatRecord.create_by == current_user.id,
Chat.oid.is_not(None),
Chat.oid == current_user.oid,
)
)


def get_chat_record_for_user(session: SessionDep, current_user: CurrentUser, chat_record_id: int) -> ChatRecord | None:
stmt = _select_chat_record_for_user(current_user, chat_record_id)
return session.execute(stmt).scalar_one_or_none()


def get_chat(session: SessionDep, chat_id: int) -> Chat:
statement = select(Chat).where(Chat.id == chat_id)
chat = session.exec(statement).scalars().first()
Expand Down Expand Up @@ -251,7 +270,7 @@ def get_chat_chart_config(session: SessionDep, chat_record_id: int):


def get_chart_data_with_user(session: SessionDep, current_user: CurrentUser, chat_record_id: int):
stmt = select(ChatRecord.data).where(and_(ChatRecord.id == chat_record_id, ChatRecord.create_by == current_user.id))
stmt = _select_chat_record_for_user(current_user, chat_record_id).with_only_columns(ChatRecord.data)
res = session.execute(stmt)
for row in res:
try:
Expand All @@ -262,9 +281,12 @@ def get_chart_data_with_user(session: SessionDep, current_user: CurrentUser, cha


def get_chart_data_with_user_live(session: SessionDep, current_user: CurrentUser, chat_record_id: int, trans: Trans):
stmt = select(ChatRecord.datasource, ChatRecord.sql).where(
and_(ChatRecord.id == chat_record_id, ChatRecord.create_by == current_user.id))
stmt = _select_chat_record_for_user(current_user, chat_record_id).with_only_columns(
ChatRecord.datasource, ChatRecord.sql
)
row = session.execute(stmt).first()
if row is None:
raise SingleMessageError(trans('i18n_permission.permission_resource_limit'))
return get_chart_data_ds(session, row.datasource, row.sql, trans)


Expand Down Expand Up @@ -301,8 +323,7 @@ def get_chat_chart_data(session: SessionDep, chat_record_id: int):


def get_chat_predict_data_with_user(session: SessionDep, current_user: CurrentUser, chat_record_id: int):
stmt = select(ChatRecord.predict_data).where(
and_(ChatRecord.id == chat_record_id, ChatRecord.create_by == current_user.id))
stmt = _select_chat_record_for_user(current_user, chat_record_id).with_only_columns(ChatRecord.predict_data)
res = session.execute(stmt)
for row in res:
try:
Expand Down Expand Up @@ -335,7 +356,7 @@ def get_chat_with_records(session: SessionDep, chart_id: int, current_user: Curr
current_assistant: CurrentAssistant, with_data: bool = False,
trans: Trans = None) -> ChatInfo:
chat = session.get(Chat, chart_id)
if not chat:
if chat is None or chat.oid is None or chat.oid != current_user.oid:
raise Exception(f"Chat with id {chart_id} not found")
if chat.create_by != current_user.id:
raise Exception(f"Chat with id {chart_id} not Owned by the current user")
Expand Down Expand Up @@ -590,13 +611,10 @@ def get_chat_log_history(session: SessionDep, chat_record_id: int, current_user:
Returns:
ChatLogHistory: 包含历史步骤和时间信息的对象
"""
# 1. 首先验证ChatRecord存在且属于当前用户
chat_record = session.get(ChatRecord, chat_record_id)
if not chat_record:
raise Exception(f"ChatRecord with id {chat_record_id} not found")

if chat_record.create_by != current_user.id:
raise Exception(f"ChatRecord with id {chat_record_id} not owned by the current user")
chat_record = get_chat_record_for_user(session, current_user, chat_record_id)
if chat_record is None:
trans = i18n(lang=current_user.language)
raise SingleMessageError(trans('i18n_permission.permission_resource_limit'))

# 2. 查询与该ChatRecord相关的所有ChatLog记录
chat_logs = session.query(ChatLog).filter(
Expand Down
216 changes: 216 additions & 0 deletions backend/tests/test_chat_record_workspace.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,216 @@
"""Offline workspace authorization checks on the real chat read routes."""

import json
from datetime import datetime
from io import BytesIO
from types import SimpleNamespace
from unittest.mock import AsyncMock, Mock
from zipfile import ZipFile

import pytest
import sqlbot_xpack # noqa: F401 -- initialize the released wheel before app routers
from fastapi import FastAPI
from fastapi.testclient import TestClient
from sqlalchemy import JSON, MetaData
from sqlalchemy.pool import StaticPool
from sqlmodel import Session, create_engine
from starlette.exceptions import HTTPException

from apps.chat.api.chat import router
from apps.chat.curd import chat as chat_service
from apps.chat.models.chat_model import (
Chat,
ChatLog,
ChatRecord,
OperationEnum,
TypeEnum,
)
from common.audit.schemas.logger_decorator import SystemLogger
from common.audit.schemas.request_context import RequestContextMiddlewareCommon
from common.core.db import get_session
from common.core.response_middleware import exception_handler

OWNER, OTHER_USER = 10, 11
WORKSPACE, OTHER_WORKSPACE = 100, 200
CHAT, OTHER_CHAT, MISSING_CHAT = 1000, 1001, 1002
RECORD, OTHER_RECORD, ORPHAN_RECORD, MISSING_RECORD = 2000, 2001, 2002, 2003
ROUTES = ("data", "data_live", "predict_data", "log", "usage", "export")
CREATED = datetime(2026, 1, 1)
RESULT = {"fields": ["value"], "data": [{"value": "saved-result"}]}
PREDICTION = [{"value": "prediction-result"}]
LOG_MESSAGE = "record-log-message"
LIVE_RESULT = {"data": [{"value": "live-result"}]}
ACCESS_DENIED = "Access denied or resource not found!"


@pytest.fixture
def chat_app(monkeypatch):
database = create_engine(
"sqlite://", connect_args={"check_same_thread": False}, poolclass=StaticPool
)
meta = MetaData()
for model in (Chat, ChatRecord, ChatLog):
# Adapt PostgreSQL JSONB only in the temporary database schema.
table = model.__table__.to_metadata(meta)
if model is ChatLog:
table.c.messages.type = JSON()
table.c.token_usage.type = JSON()
table.create(database)
with Session(database) as session:
for chat_id, workspace_id in ((CHAT, WORKSPACE), (OTHER_CHAT, OTHER_WORKSPACE)):
session.add(
Chat(
id=chat_id,
oid=workspace_id,
create_by=OWNER,
create_time=CREATED,
brief="test-chat",
engine_type="test",
)
)
for record_id, chat_id in (
(RECORD, CHAT),
(OTHER_RECORD, OTHER_CHAT),
(ORPHAN_RECORD, MISSING_CHAT),
):
session.add(
ChatRecord(
id=record_id,
chat_id=chat_id,
create_by=OWNER,
create_time=CREATED,
question="test-question",
data=json.dumps(RESULT),
predict_data=json.dumps(PREDICTION),
chart=json.dumps(
{"columns": [{"name": "value", "value": "value"}]}
),
)
)
session.add(
ChatLog(
id=record_id,
pid=record_id,
type=TypeEnum.CHAT,
operate=OperationEnum.GENERATE_SQL,
start_time=CREATED,
finish_time=CREATED,
messages=[{"content": LOG_MESSAGE}],
token_usage={"total_tokens": 3},
)
)
session.commit()

live_query = Mock(return_value=LIVE_RESULT)
monkeypatch.setattr(chat_service, "get_chart_data_ds", live_query)
monkeypatch.setattr(SystemLogger, "create_log_record", AsyncMock())

app = FastAPI()
app.include_router(router)
app.add_middleware(RequestContextMiddlewareCommon)
app.add_exception_handler(HTTPException, exception_handler.http_exception_handler)
app.add_exception_handler(Exception, exception_handler.global_exception_handler)

@app.middleware("http")
async def identify(request, call_next):
request.state.current_user = SimpleNamespace(
id=int(request.headers.get("test-user", OWNER)),
oid=int(request.headers.get("test-workspace", WORKSPACE)),
language="en",
)
return await call_next(request)

def sessions():
with Session(database) as session:
yield session

app.dependency_overrides[get_session] = sessions
try:
with TestClient(app, raise_server_exceptions=False) as client:
yield client, live_query
finally:
database.dispose()


def record_path(route, record_id):
suffix = "excel/export/0" if route == "export" else route
return f"/chat/record/{record_id}/{suffix}"


@pytest.mark.parametrize("route", ROUTES)
@pytest.mark.parametrize(
("record_id", "user"),
[
(OTHER_RECORD, OWNER),
(RECORD, OTHER_USER),
(MISSING_RECORD, OWNER),
(ORPHAN_RECORD, OWNER),
],
ids=["other-workspace", "other-user", "missing-record", "missing-parent"],
)
def test_record_read_denies_outside_access_scope(chat_app, route, record_id, user):
client, live_query = chat_app
response = client.get(
record_path(route, record_id), headers={"test-user": str(user)}
)

if route == "data":
assert response.status_code == 200
assert response.json() == {"fields": [], "fields_info": None, "data": []}
elif route == "predict_data":
assert response.status_code == 200
assert response.json() == []
else:
assert response.status_code == 500, response.text
assert response.json() == ACCESS_DENIED
live_query.assert_not_called()


@pytest.mark.parametrize("route", ROUTES)
def test_owner_can_read_record_in_active_workspace(chat_app, route):
client, live_query = chat_app
response = client.get(
record_path(route, OTHER_RECORD),
headers={"test-workspace": str(OTHER_WORKSPACE)},
)

assert response.status_code == 200, response.text
if route == "export":
assert response.headers["content-type"].startswith(
"application/vnd.openxmlformats-officedocument.spreadsheetml.sheet"
)
with ZipFile(BytesIO(response.content)) as workbook:
assert b"saved-result" in workbook.read("xl/sharedStrings.xml")
elif route == "data":
assert response.json() == {**RESULT, "fields_info": None}
elif route == "data_live":
assert response.json()["data"] == LIVE_RESULT["data"]
elif route == "predict_data":
assert response.json() == PREDICTION
elif route == "log":
assert response.json()["steps"][0]["message"] == [{"content": LOG_MESSAGE}]
else:
assert response.json()["total_tokens"] == 3
assert response.json()["steps"] == []
assert live_query.call_count == int(route == "data_live")


@pytest.mark.parametrize("suffix", ["", "/with_data"])
def test_chat_details_use_active_workspace(chat_app, suffix):
client, _live_query = chat_app
path = f"/chat/{OTHER_CHAT}{suffix}"

response = client.get(path)
assert response.status_code == 500, response.text
assert response.json() == f"Chat with id {OTHER_CHAT} not found"

headers = {"test-workspace": str(OTHER_WORKSPACE)}
response = client.get(path, headers={**headers, "test-user": str(OTHER_USER)})
assert response.status_code == 500, response.text
assert response.json() == f"Chat with id {OTHER_CHAT} not Owned by the current user"

response = client.get(path, headers=headers)
assert response.status_code == 200, response.text
assert response.json()["records"][0]["id"] == OTHER_RECORD
if suffix:
assert response.json()["records"][0]["data"]["data"] == RESULT["data"]
1 change: 1 addition & 0 deletions docs/agents/backend.md
Original file line number Diff line number Diff line change
Expand Up @@ -98,6 +98,7 @@ Endpoint 命名沿既有风格:

### 记录状态与衍生关系

- 读取会话详情、会话详情附带的数据以及单条记录的结果、日志、用量和导出时,校验当前用户归属及会话所属工作空间。按记录访问时,从数据库中的记录关联会话,实时查询在执行数据源 SQL 前完成校验。
- 记录终态二元:`finish=true` 即终态,`error` 非空即失败。生成 SQL、执行、图表任一阶段失败都写同一个 `error` 字段;失败阶段从已填充字段推断(有 SQL 无数据为执行失败,有数据无图表为图表失败),精确失败点看 ChatLog 的 `error` 标记。
- 分析和预测各生成一条新的完整记录,复制源记录的问题、图表和数据,以 `analysis_record_id` / `predict_record_id` 指回源记录;衍生记录不能再被分析、预测或再生。
- 再生记录以 `regenerate_record_id` 指向被再生记录,形成链,沿链回溯可取到原始问题。
Expand Down
Loading