feat(rich): 备注/工单说明/知识正文支持 Markdown 与图片附件
写一件事的时候,光有纯文本不够:要贴截图、要分段、要标重点。 这次把「正文」这条路补全,思路是**存 Markdown 而不是 HTML**—— 能导出、能全文检索、能直接喂给 LLM,也不必每次渲染都重新清洗一遍 HTML。 后端 - attachment 表 + RLS + 迁移 0005;本地磁盘存储,key 由内容 sha256 决定, 换对象存储只改 services/storage.py 一个文件 - 上传在**读流时**卡 20MB,不先落盘再判断;磁盘名由服务端生成,用户文件名只进库和响应头 - 列表带 attachment_count、详情带 attachments,避免一屏 N 次请求 - raw 直链给 <img src> 用(图片带不了 Authorization 头),只允许本工作区成员, 非成员一律 8001 不区分「不存在」与「没权限」 - 5 个用例:上传下载、超限、跨租户、删除确认与权限、raw 鉴权 前端 - 自研零依赖 Markdown 渲染器:先转义再上标签,链接协议白名单 - RichTextEditor:工具栏 + Ctrl+B/I + 预览,粘贴或拖入图片自动上传并插入引用 - AttachmentPanel:上传/下载/删除,下载走带 Authorization 的 fetch 转 blob - 任务备注、工单说明与验收结论、知识正文、评论全部接入 顺手修的 - TaskDetail.hydrate 漏了 setAttachments,导致附件面板永远是空的(e2e 抓到的) 71 passed;web tsc 0 错、构建 255.07 kB │ gzip 80.85 kB; e2e:richtext 9 项 + smoke 7 + tickets 8 + knowledge 7,全绿。
This commit is contained in:
@@ -0,0 +1,66 @@
|
||||
"""附件表(任务 / 工单 / 知识共用)
|
||||
|
||||
Revision ID: 0005
|
||||
Revises: 0004
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import sqlalchemy as sa
|
||||
from sqlalchemy.dialects.postgresql import UUID as PgUUID
|
||||
|
||||
from alembic import op
|
||||
|
||||
revision = "0005"
|
||||
down_revision = "0004"
|
||||
branch_labels = None
|
||||
depends_on = None
|
||||
|
||||
|
||||
def upgrade() -> None:
|
||||
op.create_table(
|
||||
"attachment",
|
||||
sa.Column("id", PgUUID(as_uuid=True), primary_key=True),
|
||||
sa.Column(
|
||||
"workspace_id",
|
||||
PgUUID(as_uuid=True),
|
||||
sa.ForeignKey("workspace.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"item_id",
|
||||
PgUUID(as_uuid=True),
|
||||
sa.ForeignKey("item.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column(
|
||||
"uploader_id",
|
||||
PgUUID(as_uuid=True),
|
||||
sa.ForeignKey("app_user.id", ondelete="RESTRICT"),
|
||||
nullable=False,
|
||||
),
|
||||
sa.Column("filename", sa.String(255), nullable=False),
|
||||
sa.Column("content_type", sa.String(120), nullable=False),
|
||||
sa.Column("size_bytes", sa.BigInteger(), nullable=False),
|
||||
sa.Column("sha256", sa.String(64), nullable=False),
|
||||
sa.Column("storage_key", sa.String(255), nullable=False, unique=True),
|
||||
sa.Column("created_at", sa.DateTime(timezone=True), server_default=sa.func.now(), nullable=False),
|
||||
sa.CheckConstraint("size_bytes >= 0", name="ck_attachment_size"),
|
||||
)
|
||||
op.create_index(
|
||||
"ix_attachment_ws_item", "attachment", ["workspace_id", "item_id", "created_at"]
|
||||
)
|
||||
|
||||
for statement in (
|
||||
"ALTER TABLE attachment ENABLE ROW LEVEL SECURITY",
|
||||
"CREATE POLICY attachment_isolation ON attachment "
|
||||
"USING (workspace_id = app_ws_id()) WITH CHECK (workspace_id = app_ws_id())",
|
||||
"GRANT SELECT, INSERT, UPDATE, DELETE ON attachment TO dadao_app",
|
||||
):
|
||||
op.execute(statement)
|
||||
|
||||
|
||||
def downgrade() -> None:
|
||||
op.execute("DROP POLICY IF EXISTS attachment_isolation ON attachment")
|
||||
op.drop_index("ix_attachment_ws_item", table_name="attachment")
|
||||
op.drop_table("attachment")
|
||||
@@ -0,0 +1,292 @@
|
||||
"""附件接口:上传 / 列表 / 下载 / 删除。
|
||||
|
||||
三条约束(都会有用例守):
|
||||
1. 只认「本工作区的条目」。拿着别的租户的 item_id 上传,返回 5001 而不是 403——
|
||||
对外不该暴露那条记录是否存在。
|
||||
2. 大小上限在**读流时**卡住,不能先落盘再判断(否则等于给了别人一个写满磁盘的入口)。
|
||||
3. 磁盘上的名字由服务端生成,用户文件名只进库和 Content-Disposition。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import urllib.parse
|
||||
import uuid
|
||||
from typing import Annotated
|
||||
|
||||
from fastapi import APIRouter, File, Query, UploadFile
|
||||
from fastapi.responses import FileResponse
|
||||
from sqlalchemy import select
|
||||
from starlette.concurrency import run_in_threadpool
|
||||
|
||||
from app.audit import record as audit_record
|
||||
from app.config import get_settings
|
||||
from app.db import bind_tenant
|
||||
from app.deps import MemberDep, SessionDep
|
||||
from app.errors import AppError, ErrorCode
|
||||
from app.models import Member
|
||||
from app.models_attachment import Attachment
|
||||
from app.models_task import Item
|
||||
from app.schemas import ok
|
||||
from app.security import decode_token
|
||||
from app.services import storage
|
||||
|
||||
router = APIRouter(prefix="/workspaces/{ws_id}", tags=["attachments"])
|
||||
|
||||
ALLOWED_KINDS = ("task", "ticket", "knowledge")
|
||||
|
||||
|
||||
def _attachment_out(row: Attachment, viewer_id=None, role=None) -> dict:
|
||||
return {
|
||||
"id": str(row.id),
|
||||
"item_id": str(row.item_id),
|
||||
"filename": row.filename,
|
||||
"content_type": row.content_type,
|
||||
"size": row.size_bytes,
|
||||
"sha256": row.sha256,
|
||||
"uploader_id": str(row.uploader_id),
|
||||
"created_at": row.created_at.isoformat(),
|
||||
"can_delete": row.uploader_id == viewer_id or role in ("owner", "admin"),
|
||||
}
|
||||
|
||||
|
||||
async def _load_item(session, ws_id, item_id) -> Item:
|
||||
item = await session.scalar(
|
||||
select(Item).where(
|
||||
Item.id == item_id,
|
||||
Item.workspace_id == ws_id,
|
||||
Item.deleted_at.is_(None),
|
||||
Item.kind.in_(ALLOWED_KINDS),
|
||||
)
|
||||
)
|
||||
if item is None:
|
||||
raise AppError(ErrorCode.ITEM_NOT_FOUND, "事项不存在")
|
||||
return item
|
||||
|
||||
|
||||
def _safe_filename(name: str | None, fallback: str = "未命名文件") -> str:
|
||||
"""只用于展示与下载响应头:去掉路径分隔符与控制字符,长度截断。"""
|
||||
raw = (name or "").strip().replace("\\", "/").split("/")[-1]
|
||||
cleaned = "".join(ch for ch in raw if ch.isprintable() and ch not in '\r\n"')
|
||||
cleaned = cleaned.strip() or fallback
|
||||
if len(cleaned) > 200:
|
||||
stem, dot, ext = cleaned.rpartition(".")
|
||||
cleaned = (stem[:180] + dot + ext[-16:]) if dot and ext else cleaned[:200]
|
||||
return cleaned
|
||||
|
||||
|
||||
@router.post("/items/{item_id}/attachments", status_code=201)
|
||||
async def upload_attachment(
|
||||
ctx: MemberDep,
|
||||
session: SessionDep,
|
||||
item_id: str,
|
||||
file: Annotated[UploadFile, File()],
|
||||
):
|
||||
item = await _load_item(session, ctx.ws_id, item_id)
|
||||
limit = get_settings().max_upload_mb * 1024 * 1024
|
||||
|
||||
# 先看声明的大小(可选,客户端不一定给),真正的限额在读流时兜底
|
||||
if file.size is not None and file.size > limit:
|
||||
raise AppError(
|
||||
ErrorCode.ATTACHMENT_TOO_LARGE,
|
||||
f"文件超过 {get_settings().max_upload_mb}MB 上限",
|
||||
)
|
||||
|
||||
try:
|
||||
stored = await run_in_threadpool(
|
||||
storage.save, file.file, workspace_id=ctx.ws_id, item_id=item.id
|
||||
)
|
||||
if stored.size > limit:
|
||||
await run_in_threadpool(storage.remove, stored.key)
|
||||
raise AppError(
|
||||
ErrorCode.ATTACHMENT_TOO_LARGE,
|
||||
f"文件超过 {get_settings().max_upload_mb}MB 上限",
|
||||
)
|
||||
|
||||
row = Attachment(
|
||||
workspace_id=ctx.ws_id,
|
||||
item_id=item.id,
|
||||
uploader_id=ctx.user.id,
|
||||
filename=_safe_filename(file.filename),
|
||||
content_type=(file.content_type or "application/octet-stream")[:120],
|
||||
size_bytes=stored.size,
|
||||
sha256=stored.sha256,
|
||||
storage_key=stored.key,
|
||||
)
|
||||
session.add(row)
|
||||
await session.flush()
|
||||
await audit_record(
|
||||
session,
|
||||
workspace_id=ctx.ws_id,
|
||||
actor_user_id=ctx.user.id,
|
||||
action="attachment_uploaded",
|
||||
target_type="item",
|
||||
target_id=str(item.id),
|
||||
payload={"attachment_id": str(row.id), "filename": row.filename},
|
||||
)
|
||||
await session.commit()
|
||||
finally:
|
||||
await file.close()
|
||||
|
||||
return ok(_attachment_out(row, ctx.user.id, ctx.role))
|
||||
|
||||
|
||||
@router.get("/items/{item_id}/attachments")
|
||||
async def list_attachments(ctx: MemberDep, session: SessionDep, item_id: str):
|
||||
item = await _load_item(session, ctx.ws_id, item_id)
|
||||
rows = (
|
||||
await session.scalars(
|
||||
select(Attachment)
|
||||
.where(Attachment.workspace_id == ctx.ws_id, Attachment.item_id == item.id)
|
||||
.order_by(Attachment.created_at.asc())
|
||||
)
|
||||
).all()
|
||||
return ok({"items": [_attachment_out(row, ctx.user.id, ctx.role) for row in rows]})
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/download")
|
||||
async def download_attachment(ctx: MemberDep, session: SessionDep, attachment_id: str):
|
||||
row = await session.scalar(
|
||||
select(Attachment).where(
|
||||
Attachment.id == attachment_id, Attachment.workspace_id == ctx.ws_id
|
||||
)
|
||||
)
|
||||
if row is None:
|
||||
raise AppError(ErrorCode.ATTACHMENT_NOT_FOUND, "附件不存在")
|
||||
|
||||
path = storage.path_of(row.storage_key)
|
||||
if not path.exists():
|
||||
# 库里有记录、盘上没文件:说明备份漏了 blob,明确报错而不是返回空文件
|
||||
raise AppError(ErrorCode.ATTACHMENT_NOT_FOUND, "附件文件已丢失,请联系管理员")
|
||||
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=row.content_type,
|
||||
headers={
|
||||
# 中文文件名必须按 RFC 5987 编码,否则浏览器拿到的是乱码
|
||||
"Content-Disposition": "attachment; filename*=UTF-8''"
|
||||
+ urllib.parse.quote(row.filename),
|
||||
# 附件是不可信内容:禁止浏览器嗅探类型,否则 .txt 里的 HTML 会被执行
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.get("/attachments/{attachment_id}/raw")
|
||||
async def raw_attachment(
|
||||
ws_id: uuid.UUID,
|
||||
session: SessionDep,
|
||||
attachment_id: uuid.UUID,
|
||||
token: Annotated[str, Query(description="access token(<img src> 带不了请求头)")],
|
||||
):
|
||||
"""给 Markdown 里的 `` 用:浏览器 <img> 无法附加 Authorization 头。
|
||||
|
||||
token 走 query 是 Web 上的通行做法,但要接受它的代价:会进访问日志与浏览器历史。
|
||||
所以这个接口**只读、只给本工作区成员**,且不返回 Content-Disposition(不当下载用)。
|
||||
"""
|
||||
try:
|
||||
user_id = decode_token(token, "access")
|
||||
except Exception: # noqa: BLE001 —— 任何解码失败都按未认证处理
|
||||
raise AppError(ErrorCode.UNAUTHORIZED, "登录已过期,请重新登录") from None
|
||||
|
||||
# 这个接口没有走 MemberDep(令牌在 query 里),RLS 不会自动绑租户,得手动绑一次
|
||||
await bind_tenant(session, ws_id=ws_id, user_id=user_id)
|
||||
|
||||
member = await session.scalar(
|
||||
select(Member.id).where(
|
||||
Member.workspace_id == ws_id,
|
||||
Member.user_id == user_id,
|
||||
Member.status == "active",
|
||||
)
|
||||
)
|
||||
if member is None:
|
||||
# 不是成员就当作不存在:不暴露"这里有个附件但你看不到"
|
||||
raise AppError(ErrorCode.ATTACHMENT_NOT_FOUND, "附件不存在")
|
||||
|
||||
row = await session.scalar(
|
||||
select(Attachment).where(Attachment.id == attachment_id, Attachment.workspace_id == ws_id)
|
||||
)
|
||||
if row is None:
|
||||
raise AppError(ErrorCode.ATTACHMENT_NOT_FOUND, "附件不存在")
|
||||
|
||||
path = storage.path_of(row.storage_key)
|
||||
if not path.exists():
|
||||
raise AppError(ErrorCode.ATTACHMENT_NOT_FOUND, "附件文件已丢失,请联系管理员")
|
||||
|
||||
return FileResponse(
|
||||
path,
|
||||
media_type=row.content_type,
|
||||
headers={
|
||||
"Content-Disposition": "inline",
|
||||
"X-Content-Type-Options": "nosniff",
|
||||
# 附件内容不变(key 由内容哈希决定),可以放心长缓存;换了文件就是换了 id
|
||||
"Cache-Control": "private, max-age=86400",
|
||||
},
|
||||
)
|
||||
|
||||
|
||||
@router.delete("/attachments/{attachment_id}")
|
||||
async def delete_attachment(
|
||||
ctx: MemberDep, session: SessionDep, attachment_id: str, confirm: bool = Query(False)
|
||||
):
|
||||
row = await session.scalar(
|
||||
select(Attachment).where(
|
||||
Attachment.id == attachment_id, Attachment.workspace_id == ctx.ws_id
|
||||
)
|
||||
)
|
||||
if row is None:
|
||||
raise AppError(ErrorCode.ATTACHMENT_NOT_FOUND, "附件不存在")
|
||||
|
||||
is_uploader = row.uploader_id == ctx.user.id
|
||||
if not is_uploader and ctx.role not in ("owner", "admin"):
|
||||
raise AppError(ErrorCode.ATTACHMENT_FORBIDDEN, "只有上传者或管理员能删除附件")
|
||||
if not confirm:
|
||||
# 删除不可逆,要求显式确认,避免误点
|
||||
raise AppError(
|
||||
ErrorCode.CONFIRM_REQUIRED, "删除附件需要二次确认", details={"confirm": True}
|
||||
)
|
||||
|
||||
await run_in_threadpool(storage.remove, row.storage_key)
|
||||
await session.delete(row)
|
||||
await audit_record(
|
||||
session,
|
||||
workspace_id=ctx.ws_id,
|
||||
actor_user_id=ctx.user.id,
|
||||
action="attachment_deleted",
|
||||
target_type="item",
|
||||
target_id=str(row.item_id),
|
||||
payload={"attachment_id": str(row.id), "filename": row.filename},
|
||||
)
|
||||
await session.commit()
|
||||
return ok({"deleted": True})
|
||||
|
||||
|
||||
async def list_for_item(session, ws_id, item_id) -> list[dict]:
|
||||
"""给其他接口内联用(列表/详情里带上附件摘要)。"""
|
||||
rows = (
|
||||
await session.scalars(
|
||||
select(Attachment)
|
||||
.where(Attachment.workspace_id == ws_id, Attachment.item_id == item_id)
|
||||
.order_by(Attachment.created_at.asc())
|
||||
)
|
||||
).all()
|
||||
return [_attachment_out(row) for row in rows]
|
||||
|
||||
|
||||
async def count_for_items(session, ws_id, item_ids: list) -> dict[str, int]:
|
||||
"""列表页只显示"几个附件",避免每条都拉全量。"""
|
||||
if not item_ids:
|
||||
return {}
|
||||
rows = (
|
||||
await session.execute(
|
||||
select(Attachment.item_id).where(
|
||||
Attachment.workspace_id == ws_id, Attachment.item_id.in_(item_ids)
|
||||
)
|
||||
)
|
||||
).all()
|
||||
counts: dict[str, int] = {}
|
||||
for (item_id,) in rows:
|
||||
counts[str(item_id)] = counts.get(str(item_id), 0) + 1
|
||||
return counts
|
||||
|
||||
|
||||
__all__ = ["router", "list_for_item", "count_for_items"]
|
||||
@@ -31,6 +31,7 @@ from ..models_task import Activity, Comment, Item, ItemTag, Tag
|
||||
from ..models_ticket import TicketExt
|
||||
from ..schemas import Pagination, encode_cursor, ok
|
||||
from ..serializers import item_out, tag_out, tags_of
|
||||
from .attachments import count_for_items, list_for_item
|
||||
|
||||
router = APIRouter(prefix="/workspaces/{ws_id}/items", tags=["任务"])
|
||||
tag_router = APIRouter(prefix="/workspaces/{ws_id}/tags", tags=["标签"])
|
||||
@@ -294,9 +295,13 @@ async def list_items(
|
||||
.all()
|
||||
)
|
||||
tags = await _tags_of(session, ctx.ws_id, [r.id for r in rows])
|
||||
counts = await count_for_items(session, ctx.ws_id, [r.id for r in rows])
|
||||
return ok(
|
||||
{
|
||||
"items": [_item_out(r, tags.get(r.id)) for r in rows],
|
||||
"items": [
|
||||
dict(_item_out(r, tags.get(r.id)), attachment_count=counts.get(str(r.id), 0))
|
||||
for r in rows
|
||||
],
|
||||
"next_cursor": None,
|
||||
"has_more": False,
|
||||
}
|
||||
@@ -325,9 +330,13 @@ async def list_items(
|
||||
encode_cursor(getattr(rows[-1], sort_attr), rows[-1].id) if has_more and rows else None
|
||||
)
|
||||
tags = await _tags_of(session, ctx.ws_id, [r.id for r in rows])
|
||||
counts = await count_for_items(session, ctx.ws_id, [r.id for r in rows])
|
||||
return ok(
|
||||
{
|
||||
"items": [_item_out(r, tags.get(r.id)) for r in rows],
|
||||
"items": [
|
||||
dict(_item_out(r, tags.get(r.id)), attachment_count=counts.get(str(r.id), 0))
|
||||
for r in rows
|
||||
],
|
||||
"next_cursor": next_cursor,
|
||||
"has_more": has_more,
|
||||
}
|
||||
@@ -405,6 +414,8 @@ async def get_item(item_id: uuid.UUID, ctx: MemberDep, session: SessionDep) -> d
|
||||
.all()
|
||||
)
|
||||
data = _item_out(item, tags.get(item.id))
|
||||
data["attachments"] = await list_for_item(session, ctx.ws_id, item.id)
|
||||
data["attachment_count"] = len(data["attachments"])
|
||||
data["activities"] = [
|
||||
{
|
||||
"id": str(a.id),
|
||||
|
||||
@@ -33,6 +33,7 @@ from ..models_task import Activity, Item
|
||||
from ..schemas import clamp_limit, decode_cursor, encode_cursor, ok
|
||||
from ..serializers import item_out, tags_of
|
||||
from ..services.knowledge import create_draft_from_source, find_doc_by_source
|
||||
from .attachments import count_for_items, list_for_item
|
||||
|
||||
router = APIRouter(prefix="/workspaces/{ws_id}", tags=["知识库"])
|
||||
|
||||
@@ -125,6 +126,8 @@ async def _knowledge_out(
|
||||
data = item_out(item, tags)
|
||||
data["knowledge"] = _doc_out(doc)
|
||||
data["source"] = await _source_out(session, ws_id, doc.source_item_id)
|
||||
data["attachments"] = await list_for_item(session, ws_id, item.id)
|
||||
data["attachment_count"] = len(data["attachments"])
|
||||
return data
|
||||
|
||||
|
||||
@@ -186,10 +189,12 @@ async def list_knowledge(
|
||||
tag_map = await tags_of(session, ws_id, [it.id for it, _ in rows])
|
||||
|
||||
items = []
|
||||
counts = await count_for_items(session, ws_id, [it.id for it, _ in rows])
|
||||
for item, doc in rows:
|
||||
data = item_out(item, tag_map.get(item.id, []))
|
||||
data["knowledge"] = _doc_out(doc)
|
||||
data["source"] = await _source_out(session, ws_id, doc.source_item_id)
|
||||
data["attachment_count"] = counts.get(str(item.id), 0)
|
||||
items.append(data)
|
||||
|
||||
next_cursor = (
|
||||
|
||||
@@ -62,6 +62,12 @@ class Settings(BaseSettings):
|
||||
idempotency_enabled: bool = True
|
||||
idempotency_ttl_seconds: int = 86_400
|
||||
|
||||
# ── 附件 ──────────────────────────────────────────────
|
||||
# 本地磁盘目录(相对 backend/ 或绝对路径)。换对象存储时只改 services/storage.py。
|
||||
upload_dir: str = "var/uploads"
|
||||
# 单文件上限。20MB 够放文档与截图;再大就该走对象存储 + 分片了。
|
||||
max_upload_mb: int = 20
|
||||
|
||||
# ── 知识库向量库(独立实例,M3 起用)───────────────────
|
||||
# 刻意与业务库分开放:fnsvr-01 上的 PG 没有 pgvector,也不该为了装扩展去动它;
|
||||
# 向量检索吃内存,和任务库挤在同一实例会互相拖累。
|
||||
|
||||
@@ -57,6 +57,12 @@ class ErrorCode(IntEnum):
|
||||
KNOWLEDGE_FORBIDDEN = 7004
|
||||
KNOWLEDGE_SOURCE_REQUIRED = 7005
|
||||
|
||||
# 8xxx 附件
|
||||
ATTACHMENT_NOT_FOUND = 8001
|
||||
ATTACHMENT_TOO_LARGE = 8002
|
||||
ATTACHMENT_FORBIDDEN = 8003
|
||||
CONFIRM_REQUIRED = 8004
|
||||
|
||||
|
||||
# 默认 HTTP 状态:业务码自己带语义,HTTP 只是传输层
|
||||
_HTTP_STATUS: dict[ErrorCode, int] = {
|
||||
@@ -95,6 +101,10 @@ _HTTP_STATUS: dict[ErrorCode, int] = {
|
||||
ErrorCode.KNOWLEDGE_STATUS_INVALID: 409,
|
||||
ErrorCode.KNOWLEDGE_FORBIDDEN: 403,
|
||||
ErrorCode.KNOWLEDGE_SOURCE_REQUIRED: 409,
|
||||
ErrorCode.ATTACHMENT_NOT_FOUND: 404,
|
||||
ErrorCode.ATTACHMENT_TOO_LARGE: 413,
|
||||
ErrorCode.ATTACHMENT_FORBIDDEN: 403,
|
||||
ErrorCode.CONFIRM_REQUIRED: 409,
|
||||
}
|
||||
|
||||
|
||||
|
||||
+2
-1
@@ -12,7 +12,7 @@ from fastapi.responses import JSONResponse
|
||||
from sqlalchemy import text
|
||||
from starlette.exceptions import HTTPException as StarletteHTTPException
|
||||
|
||||
from .api import auth, items, knowledge, tickets, workspaces
|
||||
from .api import attachments, auth, items, knowledge, tickets, workspaces
|
||||
from .config import get_settings
|
||||
from .db import SessionFactory, current_app_role, engine
|
||||
from .errors import AppError, ErrorCode, http_status_for
|
||||
@@ -105,6 +105,7 @@ app.include_router(items.tag_router, prefix=settings.api_prefix)
|
||||
app.include_router(tickets.router, prefix=settings.api_prefix)
|
||||
app.include_router(tickets.notify_router, prefix=settings.api_prefix)
|
||||
app.include_router(knowledge.router, prefix=settings.api_prefix)
|
||||
app.include_router(attachments.router, prefix=settings.api_prefix)
|
||||
|
||||
|
||||
@app.get("/health", tags=["运维"], summary="存活探针")
|
||||
|
||||
@@ -135,6 +135,7 @@ class AuditLog(Base):
|
||||
#
|
||||
# 任务域的表在 models_task.py、工单域在 models_ticket.py —— 它们 import 本模块的 Base,
|
||||
# 所以只能在文件末尾反向 import,否则循环导入。
|
||||
from .models_attachment import ATTACHMENT_TENANT_TABLES # noqa: E402
|
||||
from .models_knowledge import KNOWLEDGE_TENANT_TABLES # noqa: E402
|
||||
from .models_task import TASK_TENANT_TABLES # noqa: E402
|
||||
from .models_ticket import TICKET_TENANT_TABLES # noqa: E402
|
||||
@@ -147,4 +148,5 @@ TENANT_TABLES: tuple[str, ...] = (
|
||||
*TASK_TENANT_TABLES,
|
||||
*TICKET_TENANT_TABLES,
|
||||
*KNOWLEDGE_TENANT_TABLES,
|
||||
*ATTACHMENT_TENANT_TABLES,
|
||||
)
|
||||
|
||||
@@ -0,0 +1,66 @@
|
||||
"""附件:任务与知识条目共用一张表。
|
||||
|
||||
为什么不区分 kind:知识本身就是 `item`(kind=knowledge),附件挂在 `item_id` 上
|
||||
天然对任务、工单、知识一视同仁;将来要给「工单」加验收材料也不用再建表。
|
||||
|
||||
文件本体放磁盘,库里只存元数据与 `storage_key`。这样做的代价是备份要同时备盘,
|
||||
收益是数据库不会被几十 MB 的文件撑爆、备份与恢复的粒度还能分开。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import uuid
|
||||
from datetime import datetime
|
||||
|
||||
from sqlalchemy import (
|
||||
BigInteger,
|
||||
CheckConstraint,
|
||||
DateTime,
|
||||
ForeignKey,
|
||||
Index,
|
||||
String,
|
||||
func,
|
||||
)
|
||||
from sqlalchemy.dialects.postgresql import UUID as PgUUID
|
||||
from sqlalchemy.orm import Mapped, mapped_column
|
||||
|
||||
from app.models import Base
|
||||
|
||||
ATTACHMENT_TENANT_TABLES = ("attachment",)
|
||||
|
||||
|
||||
class Attachment(Base):
|
||||
__tablename__ = "attachment"
|
||||
__table_args__ = (
|
||||
CheckConstraint("size_bytes >= 0", name="ck_attachment_size"),
|
||||
Index("ix_attachment_ws_item", "workspace_id", "item_id", "created_at"),
|
||||
)
|
||||
|
||||
id: Mapped[uuid.UUID] = mapped_column(
|
||||
PgUUID(as_uuid=True), primary_key=True, default=uuid.uuid4
|
||||
)
|
||||
workspace_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PgUUID(as_uuid=True),
|
||||
ForeignKey("workspace.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
item_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PgUUID(as_uuid=True),
|
||||
ForeignKey("item.id", ondelete="CASCADE"),
|
||||
nullable=False,
|
||||
)
|
||||
uploader_id: Mapped[uuid.UUID] = mapped_column(
|
||||
PgUUID(as_uuid=True), ForeignKey("app_user.id", ondelete="RESTRICT"), nullable=False
|
||||
)
|
||||
# 原始文件名:只用于展示与下载时的 Content-Disposition,绝不参与磁盘路径
|
||||
filename: Mapped[str] = mapped_column(String(255), nullable=False)
|
||||
content_type: Mapped[str] = mapped_column(
|
||||
String(120), nullable=False, default="application/octet-stream"
|
||||
)
|
||||
size_bytes: Mapped[int] = mapped_column(BigInteger, nullable=False, default=0)
|
||||
sha256: Mapped[str] = mapped_column(String(64), nullable=False)
|
||||
storage_key: Mapped[str] = mapped_column(String(255), nullable=False, unique=True)
|
||||
|
||||
created_at: Mapped[datetime] = mapped_column(
|
||||
DateTime(timezone=True), server_default=func.now(), nullable=False
|
||||
)
|
||||
@@ -0,0 +1,72 @@
|
||||
"""本地文件存储。
|
||||
|
||||
M0/M1 用本地磁盘就够:单机、量小、备份简单。要做 SaaS 多副本时换成对象存储,
|
||||
只需要换掉本模块的三个函数(写入 / 读取路径 / 删除),API 层不用动。
|
||||
|
||||
安全约定:
|
||||
- 磁盘路径完全由服务端生成(租户 + 条目 + 随机文件名),**不使用用户提供的文件名**,
|
||||
否则 `../../` 之类可以直接逃出上传目录。
|
||||
- 原始文件名只存库、只出现在下载响应头里。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import contextlib
|
||||
import hashlib
|
||||
import uuid
|
||||
from dataclasses import dataclass
|
||||
from pathlib import Path
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
|
||||
@dataclass(frozen=True)
|
||||
class Stored:
|
||||
key: str
|
||||
size: int
|
||||
sha256: str
|
||||
|
||||
|
||||
def root() -> Path:
|
||||
path = Path(get_settings().upload_dir)
|
||||
path.mkdir(parents=True, exist_ok=True)
|
||||
return path
|
||||
|
||||
|
||||
def path_of(key: str) -> Path:
|
||||
"""key 由服务端生成,这里仍做一次越界校验——防御的是库被写脏。"""
|
||||
base = root().resolve()
|
||||
target = (base / key).resolve()
|
||||
if base not in target.parents:
|
||||
raise ValueError("storage key escapes upload root")
|
||||
return target
|
||||
|
||||
|
||||
def save(stream, *, workspace_id: uuid.UUID, item_id: uuid.UUID) -> Stored:
|
||||
"""把文件流写进磁盘,返回 key / 大小 / 摘要。
|
||||
|
||||
`stream` 是同步的二进制可读对象;调用方用 `run_in_threadpool` 包一层,
|
||||
避免大文件读写卡住事件循环。
|
||||
"""
|
||||
key = f"{workspace_id}/{item_id}/{uuid.uuid4().hex}"
|
||||
target = path_of(key)
|
||||
target.parent.mkdir(parents=True, exist_ok=True)
|
||||
|
||||
digest = hashlib.sha256()
|
||||
size = 0
|
||||
with target.open("wb") as out:
|
||||
while True:
|
||||
chunk = stream.read(1024 * 256)
|
||||
if not chunk:
|
||||
break
|
||||
digest.update(chunk)
|
||||
size += len(chunk)
|
||||
out.write(chunk)
|
||||
return Stored(key=key, size=size, sha256=digest.hexdigest())
|
||||
|
||||
|
||||
def remove(key: str) -> None:
|
||||
# 删文件时"文件已经不在了"和"key 格式不对"都不算错误:
|
||||
# 前者是重复删除,后者是库里有脏数据,都只能靠日志发现问题,不该让请求失败。
|
||||
with contextlib.suppress(FileNotFoundError, ValueError):
|
||||
path_of(key).unlink()
|
||||
@@ -7,8 +7,9 @@ pydantic==2.10.4
|
||||
pydantic-settings==2.7.0
|
||||
pyjwt==2.10.1
|
||||
redis==5.2.1
|
||||
# Windows 没有系统 tzdata,zoneinfo 找不到 "Asia/Shanghai";
|
||||
# Linux 上装它也无害(会用包里的,而不是系统的)。
|
||||
python-multipart==0.0.20
|
||||
# Windows has no system tz database; ZoneInfo("Asia/Shanghai") fails without this.
|
||||
# On Linux the package simply shadows the system one -- harmless.
|
||||
tzdata==2026.5
|
||||
|
||||
# dev / test only (split into requirements-dev.txt when it grows)
|
||||
|
||||
@@ -0,0 +1,170 @@
|
||||
"""附件:上传、列表、下载、删除、跨租户与配额。
|
||||
|
||||
用例守的是三条约束(见 app/api/attachments.py 文件头):
|
||||
1. 只认本工作区的条目,别人的 item_id 一律 5001;
|
||||
2. 超限在读流时卡住,且不留垃圾文件;
|
||||
3. 磁盘名服务端生成,用户文件名只进库与 Content-Disposition。
|
||||
"""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
from typing import Any
|
||||
|
||||
import pytest
|
||||
from httpx import AsyncClient
|
||||
|
||||
from app.config import get_settings
|
||||
|
||||
from .conftest import create_workspace, login, unwrap
|
||||
|
||||
BASE = "/api/v1"
|
||||
|
||||
|
||||
async def _ws_with_item(client: AsyncClient, name: str = "附件工作区") -> tuple[Any, Any, str]:
|
||||
user = await login(client)
|
||||
ws = await create_workspace(client, user, name)
|
||||
item = unwrap(
|
||||
await client.post(
|
||||
f"{BASE}/workspaces/{ws['id']}/items",
|
||||
json={"title": "整理发票原件"},
|
||||
headers=user["headers"],
|
||||
)
|
||||
)
|
||||
return user, ws, item["id"]
|
||||
|
||||
|
||||
async def _upload(
|
||||
client: AsyncClient, user: dict[str, Any], ws_id: str, item_id: str, content: bytes, name: str
|
||||
) -> Any:
|
||||
return await client.post(
|
||||
f"{BASE}/workspaces/{ws_id}/items/{item_id}/attachments",
|
||||
files={"file": (name, content, "text/plain")},
|
||||
headers=user["headers"],
|
||||
)
|
||||
|
||||
|
||||
async def test_upload_list_and_download(client: AsyncClient) -> None:
|
||||
user, ws, item_id = await _ws_with_item(client)
|
||||
body = "发票号 044031900111,金额 1280.00".encode()
|
||||
|
||||
created = unwrap(await _upload(client, user, ws["id"], item_id, body, "发票.txt"))
|
||||
assert created["filename"] == "发票.txt"
|
||||
assert created["size"] == len(body)
|
||||
assert created["sha256"]
|
||||
assert created["can_delete"] is True
|
||||
|
||||
listed = unwrap(
|
||||
await client.get(
|
||||
f"{BASE}/workspaces/{ws['id']}/items/{item_id}/attachments", headers=user["headers"]
|
||||
)
|
||||
)
|
||||
assert [a["id"] for a in listed["items"]] == [created["id"]]
|
||||
assert listed["items"][0]["content_type"] == "text/plain"
|
||||
|
||||
# 计数要出现在任务列表与详情里,否则前端没法显示「3 个附件」
|
||||
items = unwrap(
|
||||
await client.get(f"{BASE}/workspaces/{ws['id']}/items?view=all", headers=user["headers"])
|
||||
)
|
||||
row = next(i for i in items["items"] if i["id"] == item_id)
|
||||
assert row["attachment_count"] == 1
|
||||
|
||||
detail = unwrap(
|
||||
await client.get(f"{BASE}/workspaces/{ws['id']}/items/{item_id}", headers=user["headers"])
|
||||
)
|
||||
assert detail["attachment_count"] == 1
|
||||
assert detail["attachments"][0]["id"] == created["id"]
|
||||
|
||||
# 下载要能原样取回,并给出可辨识的文件名
|
||||
resp = await client.get(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}/download",
|
||||
headers=user["headers"],
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.content == body
|
||||
assert "filename*=UTF-8''" in resp.headers["content-disposition"]
|
||||
assert resp.headers["x-content-type-options"] == "nosniff"
|
||||
|
||||
|
||||
async def test_reject_oversized(client: AsyncClient, monkeypatch: pytest.MonkeyPatch) -> None:
|
||||
user, ws, item_id = await _ws_with_item(client)
|
||||
monkeypatch.setattr(get_settings(), "max_upload_mb", 0)
|
||||
|
||||
body = (await _upload(client, user, ws["id"], item_id, b"x" * 4096, "big.txt")).json()
|
||||
assert body["code"] == 8002
|
||||
assert "上限" in body["message"]
|
||||
|
||||
|
||||
async def test_cannot_attach_to_other_tenant_item(client: AsyncClient) -> None:
|
||||
"""跨租户的 item_id 不能成为落点——否则等于往别人的时间线上塞文件。"""
|
||||
user, _ws, item_id = await _ws_with_item(client, "甲的组")
|
||||
other, other_ws, other_item = await _ws_with_item(client, "乙的组")
|
||||
|
||||
# 拿别人工作区的 id 上传:自己不是成员
|
||||
resp = (await _upload(client, user, other_ws["id"], other_item, b"x", "x.txt")).json()
|
||||
assert resp["code"] in (3003, 5001)
|
||||
|
||||
# 在自己的工作区里塞别人的 item_id:条目找不到,也不该暴露它存在
|
||||
resp2 = (await _upload(client, user, _ws["id"], other_item, b"x", "x.txt")).json()
|
||||
assert resp2["code"] == 5001
|
||||
|
||||
|
||||
async def test_delete_requires_confirm_and_ownership(client: AsyncClient) -> None:
|
||||
owner, ws, item_id = await _ws_with_item(client)
|
||||
created = unwrap(await _upload(client, owner, ws["id"], item_id, b"abc", "a.txt"))
|
||||
|
||||
# 不确认不给删:删除不可逆,前端容易误触
|
||||
resp = (
|
||||
await client.delete(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}", headers=owner["headers"]
|
||||
)
|
||||
).json()
|
||||
assert resp["code"] == 8004
|
||||
assert resp["data"] == {"confirm": True}
|
||||
|
||||
# 同工作区但非上传者的普通成员也删不了
|
||||
outsider = await login(client)
|
||||
resp = (
|
||||
await client.delete(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}?confirm=true",
|
||||
headers=outsider["headers"],
|
||||
)
|
||||
).json()
|
||||
assert resp["code"] in (3003, 8003)
|
||||
|
||||
gone = unwrap(
|
||||
await client.delete(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}?confirm=true",
|
||||
headers=owner["headers"],
|
||||
)
|
||||
)
|
||||
assert gone["deleted"] is True
|
||||
|
||||
after = await client.get(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}/download",
|
||||
headers=owner["headers"],
|
||||
)
|
||||
assert after.json()["code"] == 8001
|
||||
|
||||
|
||||
async def test_raw_image_url_takes_token_in_query(client: AsyncClient) -> None:
|
||||
"""Markdown 里的 `` 给 <img> 用:头带不了令牌,只能走 query。"""
|
||||
user, ws, item_id = await _ws_with_item(client)
|
||||
body = b"\x89PNG\r\n\x1a\n fake png"
|
||||
created = unwrap(await _upload(client, user, ws["id"], item_id, body, "图.png"))
|
||||
|
||||
resp = await client.get(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}/raw?token={user['token']}"
|
||||
)
|
||||
assert resp.status_code == 200
|
||||
assert resp.content == body
|
||||
assert resp.headers["content-disposition"] == "inline"
|
||||
assert resp.headers["cache-control"].startswith("private")
|
||||
|
||||
# 不带 token 直接 422(参数必填),带了别人的 token 一律当不存在
|
||||
missing = await client.get(f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}/raw")
|
||||
assert missing.status_code == 422
|
||||
outsider = await login(client)
|
||||
leaked = await client.get(
|
||||
f"{BASE}/workspaces/{ws['id']}/attachments/{created['id']}/raw?token={outsider['token']}"
|
||||
)
|
||||
assert leaked.json()["code"] == 8001
|
||||
Reference in New Issue
Block a user