Files
ai-contract-platform/project-docs/V2-tenant-isolation-2026-06-26.md
T
yuqei a3bb78e06b
Security Quality Gate / npm audit, Bandit, pip-audit, detect-secrets (pull_request) Failing after 16m35s
release: freeze V2 release candidate
2026-07-12 15:32:24 +08:00

70 lines
2.0 KiB
Markdown
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
# AI 合同平台 V2 - 租户隔离功能闭环记录
日期:2026-06-26
## 背景
对照《AI 合同平台 V2 重构版开发方案》Phase 7 安全、性能与上线准备,本轮实现租户隔离功能,确保租户数据不可越权访问。
## 已完成内容
### 租户上下文管理
新增模块:
- `_tenant_context`: ContextVar 存储当前请求的租户ID
- `set_tenant_context(tenant_id)`: 设置租户上下文
- `get_tenant_context()`: 获取当前租户ID
- `clear_tenant_context()`: 清除租户上下文
- `DEFAULT_TENANT_ID = "default"`: 默认租户ID
### 数据模型租户字段
为以下模型添加 `tenant_id` 字段:
- `ContractModel`: 合同主表
- `ContractFileModel`: 文件表
- `ContractAuditEventModel`: 审计事件表
### 中间件层注入
在 `main.py` 中添加 `tenant_context_middleware`:
- 从请求头 `X-Tenant-Id` 读取租户ID
- 未提供时使用默认租户 "default"
- 请求结束后自动清理上下文
### 应用层租户过滤
在 `SqlAlchemyContractRepository` 中为以下方法添加租户过滤:
- `list_contracts()`: 合同列表
- `get_contract()`: 合同详情
- `create_contract()`: 创建合同时写入租户ID
- `list_files()`: 文件列表
### 越权测试
新增测试文件 `test_tenant_isolation.py`:
- `test_tenant_isolation_contracts`: 验证不同租户无法访问对方合同
- `test_tenant_context_functions`: 验证上下文函数
- `test_default_tenant_fallback`: 验证默认租户回退
## 验证结果
```powershell
python -m pytest yuqei-contract-platform/services/contract-api/tests -q # 28 passed
```
## Phase 7 进度
| 功能 | 状态 |
|------|------|
| 租户隔离 | ✅(本轮) |
| 权限矩阵 | 🔄 |
| 审计完整性 | 🔄 |
| 数据备份和恢复 | 🔄 |
| 错误监控 | 🔄 |
| 性能压测 | 🔄 |
| 安全扫描 | 🔄 |
| 部署文档 | 🔄 |
## 后续建议
下一步继续 Phase 7 的**审计完整性**功能,实现审计事件 append-only 和 hash chain 防篡改。