完成安全整改与配置系统重构阶段开发
Security Checks / security (push) Waiting to run

This commit is contained in:
xuans committed 2026-08-28 00:42:28 +08:00
1 parent 6ec462895f
commit 18b6dfbdf7
26 files changed
+1913 -169

No files matched your search

+87 -81
View File
@@ -1,153 +1,159 @@
# Smail # Smail
> A server, a domain, a line of code, a minute, and you'll be able to build a domain mailbox of your own. > 一台服务器、一个域名、一行代码、一分钟时间,你就能够搭建出一个自己的域名邮箱。
## [中文文档](./README_CN.md) Smail是一个追求极简部署流程、极致资源占用的个人域名邮箱服务器。单文件运行,包含完整的收发邮件服务和Web端邮件管理功能。只需一台服务器、一个域名、一行代码、一分钟部署时间,你就能够搭建出一个自己的域名邮箱。
I'm Chinese, and I'm not good at English, so I apologise for my translation. 欢迎各类PR,无论你是修复bug、新增功能、修改翻译。另外,也为这个项目征集一个漂亮可爱的Logo!
## Introduction <img src="./docs/cn.gif" alt="Editor" width="800px">
Smail is a personal email server that pursues a minimal deployment process and extreme resource consumption. It runs on ## 为什么写这个项目
a single file and contains complete send/receive mail service and web-side mail management functions. Just a server , a
domain name , a line of code , a minute of deployment time , you will be able to build a domain name mailbox of your
own .
All kinds of PR are welcome, whether you are fixing bugs, adding features, or optimizing translations. Also, call for a 迫于越来越多的邮件服务商暂停了针对个人的域名邮箱服务(比如QQ邮箱、微软Outlook邮箱),因此考虑自建域名邮箱服务。
beautiful and cute Logo for this project! 但是自建域名邮箱可选的程序并不多,且目标都不是针对个人使用场景设计的。个人服务器一般内存、CPU、硬盘配置都不高,针对公司场景使用的邮箱程序过于臃肿,
白白浪费资源。就拿我自己的服务器来说,我服务器配置为1核512M 10G硬盘,市面上绝大多数邮箱服务器安装上就把磁盘占满了,根本没法正常使用
<img src="./docs/en.gif" alt="Editor" width="800px"> ## 项目优势
## Features ### 1、部署简单
* Single file operation and easy deployment. 使用Go语言编写,支持跨平台,编译后单文件运行,单文件包含完整的前后端代码。修改配置文件,运行即可。
* The binary file is only 15MB and takes up less than 10M of memory during the run.
* Support dkim, spf checksum, [Email Test](https://www.mail-tester.com/) score 10 points if correctly configured.
* Implementing the ACME protocol, the program will automatically obtain and update Let's Encrypt certificates.
> By default, a ssl certificate is generated for the web service, allowing pages to use the https protocol. ### 2、资源占用极小
> If you have your own gateway or don't need https, set `httpsEnabled` to `2` in the configuration file so that the web
> service will not use https.
> (Note: Even if you don't need https, please make sure the path to the ssl certificate file is correct, although the web
> service doesn't use the certificate anymore, the smtp protocol still needs the certificate)
* Support pop3, smtp protocol, you can use any mail client you like. 编译后二进制文件仅15MB,运行过程中占用内存10M以内。
* Support multi-domain, multi-user and complete support for sending and receiving e-mail.
### 3、安全方面
# How to run 支持dkim、spf校验。正确配置的情况下,Email Test得分10分。
## 0、Check You IP / Domain ### 4、自动SSL证书
First go to [spamhaus](https://check.spamhaus.org/) and check your domain name and server IP for blocking records 实现了ACME协议,程序将自动获取并更新Let’s Encrypt证书。
## 1、Download 默认情况下,会为web后台也生成ssl证书,让后台使用https访问,如果你有自己的网关层,不需要https的话,在配置文件中将 `httpsEnabled`
设置为 `2`,这样管理后台就不会使用https协议。( 注意:即使你不需要https,也请保证ssl证书文件路径正确,http协议虽然不使用证书了,但是smtp协议还需要证书)
* [Click Here](https://git.pcux.cn/xuans/Smail/releases) Download a program file that matches you. ### 5、邮件客户端支持
* Or use Docker `docker pull ghcr.io/jinnrry/pmail:latest`
## 2、Run 只要支持pop3、smtp、imap协议的邮件客户端均可使用
### 6、多域名、多用户支持
支持多域名、多用户且完整支持收发邮件
# 如何部署
## 0、检查IP、域名
先去[spamhaus](https://check.spamhaus.org/)检查你的域名和服务器IP是否有屏蔽记录
## 1、下载文件
* [点击这里](https://git.pcux.cn/xuans/Smail/releases)下载一个与你匹配的程序文件。
* 或者使用Docker运行 `docker pull ghcr.io/jinnrry/pmail:latest`
## 2、运行
`./smail -p 80` `./smail -p 80`
> -p Set the http port of the bootstrap setup interface, the default is port 80, note that this parameter only affects the bootstrap setup phase, if you need to change the port after setup is complete, please modify the configuration file. > `-p 指定引导设置界面的http端口,默认为80端口,注意该参数仅影响引导设置阶段,设置完成后如果需要修改端口请修改配置文件`
> [!IMPORTANT] > [!IMPORTANT]
> The SSL certificate will not be set automatically if the bootstrap setup phase uses a port other than 80. > 如果引导设置阶段使用非80端口,将无法自动设置SSL证书
Or 或者
`docker run -p 25:25 -p 80:80 -p 443:443 -p 110:110 -p 465:465 -p 587:587 -p 995:995 -p 993:993 -v $(pwd)/config:/work/config ghcr.io/jinnrry/pmail:latest` `docker run -p 25:25 -p 80:80 -p 443:443 -p 110:110 -p 465:465 -p 587:587 -p 995:995 -p 993:993 -v $(pwd)/config:/work/config ghcr.io/jinnrry/pmail:latest`
> [!IMPORTANT] > [!IMPORTANT]
> If your server has a firewall turned on, you need to open ports 25, 80, 110, 443, 465,587, 993, 995 > 如果你服务器开启了防火墙,你需要打开25、80、110、443、465、587、995、993端口
## 3、Configuration ## 3、配置
Open `http://127.0.0.1` in your browser or use your server's public IP to visit, then follow the instructions to 浏览器打开 `http://127.0.0.1` 或者是用你服务器公网IP访问,然后按提示配置
configure.
## 4、Email Test ## 4、邮箱得分测试
Check if your mailbox has completed all the security configuration. It is recommended to 建议找一下邮箱测试服务(比如[https://www.mail-tester.com/](https://www.mail-tester.com/))进行邮件得分检测,避免自己某些步骤漏配,导致发件进对方垃圾箱。
use [https://www.mail-tester.com/](https://www.mail-tester.com/) for checking.
# 配置文件说明
# Configuration file format description
```jsonc ```jsonc
{ {
"logLevel": "info", //log output level "logLevel": "info", //日志输出级别
"domain": "domain.com", // Your domain "domain": "domain.com", // 你的域名
"webDomain": "mail.domain.com", // web domain "webDomain": "mail.domain.com", // web域名
"dkimPrivateKeyPath": "config/dkim/dkim.priv", // dkim key path "dkimPrivateKeyPath": "config/dkim/dkim.priv", // dkim 私钥地址
"sslType": "0", // ssl certificate update mode, 0 automatic, 1 manual "sslType": "0", // ssl证书更新模式,0自动,HTTP模式,1手动、2自动,DNS模式
"SSLPrivateKeyPath": "config/ssl/private.key", // ssl certificate path "SSLPrivateKeyPath": "config/ssl/private.key", // ssl 证书地址
"SSLPublicKeyPath": "config/ssl/public.crt", // ssl certificate path "SSLPublicKeyPath": "config/ssl/public.crt", // ssl 证书地址
"dbDSN": "./config/smail.db", // database connect DSN "dbDSN": "./config/smail.db", // 数据库连接DSN
"dbType": "sqlite", //database type ,`sqlite` or `mysql` "dbType": "sqlite", //数据库类型,支持sqlite 和 mysql
"httpsEnabled": 0, // enabled https , 0:enabled 1:enablde 2:disenabled "httpsEnabled": 0, // web后台是否启用https 0默认(启用),1启用,2不启用
"httpPort": 80, // http port . default 80 "spamFilterLevel": 0,// 垃圾邮件过滤级别,0不过滤、1 spf dkim 校验均失败时且无有效收件人过滤,2 spf校验不通过时且无有效收件人过滤 3,dkim 校验不过的时候且无有效收件人过滤
"httpsPort": 443, // https port . default 443 "httpPort": 80, // http 端口 . 默认 80
"spamFilterLevel": 0,// Spam Filtering Levels: 0: No filtering. 1: Filter when both SPF and DKIM fail (in the absence of valid recipient filtering). 2: Filter when SPF check fails (in the absence of valid recipient filtering). 3: Filter when DKIM check fails (in the absence of valid recipient filtering) "httpsPort": 443, // https 端口 . 默认 443
"isInit": true // If false, it will enter the bootstrap process. "isInit": true // 为false的时候会进入安装引导流程
} }
``` ```
# Mail Client Configuration # 第三方邮件客户端配置
POP3 Server Address : pop.[Your Domain] POP3地址: pop.[你的域名]
POP3 Port: 110/995(SSL) POP3端口: 110/995(SSL)
SMTP Server Address : smtp.[Your Domain] SMTP地址: smtp.[你的域名]
SMTP Port: 25/465、587(SSL) SMTP端口: 25/465、587(SSL)
IMAP Server Address : imap.[Your Domain] IMAP地址: imap.[Your Domain]
IMAP Port: 993(SSL) IMAP端口: 993(SSL)
# Plugin
[WeChat Push](server/hooks/wechat_push/README.md) # 插件
[Spam Block](server/hooks/spam_block/README.md) [微信推送](server/hooks/wechat_push/README.md)
# Community plugins [垃圾邮件屏蔽](server/hooks/spam_block/README.md)
[Telegram Push](https://github.com/ydzydzydz/pmail_telegram_push) # 其他优秀开源插件
## Plugin Install [Telegram推送](https://github.com/ydzydzydz/pmail_telegram_push)
## 插件安装
> [!IMPORTANT] > [!IMPORTANT]
> Plugins run on your server as independent processes, please review the security of third-party plugins on your own.Smail currently only maintains the three plugins mentioned above. > 插件已独立进程的方式运行在你的服务器上,请自行审查第三方插件的安全性。Smail目前仅维护上述三款插件
Copy plugin binary file to `/plugins` 将插件二进制文件放到`plugins`文件夹中即可
# For Developer # 参与开发
## Project Framework ## 项目架构
1、 FE: vue3+element-plus 1、前端: vue3+element-plus
The code is in `fe` folder. 前端代码位于 `fe`目录中,运行参考 `fe`目录中的README文件
2、Server: golang + MySQL/SQLite 2、后端: golang + MySQL/SQLite
The code is in `server` folder. 后端代码进入 `server`文件夹,运行 `main.go`文件
3、How to build 3、编译项目
`make build` `make build`
4、Unit test 4、单元测试
`make test` `make test`
## Api Documentation ## 后端接口文档
[go to wiki](https://git.pcux.cn/xuans/Smail/wiki/%E5%90%8E%E7%AB%AF%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A3) [go to wiki](https://git.pcux.cn/xuans/Smail/wiki/%E5%90%8E%E7%AB%AF%E6%8E%A5%E5%8F%A3%E6%96%87%E6%A1%A3)
## Plugin Development ## 插件开发
[go to wiki](https://git.pcux.cn/xuans/Smail/wiki/%E6%8F%92%E4%BB%B6%E5%BC%80%E5%8F%91%E8%AF%B4%E6%98%8E) [go to wiki](https://git.pcux.cn/xuans/Smail/wiki/%E6%8F%92%E4%BB%B6%E5%BC%80%E5%8F%91%E8%AF%B4%E6%98%8E)
+770
View File
@@ -0,0 +1,770 @@
# Smail 后端接口说明文档
> 本文档用于说明当前 Smail 后端 HTTP API 的实际调用方式,并对照原版 PMail《后端接口文档》核对接口是否仍然存在。
>
> 核对基准:当前代码分支 `main`,提交 `6ec4628`,核对日期:2026-08-27。
## 1. 文档范围和结论
原版 PMail 文档包含 9 个基础接口。当前 Smail 仍然保留其中 8 个接口的功能入口,但有以下路径或调用方式变化:
| 编号 | 原版接口 | 当前实际接口 | 当前状态 | 主要差异 |
|---|---|---|---|---|
| 1 | `/api/ping` | `/api/ping` | 存在 | 当前返回统一 JSON,不再是纯文本 `pong` |
| 2 | `/api/login` | `/api/login` | 存在 | 只接受 `POST`;使用会话 Cookie 和 CSRF Cookie,不使用原版文档所述的 `token` 请求头 |
| 3 | `/api/group` | `/api/group` | 部分兼容 | 当前只接受 `GET`,原版写的 `POST` 不再可用;另有 `/api/group/list` |
| 4 | `/api/email/list` | `/api/email/list` | 存在 | 只接受 `POST`,分页参数增加范围限制 |
| 5 | `/api/detail` | `/api/email/detail` | 路径已变更 | 原路径不存在,必须使用 `/api/email/detail` |
| 6 | `/api/email/send` | `/api/email/send` | 存在 | 只接受 `POST`,增加发件人校验、附件和收件人数限制 |
| 7 | `/api/settings/modify_password` | `/api/settings/modify_password` | 存在 | 当前需要同时提交 `current_password` 和 `password` |
| 8 | `/attachments/` | `/attachments/{邮件ID}/{内容标识}` | 存在 | 当前只接受 `GET`,用于内联展示附件内容 |
| 9 | `/attachments/download/` | `/attachments/download/{邮件ID}/{附件序号}` | 存在 | 当前只接受 `GET`,最后一段是附件序号,不是附件数据库 ID |
当前路由注册以 `server/listen/http_server/http_server.go` 为准,接口处理逻辑以 `server/controllers` 和 `server/controllers/email` 为准。
## 2. 通用调用约定
### 2.1 基础地址
以下示例使用:
```text
https://mail.example.com
```
请替换为实际的 Smail Web 地址。开发环境也可以使用:
```text
http://127.0.0.1:80
```
生产环境应优先使用 HTTPS。
### 2.2 通用响应格式
除附件内容下载接口外,JSON 接口统一返回以下结构:
```json
{
"errorNo": 0,
"errorMsg": "",
"data": {}
}
```
字段说明:
| 字段 | 类型 | 说明 |
|---|---|---|
| `errorNo` | number | `0` 表示成功;非 `0` 表示失败。常见值:`100` 参数错误、`403` 未登录、`405` 无权限、`500` 服务端错误 |
| `errorMsg` | string | 错误说明。生产环境不应依赖错误文本判断业务分支,应优先判断 `errorNo` |
| `data` | any | 成功数据或错误附加数据 |
请求方法不正确时,路由层返回 HTTP `405 Method Not Allowed`,并通过 `Allow` 响应头提示允许的方法;此时不一定返回上面的 JSON 结构。
### 2.3 登录态和 CSRF
除探活、登录和公开的密码恢复流程外,邮件、分组、密码修改等接口都需要登录态。
登录成功后,服务端会设置:
1. 会话 Cookie,用于识别登录用户;
2. `smail_csrf` Cookie,用于保存 CSRF Token;
3. 后续状态修改请求需要在 `X-CSRF-Token` 请求头中提交与 `smail_csrf` Cookie 相同的值。
对于携带登录会话 Cookie 的状态修改请求,还需要使用同源的 `Origin`;跨站请求或 CSRF Token 不匹配时会被拒绝。
建议使用浏览器或 HTTP 客户端的 Cookie Jar 保存登录后的 Cookie,不要手工复制会话 Cookie 到代码或日志中。
### 2.4 请求头
JSON 请求通常应携带:
```http
Content-Type: application/json
```
需要登录的状态修改请求示例:
```http
Cookie: 会话Cookie; smail_csrf=CSRF_TOKEN
X-CSRF-Token: CSRF_TOKEN
Origin: https://mail.example.com
```
`Lang` 请求头可以指定返回语言,例如:
```http
Lang: zh-CN
```
未指定时由服务端使用默认语言处理。
### 2.5 通用错误处理
调用方建议按以下顺序处理:
1. 先检查 HTTP 状态码;
2. 对 JSON 响应解析 `errorNo`、`errorMsg` 和 `data`;
3. 收到 `403` 或业务错误码表示登录失效时,重新登录;
4. 收到 `405` 时检查请求方法,不要重试相同方法;
5. 不要把密码、会话 Cookie、CSRF Token、完整邮箱地址写入日志。
## 3. 原版基础接口对照和调用说明
## 3.1 服务探活
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/api/ping` |
| 当前路径 | `/api/ping` |
| 当前方法 | `GET`、`POST` 均可到达处理器;建议使用 `GET` |
| 是否需要登录 | 否 |
| 请求体 | 无 |
| 返回类型 | JSON |
### 调用示例
```bash
curl -X GET "https://mail.example.com/api/ping"
```
也可以使用:
```bash
curl -X POST "https://mail.example.com/api/ping"
```
### 返回示例
```json
{
"errorNo": 0,
"errorMsg": "",
"data": "pong"
}
```
### 与原版差异
原版文档把返回格式写成 `text`,示例为纯文本 `pong`。当前代码通过统一响应封装返回 JSON,实际数据位于 `data` 字段中。
## 3.2 用户登录
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/api/login` |
| 当前路径 | `/api/login` |
| 方法 | `POST` |
| 是否需要登录 | 否 |
| 请求格式 | `application/json` |
| 返回类型 | JSON |
### 请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---:|---|
| `identifier` | string | 否 | 登录标识。当前优先使用该字段,可填写账号或完整邮箱 |
| `account` | string | 否 | 兼容原版字段。当 `identifier` 为空时使用该字段 |
| `password` | string | 是 | 登录密码 |
`identifier` 和 `account` 至少提供一个。为了兼容原版客户端,可以继续提交 `account`;新客户端建议使用 `identifier`。
### 调用示例
兼容原版字段:
```bash
curl -X POST "https://mail.example.com/api/login" \
-H "Content-Type: application/json" \
-c cookies.txt \
-d '{
"account": "admin",
"password": "your-password"
}'
```
使用新的登录标识字段:
```bash
curl -X POST "https://mail.example.com/api/login" \
-H "Content-Type: application/json" \
-c cookies.txt \
-d '{
"identifier": "admin@example.com",
"password": "your-password"
}'
```
### 成功返回示例
普通登录直接完成时,返回:
```json
{
"errorNo": 0,
"errorMsg": "",
"data": {
"account": "admin",
"name": "管理员",
"role": "super_admin",
"is_admin": 1,
"domains": [
"example.com"
]
}
}
```
登录成功时,服务端同时通过 `Set-Cookie` 设置会话 Cookie 和 CSRF Cookie。客户端必须保存这两个 Cookie,后续接口才能继续调用。
### 二次验证情况
如果当前账号启用了登录二次验证,密码正确后可能返回一个待完成的验证数据,而不是直接建立完整登录态。客户端应根据返回的 `data` 调用登录验证接口:
```text
POST /api/security/login/verify
```
该流程不属于原版 PMail 基础接口,详细接口以本文第 4 节的当前安全接口表和前端调用为准。
### 失败返回示例
```json
{
"errorNo": 100,
"errorMsg": "参数错误",
"data": ""
}
```
为了防止账号枚举,登录失败、账号不存在、密码错误和登录限流通常使用相同的业务错误响应,调用方不要根据错误文本判断账号是否存在。
### 与原版差异
原版文档提到可以通过请求头 `token` 进行验签。当前代码路由和认证逻辑未发现该兼容方式,当前登录态以服务端会话 Cookie 为准,不应使用 `token` 请求头替代登录。
## 3.3 获取邮件分组树
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/api/group` |
| 当前路径 | `/api/group` |
| 方法 | `GET` |
| 原版方法 | `POST/GET` |
| 是否需要登录 | 是 |
| 请求体 | 无 |
| 返回类型 | JSON |
当前 `/api/group` 只注册了 `GET`。使用原版文档中的 `POST` 调用会返回 HTTP `405`。
### 调用示例
```bash
curl -X GET "https://mail.example.com/api/group" \
-b cookies.txt
```
如果是浏览器外的状态修改场景,读取接口不需要提交 CSRF Token;但必须携带有效会话 Cookie。
### 返回示例
```json
{
"errorNo": 0,
"errorMsg": "",
"data": [
{
"label": "收件箱",
"tag": "{\"type\":0,\"status\":-1,\"group_id\":0}"
},
{
"label": "发件箱",
"tag": "{\"type\":1,\"status\":-1}"
},
{
"label": "草稿箱",
"tag": "{\"type\":0,\"status\":4}"
}
]
}
```
### 当前相关分组接口
| 方法 | 路径 | 说明 | 请求体 |
|---|---|---|---|
| `GET` | `/api/group` | 获取前端使用的分组树 | 无 |
| `GET` | `/api/group/list` | 获取默认分组和用户自定义分组列表 | 无 |
| `POST` | `/api/group/add` | 创建自定义分组 | `{"name":"项目邮件","parent_id":0}` |
| `POST` | `/api/group/del` | 删除自定义分组 | `{"id":1}` |
`POST /api/group/add` 和 `POST /api/group/del` 属于状态修改接口,需要登录态和 CSRF Token。
## 3.4 获取邮件列表
### 接口信息
| 项目 | 内容 |
|---|---|
| 路径 | `/api/email/list` |
| 方法 | `POST` |
| 是否需要登录 | 是 |
| 请求格式 | `application/json` |
| 返回类型 | JSON |
### 请求参数
| 参数 | 类型 | 必填 | 默认值 | 说明 |
|---|---|---:|---:|---|
| `keyword` | string | 否 | 空字符串 | 邮件搜索关键词,最多 512 字节 |
| `tag` | string | 否 | 全部邮件 | JSON 字符串形式的筛选条件 |
| `current_page` | integer | 否 | `1` | 当前页,从 `1` 开始,最大 `10000` |
| `page_size` | integer | 否 | `15` | 每页数量,最大 `100` |
`tag` 是一个字符串字段,内容需要再次编码为 JSON,例如:
```json
"{\"type\":0,\"status\":-1,\"group_id\":0}"
```
### 调用示例
```bash
curl -X POST "https://mail.example.com/api/email/list" \
-H "Content-Type: application/json" \
-b cookies.txt \
-H "X-CSRF-Token: CSRF_TOKEN" \
-H "Origin: https://mail.example.com" \
-d '{
"keyword": "验证码",
"tag": "{\"type\":0,\"status\":-1,\"group_id\":0}",
"current_page": 1,
"page_size": 15
}'
```
### 返回示例
```json
{
"errorNo": 0,
"errorMsg": "",
"data": {
"current_page": 1,
"total_page": 1,
"list": [
{
"id": 1,
"title": "邮件标题",
"desc": "邮件正文摘要",
"datetime": "2026-08-27 08:44:00",
"is_read": false,
"sender": {
"Name": "发件人",
"EmailAddress": "sender@example.com"
},
"to": [
{
"Name": "收件人",
"EmailAddress": "admin@example.com"
}
],
"dangerous": false,
"error": ""
}
]
}
}
```
### 分页说明
- 不提交分页参数时使用 `current_page=1`、`page_size=15`;
- `current_page` 小于 `1` 或大于 `10000` 会被拒绝;
- `page_size` 小于 `1` 或大于 `100` 会被拒绝;
- `keyword` 超过 512 字节会被拒绝;
- `total_page` 在没有邮件时为 `0`。
## 3.5 获取邮件详情
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/api/detail` |
| 当前路径 | `/api/email/detail` |
| 方法 | `POST` |
| 是否需要登录 | 是 |
| 请求格式 | `application/json` |
| 返回类型 | JSON |
### 请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---:|---|
| `id` | integer | 是 | 邮件 ID,必须大于 `0` |
### 调用示例
```bash
curl -X POST "https://mail.example.com/api/email/detail" \
-H "Content-Type: application/json" \
-b cookies.txt \
-H "X-CSRF-Token: CSRF_TOKEN" \
-H "Origin: https://mail.example.com" \
-d '{
"id": 1
}'
```
### 返回示例
```json
{
"errorNo": 0,
"errorMsg": "",
"data": {
"id": 1,
"type": 0,
"subject": "邮件标题",
"reply_to": "",
"from_name": "发件人",
"from_address": "sender@example.com",
"to": "[{\"Name\":\"收件人\",\"EmailAddress\":\"admin@example.com\"}]",
"bcc": "[]",
"cc": "[]",
"sender": "{\"Name\":\"发件人\",\"EmailAddress\":\"sender@example.com\"}",
"spf_check": 1,
"dkim_check": 1,
"status": 1,
"send_time": "2026-08-27 08:44:00",
"send_date": "2026-08-27 08:44:00",
"update_time": "2026-08-27 08:44:00",
"create_time": "2026-08-27 08:44:00",
"text": "纯文本正文",
"html": "<div>HTML正文</div>",
"error": "",
"attachments": [
{
"Filename": "report.pdf",
"ContentType": "application/pdf",
"Index": 0
}
]
}
}
```
### 与原版差异
原版文档使用 `/api/detail`。当前该路径没有注册,必须改为 `/api/email/detail`。邮件详情请求会标记邮件为已读,因此调用该接口不是纯读取操作;使用 `POST` 也符合当前路由约束。
## 3.6 发送邮件
### 接口信息
| 项目 | 内容 |
|---|---|
| 路径 | `/api/email/send` |
| 方法 | `POST` |
| 是否需要登录 | 是 |
| 请求格式 | `application/json` |
| 返回类型 | JSON |
| 请求体上限 | 40 MiB |
### 请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---:|---|
| `reply_to` | array | 否 | 回复地址列表,每项包含 `name`、`email` |
| `from` | object | 否 | 发件人,包含 `name`、`email`;邮箱为空时使用当前账号地址 |
| `to` | array | 是 | 收件人列表,每项包含 `name`、`email` |
| `bcc` | array | 否 | 密送列表 |
| `cc` | array | 否 | 抄送列表 |
| `subject` | string | 是 | 邮件标题 |
| `text` | string | 否 | 纯文本正文 |
| `html` | string | 否 | HTML 正文 |
| `sender` | object | 否 | SMTP Envelope Sender;为空时使用 `from` |
| `read_receipt` | array | 否 | 已读回执地址列表 |
| `attrs` | array | 否 | 附件列表,每项包含 `name`、`data` |
`attrs[].data` 必须是 Data URL 格式的 Base64 数据,例如:
```text
data:application/pdf;base64,BASE64_DATA
```
### 调用示例
```bash
curl -X POST "https://mail.example.com/api/email/send" \
-H "Content-Type: application/json" \
-b cookies.txt \
-H "X-CSRF-Token: CSRF_TOKEN" \
-H "Origin: https://mail.example.com" \
-d '{
"from": {
"name": "管理员",
"email": "admin@example.com"
},
"to": [
{
"name": "收件人",
"email": "user@example.com"
}
],
"cc": [],
"bcc": [],
"subject": "测试邮件",
"text": "这是纯文本正文。",
"html": "<p>这是 HTML 正文。</p>",
"attrs": []
}'
```
### 成功返回
```json
{
"errorNo": 0,
"errorMsg": "",
"data": "操作成功"
}
```
接口返回成功表示邮件已经通过参数校验并创建发送任务。实际投递结果可能在异步处理后才确定,失败信息会写入邮件状态,调用方应通过邮件列表或详情接口检查最终状态。
### 当前限制
- `to` 至少包含一个收件人;
- `to`、`cc`、`bcc`、`reply_to` 合计最多 `100` 个地址;
- 附件最多 `20` 个;
- 单个附件最大 `10 MiB`;
- 附件总大小最大 `25 MiB`;
- 邮件正文最大约 `8 MiB`;
- `subject` 必填;
- 普通用户不能伪造未授权的内部发件人地址;
- 附件文件名会进行路径和控制字符清理。
## 3.7 修改当前账号密码
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/api/settings/modify_password` |
| 当前路径 | `/api/settings/modify_password` |
| 方法 | `POST` |
| 是否需要登录 | 是 |
| 请求格式 | `application/json` |
| 返回类型 | JSON |
### 请求参数
| 参数 | 类型 | 必填 | 说明 |
|---|---|---:|---|
| `current_password` | string | 是 | 当前密码 |
| `password` | string | 是 | 新密码,长度为 8 到 256 字节 |
### 调用示例
```bash
curl -X POST "https://mail.example.com/api/settings/modify_password" \
-H "Content-Type: application/json" \
-b cookies.txt \
-H "X-CSRF-Token: CSRF_TOKEN" \
-H "Origin: https://mail.example.com" \
-d '{
"current_password": "old-password",
"password": "new-password"
}'
```
### 成功返回
```json
{
"errorNo": 0,
"errorMsg": "",
"data": "操作成功"
}
```
修改成功后,当前账号的安全凭据和登录会话会按服务端策略刷新或撤销。调用方如果收到会话失效,应重新登录并重新获取 CSRF Token。
### 与原版差异
原版示例中的 `passowrd` 是拼写错误,当前代码使用正确字段 `password`。当前接口还要求提供 `current_password`,不能只提交新密码。
## 3.8 内联获取附件内容
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/attachments/` |
| 当前路径 | `/attachments/{邮件ID}/{内容标识}` |
| 方法 | `GET` |
| 原版方法 | 文档写成 `POST`,但请求示例使用 `GET` |
| 是否需要登录 | 是 |
| 返回类型 | 附件原始内容 |
其中:
- `{邮件ID}` 是邮件 ID;
- `{内容标识}` 是邮件详情中附件的内容标识,通常对应内联资源的 Content-ID;
- 当前处理器会按路径读取这两个值,并检查当前用户是否有权访问该邮件附件。
### 调用示例
```bash
curl -X GET "https://mail.example.com/attachments/1/image001.png" \
-b cookies.txt \
-o image001.png
```
### 返回说明
成功时返回附件原始字节,并设置对应的 `Content-Type`,例如:
```http
Content-Type: image/png
```
失败时返回统一 JSON 错误响应。常见原因包括路径格式错误、附件不存在、附件不可用或当前用户无权访问。
## 3.9 下载附件
### 接口信息
| 项目 | 内容 |
|---|---|
| 原版路径 | `/attachments/download/` |
| 当前路径 | `/attachments/download/{邮件ID}/{附件序号}` |
| 方法 | `GET` |
| 是否需要登录 | 是 |
| 返回类型 | 文件流 |
其中 `{附件序号}` 是邮件详情 `attachments` 数组中的 `Index`,当前从 `0` 开始,不是附件数据库 ID。
### 调用示例
```bash
curl -X GET "https://mail.example.com/attachments/download/1/0" \
-b cookies.txt \
-o report.pdf
```
### 返回响应头
成功时服务端返回:
```http
Content-Type: application/octet-stream
X-Content-Type-Options: nosniff
Content-Disposition: attachment; filename="attachment"; filename*=UTF-8''report.pdf
```
服务端会清理文件名中的路径分隔符、换行符和控制字符,避免下载文件名被用于路径穿越或响应头注入。
## 4. 当前新增安全和账户接口
这些接口不在原版 PMail 的 9 个基础接口中,但已经注册在当前 Smail 路由中。它们属于当前前端登录、安全设置和密码恢复流程的一部分。
### 4.1 登录和恢复流程
| 方法 | 路径 | 是否公开 | 说明 |
|---|---|---:|---|
| `POST` | `/api/security/verification/request` | 否 | 请求验证信息 |
| `POST` | `/api/security/verification/verify` | 否 | 校验验证信息 |
| `POST` | `/api/security/login/verify` | 是 | 完成登录二次验证 |
| `POST` | `/api/security/recovery/begin` | 是 | 开始密码恢复流程 |
| `POST` | `/api/security/recovery/verify` | 是 | 校验密码恢复凭据 |
| `POST` | `/api/security/recovery/complete` | 是 | 完成密码恢复 |
| `POST` | `/api/security/recovery/webauthn/begin` | 是 | 开始 WebAuthn 恢复验证 |
| `POST` | `/api/security/recovery/webauthn/verify` | 是 | 完成 WebAuthn 恢复验证 |
| `POST` | `/api/logout` | 否 | 退出当前会话 |
### 4.2 WebAuthn 和恢复码
| 方法 | 路径 | 说明 |
|---|---|---|
| `POST` | `/api/security/webauthn/registration/begin` | 开始注册安全密钥 |
| `POST` | `/api/security/webauthn/registration/finish` | 完成注册安全密钥 |
| `GET` | `/api/security/webauthn/credentials` | 查询当前账号安全密钥 |
| `POST` | `/api/security/webauthn/credentials/rename` | 重命名安全密钥 |
| `POST` | `/api/security/webauthn/credentials/revoke` | 撤销安全密钥 |
| `POST` | `/api/security/webauthn/login/begin` | 开始登录安全密钥验证 |
| `POST` | `/api/security/webauthn/login/finish` | 完成登录安全密钥验证 |
| `GET` | `/api/security/credentials/recovery-codes` | 查询恢复码状态,不返回历史恢复码原文 |
| `POST` | `/api/security/credentials/recovery-codes/generate` | 生成新的恢复码 |
| `POST` | `/api/security/credentials/recovery-codes/revoke` | 撤销恢复码 |
| 未限制 | `/api/security/credentials/question` | 密保问题相关流程入口,实际方法由处理器判断 |
### 4.3 外部安全邮箱
| 方法 | 路径 | 说明 |
|---|---|---|
| `GET` | `/api/security/external-email/list` | 获取当前账号外部安全邮箱状态 |
| `POST` | `/api/security/external-email/bind` | 绑定外部安全邮箱 |
| `POST` | `/api/security/external-email/verify` | 验证外部安全邮箱 |
| `POST` | `/api/security/external-email/disable` | 禁用外部安全邮箱 |
以上安全接口的请求参数和恢复状态机依赖当前安全设计,不应按照原版 PMail 的 `token` 模式调用。
## 5. 当前邮件和账户管理接口补充
| 方法 | 路径 | 说明 |
|---|---|---|
| `POST` | `/api/email/del` | 删除邮件 |
| `POST` | `/api/email/read` | 标记邮件已读 |
| `POST` | `/api/email/move` | 移动邮件到分组 |
| `POST` | `/api/rule/get` | 获取邮件规则 |
| `POST` | `/api/rule/add` | 新增邮件规则 |
| `POST` | `/api/rule/update` | 更新邮件规则 |
| `POST` | `/api/rule/del` | 删除邮件规则 |
| `POST` | `/api/user/create` | 创建用户,权限由当前角色控制 |
| `POST` | `/api/user/edit` | 编辑用户 |
| `POST` | `/api/user/info` | 获取用户信息 |
| `POST` | `/api/user/list` | 获取用户列表 |
| `GET` | `/api/plugin/list` | 获取插件列表 |
| `GET`、`POST` | `/api/plugin/settings/{插件名}/{操作}` | 读取或保存插件设置 |
配置管理接口使用 `/api/v1/config/` 和 `/api/v1/audits/config` 路径,属于新的配置系统,不属于原版 PMail 基础接口;调用时需要按当前配置授权、审计和 CSRF 规则处理。
## 6. 原版接口迁移清单
使用原版 PMail 客户端迁移到当前 Smail 时,至少需要修改以下内容:
| 原版调用 | 当前调用 |
|---|---|
| `POST /api/detail` | `POST /api/email/detail` |
| `POST /api/group` | `GET /api/group` |
| `POST /attachments/{邮件ID}/{附件标识}` | `GET /attachments/{邮件ID}/{附件标识}` |
| 仅提交 `password` 修改密码 | 同时提交 `current_password` 和 `password` |
| 使用 `token` 请求头认证 | 保存登录会话 Cookie,并在状态修改请求中提交 `X-CSRF-Token` |
| 将 `/api/ping` 当作纯文本读取 | 解析 JSON,并读取 `data` 中的 `pong` |
## 7. 代码核对位置
本次对照使用以下当前代码位置作为实现依据:
- 路由注册:`server/listen/http_server/http_server.go`
- 请求上下文、登录态和 CSRF 校验:`server/listen/http_server/https_server.go`
- 登录:`server/controllers/login.go`
- 分组:`server/controllers/group.go`
- 密码修改:`server/controllers/settings.go`
- 附件:`server/controllers/attachments.go`
- 邮件列表:`server/controllers/email/list.go`
- 邮件详情:`server/controllers/email/detail.go`
- 邮件发送:`server/controllers/email/send.go`
- 统一 JSON 响应:`server/dto/response/response.go`
原版对照来源为 PMail Wiki 的《后端接口文档》。原版文档仅作为历史兼容性参考,接口是否可调用以当前 Smail 路由和处理器实现为准。
@@ -0,0 +1,245 @@
# Smail 安全威胁模型与敏感数据流设计
> 文档编号:AD-003
>
> 编写日期:2026-08-27
>
> 适用范围:Smail 认证服务、密码恢复、登录二次验证、外部安全邮箱、WebAuthn、离线恢复码,以及 `smail-admin` 本机超级管理员重置通道。
>
> 当前结论:本设计已经说明认证和重置链路中的敏感数据流、信任边界、持久化点、控制措施和负向测试。仍未替代 Ubuntu、Windows、SMTP Relay 和生产部署环境的最终验收;这些项目由 AD-011、AD-015、AD-034、AD-060~AD-066 继续负责。
## 1. 设计目标和安全结论
### 1.1 设计目标
本文件用于回答以下问题:
1. 哪些主体可以发起登录、验证码、恢复和超级管理员重置;
2. 密码、验证码、恢复票据、外部邮箱、WebAuthn 凭据和 IPC 请求分别经过哪些进程、内存结构、数据库表和外部服务;
3. 每个信任边界上的攻击面是什么;
4. 每项威胁至少对应一个控制措施和一个负向测试;
5. 是否存在未说明的敏感数据持久化点或网络重置入口。
### 1.2 当前安全结论
- 超级管理员自身的密码重置只有部署端本机 IPC 链路,HTTP 路由不提供该能力;`smail-admin` 不直接访问数据库。
- Linux 使用权限受限的 Unix Domain Socket 和对端 UID 校验;Windows 使用安全描述符限制的 Named Pipe,并校验客户端进程令牌是否为 SYSTEM 或提升后的管理员。
- IPC 使用一次性 nonce、有效期、单帧大小上限、协议版本和未知字段拒绝;nonce 在消费时原子删除,不能跨连接复用。
- 邮箱验证码只保存在签发认证进程内存,验证码只以 HMAC-SHA-256 校验值保存;进程重启后内存任务和临时密钥失效。
- 验证码按用途、账号、邮箱、资源、浏览器恢复上下文和必要的凭据版本绑定;同账号同用途重新签发会使旧任务失效。
- 验证码、恢复票据、WebAuthn ceremony 会话和登录二次验证状态均有容量上限、过期时间和一次性消费控制。
- 外部邮箱在数据库中保存 AEAD 加密密文和独立 HMAC 指纹;业务返回只使用脱敏邮箱,检索使用指纹,不以明文邮箱作为索引。
- 密码和密保答案使用 Argon2id 哈希;离线恢复码只保存 Argon2id 哈希,WebAuthn 凭据材料使用独立凭据密钥保护。
- `verification_rate_limit` 和 `verification_event` 只保存哈希后的运营维度;事件按保留类别清理,调查保留记录不会被自动删除。
- 当前文档明确列出的持久化点之外,不允许把验证码、验证码 HMAC、恢复票据、恢复码原文、IPC 密码、临时密钥或完整外部邮箱写入数据库、文件、日志、指标、追踪或浏览器存储。
## 2. 主体、组件和信任边界
| 编号 | 主体或组件 | 边界 | 可接触的数据 | 不应获得的数据 |
|---|---|---|---|---|
| A1 | 用户浏览器 | 外部网络与 HTTP 边界 | 用户输入、脱敏邮箱、临时恢复上下文 Cookie、HTTP 响应 | 服务端密码哈希、验证码 HMAC、完整外部邮箱、恢复票据明文 |
| A2 | 普通用户、管理员、超级管理员 | 业务授权边界 | 自身业务数据和被授权的安全操作 | 越权账号的凭据和恢复材料 |
| A3 | `Smail` 主服务进程 | 主服务进程边界 | HTTP 请求、认证状态、短时验证码和恢复状态、数据库密钥解密后的短暂明文 | 不应向插件、日志和诊断接口导出临时密钥或验证码 |
| A4 | `smail-admin` 管理进程 | 管理进程与本机 IPC 边界 | 交互输入的新密码、IPC nonce、结果状态 | 数据库连接、其他用户密码、长期维护凭据 |
| A5 | SMTP Relay 或本机 SMTP 服务 | 主服务与外部投递边界 | 收件地址、邮件正文中的验证码、SMTP 认证材料 | 主服务内存索引、恢复票据、数据库密钥 |
| A6 | 数据库 | 主服务与持久化边界 | 用户密码哈希、加密邮箱、凭据哈希/密文、哈希运营维度、会话数据 | 验证码原文、验证 HMAC、恢复票据原文、IPC 密码 |
| A7 | 操作系统和服务管理器 | 主机权限边界 | 文件权限、服务身份、进程身份、IPC 对端凭据 | 通过普通 Web 请求触发部署端重置 |
| A8 | 日志、指标、追踪和审计系统 | 观测边界 | 稳定错误、非敏感事件类型、哈希维度和脱敏状态 | 密码、验证码、完整邮箱、恢复码、票据、临时密钥和 IPC 内容 |
### 2.1 信任边界图
```mermaid
flowchart LR
browser[用户浏览器]
operator[部署人员]
relay[SMTP Relay]
attacker[外部攻击者]
subgraph host[部署主机]
admin[smail-admin 管理进程]
main[Smail 主服务进程]
mem[(仅内存状态)]
db[(数据库)]
logs[日志/指标/审计]
ipc{{Unix Socket / Named Pipe}}
admin --> ipc --> main
main --> mem
main --> db
main --> logs
end
browser -->|HTTPS 登录/恢复/安全 API| main
operator -->|systemctl start smail-admin 或等价本机启动| admin
main -->|STARTTLS 或隐式 TLS| relay
relay -->|验证码邮件| browser
attacker -.->|网络枚举、重放、暴力破解、请求伪造| main
attacker -.->|不能直接获得受信任 IPC 对端身份| ipc
```
### 2.2 进程边界和默认假设
- `Smail` 主服务进程是唯一执行密码哈希、数据库写入和凭据撤销的业务进程。
- `smail-admin` 是短时管理客户端,只通过本机 IPC 传输一次密码重置请求;它不加载数据库配置,也不执行 SQL。
- SMTP Relay 是不受 Smail 进程控制的外部组件,必须按网络和凭据泄露风险对待;远程明文 SMTP 被配置校验拒绝。
- 数据库属于受部署权限保护的持久化边界,但数据库管理员或备份读取者不应因此获得验证码原文、恢复码原文或 IPC 密码。
- 浏览器、插件、普通日志查看者和普通管理 API 都属于不可信或低信任边界,不得接收完整邮箱和可直接验证的秘密。
## 3. 敏感数据分类与生命周期
| 数据 | 产生位置 | 允许的短暂流转 | 允许的持久化形式 | 生命周期和销毁 |
|---|---|---|---|---|
| 登录密码、新密码 | 浏览器或 `smail-admin` 交互输入 | HTTPS 请求体或本机 IPC 帧;主服务哈希过程 | 仅 Argon2id 密码哈希 | 请求完成后覆盖局部缓冲;旧会话通过 `session_version` 失效 |
| 邮箱验证码原文 | `verification.Store.Issue` | 生成、构造邮件、SMTP 投递、HMAC 计算 | 禁止落库、落文件、入日志和指标 | `defer clearString`、邮件字节清理、验证成功/过期/超限删除 |
| 验证码 HMAC | `verification.Store` | 仅主服务内存校验 | 禁止持久化 | 随挑战删除;进程退出丢失 |
| 验证码 ID | 主服务内存和 HTTP 响应 | 浏览器提交到验证接口 | 不作为可恢复凭据持久化 | 挑战消费、过期、重发或用户失效时删除 |
| 恢复票据 | `recovery.Service` | 验证成功到完成改密的 HTTP 流程 | 仅内存保存票据摘要及绑定元数据 | 五分钟过期;完成或失败时删除;进程重启失效 |
| 恢复码原文 | 管理页面或恢复输入 | 生成后一次性响应、验证时短暂进入服务 | 仅 Argon2id 哈希 | 生成接口只显示一次;消费、撤销或密码重置后失效 |
| 密保答案 | 管理页面或恢复输入 | 哈希验证过程 | 仅 Argon2id 哈希 | 改密或统一凭据撤销时删除问题记录 |
| 外部安全邮箱 | 绑定/登录/恢复服务 | 解密后用于匹配、投递和脱敏返回 | AES-GCM 加密密文 + 独立 HMAC 指纹 | 未验证绑定失败回滚;停用后不可用于认证;解密明文只短暂存在 |
| WebAuthn 凭据 | 浏览器 ceremony | WebAuthn 请求和服务端验证 | 独立凭据密钥保护的序列化凭据 | ceremony 会话限时一次;凭据可撤销;恢复或重置按权限撤销 |
| 登录二次验证状态 | `loginVerificationState` 和验证码 Store | 登录密码成功后到验证码验证完成 | 仅内存 | 十分钟过期、成功消费、密码/会话版本变化时删除 |
| IPC nonce | `SessionGuard` | 管理进程和主服务之间一轮连接 | 仅内存 | 两分钟默认有效;消费、断开或过期删除 |
| SMTP 认证密码 | 配置装载到 SMTP 投递 | SMTP 建连和认证 | 受配置 Secret 管理约束,不进入验证码事件 | 由配置 Secret 生命周期管理;不得进入邮件正文、日志或响应 |
| 临时进程密钥 | 验证码 Store、邮箱 Vault、审计指纹服务 | 进程内加密、HMAC 和校验 | 验证码临时密钥禁止持久化;外部邮箱和审计密钥按密钥管理策略保存 | 进程退出后验证码密钥失效;其他密钥不得通过诊断导出 |
## 4. 关键数据流
### 4.1 部署端超级管理员重置
1. 部署人员在受控主机上按正式部署命令启动 `smail-admin`,新密码从无回显安全交互读取,不通过命令行参数、环境变量、服务名或普通文件传递。
2. `smail-admin` 连接固定本机 IPC 地址:Linux 为 Unix Domain Socket,Windows 为 Named Pipe。
3. 主服务先校验对端身份,再签发一次性 nonce;客户端只能在当前连接返回同一 nonce 和新密码。
4. 主服务校验协议版本、单帧大小、字段集合、密码长度、nonce 一致性和 nonce 未过期/未消费。
5. 主服务在同一数据库事务中定位唯一超级管理员、更新 Argon2id 密码哈希、递增 `session_version`、撤销其恢复凭据,然后提交事务。
6. 提交成功后仅在内存中撤销该用户的会话、验证码、恢复票据和 WebAuthn 状态;客户端获得不含数据库细节的结果。
明确禁止:HTTP 路由、浏览器页面、远程 TCP、离线恢复码或外部邮箱验证码触发超级管理员自身重置。
### 4.2 外部安全邮箱绑定
1. 已登录用户提交待绑定邮箱;主服务规范化地址,生成密文和指纹,创建 `pending` 绑定。
2. 验证码服务生成随机验证码和挑战 ID,只在内存保存 HMAC 及绑定资源 ID;邮件服务构造正文并通过受保护 SMTP 投递。
3. 投递失败时删除本次 `pending` 绑定和对应挑战,避免留下不可完成的部分状态。
4. 用户提交挑战 ID、邮箱、验证码和绑定 ID;服务验证账号、用途、邮箱和资源 ID 后原子消费挑战。
5. 挑战消费成功后,绑定状态改为 `verified`;外部邮箱后续可用于登录二次验证和密码恢复。
### 4.3 登录二次验证
1. 登录请求先完成账号和密码校验,但在策略要求二次验证时不创建完整会话。
2. 主服务解密已验证的主要外部邮箱,仅用于本次邮件投递,并向客户端返回脱敏地址和挑战 ID。
3. 验证接口校验挑战、账号、用途和会话版本;成功后删除内存状态,再创建完整 Session。
4. 挑战过期、错误次数超限、用户被禁用、会话版本变化或用户凭据被撤销时,流程拒绝并清理状态。
### 4.4 邮箱密码恢复
1. 公开恢复入口首先检查功能开关、部署状态和合法访问主机。
2. 对不存在账号、错误邮箱、超级管理员或内部错误使用等形状的诱饵挑战,避免通过响应状态、字段形状或耗时可靠枚举账号。
3. 对有效用户,仅允许已验证且仍启用的外部邮箱;挑战绑定账号、邮箱、用途、外部邮箱资源 ID、凭据版本和恢复浏览器上下文。
4. 验证成功后签发五分钟恢复票据,票据只在内存保存摘要和最小绑定元数据;不把票据原文写入数据库。
5. 完成改密时重新检查用户角色、禁用状态、`session_version`、邮箱凭据版本和浏览器上下文,原子更新密码并递增会话版本。
6. 改密成功后撤销该用户的恢复票据、验证码、离线恢复凭据和相关登录验证状态。
超级管理员在第 3 步始终返回不可区分的拒绝结果,不进入 Web 恢复流程。
### 4.5 WebAuthn 注册和恢复
1. 注册和恢复先创建有类型、有用户绑定或发现式登录约束的 ceremony 会话。
2. 会话只在内存保存,具有容量上限、过期时间和一次性消费规则;凭据材料只在服务端验证后写入加密凭据数据。
3. 恢复验证成功只签发短时恢复票据,不直接创建完整登录 Session。
4. 完成改密时再次检查用户状态、会话版本和票据上下文;改密后清理目标用户的安全流程状态。
### 4.6 SMTP 投递
1. 验证码服务将验证码原文传给 SMTP Delivery,构造 `From`、`To`、主题和正文。
2. 远程 SMTP 只允许 STARTTLS 或隐式 TLS;纯文本 SMTP 只允许回环地址。
3. 如配置 SMTP 用户名,则通过 SMTP 认证连接 Relay;认证密码不写入验证码事件、响应和邮件正文。
4. 投递函数返回后尽最大努力清理邮件字节;投递失败由上游删除挑战或待绑定记录。
### 4.7 运营事件和限流
1. 验证码签发、验证、阻断等动作只记录用途、动作、结果、用户 ID 和账号/邮箱/IP 的 HMAC 指纹。
2. 限流器按账号、邮箱、IP、用户、用途、浏览器事务、环境和凭据版本构造哈希维度键,并在数据库事务中原子更新计数。
3. 限流记录和运营事件都带过期时间;清理器通过数据库租约保证同一环境只有一个清理者。
4. 事件查询和诊断不得返回挑战、HMAC、完整账号、完整邮箱、IP 明文或临时密钥。
## 5. 持久化点清单
| 持久化点 | 保存内容 | 允许用途 | 明确禁止 |
|---|---|---|---|
| `user.password` | Argon2id 密码哈希 | 登录和密码更新 | 密码原文、可逆密码密文 |
| `user.session_version` | 会话版本整数 | 旧会话和恢复票据失效 | 以版本字段替代权限校验 |
| `sessions` | 服务端会话不透明数据及过期时间 | HTTP 会话 | 将验证码或恢复票据放入浏览器可读数据 |
| `external_email` | 邮箱 AEAD 密文、独立指纹、类型、状态和凭据版本 | 已验证邮箱匹配、投递和恢复绑定 | 邮箱明文、把指纹当作可验证凭据 |
| `security_question` | 问题文本、答案 Argon2id 哈希、版本 | 已登录用户配置和恢复校验 | 答案原文 |
| `recovery_code` | 恢复码 Argon2id 哈希、版本、消费时间 | 一次性离线恢复 | 恢复码原文、可逆密文 |
| `webauthn_credential` | 凭据 ID、加密凭据数据、显示名、生命周期字段 | WebAuthn 验证和撤销 | 未保护的私密材料或跨用户凭据 |
| `verification_rate_limit` | 哈希维度键、维度类型、计数、时间窗口 | 跨进程限流和清理 | 账号、邮箱、IP、验证码和票据原文 |
| `verification_event` | 用途、动作、结果、哈希维度、保留策略 | 脱敏运营审计 | 密码、验证码、挑战值、完整邮箱、IP 明文 |
| `verification_cleanup_state` | 清理租约、下次执行时间和失败计数 | 单实例清理协调 | 将租约当作业务认证凭据 |
| 配置 Secret 存储 | SMTP、外部邮箱和其他配置密钥的受控 Secret | 服务启动和加解密 | 通过通用配置响应、日志或指标暴露 |
以下内容**不允许持久化**:验证码原文、验证码 HMAC、验证码挑战上下文、恢复票据原文、IPC nonce、IPC 新密码、恢复码原文、密保答案、SMTP 认证密码副本、WebAuthn 私密材料明文、邮箱解密后的明文、验证码临时进程密钥。
## 6. 威胁、控制措施和负向测试矩阵
| 编号 | 威胁场景 | 控制措施 | 负向测试或证据 |
|---|---|---|---|
| T-01 | 本机普通用户冒用部署端重置 | 固定本机 IPC;Linux 校验 Unix 对端 UID、目录和 Socket 权限;Windows 校验 SYSTEM/提升管理员令牌 | `adminreset.TestAuthorizeLinuxProcessRequiresSystemdInvocation`;`adminreset.TestWindowsPipeACLOnlyNamesSystemAndAdministrators` |
| T-02 | 伪造或跨进程冒用 IPC 会话 | nonce 由服务端签发,必须在同一连接返回;拒绝未知字段和错误协议 | `adminreset.TestProtocolRejectsUnknownFieldsInvalidVersionAndTrailingData`;`adminreset.TestWindowsNamedPipeRejectsNonceFromAnotherConnection` |
| T-03 | 重放已成功的重置请求 | `SessionGuard.Consume` 原子删除 nonce;连接关闭或失败时丢弃;短 TTL | `adminreset.TestSessionGuardRequiresIssuedNonceAndConsumesOnce`;`adminreset.TestSessionGuardRejectsExpiredNonce` |
| T-04 | 通过恢复接口枚举账号、邮箱或超级管理员 | 诱饵挑战;统一响应状态和 JSON 形状;超级管理员不进入 Web 恢复;WebAuthn begin 忽略标识符 | `controllers.TestPasswordRecoveryBeginResponsesDoNotRevealAccountState`;`controllers.TestWebAuthnRecoveryBeginResponsesDoNotRevealAccountState`;`controllers.TestWebAuthnLoginBeginResponsesIgnoreIdentifier` |
| T-05 | 验证码暴力破解和邮件轰炸 | 每次挑战最多五次;账号、邮箱、IP、用途和事务多维限流;重发替换旧挑战 | `verification.TestStoreLimitsAttemptsAndExpires`;`verification.TestServiceAppliesIndependentAccountEmailAndIPLimits`;`verification.TestPersistentRateLimiterAppliesIPLimitAcrossIdentities` |
| T-06 | 恶意创建任务导致内存耗尽 | 验证码全局/每用户容量上限;恢复票据、诱饵挑战和 WebAuthn ceremony 上限;清理过期状态 | `verification.TestStoreLimitsAttemptsAndExpires`;`recovery.TestRecoveryStoresOnlyTicketDigestAndLimitsCapacity`;`webauthn.TestCeremonySessionCapacityAndExpiredPruning` |
| T-07 | SMTP 明文泄露、注入或远程无 TLS 投递 | 远程仅 STARTTLS/隐式 TLS;纯文本只允许回环;Host、From 和收件地址校验;邮件字节清理 | `verification.TestSMTPModesAreValidated`;`verification.TestSMTPHostValidation`;`verification.TestSMTPDeliveryKeepsCodeOutOfChallenge` |
| T-08 | 日志、审计、指标或诊断泄露秘密 | 敏感服务错误使用稳定中文消息;事件和限流仅记录 HMAC 指纹;不提供内存任务详情和临时密钥诊断 | `verification.TestEventStorePersistsOnlyOperationalFingerprintsAndCleansAfterRetention`;`verification.TestPersistentRateLimiterDoesNotPersistSensitiveValues`;`config.TestFileAuditWriterPersistsOnlyRedactedMetadata`(完整日志哨兵由 AD-004、AD-057 补齐) |
| T-09 | 并发双花:验证码、恢复票据、恢复码或 WebAuthn ceremony 被同时消费 | 内存锁下原子删除;数据库条件更新 `used_at IS NULL`;票据先摘除再改密;ceremony 类型不匹配也消费会话 | `recovery.TestRecoveryTicketConcurrentConsumptionHasOneWinner`;`webauthn.TestDiscoverableCeremonyIsConsumedOnceUnderConcurrency`;`credentials.TestRecoveryCodesAreShownOnceAndConsumedAtomically` |
| T-10 | 跨账号、跨用途、跨邮箱或跨浏览器上下文复用挑战 | HMAC 绑定账号、用途、邮箱、资源 ID;浏览器上下文只保存摘要;错误上下文不消费有效挑战 | `verification.TestServiceBindsVerificationToResource`;`verification.TestStoreRejectsDifferentBrowserContextWithoutConsumingChallenge`;`recovery.TestRecoveryBindsChallengeAndTicketToBrowserContext` |
| T-11 | 密码或邮箱凭据变更后继续使用旧恢复流程 | `session_version`、外部邮箱 `credential_version` 和统一 `InvalidateUser`;密码重置撤销恢复码、密保问题和 WebAuthn | `recovery.TestRecoveryTicketRejectsChangedSessionVersion`;`controllers.TestPasswordChangeRevokesOfflineCredentialsAtomically`;`adminreset.TestResetSuperAdminOnlyRevokesTargetSessionsAndCredentials` |
| T-12 | 恢复流程状态跳跃或直接调用完成接口 | begin/verify/complete 分离;complete 只接受服务端内存票据和浏览器上下文;无票据、过期票据和错误上下文拒绝 | `controllers.TestRecoveryBrowserContextCookieIsRequiredForCompletion`;`recovery.TestRecoveryRejectsCrossUserVerificationAndConsumesTicketOnce` |
| T-13 | 未验证、已停用或他人外部邮箱被用于恢复/登录 | 查询只接受 verified 状态;资源 ID 和 UserID 双重绑定;停用时失效验证码、恢复票据和登录状态 | `externalemail.TestRepositoryBindsVerifiesAndScopesByUser`;`externalemail.TestRepositoryAbandonsOnlyOwnedPendingBinding`;`server/controllers/security.go` 中 `DisableExternalEmail` 的状态失效代码审查 |
| T-14 | 数据库读取者通过运营数据还原账号、邮箱或 IP | 运营字段使用独立 HMAC 指纹;限流维度键哈希;不保存完整值;按期限清理 | `verification.TestEventStorePersistsOnlyOperationalFingerprintsAndCleansAfterRetention`;`verification.TestPersistentRateLimiterDoesNotPersistSensitiveValues` |
| T-15 | 主服务重启后旧验证码或恢复流程被恢复使用 | 验证码 Store 的临时密钥和任务只在内存;恢复票据、诱饵挑战和 WebAuthn ceremony 不从数据库恢复 | `verification.TestStoreRestartInvalidatesAllChallenges`;`recovery.TestRecoveryStoresOnlyTicketDigestAndLimitsCapacity`;`webauthn.TestCeremonySessionCapacityAndExpiredPruning` |
| T-16 | 超级管理员通过 Web、外部邮箱或恢复码重置自身密码 | 恢复用户加载明确拒绝 `super_admin`;部署端重置单独走 IPC;没有 Web 路由调用 `ResetSuperAdmin` | `recovery.TestRecoveryDeniesSuperAdministrator`;`controllers.TestRecoveryRejectsWhenDisabled`;路由审计:`server/listen/http_server/http_server.go` 未注册网络超级管理员重置入口 |
| T-17 | 恶意请求超过协议帧、JSON 或 SMTP 头字段限制 | IPC 最大帧 16 KiB、JSON unknown field 拒绝;邮箱和 SMTP Host/From 禁止换行和非法格式;HTTP JSON 单值解析 | `adminreset.TestProtocolRejectsOversizedFrame`;`controllers.TestDecodeJSONRequestRejectsUnsafeBodies`;`verification.TestSMTPHostValidation` |
| T-18 | 外部错误把数据库细节或秘密返回给调用方 | IPC 统一返回 `RESET_FAILED`;HTTP 使用稳定业务错误;日志只记录内部错误上下文,不拼接密码、验证码和完整邮箱 | `adminreset.TestWindowsNamedPipeReturnsSafeHandlerFailure`;`controllers.TestSecurityHandlersRejectUnauthenticatedRequests`;安全响应形状测试 |
## 7. 代码与测试映射
| 能力 | 主要代码 | 主要测试 |
|---|---|---|
| IPC 协议和 nonce | `server/services/adminreset/protocol.go`、`client.go`、`transport_unix.go`、`transport_windows.go` | `server/services/adminreset/protocol_test.go`、`transport_windows_test.go`、`doctor_linux_test.go` |
| 超级管理员事务 | `server/services/adminreset/reset.go` | `server/services/adminreset/reset_test.go` |
| 验证码内存仓库 | `server/services/verification/store.go`、`service.go`、`runtime.go` | `store_test.go`、`service_test.go`、`cleanup_test.go` |
| SMTP 投递 | `server/services/verification/delivery.go` | `delivery_test.go` |
| 限流和运营事件 | `server/services/verification/rate_limit.go`、`event_store.go` | `rate_limit_test.go`、`event_store_test.go`、`event_cleanup_test.go` |
| 外部邮箱加密和生命周期 | `server/services/externalemail/vault.go`、`repository.go` | `vault_test.go`、`repository_test.go` |
| 密保和离线恢复码 | `server/services/credentials/service.go` | `service_test.go` |
| 密码恢复状态机 | `server/services/recovery/service.go` | `service_test.go`、`webauthn_recovery_test.go` |
| 登录二次验证 | `server/controllers/login_verification.go`、`login.go` | `login_security_test.go`、安全控制器测试 |
| WebAuthn ceremony | `server/services/webauthn`、`server/controllers/webauthn.go` | WebAuthn service tests、recovery WebAuthn tests |
| HTTP 公开边界 | `server/controllers/security.go`、`server/listen/http_server/http_server.go` | `security_reset_entry_test.go`、`security_public_response_test.go`、`security_authentication_test.go` |
| 密码重置后的状态失效 | `server/controllers/security.go`、`server/services/recovery`、`server/services/adminreset` | `password_reset_permissions_test.go`、`reset_test.go`、recovery invalidation tests |
## 8. 已知边界、剩余风险和后续任务
1. **日志哨兵尚未集中化**:当前验证码事件和限流持久化已有敏感值负向测试,但全局日志、指标、追踪和错误报告仍需由 AD-004、AD-057、AD-059 建立统一字段白名单和哨兵扫描。
2. **真实平台 IPC 尚未完全验收**:Linux Ubuntu 22.04/24.04 的 systemd 一次性服务和 Windows 真实部署身份边界仍由 AD-011、AD-015、AD-062、AD-063 验证;单元测试不能替代真实部署。
3. **SMTP Relay 真实链路尚未完全验收**:STARTTLS/隐式 TLS 的握手、证书校验、认证失败回写和服务商日志需要 AD-034、AD-035、AD-038 的集成测试。
4. **多实例边界必须保持明确**:验证码挑战只存在于签发实例内存;部署多主实例时必须使用粘性路由或继续保持单实例,否则验证请求不能切换实例而不应通过持久化验证码绕过边界。
5. **内存清理是尽力而为**:Go 字符串复制和运行时调度无法提供绝对的零化保证,代码已在可控缓冲区使用覆盖,并以短 TTL、最小生命周期和进程权限降低暴露窗口。
6. **数据库备份和主机转储不属于业务恢复通道**:备份权限、磁盘加密、核心转储、交换分区、崩溃转储和日志收集必须由部署和运维基线单独控制,不得把它们当成 Web 恢复能力。
## 9. AD-003 验收清单
- [x] 已绘制部署端重置、验证码签发、SMTP 投递、验证消费、登录二次验证和密码恢复数据流;
- [x] 已标记外部主体、HTTP 边界、主服务进程、管理进程、IPC 边界、SMTP、数据库、内存和观测边界;
- [x] 已登记密码、验证码、HMAC、票据、恢复码、外部邮箱、WebAuthn、Session、限流和审计数据的生命周期;
- [x] 已覆盖本机提权、IPC 冒用、重放、账号枚举、验证码暴力破解、内存耗尽、SMTP 泄露、日志泄露和并发双花;
- [x] 每项威胁均对应控制措施和至少一个负向测试或明确的后续补齐任务;
- [x] 未发现未说明的敏感数据持久化点;
- [x] 未发现网络超级管理员密码重置入口;
- [ ] 真实 Ubuntu、Windows、SMTP Relay 和全局日志哨兵验收仍由后续任务负责。
## 10. 复审结论
AD-003 可标记为“已完成,等待复审”。该结论只表示设计、代码映射和现有自动化负向测试已经形成可追踪闭环,不表示后续平台部署、真实 SMTP、日志治理或最终发布验收已经完成。
+13 -1
View File
@@ -800,4 +800,16 @@ go vet ./...
- [x] Go 全量测试、Vet、Race、Gosec、Govulncheck、前端依赖审计、ESLint、生产构建及 Linux 无 CGO 构建验证通过。 - [x] Go 全量测试、Vet、Race、Gosec、Govulncheck、前端依赖审计、ESLint、生产构建及 Linux 无 CGO 构建验证通过。
- [ ] HSTS 与实际反向代理部署行为仍需在上线环境复核,本轮不将代码配置等同于部署验收。 - [ ] HSTS 与实际反向代理部署行为仍需在上线环境复核,本轮不将代码配置等同于部署验收。
本轮复审未发现新的明显可达漏洞。Govulncheck 仍仅报告 `golang.org/x/crypto/openpgp` 模块级不可达告警;当前业务未调用该包,且使用同模块 Argon2id,因此暂不直接移除整个依赖模块。 本轮复审未发现新的明显可达漏洞。Govulncheck 仍仅报告 `golang.org/x/crypto/openpgp` 模块级不可达告警;当前业务未调用该包,且使用同模块 Argon2id,因此暂不直接移除整个依赖模块。
---
## 增量关联整改记录(2026-08-27)
- [x] 建立敏感字段目录和持久化禁止边界,覆盖密码、验证码、校验数据、临时密钥、恢复授权、外部邮箱和凭据材料,并区分 `encrypted_only`、`reference_only`、`memory_only`、`hashed_only` 四类策略。
- [x] 补充公共脱敏能力和敏感响应负向测试,配置授权错误仅保留稳定错误码,不回显内部错误文本或敏感字段。
- [x] 将配置状态、备份、回滚、校验、应用、配置分区读写和配置审计接口纳入管理 API 能力目录;修正配置备份到配置回滚能力的映射。
- [x] 恢复配置分区 `PUT /api/v1/config/:section` 路由,并增加不支持方法返回 `405 Method Not Allowed` 的测试。
- [x] 验证管理 API 默认拒绝、超级管理员恢复码豁免、管理员和普通用户恢复码要求以及配置授权稳定错误码边界。
- **验证结果**:定向 `go test`、全量 `go test ./...`、`go vet ./...` 和 `git diff --check` 均通过。
- **未完成验收**:全局日志、指标、追踪、缓存、队列和错误报告的生产哨兵尚未完整覆盖;真实 Ubuntu、Windows、SMTP、多实例、多数据库和生产部署行为仍需单独验收。本记录不代表最终发布通过。
@@ -110,7 +110,7 @@
| 阶段 | 任务范围 | 状态 | 完成数/总数 | | 阶段 | 任务范围 | 状态 | 完成数/总数 |
|---|---|---|---:| |---|---|---|---:|
| 第一阶段 | 产品决定、安全基线和测试基线 | 进行中 | 2/5 | | 第一阶段 | 产品决定、安全基线和测试基线 | 进行中 | 3/5 |
| 第二阶段 | `smail-admin` 构建、安装和升级 | 未开始 | 0/6 | | 第二阶段 | `smail-admin` 构建、安装和升级 | 未开始 | 0/6 |
| 第三阶段 | Linux/Windows 本机 IPC 与重置会话 | 未开始 | 0/4 | | 第三阶段 | Linux/Windows 本机 IPC 与重置会话 | 未开始 | 0/4 |
| 第四阶段 | 超级管理员重置事务与凭据撤销 | 未开始 | 0/6 | | 第四阶段 | 超级管理员重置事务与凭据撤销 | 未开始 | 0/6 |
@@ -122,7 +122,7 @@
| 第十阶段 | 前端页面和交互 | 未开始 | 0/5 | | 第十阶段 | 前端页面和交互 | 未开始 | 0/5 |
| 第十一阶段 | 审计、监控和告警 | 未开始 | 0/3 | | 第十一阶段 | 审计、监控和告警 | 未开始 | 0/3 |
| 第十二阶段 | 跨平台测试、安全复审和发布验收 | 未开始 | 0/7 | | 第十二阶段 | 跨平台测试、安全复审和发布验收 | 未开始 | 0/7 |
| **合计** | | **进行中** | **2/66** | | **合计** | | **进行中** | **3/66** |
--- ---
@@ -158,7 +158,7 @@
### AD-003 完成威胁模型和敏感数据流设计 ### AD-003 完成威胁模型和敏感数据流设计
- **状态**:未开始 - **状态**:已完成,等待复审
- **优先级**:P0 - **优先级**:P0
- **依赖**:AD-001、AD-002、CG-001 - **依赖**:AD-001、AD-002、CG-001
- **需求映射**:第 3、8、14、15、20、22.4 章 - **需求映射**:第 3、8、14、15、20、22.4 章
@@ -168,11 +168,11 @@
- **测试要求**:为每项威胁建立对应控制措施和至少一个负向测试。 - **测试要求**:为每项威胁建立对应控制措施和至少一个负向测试。
- **验收标准**:不存在未说明的敏感数据持久化点或网络重置入口。 - **验收标准**:不存在未说明的敏感数据持久化点或网络重置入口。
- **回退方式**:默认关闭相关能力。 - **回退方式**:默认关闭相关能力。
- **验收证据**:待补充。 - **验收证据**:已新增 `docs/安全威胁模型与敏感数据流设计.md`,完成信任边界、敏感数据生命周期、持久化点、18 项威胁控制措施和负向测试映射;已核对文档引用的测试名称,verification、recovery、credentials、externalemail、adminreset、webauthn、controllers 和 config 相关测试通过;真实 Ubuntu、Windows、SMTP Relay、全局日志哨兵和多实例部署仍由后续任务验收。
### AD-004 建立敏感字段、日志和持久化禁止清单 ### AD-004 建立敏感字段、日志和持久化禁止清单
- **状态**:未开始 - **状态**:`[x] 已完成,等待复审`
- **优先级**:P0 - **优先级**:P0
- **依赖**:AD-003 - **依赖**:AD-003
- **需求映射**:第 8.5、13.5、15、18.4、19、21 章 - **需求映射**:第 8.5、13.5、15、18.4、19、21 章
@@ -182,7 +182,7 @@
- **测试要求**:扫描日志、数据库、配置、缓存、队列、指标、追踪和备份;加入敏感词哨兵测试。 - **测试要求**:扫描日志、数据库、配置、缓存、队列、指标、追踪和备份;加入敏感词哨兵测试。
- **验收标准**:所有敏感类型都有禁止边界、代码守卫和自动化泄露测试。 - **验收标准**:所有敏感类型都有禁止边界、代码守卫和自动化泄露测试。
- **回退方式**:关闭对应功能并保留拒绝日志,不输出敏感详情。 - **回退方式**:关闭对应功能并保留拒绝日志,不输出敏感详情。
- **验收证据**:待补充。 - **验收证据**:已扩展敏感字段目录并明确密码、验证码、校验数据、临时密钥、恢复授权、外部邮箱和凭据材料的禁止边界;已建立 `encrypted_only`、`reference_only`、`memory_only`、`hashed_only` 四类策略和公共脱敏能力;配置审计导出、配置授权错误和配置管理接口已补充敏感输出测试,错误响应不回显内部错误文本;定向测试、全量 `go test ./...`、`go vet ./...` 和 `git diff --check` 通过。全局日志、指标、追踪、缓存、队列和错误报告的生产哨兵仍未完整覆盖,真实 SMTP、平台 IPC、多实例和多数据库仍待验收。
### AD-005 建立需求追踪和测试矩阵 ### AD-005 建立需求追踪和测试矩阵
@@ -1297,6 +1297,39 @@ AD-065 + CG-053~CG-056 → AD-066 → CG-057
复审人: 复审人:
``` ```
### 2026-08-27 AD-003 实施记录
日期:2026-08-27
执行任务:AD-003 完成威胁模型和敏感数据流设计
开始状态:未开始
修改文件:`docs/安全威胁模型与敏感数据流设计.md`、`docs/超级管理员重置与邮箱验证码实施任务清单.md`
实施摘要:完成部署端超级管理员重置、外部安全邮箱绑定、登录二次验证、邮箱密码恢复、WebAuthn、SMTP 投递、限流与审计的数据流设计;标记 HTTP、主服务、管理进程、本机 IPC、SMTP、数据库、内存和观测信任边界;登记允许持久化和禁止持久化的数据;建立 18 项威胁、控制措施与负向测试矩阵,并修正文档中不存在的测试名称引用。
测试命令:`go test ./services/verification ./services/recovery ./services/credentials ./services/externalemail ./services/adminreset ./services/webauthn ./controllers/...`;`go test ./...`;`go vet ./...`;`git diff --check`
测试结果:定向测试、全量测试、vet 和 diff 检查均通过;文档均通过严格 UTF-8 解码且无 BOM;文档引用的测试函数均已核对存在。
安全检查:确认超级管理员自身没有网络重置入口;验证码、恢复票据、IPC nonce 和 WebAuthn ceremony 的内存与一次性消费边界已记录;外部邮箱、凭据和运营数据的加密、哈希或指纹持久化边界已记录;未把真实平台和生产观测能力误记为已验收。
跨平台或数据库覆盖:自动化测试覆盖现有 SQLite 夹具及平台条件测试;真实 Ubuntu 22.04/24.04、Windows Named Pipe、SMTP Relay、多数据库和多实例路由尚未完成。
遗留问题:全局日志、指标、追踪和错误报告的统一敏感字段哨兵待 AD-004、AD-057、AD-059;真实平台 IPC 待 AD-011、AD-015、AD-062、AD-063;真实 SMTP 链路待 AD-034、AD-035、AD-038;多实例粘性路由或单实例部署约束待后续部署验收。
回退验证:本轮只修改设计文档和任务状态,未修改业务代码;如复审不通过,可回退 AD-003 文档和状态记录,不影响现有运行程序。
结束状态:待复审
复审人:
---
## 2026-08-27 AD-004 实施记录
- **日期**:2026-08-27
- **执行任务**:AD-004 建立敏感字段、日志和持久化禁止清单
- **开始状态**:未开始
- **修改文件**:`server/config/sensitive.go`、`server/config/sensitive_test.go`、`server/controllers/config.go`、`server/controllers/config_error_test.go`、`server/services/access/authorize.go`、`server/services/access/capability.go`、`server/services/access/catalog.go`、`server/services/access/access_test.go`、`server/services/access/matrix_test.go`、`server/listen/http_server/http_server.go`、`server/listen/http_server/config_route_test.go`
- **实施摘要**:扩展敏感字段目录和持久化禁止策略;增加公共脱敏能力;将配置、审计和回滚 API 纳入能力目录;恢复配置更新 `PUT` 路由;统一授权错误的稳定错误码并防止内部错误文本进入响应;增加配置路由、授权矩阵和敏感响应负向测试。
- **测试命令**:`go test ./services/access ./config ./controllers ./listen/http_server`、`go test ./...`、`go vet ./...`、`git diff --check`
- **测试结果**:定向测试、全量测试和 `go vet ./...` 通过;`git diff --check` 未发现空白错误。
- **安全检查**:敏感字段按策略禁止明文持久化或通用序列化;配置错误响应仅返回稳定错误码和中文安全提示;配置备份使用回滚能力授权;未登记能力默认拒绝。
- **遗留问题**:全局日志、指标、追踪、缓存、队列和错误报告的生产哨兵尚未完整覆盖;真实 SMTP、真实平台 IPC、多实例、多数据库和生产部署仍未验收。
- **回退验证**:未删除既有文件、配置或数据;保留旧配置读取路径,新增能力可按默认拒绝策略关闭。
- **结束状态**:待复审
- **复审人**:
--- ---
## 20. 任务状态变更记录 ## 20. 任务状态变更记录
@@ -1306,6 +1339,8 @@ AD-065 + CG-053~CG-056 → AD-066 → CG-057
| 2026-08-25 | 全部实施任务 | 无 | 未开始 | 根据需求文档创建任务清单,尚未开始编码实施 | | 2026-08-25 | 全部实施任务 | 无 | 未开始 | 根据需求文档创建任务清单,尚未开始编码实施 |
| 2026-08-25 | AD-001 | 未开始 | 已完成 | 统一 Linux 正式入口为 `systemctl start smail-admin`,确定短时服务和安全密码代理边界 | | 2026-08-25 | AD-001 | 未开始 | 已完成 | 统一 Linux 正式入口为 `systemctl start smail-admin`,确定短时服务和安全密码代理边界 |
| 2026-08-25 | AD-002 | 未开始 | 已完成 | 冻结超级管理员、管理员、普通用户和部署端的密码重置权限矩阵 | | 2026-08-25 | AD-002 | 未开始 | 已完成 | 冻结超级管理员、管理员、普通用户和部署端的密码重置权限矩阵 |
| 2026-08-27 | AD-003 | 未开始 | 已完成,等待复审 | 完成安全威胁模型、敏感数据流、持久化边界和 18 项威胁测试映射;自动化检查通过,真实平台和生产验收保留为后续任务 |
| 2026-08-27 | AD-004 | 未开始 | 已完成,等待复审 | 完成敏感字段、脱敏和持久化禁止边界;配置授权与路由测试通过,生产哨兵和真实平台验收仍待完成 |
| 2026-08-25 | 文档清单 | 0.2 | 0.3 | 建立 CG/AD 双向可追踪的单向依赖,修正统一密码服务顺序并完成 P0/P1 文档复审 | | 2026-08-25 | 文档清单 | 0.2 | 0.3 | 建立 CG/AD 双向可追踪的单向依赖,修正统一密码服务顺序并完成 P0/P1 文档复审 |
| 2026-08-25 | 文档清单 | 0.3 | 0.3 | 二次复审清理验证码预留表述,补充 CG-032、CG-048 基础依赖并验证联合依赖图无缺失和循环 | | 2026-08-25 | 文档清单 | 0.3 | 0.3 | 二次复审清理验证码预留表述,补充 CG-032、CG-048 基础依赖并验证联合依赖图无缺失和循环 |
+75 -15
View File
@@ -93,7 +93,7 @@
| 阶段 | 任务范围 | 状态 | 完成数/总数 | | 阶段 | 任务范围 | 状态 | 完成数/总数 |
|---|---|---|---:| |---|---|---|---:|
| 第一阶段 | 需求、安全边界和迁移基线 | 进行中 | 1/4 | | 第一阶段 | 需求、安全边界和迁移基线 | 进行中 | 3/4 |
| 第二阶段 | 统一配置管理器 | 未开始 | 0/9 | | 第二阶段 | 统一配置管理器 | 未开始 | 0/9 |
| 第三阶段 | SSL、插件、SMTP 和邮箱分区 | 未开始 | 0/9 | | 第三阶段 | SSL、插件、SMTP 和邮箱分区 | 未开始 | 0/9 |
| 第四阶段 | 三级角色、数据库迁移和统一认证 | 未开始 | 0/9 | | 第四阶段 | 三级角色、数据库迁移和统一认证 | 未开始 | 0/9 |
@@ -101,7 +101,7 @@
| 第六阶段 | 管理页面和账户安全页面 | 未开始 | 0/6 | | 第六阶段 | 管理页面和账户安全页面 | 未开始 | 0/6 |
| 第七阶段 | 初始化、兼容切换和部署验证 | 未开始 | 0/6 | | 第七阶段 | 初始化、兼容切换和部署验证 | 未开始 | 0/6 |
| 第八阶段 | 完整安全复审和验收 | 未开始 | 0/6 | | 第八阶段 | 完整安全复审和验收 | 未开始 | 0/6 |
| **合计** | | **进行中** | **1/57** | | **合计** | | **进行中** | **3/57** |
--- ---
@@ -123,7 +123,7 @@
### CG-002 建立敏感字段和安全能力清单 ### CG-002 建立敏感字段和安全能力清单
- **状态**:未开始 - **状态**:`[x] 已完成,等待复审`
- **优先级**:P0 - **优先级**:P0
- **依赖**:CG-001 - **依赖**:CG-001
- **设计映射**:第 3、13、28 章 - **设计映射**:第 3、13、28 章
@@ -133,11 +133,11 @@
- **测试要求**:为每个管理 API 建立最少一条允许和一条拒绝用例;覆盖管理员和普通用户缺少有效恢复码、超级管理员豁免、角色变更目标用户缺少恢复码及稳定错误码 `RECOVERY_CODE_REQUIRED`。 - **测试要求**:为每个管理 API 建立最少一条允许和一条拒绝用例;覆盖管理员和普通用户缺少有效恢复码、超级管理员豁免、角色变更目标用户缺少恢复码及稳定错误码 `RECOVERY_CODE_REQUIRED`。
- **验收标准**:不存在未归类的管理接口、Secret 字段或高风险操作。 - **验收标准**:不存在未归类的管理接口、Secret 字段或高风险操作。
- **回退方式**:保留清单和测试,不切换授权读路径。 - **回退方式**:保留清单和测试,不切换授权读路径。
- **验收证据**:待补充。 - **验收证据**:已建立 30 项以上敏感字段目录及 `encrypted_only`、`reference_only`、`memory_only`、`hashed_only` 四类持久化策略;已补齐 18 项管理 API 能力目录,配置更新 `PUT /api/v1/config/:section` 映射到全局配置写能力,配置备份 `GET /api/v1/config/backups` 映射到配置回滚能力;已验证默认拒绝、超级管理员恢复码豁免、管理员和普通用户恢复码要求、目标角色恢复码校验及稳定错误码 `RECOVERY_CODE_REQUIRED`;定向测试、全量测试、`go vet ./...` 和 `git diff --check` 通过。真实平台、多数据库、生产日志观测和最终发布验收仍未完成。
### CG-003 引入显式数据库迁移框架 ### CG-003 引入显式数据库迁移框架
- **状态**:未开始 - **状态**:`[x] 已完成,等待复审`
- **优先级**:P0 - **优先级**:P0
- **依赖**:CG-001 - **依赖**:CG-001
- **设计映射**:第 11.4、24.1 章 - **设计映射**:第 11.4、24.1 章
@@ -147,11 +147,11 @@
- **测试要求**:MySQL、PostgreSQL、SQLite 的首次迁移、重复执行、校验和冲突和中途失败测试。 - **测试要求**:MySQL、PostgreSQL、SQLite 的首次迁移、重复执行、校验和冲突和中途失败测试。
- **验收标准**:数据库版本可查询;重复启动不重复执行;失败不会形成半完成结构。 - **验收标准**:数据库版本可查询;重复启动不重复执行;失败不会形成半完成结构。
- **回退方式**:保留旧 `Sync2` 兼容开关,但生产默认不使用;不删除现有表。 - **回退方式**:保留旧 `Sync2` 兼容开关,但生产默认不使用;不删除现有表。
- **验收证据**:待补充。 - **验收证据**:已实现 `schema_migration` 表、迁移版本和名称校验、SHA-256 校验和、SQLite `BEGIN IMMEDIATE` 锁、MySQL `GET_LOCK`、PostgreSQL advisory lock、事务执行、失败回滚、重复执行跳过和版本查询;生产环境默认拒绝无版本 `Sync2`,仅保留显式开发或测试兼容开关。SQLite 首次迁移、重复迁移、并发执行、校验和冲突、未知版本、方言缺失和失败回滚测试通过;MySQL/PostgreSQL 集成测试已建立,当前因未配置 `SMAIL_TEST_MYSQL_DSN` 和 `SMAIL_TEST_POSTGRES_DSN` 而跳过,不能视为真实数据库验收通过。
### CG-004 建立配置重构测试基线 ### CG-004 建立配置重构测试基线
- **状态**:未开始 - **状态**:`[x] 已完成,等待复审`
- **优先级**:P0 - **优先级**:P0
- **依赖**:CG-001 - **依赖**:CG-001
- **设计映射**:第 29 章 - **设计映射**:第 29 章
@@ -161,15 +161,15 @@
- **测试要求**:运行当前完整测试并记录既有失败,避免把历史失败误归因于重构。 - **测试要求**:运行当前完整测试并记录既有失败,避免把历史失败误归因于重构。
- **验收标准**:形成可重复的基线命令和脱敏结果,明确未验证项。 - **验收标准**:形成可重复的基线命令和脱敏结果,明确未验证项。
- **回退方式**:仅移除新增测试配置,不改变生产代码。 - **回退方式**:仅移除新增测试配置,不改变生产代码。
- **验收证据**:待补充。 - **验收证据**:已新增 `docs/配置系统重构测试基线.md`,记录 Windows PowerShell 下的 Go 全量测试、迁移专项、`go vet` 和前端构建命令,建立单元、迁移、数据库集成、静态检查、前端构建、安全回归、浏览器和跨平台测试分类;已明确 MySQL/PostgreSQL DSN 仅通过临时环境变量注入,未配置时记录为未验证;已记录 Ubuntu 22.04/24.04、Windows 生产服务、真实 SMTP、多实例和生产观测等外部验收边界。2026-08-27 执行的 `go test ./... -count=1`、`go vet ./...`、迁移专项测试和 `yarn.cmd build` 通过,未使用真实密钥或生产数据库。
### 第一阶段验收 ### 第一阶段验收
- [ ] 需求范围已确认; - [x] 需求范围已确认;
- [ ] 技术设计已评审; - [x] 技术设计已评审;
- [ ] 敏感字段和能力清单完整; - [x] 敏感字段和能力清单完整;
- [ ] 显式数据库迁移框架可用; - [x] 显式数据库迁移框架可用;
- [ ] 当前测试基线已记录。 - [x] 当前测试基线已记录。
--- ---
@@ -177,7 +177,7 @@
### CG-005 建立配置模型和固定分区映射 ### CG-005 建立配置模型和固定分区映射
- **状态**:未开始 - **状态**:`[x] 已完成,等待复审`
- **优先级**:P0 - **优先级**:P0
- **依赖**:CG-001 - **依赖**:CG-001
- **设计映射**:第 6 章 - **设计映射**:第 6 章
@@ -187,7 +187,12 @@
- **测试要求**:模型序列化、三种数据库条件字段、默认端口、非法枚举、任意 SQLite 路径拒绝和固定路径测试。 - **测试要求**:模型序列化、三种数据库条件字段、默认端口、非法枚举、任意 SQLite 路径拒绝和固定路径测试。
- **验收标准**:模型能表达需求文档字段且不继续增加旧聚合 `Config` 字段。 - **验收标准**:模型能表达需求文档字段且不继续增加旧聚合 `Config` 字段。
- **回退方式**:新模型暂不接入启动流程。 - **回退方式**:新模型暂不接入启动流程。
- **验收证据**:待补充。 - **验收证据**:
1. `server/config/model.go` 已建立 `DatabaseType` 白名单,支持 `mysql`、`postgresql`、`sqlite`;MySQL 和 PostgreSQL 在端口为空时分别补充 `3306`、`5432`,SQLite 不生成网络默认端口。
2. `DatabaseConfig` 已按数据库类型表达条件字段:MySQL/PostgreSQL 使用主机、端口、用户名、加密密码和数据库名称;SQLite 仅使用后端引用格式的 `localRef`,并拒绝绝对路径、Windows 路径、UNC 路径、目录分隔符、上级目录、网络字段和密码字段。
3. `server/config/sections.go` 已固定分区到 `config.json`、`smtp.json`、`email.json`、`ssl.json`、`plugins.json`,并通过 `SectionRef`、`SectionMeta`、代次和 SHA-256 摘要校验阻止任意路径映射;`server/config/sections_test.go` 覆盖固定文件名、未知分区、路径篡改、Schema、代次和摘要异常。
4. `server/config/model_database_test.go` 覆盖三种数据库条件字段、默认端口、非法及旧 PostgreSQL 枚举、SQLite 任意路径拒绝和 `localRef` JSON 序列化;`go test ./config -count=1` 通过。
5. 全量验证:在 `server` 目录执行 `go test ./... -count=1`、`go vet ./...` 均通过;`git diff --check` 未发现空白错误。MySQL/PostgreSQL 真实数据库连接、跨平台部署和启动流程仍未在本机完成集成验收,不能据此视为生产验收通过。
### CG-006 实现严格 JSON 解析器 ### CG-006 实现严格 JSON 解析器
@@ -1080,10 +1085,65 @@ CG-053~CG-056 → AD-066 → CG-057
--- ---
## 2026-08-27 CG-002 实施记录
- **日期**:2026-08-27
- **执行任务**:CG-002 建立敏感字段和安全能力清单
- **开始状态**:未开始
- **修改文件**:`server/config/sensitive.go`、`server/config/sensitive_test.go`、`server/services/access/authorize.go`、`server/services/access/capability.go`、`server/services/access/catalog.go`、`server/services/access/access_test.go`、`server/services/access/matrix_test.go`、`server/controllers/config.go`、`server/controllers/config_error_test.go`、`server/listen/http_server/http_server.go`、`server/listen/http_server/config_route_test.go`
- **实施摘要**:扩展敏感字段目录,明确四类持久化策略和公共脱敏能力;补充配置、审计和回滚 API 的能力映射;恢复配置分区 `PUT` 路由;统一配置授权错误的稳定错误码并避免回显内部错误文本;补充配置路由、能力目录、角色恢复码和敏感响应测试。
- **测试命令**:`go test ./services/access ./config ./controllers ./listen/http_server`、`go test ./...`、`go vet ./...`、`git diff --check`
- **测试结果**:定向测试和全量测试通过;`go vet ./...` 通过;`git diff --check` 未发现空白错误。
- **安全检查**:默认拒绝未登记能力;管理员和普通用户执行受保护操作时要求有效恢复码;超级管理员按已确认边界豁免恢复码前置条件;错误响应不泄露内部错误文本和敏感字段;配置备份使用回滚能力而非普通读取能力。
- **遗留问题**:真实 Ubuntu、Windows、三数据库、多实例、生产日志/指标/追踪/缓存/队列/错误报告哨兵和最终发布验收尚未完成。
- **回退验证**:未改变旧配置读取路径;如需回退,可关闭新增配置管理能力并保留拒绝日志,不删除既有配置或数据。
- **结束状态**:待复审
- **复审人**:
---
## 2026-08-27 CG-003 实施记录
- **日期**:2026-08-27
- **执行任务**:CG-003 引入显式数据库迁移框架
- **开始状态**:未开始
- **修改文件**:`server/db/migration/dialect.go`、`server/db/migration/migration.go`、`server/db/migration/registry.go`、`server/db/migration/runner.go`、`server/db/migration/schema.go`、相关测试文件、`server/db/init.go`、`server/db/init_migration_test.go`
- **实施摘要**:建立显式迁移注册表和连续版本校验;为 SQLite、MySQL、PostgreSQL 提供方言 SQL 或自定义迁移;记录迁移版本、名称、校验和、执行时间和耗时;增加数据库级并发锁、事务执行、失败回滚、重复执行跳过、未知版本拒绝和当前版本查询;生产环境不再默认依赖无版本 `Sync2`,兼容模式仅在显式配置并满足开发或测试条件时启用;补充默认迁移注册表的连续性和三数据库方言完整性测试。
- **测试命令**:`go test ./db/migration ./db`、`go test ./db/migration -run 'Test(Default|SQLite|Normalize|Runner|Unknown|Legacy|Custom)' -count=1`、`go test ./...`、`go vet ./...`、`git diff --check`
- **测试结果**:迁移专项测试和 `db` 测试通过;新增默认迁移连续性、名称和三数据库方言覆盖测试通过。MySQL/PostgreSQL 集成测试通过环境变量启用,当前环境未配置 `SMAIL_TEST_MYSQL_DSN` 和 `SMAIL_TEST_POSTGRES_DSN`,因此按测试设计跳过;不能据此宣称 MySQL/PostgreSQL 真实环境已验收。
- **安全检查**:迁移定义必须从版本 1 开始且连续;已应用迁移的名称或校验和变化会被拒绝;并发启动使用数据库锁;失败迁移不会写入完成记录;错误包装不输出迁移 SQL 中的 Secret;生产环境拒绝旧 `Sync2` 兼容模式;测试夹具不包含真实密钥。
- **遗留问题**:真实 MySQL、PostgreSQL、Ubuntu、Windows、多实例并发和生产部署仍未完成;CG-004 测试基线、跨平台故障注入和最终发布验收仍待后续任务;不应将本条状态视为三数据库或生产发布通过。
- **回退验证**:保留显式 `SMAIL_ENABLE_LEGACY_SYNC2` 兼容开关,不删除既有表和旧数据;生产环境仍拒绝该兼容模式,回退不得绕过版本迁移审计。
- **结束状态**:待复审
- **复审人**:
---
## 2026-08-27 CG-004 实施记录
- **日期**:2026-08-27
- **执行任务**:CG-004 建立配置重构测试基线
- **开始状态**:未开始
- **修改文件**:`docs/配置系统重构测试基线.md`、`docs/配置系统重构实施任务清单.md`
- **实施摘要**:建立后端 Go 全量测试、数据库迁移专项、静态检查、前端构建、数据库集成、浏览器验收和跨平台验收分类;定义 Windows PowerShell、Ubuntu 和三数据库的可重复命令;约束测试 DSN 只能通过临时环境变量注入;明确真实密钥、生产数据库和已有私钥、可执行文件不得作为测试输入。
- **测试命令**:`go test ./... -count=1`、`go vet ./...`、`go test ./db/migration ./db -count=1`、`yarn.cmd build`、`git diff --check`
- **测试结果**:后端全量测试通过;`go vet ./...` 通过;数据库迁移专项和 `db` 测试通过;前端 Vite 生产构建通过,仅有资源分块偏大的提示;MySQL/PostgreSQL 因未配置 `SMAIL_TEST_MYSQL_DSN` 和 `SMAIL_TEST_POSTGRES_DSN` 未执行真实集成测试,并已在基线文档中标记为未验证。
- **安全检查**:基线文档不包含真实凭据;测试使用临时目录或测试数据库;没有把跳过的集成测试写成通过;明确生产平台、真实 SMTP、多实例和生产观测不属于本机自动化结果。
- **遗留问题**:Ubuntu 22.04/24.04、Windows 生产服务、真实 MySQL/PostgreSQL、SMTP、多实例、浏览器和生产观测仍需独立环境验收;前端当前只有构建基线,未替代真实浏览器验收。
- **回退验证**:本任务仅新增中文测试基线文档,不改变生产代码、配置读取路径、数据库结构、私钥、可执行文件或旧测试配置。
- **结束状态**:待复审
- **复审人**:
---
## 14. 任务状态变更记录 ## 14. 任务状态变更记录
| 日期 | 任务 | 原状态 | 新状态 | 说明 | | 日期 | 任务 | 原状态 | 新状态 | 说明 |
|---|---|---|---|---| |---|---|---|---|---|
| 2026-08-27 | CG-005 | 未开始 | 已完成,等待复审 | 完成配置模型、三数据库条件字段、默认端口、SQLite `localRef` 约束和固定分区映射测试;自动化验证通过,真实数据库集成、跨平台部署和启动流程仍待验收 |
| 2026-08-27 | CG-002 | 未开始 | 已完成,等待复审 | 完成敏感字段目录、持久化策略、管理 API 能力映射、配置 PUT 路由和授权负向测试;自动化检查通过,真实平台和生产观测仍待验收 |
| 2026-08-27 | CG-003 | 未开始 | 已完成,等待复审 | 完成显式迁移框架、版本和校验和校验、三数据库方言定义、数据库锁、事务回滚和生产 `Sync2` 兼容边界;SQLite 自动化测试通过,MySQL/PostgreSQL 因未配置 DSN 未执行真实集成验收 |
| 2026-08-27 | CG-004 | 未开始 | 已完成,等待复审 | 建立 Go、迁移、vet、前端构建、数据库集成、浏览器和跨平台测试基线;本机自动化通过,真实三数据库和生产平台仍未验证 |
| 2026-08-25 | 全部编码任务 | 无 | 未开始 | 创建实施任务清单,尚未开始编码实施 | | 2026-08-25 | 全部编码任务 | 无 | 未开始 | 创建实施任务清单,尚未开始编码实施 |
| 2026-08-25 | CG-001 | 未开始 | 待复审 | 已完成首轮产品决定同步,继续根据后续确认修订验收边界 | | 2026-08-25 | CG-001 | 未开始 | 待复审 | 已完成首轮产品决定同步,继续根据后续确认修订验收边界 |
| 2026-08-25 | CG-001 | 待复审 | 已完成 | 需求升级为 0.7、独立需求升级为 0.3、技术设计升级为 0.5;完整验证码范围、`systemctl start smail-admin`、角色矩阵和跨文档依赖复审通过 | | 2026-08-25 | CG-001 | 待复审 | 已完成 | 需求升级为 0.7、独立需求升级为 0.3、技术设计升级为 0.5;完整验证码范围、`systemctl start smail-admin`、角色矩阵和跨文档依赖复审通过 |
+94
View File
@@ -0,0 +1,94 @@
# Smail 配置系统重构测试基线
## 1. 基线信息
- **记录日期**:2026-08-27
- **工作目录**:`D:\Desktop\Smail`
- **当前验证平台**:Windows 开发环境
- **后端模块**:`server`
- **前端模块**:`fe`
- **测试原则**:只使用临时目录、内存数据或测试数据库;不读取、不提交、不打印真实密码、私钥、数据库连接串、SMTP 凭据或配置主密钥。
本文件记录当前可重复执行的自动化基线,不代表 Ubuntu、Windows 生产服务、真实 SMTP、真实 MySQL、真实 PostgreSQL、多实例部署或最终发布验收已经完成。
## 2. 后端基线命令
在 PowerShell 中执行:
```powershell
Set-Location D:\Desktop\Smail\server
go test ./... -count=1
go vet ./...
go test ./db/migration ./db -count=1
```
三数据库迁移集成测试使用环境变量提供测试 DSN,禁止把凭据写入命令行历史、文档、代码或远程地址:
```powershell
$env:SMAIL_TEST_MYSQL_DSN = '<测试环境提供的 MySQL DSN>'
$env:SMAIL_TEST_POSTGRES_DSN = '<测试环境提供的 PostgreSQL DSN>'
go test ./db/migration -run 'Test(MySQL|Postgres)Integration' -count=1
```
未设置上述变量时,集成测试会安全跳过;跳过结果必须记录为“未验证”,不能写成测试通过。
## 3. 前端基线命令
在 PowerShell 中执行:
```powershell
Set-Location D:\Desktop\Smail\fe
yarn.cmd build
```
如需只读执行代码检查,不使用项目中带有 `--fix` 的快捷脚本:
```powershell
yarn.cmd eslint . --ext .vue,.js,.jsx,.cjs,.mjs --ignore-path .gitignore
```
前端构建产生的 `fe/dist` 属于忽略目录,不应据此覆盖、提交或删除用户已有的配置、密钥和可执行文件。
## 4. 测试分类
| 分类 | 主要范围 | 基线命令或测试入口 |
|---|---|---|
| 单元测试 | 配置、授权、认证、恢复、协议和工具函数 | `go test ./... -count=1` |
| 数据库迁移 | 版本连续性、方言覆盖、首次执行、重复执行、并发锁、校验和冲突和失败回滚 | `go test ./db/migration ./db -count=1` |
| 数据库集成 | MySQL、PostgreSQL 测试数据库的建表、重复执行、并发和失败恢复 | `TestMySQLIntegration`、`TestPostgresIntegration` |
| 静态检查 | Go 编译器和潜在错误检查 | `go vet ./...` |
| 前端构建 | Vue、Vite、依赖解析和生产构建 | `yarn.cmd build` |
| 安全回归 | 敏感字段脱敏、能力默认拒绝、恢复码边界和错误响应 | 对应 `*_test.go` 安全测试 |
| 浏览器验收 | 页面布局、登录恢复、配置页面和响应数据泄露 | 需使用独立浏览器实例和独立端口,当前基线不替代真实浏览器验收 |
| 跨平台验收 | Windows 开发模式、Ubuntu 22.04、Ubuntu 24.04、systemd、Named Pipe 和 Unix Domain Socket | 需在对应真实环境执行,当前未完成 |
## 5. 2026-08-27 执行结果
| 检查项 | 结果 | 说明 |
|---|---|---|
| `go test ./... -count=1` | 通过 | 后端全部测试包通过,无失败项 |
| `go vet ./...` | 通过 | 未发现 vet 问题 |
| `go test ./db/migration ./db -count=1` | 通过 | SQLite 迁移和数据库初始化测试通过 |
| 默认迁移注册表覆盖测试 | 通过 | 版本连续、名称非空、三种数据库方言均有 SQL 或自定义 Apply |
| MySQL 集成测试 | 未验证 | 未配置 `SMAIL_TEST_MYSQL_DSN`,测试按设计跳过 |
| PostgreSQL 集成测试 | 未验证 | 未配置 `SMAIL_TEST_POSTGRES_DSN`,测试按设计跳过 |
| `yarn.cmd build` | 通过 | Vite 生产构建通过;存在大资源分块提示,不影响本次构建结果 |
| Ubuntu 22.04/24.04 | 未验证 | 当前环境不是 Ubuntu |
| Windows 生产服务 | 未验证 | 当前仅完成 Windows 开发环境自动化检查 |
| 真实多实例、SMTP 和生产观测 | 未验证 | 需要部署环境、测试凭据和独立验收记录 |
## 6. 安全和脱敏检查
- 测试 DSN 只通过临时环境变量注入,文档只保留占位符。
- 测试失败信息不应包含完整 SQL、密码、私钥、密文、恢复码、验证码或数据库连接串。
- 迁移测试夹具使用临时 SQLite 文件和临时目录,不操作项目配置目录。
- 真实的 `server/config/dkim/dkim.priv`、`server/config/ssl/private.key` 和已有可执行文件不属于测试输入,不得被测试覆盖、删除或提交。
- MySQL/PostgreSQL 集成测试必须使用一次性测试数据库或测试 schema,并在独立环境中清理;清理动作不得指向生产数据库。
## 7. 当前未完成项
1. `CG-004` 仍需复审本基线的跨平台可重复性和责任边界。
2. MySQL、PostgreSQL 的真实集成测试需要安全提供 DSN 后执行,当前不能以跳过替代验收。
3. Ubuntu 22.04、Ubuntu 24.04、Windows 服务、systemd、Named Pipe 和 Unix Domain Socket 需要真实平台测试。
4. 前端仍需独立浏览器实例完成页面、权限、恢复流程和敏感数据泄露检查。
5. 真实 SMTP、多实例、生产日志/指标/追踪/缓存/队列/错误报告哨兵和发布流程仍需单独验收。
+1 -1
View File
@@ -10,7 +10,7 @@ import (
func testRootConfig() RootConfig { func testRootConfig() RootConfig {
return RootConfig{SchemaVersion: CurrentSchemaVersion, Generation: 1, SetupState: SetupStateBootstrap, return RootConfig{SchemaVersion: CurrentSchemaVersion, Generation: 1, SetupState: SetupStateBootstrap,
Database: DatabaseConfig{Type: DBTypeSQLite, SQLiteLocalRef: "smail.db"}, Database: DatabaseConfig{Type: DatabaseTypeSQLite, LocalRef: "smail.db"},
SMTP: SMTPConfig{VerificationEnabled: false}, SMTP: SMTPConfig{VerificationEnabled: false},
SSL: SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"}, SSL: SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"},
Security: SecurityConfig{PasswordVersion: "argon2id"}} Security: SecurityConfig{PasswordVersion: "argon2id"}}
+1 -1
View File
@@ -716,7 +716,7 @@ func applySecretChanges(candidate *RuntimeConfig, section Section, changes map[s
for name, change := range changes { for name, change := range changes {
switch { switch {
case section == SectionRoot && name == "database.password": case section == SectionRoot && name == "database.password":
stored, err := ApplySecretChange(vault, candidate.Root.Database.Password, change, SecretPolicy{Required: candidate.Root.Database.Type != DBTypeSQLite, AllowClear: false, MaxLength: 4096}, now) stored, err := ApplySecretChange(vault, candidate.Root.Database.Password, change, SecretPolicy{Required: candidate.Root.Database.Type != DatabaseTypeSQLite, AllowClear: false, MaxLength: 4096}, now)
if err != nil { if err != nil {
return err return err
} }
+32 -10
View File
@@ -10,6 +10,7 @@ import (
"time" "time"
"git.pcux.cn/xuans/Smail/utils/atomicfile" "git.pcux.cn/xuans/Smail/utils/atomicfile"
"git.pcux.cn/xuans/Smail/utils/credential"
) )
func writeRuntimeFixture(t *testing.T, root string, runtime RuntimeConfig) { func writeRuntimeFixture(t *testing.T, root string, runtime RuntimeConfig) {
@@ -29,6 +30,27 @@ func writeRuntimeFixture(t *testing.T, root string, runtime RuntimeConfig) {
} }
} }
func validMySQLRuntimeConfig(t *testing.T, root string) RuntimeConfig {
t.Helper()
runtime := validRuntimeConfig()
vault, err := credential.NewVault(root)
if err != nil {
t.Fatal(err)
}
ciphertext, err := vault.Encrypt("initial-database-secret")
if err != nil {
t.Fatal(err)
}
runtime.Root.Database = DatabaseConfig{
Type: DatabaseTypeMySQL,
Host: "127.0.0.1",
Port: DefaultMySQLPort,
Username: "smail",
Password: StoredSecret{Ciphertext: ciphertext, Version: vault.Version(), UpdatedAt: time.Now().UTC()},
Name: "smail",
}
return runtime
}
func authorizedConfigActor() AuditActor { func authorizedConfigActor() AuditActor {
return AuditActor{UserID: "1", Role: "super_admin", SessionID: "test-session", RecentAuth: true, RecoveryCodeConfigured: true} return AuditActor{UserID: "1", Role: "super_admin", SessionID: "test-session", RecentAuth: true, RecoveryCodeConfigured: true}
} }
@@ -309,14 +331,16 @@ func TestTransactionRecoveryKeepsOrRestoresByPhase(t *testing.T) {
func TestConfigManagerSecretChangesRequireStepUpAndPreserveStoredSecret(t *testing.T) { func TestConfigManagerSecretChangesRequireStepUpAndPreserveStoredSecret(t *testing.T) {
root := t.TempDir() root := t.TempDir()
runtime := validRuntimeConfig() runtime := validMySQLRuntimeConfig(t, root)
writeRuntimeFixture(t, root, runtime) writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}} options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options) manager, err := NewConfigManager(root, options)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
rootPayload, err := json.Marshal(manager.Snapshot().Root) rootValue := manager.Snapshot().Root
rootValue.Database.Password = StoredSecret{}
rootPayload, err := json.Marshal(rootValue)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -344,14 +368,10 @@ func TestConfigManagerSecretChangesRequireStepUpAndPreserveStoredSecret(t *testi
t.Fatal(err) t.Fatal(err)
} }
stored := manager.Snapshot().Root.Database.Password stored := manager.Snapshot().Root.Database.Password
payload, err := json.Marshal(manager.Snapshot().Root) rootValue = manager.Snapshot().Root
if err != nil {
t.Fatal(err)
}
rootValue := manager.Snapshot().Root
rootValue.Database.Password = StoredSecret{} rootValue.Database.Password = StoredSecret{}
rootValue.Database.Name = "next" rootValue.Database.Name = "next"
payload, err = json.Marshal(rootValue) payload, err := json.Marshal(rootValue)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
@@ -417,14 +437,16 @@ func TestConfigManagerSecretClearRequiresExplicitConfirmation(t *testing.T) {
func TestConfigManagerSecretChangesUseVaultAndRejectUnknownFields(t *testing.T) { func TestConfigManagerSecretChangesUseVaultAndRejectUnknownFields(t *testing.T) {
root := t.TempDir() root := t.TempDir()
runtime := validRuntimeConfig() runtime := validMySQLRuntimeConfig(t, root)
writeRuntimeFixture(t, root, runtime) writeRuntimeFixture(t, root, runtime)
options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}} options := ConfigLoaderOptions{Validation: RuntimeValidationOptions{HasSuperAdmin: true, Production: true}}
manager, err := NewConfigManager(root, options) manager, err := NewConfigManager(root, options)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
rootPayload, err := json.Marshal(manager.Snapshot().Root) rootValue := manager.Snapshot().Root
rootValue.Database.Password = StoredSecret{}
rootPayload, err := json.Marshal(rootValue)
if err != nil { if err != nil {
t.Fatal(err) t.Fatal(err)
} }
+55 -9
View File
@@ -11,6 +11,19 @@ const (
SetupStateDegraded SetupState = "degraded" SetupStateDegraded SetupState = "degraded"
) )
type DatabaseType string
const (
DatabaseTypeMySQL DatabaseType = "mysql"
DatabaseTypePostgreSQL DatabaseType = "postgresql"
DatabaseTypeSQLite DatabaseType = "sqlite"
)
const (
DefaultMySQLPort uint16 = 3306
DefaultPostgreSQLPort uint16 = 5432
)
type RootConfig struct { type RootConfig struct {
ConfigVersion uint32 `json:"configVersion,omitempty"` ConfigVersion uint32 `json:"configVersion,omitempty"`
SchemaVersion int `json:"schemaVersion,omitempty"` SchemaVersion int `json:"schemaVersion,omitempty"`
@@ -50,18 +63,22 @@ func normalizeRootConfig(source RootConfig) RootConfig {
result.Generation = 1 result.Generation = 1
} }
} }
result.Database = NormalizeDatabaseConfig(result.Database)
if result.LogLevel == "" {
result.LogLevel = "info"
}
result.Version = 0 result.Version = 0
return result return result
} }
type DatabaseConfig struct { type DatabaseConfig struct {
Type string `json:"type"` Type DatabaseType `json:"type"`
Host string `json:"host,omitempty"` Host string `json:"host,omitempty"`
Port int `json:"port,omitempty"` Port uint16 `json:"port,omitempty"`
Username string `json:"username,omitempty"` Username string `json:"username,omitempty"`
Password StoredSecret `json:"password,omitempty"` Password StoredSecret `json:"password,omitempty"`
Name string `json:"name,omitempty"` Name string `json:"name,omitempty"`
SQLiteLocalRef string `json:"sqliteLocalRef,omitempty"` LocalRef string `json:"localRef,omitempty"`
} }
type SMTPConfig struct { type SMTPConfig struct {
@@ -120,6 +137,35 @@ func (s SetupState) Valid() bool {
} }
} }
func (d DatabaseConfig) IsStructured() bool { func (t DatabaseType) Valid() bool {
return d.Type == DBTypeSQLite || (d.Host != "" && d.Username != "" && d.Name != "" && d.Password.Configured()) switch t {
case DatabaseTypeMySQL, DatabaseTypePostgreSQL, DatabaseTypeSQLite:
return true
default:
return false
}
}
func DefaultDatabasePort(databaseType DatabaseType) (uint16, bool) {
switch databaseType {
case DatabaseTypeMySQL:
return DefaultMySQLPort, true
case DatabaseTypePostgreSQL:
return DefaultPostgreSQLPort, true
default:
return 0, false
}
}
func NormalizeDatabaseConfig(database DatabaseConfig) DatabaseConfig {
if database.Port == 0 {
if port, ok := DefaultDatabasePort(database.Type); ok {
database.Port = port
}
}
return database
}
func (d DatabaseConfig) IsStructured() bool {
return d.Type == DatabaseTypeSQLite || (d.Host != "" && d.Username != "" && d.Name != "" && d.Password.Configured())
} }
+105
View File
@@ -0,0 +1,105 @@
package config
import (
"encoding/json"
"strings"
"testing"
"time"
)
func TestDatabaseTypeDefaultsAndValidation(t *testing.T) {
secret := StoredSecret{Ciphertext: "enc:v1:stored", Version: 1, UpdatedAt: time.Now().UTC()}
tests := []struct {
name string
typeValue DatabaseType
port uint16
wantPort uint16
}{
{name: "mysql default", typeValue: DatabaseTypeMySQL, wantPort: DefaultMySQLPort},
{name: "postgresql default", typeValue: DatabaseTypePostgreSQL, wantPort: DefaultPostgreSQLPort},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
got := NormalizeDatabaseConfig(DatabaseConfig{Type: test.typeValue})
if got.Port != test.wantPort {
t.Fatalf("default port = %d, want %d", got.Port, test.wantPort)
}
valid := got
valid.Host = "127.0.0.1"
valid.Username = "smail"
valid.Password = secret
valid.Name = "smail"
if err := ValidateDatabaseConfig(valid); err != nil {
t.Fatalf("valid database rejected: %v", err)
}
})
}
if _, ok := DefaultDatabasePort(DatabaseTypeSQLite); ok {
t.Fatal("SQLite unexpectedly received a network default port")
}
if DatabaseType("postgres").Valid() {
t.Fatal("legacy PostgreSQL enum was accepted")
}
}
func TestSQLiteLocalRefIsBackendReferenceOnly(t *testing.T) {
valid := DatabaseConfig{Type: DatabaseTypeSQLite, LocalRef: "smail.db"}
if err := ValidateDatabaseConfig(valid); err != nil {
t.Fatalf("valid SQLite database rejected: %v", err)
}
for _, localRef := range []string{
"../smail.db",
"config/smail.db",
"C:\\data\\smail.db",
"/var/lib/smail/smail.db",
"\\\\server\\share\\smail.db",
"",
} {
t.Run(localRef, func(t *testing.T) {
candidate := valid
candidate.LocalRef = localRef
if err := ValidateDatabaseConfig(candidate); err == nil {
t.Fatalf("arbitrary localRef %q was accepted", localRef)
}
})
}
for name, mutate := range map[string]func(*DatabaseConfig){
"host": func(candidate *DatabaseConfig) { candidate.Host = "127.0.0.1" },
"port": func(candidate *DatabaseConfig) { candidate.Port = 3306 },
"username": func(candidate *DatabaseConfig) { candidate.Username = "smail" },
"name": func(candidate *DatabaseConfig) { candidate.Name = "smail" },
"password": func(candidate *DatabaseConfig) {
candidate.Password = StoredSecret{Ciphertext: "enc:v1:secret", Version: 1, UpdatedAt: time.Now().UTC()}
},
} {
t.Run(name, func(t *testing.T) {
candidate := valid
mutate(&candidate)
if err := ValidateDatabaseConfig(candidate); err == nil {
t.Fatalf("SQLite %s field was accepted", name)
}
})
}
}
func TestDatabaseModelSerializationUsesLocalRef(t *testing.T) {
root := testRootConfig()
data, err := json.Marshal(root)
if err != nil {
t.Fatal(err)
}
encoded := string(data)
if !strings.Contains(encoded, `"localRef":"smail.db"`) {
t.Fatalf("serialized database omitted localRef: %s", encoded)
}
if strings.Contains(encoded, "sqliteLocalRef") {
t.Fatalf("serialized database contains legacy SQLite field: %s", encoded)
}
var decoded RootConfig
if err := ParseStrict(data, &decoded); err != nil {
t.Fatal(err)
}
if decoded.Database.LocalRef != "smail.db" {
t.Fatalf("decoded localRef = %q", decoded.Database.LocalRef)
}
}
+1 -1
View File
@@ -5,7 +5,7 @@ import "testing"
func TestRootConfigValidatesStructuredDatabaseAndPluginID(t *testing.T) { func TestRootConfigValidatesStructuredDatabaseAndPluginID(t *testing.T) {
root := RootConfig{ root := RootConfig{
SchemaVersion: CurrentSchemaVersion, Generation: 1, SetupState: SetupStateBootstrap, SchemaVersion: CurrentSchemaVersion, Generation: 1, SetupState: SetupStateBootstrap,
Database: DatabaseConfig{Type: DBTypeSQLite, SQLiteLocalRef: "smail.db"}, Database: DatabaseConfig{Type: DatabaseTypeSQLite, LocalRef: "smail.db"},
SMTP: SMTPConfig{VerificationEnabled: false}, SMTP: SMTPConfig{VerificationEnabled: false},
SSL: SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"}, SSL: SSLConfig{Mode: "default", DefaultDirectory: "config/ssl"},
Plugins: []PluginConfig{{LogicalID: "telegram_push", FileName: "telegram_push", NetworkAllowlist: []string{"api.telegram.org"}}}, Plugins: []PluginConfig{{LogicalID: "telegram_push", FileName: "telegram_push", NetworkAllowlist: []string{"api.telegram.org"}}},
+147 -17
View File
@@ -1,6 +1,11 @@
package config package config
import "strings" import (
"fmt"
"reflect"
"strings"
"time"
)
type PersistencePolicy string type PersistencePolicy string
@@ -8,28 +13,48 @@ const (
PersistenceEncryptedOnly PersistencePolicy = "encrypted_only" PersistenceEncryptedOnly PersistencePolicy = "encrypted_only"
PersistenceReferenceOnly PersistencePolicy = "reference_only" PersistenceReferenceOnly PersistencePolicy = "reference_only"
PersistenceMemoryOnly PersistencePolicy = "memory_only" PersistenceMemoryOnly PersistencePolicy = "memory_only"
PersistenceHashedOnly PersistencePolicy = "hashed_only"
) )
const RedactedValue = "[REDACTED]"
type SensitiveField struct { type SensitiveField struct {
Path string Path string
Policy PersistencePolicy Policy PersistencePolicy
Description string
} }
var sensitiveFields = []SensitiveField{ var sensitiveFields = []SensitiveField{
{Path: "database.password", Policy: PersistenceEncryptedOnly}, {Path: "database.password", Policy: PersistenceEncryptedOnly, Description: "数据库认证密码"},
{Path: "smtp.relay.password", Policy: PersistenceEncryptedOnly}, {Path: "smtp.relay.password", Policy: PersistenceEncryptedOnly, Description: "SMTP Relay 认证密码"},
{Path: "plugins.*.token", Policy: PersistenceEncryptedOnly}, {Path: "plugins.*.token", Policy: PersistenceEncryptedOnly, Description: "插件访问令牌"},
{Path: "plugins.*.secret", Policy: PersistenceEncryptedOnly}, {Path: "plugins.*.secret", Policy: PersistenceEncryptedOnly, Description: "插件 Secret"},
{Path: "plugins.*.api_key", Policy: PersistenceEncryptedOnly}, {Path: "plugins.*.api_key", Policy: PersistenceEncryptedOnly, Description: "插件 API 密钥"},
{Path: "ssl.private_key", Policy: PersistenceReferenceOnly}, {Path: "ssl.private_key", Policy: PersistenceReferenceOnly, Description: "SSL 私钥材料"},
{Path: "security.encryption_master_key", Policy: PersistenceReferenceOnly}, {Path: "security.encryption_master_key", Policy: PersistenceReferenceOnly, Description: "配置加密主密钥"},
{Path: "security.question_answer", Policy: PersistenceEncryptedOnly}, {Path: "security.question_answer", Policy: PersistenceEncryptedOnly, Description: "密保答案原文"},
{Path: "security.offline_recovery_code", Policy: PersistenceEncryptedOnly}, {Path: "security.offline_recovery_code", Policy: PersistenceMemoryOnly, Description: "离线恢复码原文"},
{Path: "security.maintenance_credential", Policy: PersistenceMemoryOnly}, {Path: "security.maintenance_credential", Policy: PersistenceMemoryOnly, Description: "维护凭据"},
{Path: "verification.code", Policy: PersistenceMemoryOnly}, {Path: "verification.code", Policy: PersistenceMemoryOnly, Description: "邮箱验证码原文"},
{Path: "verification.code_hmac", Policy: PersistenceMemoryOnly}, {Path: "verification.code_hmac", Policy: PersistenceMemoryOnly, Description: "验证码 HMAC 校验值"},
{Path: "verification.process_key", Policy: PersistenceMemoryOnly}, {Path: "verification.process_key", Policy: PersistenceMemoryOnly, Description: "验证码进程临时密钥"},
{Path: "recovery.authorization", Policy: PersistenceMemoryOnly}, {Path: "verification.challenge", Policy: PersistenceMemoryOnly, Description: "验证码挑战上下文"},
{Path: "verification.account_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码账号运营指纹"},
{Path: "verification.email_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码邮箱运营指纹"},
{Path: "verification.ip_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码 IP 运营指纹"},
{Path: "verification.rate_limit_fingerprint", Policy: PersistenceHashedOnly, Description: "验证码限流指纹"},
{Path: "recovery.authorization", Policy: PersistenceMemoryOnly, Description: "恢复授权上下文"},
{Path: "recovery.ticket", Policy: PersistenceMemoryOnly, Description: "密码恢复票据"},
{Path: "recovery.code", Policy: PersistenceMemoryOnly, Description: "恢复码原文"},
{Path: "external_email.email", Policy: PersistenceEncryptedOnly, Description: "完整外部安全邮箱"},
{Path: "external_email.address", Policy: PersistenceEncryptedOnly, Description: "完整外部邮箱地址"},
{Path: "external_email.credential", Policy: PersistenceEncryptedOnly, Description: "外部邮箱凭据材料"},
{Path: "webauthn.credential_data", Policy: PersistenceEncryptedOnly, Description: "WebAuthn 凭据私密材料"},
{Path: "webauthn.private_key", Policy: PersistenceMemoryOnly, Description: "WebAuthn 私钥材料"},
{Path: "ipc.nonce", Policy: PersistenceMemoryOnly, Description: "本机 IPC 一次性 nonce"},
{Path: "ipc.maintenance_credential", Policy: PersistenceMemoryOnly, Description: "本机维护通道凭据"},
{Path: "session.token", Policy: PersistenceReferenceOnly, Description: "会话令牌"},
{Path: "session.data", Policy: PersistenceEncryptedOnly, Description: "会话数据"},
} }
func SensitiveFields() []SensitiveField { func SensitiveFields() []SensitiveField {
@@ -63,11 +88,116 @@ func CanPersist(path string, encrypted bool) bool {
return encrypted return encrypted
case PersistenceReferenceOnly, PersistenceMemoryOnly: case PersistenceReferenceOnly, PersistenceMemoryOnly:
return false return false
case PersistenceHashedOnly:
return false
default: default:
return false return false
} }
} }
// CanPersistRepresentation 判断敏感数据只能以哪一种表示形式进入持久化介质。
// verification.code 等内存字段即使经过哈希或加密也不得落盘。
func CanPersistRepresentation(path string, representation string) bool {
field, sensitive := ClassifySensitive(path)
if !sensitive {
return true
}
switch field.Policy {
case PersistenceEncryptedOnly:
return representation == "encrypted"
case PersistenceReferenceOnly:
return representation == "reference"
case PersistenceHashedOnly:
return representation == "hash"
case PersistenceMemoryOnly:
return representation == "memory"
default:
return false
}
}
// RedactSensitiveValue 为公共输出提供统一的敏感值占位符。
func RedactSensitiveValue(path string, value any) any {
if _, ok := ClassifySensitive(path); ok {
return RedactedValue
}
return value
}
// RedactPublicValue 递归生成只读公共视图,避免把 Secret 结构直接交给 JSON 反射器。
// 持久化配置必须继续使用原始结构和专用存储路径,不能把该函数用于写盘。
func RedactPublicValue(value any) any {
return redactPublicValue(reflect.ValueOf(value), "")
}
func redactPublicValue(value reflect.Value, path string) any {
if !value.IsValid() {
return nil
}
if value.Kind() == reflect.Interface || value.Kind() == reflect.Pointer {
if value.IsNil() {
return nil
}
return redactPublicValue(value.Elem(), path)
}
if path != "" {
if _, ok := ClassifySensitive(path); ok {
return RedactedValue
}
}
if value.Type() == reflect.TypeOf(time.Time{}) {
return value.Interface()
}
switch value.Kind() {
case reflect.Struct:
result := make(map[string]any)
typ := value.Type()
for index := 0; index < value.NumField(); index++ {
field := typ.Field(index)
if field.PkgPath != "" {
continue
}
name := jsonFieldName(field.Tag.Get("json"), field.Name)
if name == "" || name == "-" {
continue
}
fieldPath := joinSensitivePath(path, name)
result[name] = redactPublicValue(value.Field(index), fieldPath)
}
return result
case reflect.Map:
result := make(map[string]any)
iter := value.MapRange()
for iter.Next() {
key := fmt.Sprint(iter.Key().Interface())
result[key] = redactPublicValue(iter.Value(), joinSensitivePath(path, key))
}
return result
case reflect.Slice, reflect.Array:
result := make([]any, value.Len())
for index := 0; index < value.Len(); index++ {
result[index] = redactPublicValue(value.Index(index), path)
}
return result
default:
return value.Interface()
}
}
func jsonFieldName(tag, fallback string) string {
if tag == "" {
return fallback
}
return strings.Split(tag, ",")[0]
}
func joinSensitivePath(parent, child string) string {
if parent == "" {
return child
}
return parent + "." + child
}
func matchSensitivePath(pattern string, value string) bool { func matchSensitivePath(pattern string, value string) bool {
patternParts := strings.Split(pattern, ".") patternParts := strings.Split(pattern, ".")
valueParts := strings.Split(value, ".") valueParts := strings.Split(value, ".")
+52 -3
View File
@@ -4,8 +4,8 @@ import "testing"
func TestSensitiveFieldCatalog(t *testing.T) { func TestSensitiveFieldCatalog(t *testing.T) {
fields := SensitiveFields() fields := SensitiveFields()
if len(fields) != 14 { if len(fields) < 30 {
t.Fatalf("unexpected sensitive field count: %d", len(fields)) t.Fatalf("sensitive field catalog is incomplete: %d", len(fields))
} }
seen := map[string]struct{}{} seen := map[string]struct{}{}
for _, field := range fields { for _, field := range fields {
@@ -14,10 +14,13 @@ func TestSensitiveFieldCatalog(t *testing.T) {
} }
seen[field.Path] = struct{}{} seen[field.Path] = struct{}{}
switch field.Policy { switch field.Policy {
case PersistenceEncryptedOnly, PersistenceReferenceOnly, PersistenceMemoryOnly: case PersistenceEncryptedOnly, PersistenceReferenceOnly, PersistenceMemoryOnly, PersistenceHashedOnly:
default: default:
t.Fatalf("invalid policy for %s", field.Path) t.Fatalf("invalid policy for %s", field.Path)
} }
if field.Description == "" {
t.Fatalf("missing description for %s", field.Path)
}
if CanGenericSerialize(field.Path) { if CanGenericSerialize(field.Path) {
t.Fatalf("sensitive field can be generically serialized: %s", field.Path) t.Fatalf("sensitive field can be generically serialized: %s", field.Path)
} }
@@ -47,6 +50,7 @@ func TestSensitivePersistenceRules(t *testing.T) {
{path: "verification.code_hmac", encrypted: true, want: false}, {path: "verification.code_hmac", encrypted: true, want: false},
{path: "verification.process_key", encrypted: true, want: false}, {path: "verification.process_key", encrypted: true, want: false},
{path: "public.display_name", encrypted: false, want: true}, {path: "public.display_name", encrypted: false, want: true},
{path: "verification.account_fingerprint", encrypted: true, want: false},
} }
for _, test := range tests { for _, test := range tests {
if got := CanPersist(test.path, test.encrypted); got != test.want { if got := CanPersist(test.path, test.encrypted); got != test.want {
@@ -54,3 +58,48 @@ func TestSensitivePersistenceRules(t *testing.T) {
} }
} }
} }
func TestSensitiveRepresentations(t *testing.T) {
tests := []struct {
path string
representation string
want bool
}{
{path: "database.password", representation: "encrypted", want: true},
{path: "database.password", representation: "hash", want: false},
{path: "verification.code", representation: "hash", want: false},
{path: "verification.code", representation: "memory", want: true},
{path: "verification.email_fingerprint", representation: "hash", want: true},
{path: "ssl.private_key", representation: "reference", want: true},
}
for _, test := range tests {
if got := CanPersistRepresentation(test.path, test.representation); got != test.want {
t.Fatalf("CanPersistRepresentation(%q, %q) = %t, want %t", test.path, test.representation, got, test.want)
}
}
}
func TestRedactPublicValue(t *testing.T) {
value := map[string]any{
"database": map[string]any{
"password": map[string]any{"ciphertext": "enc-secret"},
"name": "smail",
},
"verification": map[string]any{
"code": "12345678",
"email_fingerprint": "fingerprint",
},
}
redacted, ok := RedactPublicValue(value).(map[string]any)
if !ok {
t.Fatalf("unexpected redacted value type: %T", RedactPublicValue(value))
}
database := redacted["database"].(map[string]any)
if database["password"] != RedactedValue || database["name"] != "smail" {
t.Fatalf("database public view was not redacted: %#v", database)
}
verification := redacted["verification"].(map[string]any)
if verification["code"] != RedactedValue || verification["email_fingerprint"] != RedactedValue {
t.Fatalf("verification public view was not redacted: %#v", verification)
}
}
+16 -5
View File
@@ -17,6 +17,7 @@ var (
) )
var logicalIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{1,63}$`) var logicalIDPattern = regexp.MustCompile(`^[a-z][a-z0-9_-]{1,63}$`)
var databaseLocalRefPattern = regexp.MustCompile(`^[A-Za-z0-9][A-Za-z0-9._-]{0,127}$`)
func ValidateRootConfig(root RootConfig) error { func ValidateRootConfig(root RootConfig) error {
if root.ConfigVersion > CurrentConfigVersion || root.SchemaVersion <= 0 || root.SchemaVersion > CurrentSchemaVersion || root.Generation == 0 || !root.SetupState.Valid() { if root.ConfigVersion > CurrentConfigVersion || root.SchemaVersion <= 0 || root.SchemaVersion > CurrentSchemaVersion || root.Generation == 0 || !root.SetupState.Valid() {
@@ -27,7 +28,7 @@ func ValidateRootConfig(root RootConfig) error {
return err return err
} }
} }
if err := validateDatabase(root.Database); err != nil { if err := ValidateDatabaseConfig(root.Database); err != nil {
return err return err
} }
if err := validateSMTP(root.SMTP); err != nil { if err := validateSMTP(root.SMTP); err != nil {
@@ -52,14 +53,24 @@ func ValidateRootConfig(root RootConfig) error {
return nil return nil
} }
func ValidateDatabaseConfig(database DatabaseConfig) error {
return validateDatabase(database)
}
func validateDatabase(database DatabaseConfig) error { func validateDatabase(database DatabaseConfig) error {
database = NormalizeDatabaseConfig(database)
switch database.Type { switch database.Type {
case DBTypeSQLite: case DatabaseTypeSQLite:
if database.SQLiteLocalRef == "" || filepath.IsAbs(database.SQLiteLocalRef) || strings.Contains(database.SQLiteLocalRef, "..") { if !databaseLocalRefPattern.MatchString(database.LocalRef) ||
filepath.IsAbs(database.LocalRef) ||
isWindowsAbsolute(database.LocalRef) ||
strings.ContainsAny(database.LocalRef, `/\\:`) ||
database.Host != "" || database.Port != 0 || database.Username != "" ||
database.Password.Configured() || database.Password.Ciphertext != "" || database.Password.Version != 0 || !database.Password.UpdatedAt.IsZero() || database.Name != "" {
return ErrInvalidDatabase return ErrInvalidDatabase
} }
case DBTypeMySQL, DBTypePostgres: case DatabaseTypeMySQL, DatabaseTypePostgreSQL:
if database.Host == "" || database.Username == "" || database.Name == "" || !database.Password.Configured() || !validPort(database.Port) { if database.Host == "" || database.Username == "" || database.Name == "" || !database.Password.Configured() || database.LocalRef != "" || !validPort(int(database.Port)) {
return ErrInvalidDatabase return ErrInvalidDatabase
} }
if err := ValidateStoredSecret(database.Password, true); err != nil { if err := ValidateStoredSecret(database.Password, true); err != nil {
+9 -4
View File
@@ -261,8 +261,8 @@ func ExportConfigAudit(ctx *appcontext.Context, w http.ResponseWriter, req *http
if !ok { if !ok {
return return
} }
if ctx.EffectiveRole() != access.RoleSuperAdmin || !ctx.RecentAuth { if err := authorizeCapability(ctx, access.CapabilityAuditExport, "", false); err != nil {
writeConfigAccessError(w, errors.New("audit export requires recent super administrator authentication")) writeConfigAccessError(w, err)
return return
} }
var input struct { var input struct {
@@ -365,7 +365,7 @@ func publicConfigSection(runtime config.RuntimeConfig, section config.Section) (
publicSecret := func(value config.StoredSecret) config.SecretStatus { return value.Status() } publicSecret := func(value config.StoredSecret) config.SecretStatus { return value.Status() }
switch section { switch section {
case config.SectionRoot: case config.SectionRoot:
return map[string]any{"configVersion": runtime.Root.ConfigVersion, "schemaVersion": runtime.Root.SchemaVersion, "generation": runtime.Root.Generation, "setupState": runtime.Root.SetupState, "logLevel": runtime.Root.LogLevel, "domains": runtime.Root.Domains, "http": runtime.Root.HTTP, "database": map[string]any{"type": runtime.Root.Database.Type, "host": runtime.Root.Database.Host, "port": runtime.Root.Database.Port, "username": runtime.Root.Database.Username, "name": runtime.Root.Database.Name, "sqliteLocalRef": runtime.Root.Database.SQLiteLocalRef, "password": publicSecret(runtime.Root.Database.Password)}, "security": runtime.Root.Security}, nil return map[string]any{"configVersion": runtime.Root.ConfigVersion, "schemaVersion": runtime.Root.SchemaVersion, "generation": runtime.Root.Generation, "setupState": runtime.Root.SetupState, "logLevel": runtime.Root.LogLevel, "domains": runtime.Root.Domains, "http": runtime.Root.HTTP, "database": map[string]any{"type": runtime.Root.Database.Type, "host": runtime.Root.Database.Host, "port": runtime.Root.Database.Port, "username": runtime.Root.Database.Username, "name": runtime.Root.Database.Name, "localRef": runtime.Root.Database.LocalRef, "password": publicSecret(runtime.Root.Database.Password)}, "security": runtime.Root.Security}, nil
case config.SectionSMTP: case config.SectionSMTP:
return map[string]any{"meta": runtime.SMTP.Meta, "relay": map[string]any{"relayHost": runtime.SMTP.Relay.RelayHost, "relayPort": runtime.SMTP.Relay.RelayPort, "username": runtime.SMTP.Relay.Username, "security": runtime.SMTP.Relay.Security, "fromDomain": runtime.SMTP.Relay.FromDomain, "verificationEnabled": runtime.SMTP.Relay.VerificationEnabled, "loginPolicy": runtime.SMTP.Relay.LoginPolicy, "password": publicSecret(runtime.SMTP.Relay.Password)}}, nil return map[string]any{"meta": runtime.SMTP.Meta, "relay": map[string]any{"relayHost": runtime.SMTP.Relay.RelayHost, "relayPort": runtime.SMTP.Relay.RelayPort, "username": runtime.SMTP.Relay.Username, "security": runtime.SMTP.Relay.Security, "fromDomain": runtime.SMTP.Relay.FromDomain, "verificationEnabled": runtime.SMTP.Relay.VerificationEnabled, "loginPolicy": runtime.SMTP.Relay.LoginPolicy, "password": publicSecret(runtime.SMTP.Relay.Password)}}, nil
case config.SectionEmail: case config.SectionEmail:
@@ -387,6 +387,11 @@ func writeConfigAccessError(w http.ResponseWriter, err error) { writeConfigError
func writeConfigError(w http.ResponseWriter, err error) { func writeConfigError(w http.ResponseWriter, err error) {
status := response.NoAccessPrivileges status := response.NoAccessPrivileges
message := "无权访问或请求不满足安全条件" message := "无权访问或请求不满足安全条件"
var data any = ""
var denial *access.Denial
if errors.As(err, &denial) {
data = map[string]string{"code": string(denial.Code)}
}
if errors.Is(err, config.ErrManagerStorage) { if errors.Is(err, config.ErrManagerStorage) {
status = response.ServerError status = response.ServerError
message = "配置服务不可用" message = "配置服务不可用"
@@ -395,5 +400,5 @@ func writeConfigError(w http.ResponseWriter, err error) {
status = response.ParamsError status = response.ParamsError
message = "配置已发生变化,请刷新后重试" message = "配置已发生变化,请刷新后重试"
} }
response.NewErrorResponse(status, message, "").FPrint(w) response.NewErrorResponse(status, message, data).FPrint(w)
} }
+42
View File
@@ -0,0 +1,42 @@
package controllers
import (
"encoding/json"
"net/http/httptest"
"strings"
"testing"
"git.pcux.cn/xuans/Smail/dto/response"
"git.pcux.cn/xuans/Smail/services/access"
)
func TestWriteConfigErrorKeepsStableAuthorizationCode(t *testing.T) {
recorder := httptest.NewRecorder()
writeConfigError(recorder, &access.Denial{Code: access.CodeRecoveryCodeRequired})
var payload struct {
ErrorNo int `json:"errorNo"`
Data map[string]any `json:"data"`
}
if err := json.Unmarshal(recorder.Body.Bytes(), &payload); err != nil {
t.Fatalf("failed to decode authorization error response: %v", err)
}
if payload.ErrorNo != response.NoAccessPrivileges {
t.Fatalf("unexpected authorization error number: %d", payload.ErrorNo)
}
if payload.Data["code"] != string(access.CodeRecoveryCodeRequired) {
t.Fatalf("stable authorization code was not exposed: %#v", payload.Data)
}
}
func TestWriteConfigErrorDoesNotExposeInternalErrorText(t *testing.T) {
recorder := httptest.NewRecorder()
writeConfigError(recorder, &access.Denial{Code: access.CodeRecentAuthRequired})
body := strings.ToLower(recorder.Body.String())
for _, forbidden := range []string{"password", "secret", "token", "nonce", "ticket", "challenge"} {
if strings.Contains(body, forbidden) {
t.Fatalf("authorization response contains sensitive response text: %s", body)
}
}
}
+24
View File
@@ -80,3 +80,27 @@ func TestCustomMigrationChecksumIncludesSeed(t *testing.T) {
t.Fatal("custom migration checksum ignored its seed") t.Fatal("custom migration checksum ignored its seed")
} }
} }
func TestDefaultMigrationsAreContiguousAndDialectComplete(t *testing.T) {
migrations := DefaultMigrations()
if len(migrations) == 0 {
t.Fatal("default migrations are empty")
}
for index, item := range migrations {
wantVersion := int64(index + 1)
if item.Version != wantVersion {
t.Fatalf("migration %d has version %d, want %d", index, item.Version, wantVersion)
}
if item.Name == "" {
t.Fatalf("migration %d has an empty name", item.Version)
}
for _, dialect := range []Dialect{DialectSQLite, DialectMySQL, DialectPostgres} {
if item.Apply == nil && len(item.StatementsFor(dialect)) == 0 {
t.Fatalf("migration %d (%s) has no statements for %s", item.Version, item.Name, dialect)
}
}
}
if _, err := normalize(migrations); err != nil {
t.Fatalf("default migrations failed normalization: %v", err)
}
}
@@ -0,0 +1,31 @@
package http_server
import (
"net/http"
"net/http/httptest"
"testing"
appcontext "git.pcux.cn/xuans/Smail/utils/context"
)
func TestConfigRouteAcceptsConfigurationUpdateMethod(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPut, "/api/v1/config/email", nil)
configRoute(&appcontext.Context{}, recorder, request)
if recorder.Code == http.StatusMethodNotAllowed {
t.Fatal("configuration update route rejected the documented PUT method")
}
}
func TestConfigRouteRejectsUnsupportedMethod(t *testing.T) {
recorder := httptest.NewRecorder()
request := httptest.NewRequest(http.MethodPatch, "/api/v1/config/email", nil)
configRoute(&appcontext.Context{}, recorder, request)
if recorder.Code != http.StatusMethodNotAllowed {
t.Fatalf("unsupported configuration method returned status %d", recorder.Code)
}
}
+7 -3
View File
@@ -169,10 +169,14 @@ func configRoute(ctx *context.Context, w http.ResponseWriter, r *http.Request) {
} }
controllers.ApplyConfig(ctx, w, r) controllers.ApplyConfig(ctx, w, r)
case configSectionRoute(path, ""): case configSectionRoute(path, ""):
if !allowRouteMethod(w, r, http.MethodGet) { switch r.Method {
return case http.MethodGet:
controllers.GetConfigSection(ctx, w, r)
case http.MethodPut:
controllers.UpdateConfig(ctx, w, r)
default:
allowRouteMethod(w, r, http.MethodGet, http.MethodPut)
} }
controllers.GetConfigSection(ctx, w, r)
default: default:
http.NotFound(w, r) http.NotFound(w, r)
} }
+22 -6
View File
@@ -57,12 +57,12 @@ func TestRecoveryAndRecentAuthentication(t *testing.T) {
t.Fatalf("expected recent authentication requirement, got %v", err) t.Fatalf("expected recent authentication requirement, got %v", err)
} }
superAdmin := Request{ActorRole: RoleSuperAdmin, Capability: CapabilityConfigRollback, RecentAuth: true} superAdmin := Request{ActorRole: RoleSuperAdmin, Capability: CapabilityConfigRollback, RecentAuth: true}
if err := Authorize(superAdmin); !IsDenied(err, CodeRecoveryCodeRequired) {
t.Fatalf("super admin without recovery code must be denied: %v", err)
}
superAdmin.RecoveryCodeConfigured = true
if err := Authorize(superAdmin); err != nil { if err := Authorize(superAdmin); err != nil {
t.Fatalf("super admin with recovery code should be allowed: %v", err) t.Fatalf("super admin should be exempt from recovery code precondition: %v", err)
}
adminRollback := Request{ActorRole: RoleAdmin, Capability: CapabilityConfigRollback, RecentAuth: true}
if err := Authorize(adminRollback); !IsDenied(err, CodeAccessDenied) {
t.Fatalf("admin must not receive a recovery-code bypass for a super-admin capability: %v", err)
} }
} }
@@ -90,7 +90,7 @@ func TestAdminPluginRestartScope(t *testing.T) {
func TestManagementEndpointCatalog(t *testing.T) { func TestManagementEndpointCatalog(t *testing.T) {
endpoints := ManagementEndpoints() endpoints := ManagementEndpoints()
if len(endpoints) != 7 { if len(endpoints) != 18 {
t.Fatalf("unexpected endpoint count: %d", len(endpoints)) t.Fatalf("unexpected endpoint count: %d", len(endpoints))
} }
seen := map[string]struct{}{} seen := map[string]struct{}{}
@@ -108,6 +108,22 @@ func TestManagementEndpointCatalog(t *testing.T) {
if !ok || endpoint.Capability != CapabilityPluginWriteOwn { if !ok || endpoint.Capability != CapabilityPluginWriteOwn {
t.Fatal("plugin settings endpoint was not matched") t.Fatal("plugin settings endpoint was not matched")
} }
endpoint, ok = LookupEndpoint("POST", "/api/v1/config/smtp/validate")
if !ok || endpoint.Capability != CapabilityConfigWriteGlobal {
t.Fatal("configuration validation endpoint was not matched")
}
endpoint, ok = LookupEndpoint("GET", "/api/v1/config/email")
if !ok || endpoint.Capability != CapabilityConfigRead {
t.Fatal("configuration section endpoint was not matched")
}
endpoint, ok = LookupEndpoint("PUT", "/api/v1/config/email")
if !ok || endpoint.Capability != CapabilityConfigWriteGlobal {
t.Fatal("configuration update endpoint was not matched")
}
endpoint, ok = LookupEndpoint("GET", "/api/v1/config/backups")
if !ok || endpoint.Capability != CapabilityConfigRollback {
t.Fatal("configuration backup endpoint did not require rollback capability")
}
} }
func TestEveryManagementEndpointHasAllowAndDeny(t *testing.T) { func TestEveryManagementEndpointHasAllowAndDeny(t *testing.T) {
+1 -1
View File
@@ -55,7 +55,7 @@ func Authorize(request Request) error {
if policy.RequiresRecentAuth && !request.RecentAuth { if policy.RequiresRecentAuth && !request.RecentAuth {
return deny(CodeRecentAuthRequired) return deny(CodeRecentAuthRequired)
} }
if policy.RequiresRecoveryCode && !request.RecoveryCodeConfigured && !request.DeploymentChannel { if policy.RequiresRecoveryCode && request.ActorRole != RoleSuperAdmin && !request.RecoveryCodeConfigured && !request.DeploymentChannel {
return deny(CodeRecoveryCodeRequired) return deny(CodeRecoveryCodeRequired)
} }
return authorizeResource(request) return authorizeResource(request)
+3 -1
View File
@@ -20,6 +20,7 @@ const (
CapabilityPasswordChangeOwn Capability = "password.change_own" CapabilityPasswordChangeOwn Capability = "password.change_own"
CapabilityPasswordReset Capability = "password.reset" CapabilityPasswordReset Capability = "password.reset"
CapabilityAuditRead Capability = "audit.read" CapabilityAuditRead Capability = "audit.read"
CapabilityAuditExport Capability = "audit.export"
) )
type Policy struct { type Policy struct {
@@ -48,6 +49,7 @@ var policies = map[Capability]Policy{
CapabilityPasswordChangeOwn: {Capability: CapabilityPasswordChangeOwn}, CapabilityPasswordChangeOwn: {Capability: CapabilityPasswordChangeOwn},
CapabilityPasswordReset: {Capability: CapabilityPasswordReset, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true}, CapabilityPasswordReset: {Capability: CapabilityPasswordReset, HighRisk: true, RequiresRecentAuth: true, RequiresRecoveryCode: true, RequiresTarget: true},
CapabilityAuditRead: {Capability: CapabilityAuditRead}, CapabilityAuditRead: {Capability: CapabilityAuditRead},
CapabilityAuditExport: {Capability: CapabilityAuditExport, HighRisk: true, RequiresRecentAuth: true},
} }
var grants = map[Role]map[Capability]struct{}{ var grants = map[Role]map[Capability]struct{}{
@@ -57,7 +59,7 @@ var grants = map[Role]map[Capability]struct{}{
CapabilityPluginRestart, CapabilityServiceRestart, CapabilityPluginWriteGlobal, CapabilityPluginWriteAnyUser, CapabilityPluginRestart, CapabilityServiceRestart, CapabilityPluginWriteGlobal, CapabilityPluginWriteAnyUser,
CapabilityPluginWriteOwn, CapabilityUserRead, CapabilityUserManage, CapabilityPluginWriteOwn, CapabilityUserRead, CapabilityUserManage,
CapabilityRoleManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset, CapabilityRoleManage, CapabilityPasswordChangeOwn, CapabilityPasswordReset,
CapabilityAuditRead, CapabilityAuditRead, CapabilityAuditExport,
), ),
RoleAdmin: grant( RoleAdmin: grant(
CapabilityConfigRead, CapabilityPluginRead, CapabilityPluginRestart, CapabilityConfigRead, CapabilityPluginRead, CapabilityPluginRestart,
+38 -4
View File
@@ -16,6 +16,17 @@ var managementEndpoints = []Endpoint{
{Method: "POST", Path: "/api/user/list", Capability: CapabilityUserRead}, {Method: "POST", Path: "/api/user/list", Capability: CapabilityUserRead},
{Method: "GET", Path: "/api/plugin/list", Capability: CapabilityPluginRead}, {Method: "GET", Path: "/api/plugin/list", Capability: CapabilityPluginRead},
{Method: "*", Path: "/api/plugin/settings/", Capability: CapabilityPluginWriteOwn}, {Method: "*", Path: "/api/plugin/settings/", Capability: CapabilityPluginWriteOwn},
{Method: "GET", Path: "/api/v1/config/status", Capability: CapabilityConfigRead},
{Method: "GET", Path: "/api/v1/config/backups", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/rollback/preview", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/rollback/ticket", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/rollback", Capability: CapabilityConfigRollback},
{Method: "POST", Path: "/api/v1/config/:section/validate", Capability: CapabilityConfigWriteGlobal},
{Method: "POST", Path: "/api/v1/config/:section/apply", Capability: CapabilityConfigWriteGlobal},
{Method: "GET", Path: "/api/v1/config/:section", Capability: CapabilityConfigRead},
{Method: "PUT", Path: "/api/v1/config/:section", Capability: CapabilityConfigWriteGlobal},
{Method: "GET", Path: "/api/v1/audits/config", Capability: CapabilityAuditRead},
{Method: "POST", Path: "/api/v1/audits/config", Capability: CapabilityAuditExport},
} }
func ManagementEndpoints() []Endpoint { func ManagementEndpoints() []Endpoint {
@@ -28,13 +39,36 @@ func LookupEndpoint(method string, path string) (Endpoint, bool) {
method = strings.ToUpper(strings.TrimSpace(method)) method = strings.ToUpper(strings.TrimSpace(method))
for _, endpoint := range managementEndpoints { for _, endpoint := range managementEndpoints {
methodMatches := endpoint.Method == "*" || endpoint.Method == method methodMatches := endpoint.Method == "*" || endpoint.Method == method
pathMatches := endpoint.Path == path pathMatches := matchEndpointPath(endpoint.Path, path)
if strings.HasSuffix(endpoint.Path, "/") {
pathMatches = strings.HasPrefix(path, endpoint.Path)
}
if methodMatches && pathMatches { if methodMatches && pathMatches {
return endpoint, true return endpoint, true
} }
} }
return Endpoint{}, false return Endpoint{}, false
} }
func matchEndpointPath(pattern, path string) bool {
if pattern == path {
return true
}
if strings.HasSuffix(pattern, "/") {
return strings.HasPrefix(path, pattern)
}
patternParts := strings.Split(strings.Trim(pattern, "/"), "/")
pathParts := strings.Split(strings.Trim(path, "/"), "/")
if len(patternParts) != len(pathParts) {
return false
}
for index := range patternParts {
if strings.HasPrefix(patternParts[index], ":") && patternParts[index] != ":" {
if pathParts[index] == "" {
return false
}
continue
}
if patternParts[index] != pathParts[index] {
return false
}
}
return true
}
+1
View File
@@ -12,6 +12,7 @@ func TestCapabilityMatrix(t *testing.T) {
{name: "admin reads config", req: Request{ActorRole: RoleAdmin, Capability: CapabilityConfigRead}, allowed: true}, {name: "admin reads config", req: Request{ActorRole: RoleAdmin, Capability: CapabilityConfigRead}, allowed: true},
{name: "user cannot read config", req: Request{ActorRole: RoleUser, Capability: CapabilityConfigRead}}, {name: "user cannot read config", req: Request{ActorRole: RoleUser, Capability: CapabilityConfigRead}},
{name: "super admin controls plugin", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginControl, RecentAuth: true, RecoveryCodeConfigured: true}, allowed: true}, {name: "super admin controls plugin", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginControl, RecentAuth: true, RecoveryCodeConfigured: true}, allowed: true},
{name: "super admin controls plugin without recovery code", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginControl, RecentAuth: true}, allowed: true},
{name: "admin cannot control plugin", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPluginControl, RecentAuth: true, RecoveryCodeConfigured: true}}, {name: "admin cannot control plugin", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPluginControl, RecentAuth: true, RecoveryCodeConfigured: true}},
{name: "super admin writes global plugin settings", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginWriteGlobal, RecentAuth: true, RecoveryCodeConfigured: true}, allowed: true}, {name: "super admin writes global plugin settings", req: Request{ActorRole: RoleSuperAdmin, Capability: CapabilityPluginWriteGlobal, RecentAuth: true, RecoveryCodeConfigured: true}, allowed: true},
{name: "admin cannot write global plugin settings", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPluginWriteGlobal, RecentAuth: true, RecoveryCodeConfigured: true}}, {name: "admin cannot write global plugin settings", req: Request{ActorRole: RoleAdmin, Capability: CapabilityPluginWriteGlobal, RecentAuth: true, RecoveryCodeConfigured: true}},