数据:收窄账号所有权与单值凭证读取

This commit is contained in:
Christ committed 2026-08-14 11:27:51 +08:00
1 parent aa3003ceda
commit b32f0a1173
13 files changed
+165 -56

No files matched your search

+7 -5
View File
@@ -91,7 +91,7 @@ app shell / routes
| --- | --- | --- | --- |
| 0. 治理文档与强约束 | 已完成 | 总计划、依赖规则、注释规范、AGENTS 门禁、注释检查器 | 文档、门禁规则、Go/TypeScript 检查器和历史基线已落盘 |
| 1. PR CI 与测试基础 | 已完成 | 独立 CI、测试 DB 模板、可执行 race | CI、独立模板、server smoke race 和完整 race 均有验证 |
| 2. 敏感数据访问边界 | 进行中 | 摘要、凭证、登录秘密分离 | `CookieSummary`、`ListOwnedIDs`、`ExistsOwned` 及 SQLite 回归测试已建立 |
| 2. 敏感数据访问边界 | 进行中 | 摘要、凭证、登录秘密分离 | `CookieSummary`、所有权窄查询、单值凭证读取及 SQLite 回归测试已建立 |
| 3. HTTP API 契约 | 未开始 | 统一错误、具名 DTO、版本化路径 | 契约测试与前端类型 |
| 4. Server 应用服务 | 未开始 | 订单、发布、登录、聊天纵向抽取 | handler 不再直接编排基础设施 |
| 5. 应用生命周期装配 | 未开始 | 消除必需依赖 setter 回填 | 构造验证与幂等关闭测试 |
@@ -107,8 +107,9 @@ app shell / routes
- 已完成:总计划、依赖规则、中文注释规范、`AGENTS.md` 强约束,以及 Go/TypeScript AST 注释检查器和历史基线;
- 阶段 1 已完成:server 测试模板预置管理员和账号 cookie,普通测试约 21.3 秒,完整 server race 约 194.3 秒通过;
- 已完成阶段 2 第一个切片:建立不读取或解密敏感字段的 `CookieSummary`、`ListOwnedIDs`、`ExistsOwned`,并覆盖跨用户和无效 user ID 回归测试;
- 下一最小工作项:把 `internal/server/ownership_helpers.go` 的账号所有权检查迁移到 `ExistsOwned`,确保不再通过 `AllForUser` 读取或解密全部 Cookie;
- 随后工作项:将账号列表和非敏感详情接口迁移到 `ListSummaries`,再处理需要凭证的业务流程;
- 已完成阶段 2 第二个切片:新增 `GetOwnerID`、原子 `GetValueOwned`,将 server 的账号所有权检查和订单凭证读取迁移到窄查询,纯所有权 handler 不再解密完整账号详情,并保留 404/403 行为回归;
- 下一最小工作项:将账号列表和非敏感详情接口迁移到 `ListSummaries`,消除列表接口的批量凭证读取和详情 N+1 敏感查询;
- 随后工作项:再处理明确需要平台凭证的业务流程,统一使用按用户和账号 ID 过滤的单值凭证接口;
- 禁止跳过当前入口直接开始 Engine、Automation 或 DB 的大规模拆分。
## 6. 阶段 0:治理文档与强约束
@@ -199,8 +200,9 @@ app shell / routes
当前实现先落地了 Cookie 领域的窄查询:`CookieSummary` 不包含 `Value`、`Password` 或 `MetadataJSON`;
`ListOwnedIDs` 只返回账号 ID;`ExistsOwned` 只返回布尔存在性,并拒绝 `userID=0` 的隐式管理员查询。
测试使用故意无效的密文值验证摘要查询不会触发解密。旧 `AllForUser` 和 `GetDetails` 调用方暂不批量替换,
每次迁移一个消费方并保留行为回归测试。
`GetOwnerID` 只返回所有者 ID;`GetValueOwned` 在同一条带 user_id 过滤的查询中读取并解密单个 Cookie,避免
所有权检查与凭证读取之间的竞态窗口。测试使用故意无效的密文值验证摘要查询和所有权检查不会触发解密,
并使用正常加密值覆盖单值凭证读取。旧 `AllForUser` 和 `GetDetails` 调用方暂不批量替换,每次迁移一个消费方并保留行为回归测试。
逐步替换使用 `AllForUser` 进行所有权检查以及使用 `GetDetails` 获取非敏感字段的调用。
+33
View File
@@ -127,6 +127,39 @@ func (c *Cookies) ExistsOwned(ctx context.Context, userID int64, cookieID string
return exists, queryErr
}
// GetOwnerID 返回指定账号的所有者 ID,不读取或解密账号凭证。
func (c *Cookies) GetOwnerID(ctx context.Context, cookieID string) (int64, error) {
// ownerID 保存数据库中指定账号的所有者 ID。
var ownerID int64
// queryErr 表示按账号 ID 查询所有者失败的原因。
if queryErr := c.DB.QueryRowContext(ctx, `SELECT user_id FROM cookies WHERE id=?`, cookieID).Scan(&ownerID); queryErr != nil {
if errors.Is(queryErr, sql.ErrNoRows) {
return 0, ErrNotFound
}
return 0, queryErr
}
return ownerID, nil
}
// GetValueOwned 原子查询并解密指定用户拥有的单个账号 Cookie,避免先查所有权再读取凭证的竞态窗口。
func (c *Cookies) GetValueOwned(ctx context.Context, userID int64, cookieID string) (string, error) {
// ownerErr 表示用户 ID 未通过正数所有权校验的原因。
if ownerErr := validateCookieOwnerID(userID); ownerErr != nil {
return "", ownerErr
}
// encryptedValue 保存经过所有权过滤后读取到的单个 Cookie 密文。
var encryptedValue string
// queryErr 表示按账号和用户联合条件读取 Cookie 失败的原因。
if queryErr := c.DB.QueryRowContext(ctx,
`SELECT value FROM cookies WHERE id=? AND user_id=?`, cookieID, userID).Scan(&encryptedValue); queryErr != nil {
if errors.Is(queryErr, sql.ErrNoRows) {
return "", ErrNotFound
}
return "", queryErr
}
return c.codec.decrypt("cookie", cookieID, encryptedValue)
}
// validateCookieOwnerID 拒绝使用 0 代表管理员的隐式所有权查询。
func validateCookieOwnerID(userID int64) error {
if userID <= 0 {
+29
View File
@@ -2,6 +2,7 @@ package db
import (
"context"
"errors"
"testing"
)
@@ -66,6 +67,30 @@ func TestCookieScopedQueriesExcludeSecrets(t *testing.T) {
if otherErr != nil || otherOwned {
t.Fatalf("ExistsOwned cross-owner: owned=%v err=%v", otherOwned, otherErr)
}
// ownerOfCookie 是不读取凭证字段即可确认账号归属的结果。
ownerOfCookie, ownerLookupErr := store.Cookies.GetOwnerID(ctx, "scope-owned")
if ownerLookupErr != nil || ownerOfCookie != ownerID {
t.Fatalf("GetOwnerID: owner=%d err=%v", ownerOfCookie, ownerLookupErr)
}
// readableCookieID 是通过正常加密流程创建的账号,用于验证单值凭证读取。
const readableCookieID = "scope-readable"
// saveErr 表示创建可解密测试账号失败的原因。
if saveErr := store.Cookies.Save(ctx, readableCookieID, "readable-cookie", ownerID); saveErr != nil {
t.Fatalf("创建可读 cookie: %v", saveErr)
}
// readableValue 是 owner 读取自己账号时得到的 Cookie 明文。
readableValue, readableErr := store.Cookies.GetValueOwned(ctx, ownerID, readableCookieID)
if readableErr != nil || readableValue != "readable-cookie" {
t.Fatalf("GetValueOwned owner: value=%q err=%v", readableValue, readableErr)
}
// wrongOwnerErr 表示其他用户不能读取该账号的 Cookie 密文。
if _, wrongOwnerErr := store.Cookies.GetValueOwned(ctx, otherID, readableCookieID); !errors.Is(wrongOwnerErr, ErrNotFound) {
t.Fatalf("GetValueOwned cross-owner 应 ErrNotFound, err=%v", wrongOwnerErr)
}
// missingOwnerErr 表示不存在账号的所有者查询应返回统一的未找到错误。
if _, missingOwnerErr := store.Cookies.GetOwnerID(ctx, "scope-missing"); !errors.Is(missingOwnerErr, ErrNotFound) {
t.Fatalf("GetOwnerID missing 应 ErrNotFound, err=%v", missingOwnerErr)
}
// invalidListErr 表示 userID=0 被所有权列表查询拒绝的错误。
if _, invalidListErr := store.Cookies.ListOwnedIDs(ctx, 0); invalidListErr != ErrInvalidUserID {
t.Fatalf("userID=0 应拒绝隐式管理员查询,err=%v", invalidListErr)
@@ -74,4 +99,8 @@ func TestCookieScopedQueriesExcludeSecrets(t *testing.T) {
if _, invalidExistsErr := store.Cookies.ExistsOwned(ctx, 0, "scope-owned"); invalidExistsErr != ErrInvalidUserID {
t.Fatalf("ExistsOwned userID=0 应拒绝,err=%v", invalidExistsErr)
}
// invalidValueErr 表示 userID=0 被单值凭证查询拒绝的错误。
if _, invalidValueErr := store.Cookies.GetValueOwned(ctx, 0, "scope-owned"); invalidValueErr != ErrInvalidUserID {
t.Fatalf("GetValueOwned userID=0 应拒绝,err=%v", invalidValueErr)
}
}
+1 -1
View File
@@ -129,7 +129,7 @@ func (s *Server) listAutomationRules(w http.ResponseWriter, r *http.Request) {
}
cookieID := strings.TrimSpace(query.Get("cookie_id"))
if cookieID != "" {
if _, ok := s.cookieForUser(r, sess.UserID, cookieID); !ok {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
+4 -4
View File
@@ -693,7 +693,7 @@ func (s *Server) deleteCookie(w http.ResponseWriter, r *http.Request) {
// setCookieAutoConfirm 设置自动确认发货。
func (s *Server) setCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -728,7 +728,7 @@ func (s *Server) getCookieAutoConfirm(w http.ResponseWriter, r *http.Request) {
// setCookieRemark 设置备注。
func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -749,7 +749,7 @@ func (s *Server) setCookieRemark(w http.ResponseWriter, r *http.Request) {
// setCookiePauseDuration 设置暂停时长。
func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -776,7 +776,7 @@ func (s *Server) setCookiePauseDuration(w http.ResponseWriter, r *http.Request)
// getCookiePauseDuration 获取暂停时长。
func (s *Server) getCookiePauseDuration(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
paused, pausedUntil, _ := s.Store.Cookies.IsPaused(r.Context(), cid)
+4 -4
View File
@@ -40,7 +40,7 @@ func (s *Server) mountDefaultRepliesReal(r chi.Router) {
func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
dr, err := s.Store.DefaultReps.Get(r.Context(), cid)
@@ -56,7 +56,7 @@ func (s *Server) getDefaultReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) setDefaultReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -153,7 +153,7 @@ func (s *Server) listDefaultRepliesMap(w http.ResponseWriter, r *http.Request) {
func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
_, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_replies WHERE cookie_id=?`, cid)
@@ -166,7 +166,7 @@ func (s *Server) deleteDefaultReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) clearDefaultReplyRecords(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
if _, err := s.Store.DB.ExecContext(r.Context(), `DELETE FROM default_reply_records WHERE cookie_id=?`, cid); err != nil {
+7 -7
View File
@@ -632,7 +632,7 @@ func (s *Server) enrichSyncedItemMultiSpec(ctx context.Context, client mtop.Clie
func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
items, err := s.Store.Items.AllForCookie(r.Context(), cid)
@@ -649,7 +649,7 @@ func (s *Server) listItemsByCookie(w http.ResponseWriter, r *http.Request) {
func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
@@ -668,7 +668,7 @@ func (s *Server) getItem(w http.ResponseWriter, r *http.Request) {
func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -702,7 +702,7 @@ func (s *Server) createItem(w http.ResponseWriter, r *http.Request) {
func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
@@ -773,7 +773,7 @@ func (s *Server) updateItem(w http.ResponseWriter, r *http.Request) {
func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
@@ -786,7 +786,7 @@ func (s *Server) deleteItem(w http.ResponseWriter, r *http.Request) {
func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
@@ -806,7 +806,7 @@ func (s *Server) setItemMultiSpec(w http.ResponseWriter, r *http.Request) {
func (s *Server) setItemMultiQuantity(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
+22 -9
View File
@@ -1400,44 +1400,53 @@ func (s *Server) cleanupExpiredPublishUploads(ctx context.Context) {
}
}
// cookieOwnedByUser 判断指定账号是否属于用户,不读取或解密 Cookie 明文。
func (s *Server) cookieOwnedByUser(ctx context.Context, userID int64, cookieID string) bool {
all, err := s.Store.Cookies.AllForUser(ctx, userID)
if err != nil {
return false
}
_, ok := all[cookieID]
return ok
// owned 表示数据库中是否存在匹配用户和账号 ID 的记录。
owned, err := s.Store.Cookies.ExistsOwned(ctx, userID, cookieID)
return err == nil && owned
}
// cookieValueForUser 读取指定用户拥有的单个账号 Cookie 明文。
func (s *Server) cookieValueForUser(ctx context.Context, userID int64, cookieID string) (string, error) {
all, err := s.Store.Cookies.AllForUser(ctx, userID)
// value 是按 user_id 与账号 ID 联合过滤后解密的单个 Cookie 明文。
value, err := s.Store.Cookies.GetValueOwned(ctx, userID, cookieID)
if err != nil {
if errors.Is(err, db.ErrNotFound) {
return "", errors.New("账号不存在或 Cookie 为空")
}
return "", err
}
value, ok := all[cookieID]
if !ok || strings.TrimSpace(value) == "" {
if strings.TrimSpace(value) == "" {
return "", errors.New("账号不存在或 Cookie 为空")
}
return value, nil
}
// cardOwnedByUser 判断指定卡券组是否属于用户。
func (s *Server) cardOwnedByUser(ctx context.Context, userID int64, cardID int64) bool {
// exists 表示数据库中是否存在匹配用户和卡券组 ID 的记录。
var exists bool
// err 表示卡券组所有权查询失败的原因。
err := s.Store.DB.QueryRowContext(ctx, `SELECT EXISTS(SELECT 1 FROM cards WHERE id=? AND user_id=?)`, cardID, userID).Scan(&exists)
return err == nil && exists
}
// publishUploadRoot 返回发布图片上传文件的根目录。
func (s *Server) publishUploadRoot() string {
return defaultPublishUploadRoot()
}
// defaultPublishUploadRoot 返回环境变量指定或默认的发布上传目录。
func defaultPublishUploadRoot() string {
// v 是去除首尾空白后的上传目录环境变量值。
if v := strings.TrimSpace(os.Getenv("XIANYU_UPLOAD_DIR")); v != "" {
return v
}
return filepath.Join("data", "uploads")
}
// parseLooseBool 将常见的真值文本转换为布尔值。
func parseLooseBool(raw string) bool {
raw = strings.ToLower(strings.TrimSpace(raw))
switch raw {
@@ -1448,18 +1457,22 @@ func parseLooseBool(raw string) bool {
}
}
// atoiPublishDefault 将数字文本转换为整数,无法解析时返回给定默认值。
func atoiPublishDefault(raw string, def int) int {
raw = strings.TrimSpace(raw)
if raw == "" {
return def
}
// f 和 err 分别表示解析出的浮点数及其错误。
if f, err := strconv.ParseFloat(raw, 64); err == nil {
return int(f)
}
return def
}
// firstNonEmpty 返回参数中第一个非空白字符串。
func firstNonEmpty(values ...string) string {
// v 是当前遍历到的候选字符串。
for _, v := range values {
if strings.TrimSpace(v) != "" {
return v
+11 -11
View File
@@ -26,7 +26,7 @@ func (s *Server) mountKeywordsReal(r chi.Router) {
func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
@@ -43,7 +43,7 @@ func (s *Server) listKeywords(w http.ResponseWriter, r *http.Request) {
func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
@@ -60,7 +60,7 @@ func (s *Server) listKeywordsWithItemID(w http.ResponseWriter, r *http.Request)
func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
rows, err := s.Store.Keywords.AllRows(r.Context(), cid)
@@ -80,7 +80,7 @@ func (s *Server) listKeywordsWithType(w http.ResponseWriter, r *http.Request) {
func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -104,7 +104,7 @@ func (s *Server) addKeyword(w http.ResponseWriter, r *http.Request) {
func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
@@ -204,7 +204,7 @@ func (s *Server) addKeywordWithItemID(w http.ResponseWriter, r *http.Request) {
func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
@@ -261,7 +261,7 @@ func (s *Server) updateKeywordByID(w http.ResponseWriter, r *http.Request) {
func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
id, err := strconv.ParseInt(chi.URLParam(r, "id"), 10, 64)
@@ -278,7 +278,7 @@ func (s *Server) deleteKeywordByID(w http.ResponseWriter, r *http.Request) {
func (s *Server) deleteKeyword(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
index := atoiDefault(chi.URLParam(r, "index"), -1)
@@ -314,7 +314,7 @@ func (s *Server) listItemReplies(w http.ResponseWriter, r *http.Request) {
func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
@@ -330,7 +330,7 @@ func (s *Server) getItemReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
@@ -350,7 +350,7 @@ func (s *Server) setItemReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) deleteItemReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
itemID := chi.URLParam(r, "item_id")
+2 -2
View File
@@ -158,7 +158,7 @@ func (s *Server) testChannel(w http.ResponseWriter, r *http.Request) {
func (s *Server) getAccountBindings(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
ids, err := s.Store.Notifications.AccountBindings(r.Context(), cid)
@@ -208,7 +208,7 @@ func (s *Server) listMessageNotifications(w http.ResponseWriter, r *http.Request
func (s *Server) setAccountBindings(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cid")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
var req struct {
+1 -1
View File
@@ -56,7 +56,7 @@ func (s *Server) listOrders(w http.ResponseWriter, r *http.Request) {
pageSize = 20
}
if cookieID != "" {
if _, ok := s.cookieForUser(r, sess.UserID, cookieID); !ok {
if !s.cookieOwnedByUser(r.Context(), sess.UserID, cookieID) {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return
}
+42 -10
View File
@@ -25,12 +25,45 @@ func (s *Server) requireCookieOwner(w http.ResponseWriter, r *http.Request, cook
return d, true
}
// requireCookieOwnership 校验当前会话是否拥有账号,只读取账号所有权元数据,不解密凭证。
func (s *Server) requireCookieOwnership(w http.ResponseWriter, r *http.Request, cookieID string) bool {
// sess 是当前请求经过认证中间件注入的会话。
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
// owned 表示当前用户是否直接拥有该账号。
owned, ownedErr := s.Store.Cookies.ExistsOwned(r.Context(), sess.UserID, cookieID)
if ownedErr != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
return false
}
if owned {
return true
}
// ownerID 用于区分账号不存在和账号属于其他用户,保持原有 404/403 响应语义。
ownerID, ownerErr := s.Store.Cookies.GetOwnerID(r.Context(), cookieID)
if ownerErr != nil {
writeErr(w, http.StatusNotFound, "账号不存在")
return false
}
if ownerID != sess.UserID {
writeErr(w, http.StatusForbidden, "无权限操作该账号")
return false
}
return true
}
// requireOrderOwner 校验当前会话是否拥有订单关联的账号。
func (s *Server) requireOrderOwner(w http.ResponseWriter, r *http.Request, orderID string) (*db.Order, bool) {
// sess 是当前请求经过认证中间件注入的会话。
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return nil, false
}
// order 和 err 分别表示订单记录及其查询错误。
order, err := s.Store.Orders.Get(r.Context(), orderID)
if err != nil || order == nil {
writeErr(w, http.StatusNotFound, "订单不存在")
@@ -40,19 +73,23 @@ func (s *Server) requireOrderOwner(w http.ResponseWriter, r *http.Request, order
writeErr(w, http.StatusForbidden, "订单未绑定账号,无法操作")
return nil, false
}
if _, ok := s.cookieForUser(r, sess.UserID, order.CookieID); !ok {
// owned 表示当前会话是否拥有订单绑定的账号。
if !s.cookieOwnedByUser(r.Context(), sess.UserID, order.CookieID) {
writeErr(w, http.StatusForbidden, "无权操作此订单")
return nil, false
}
return order, true
}
// requireCardOwner 校验当前会话是否拥有卡券组。
func (s *Server) requireCardOwner(w http.ResponseWriter, r *http.Request, cardID int64) (*db.CardFull, bool) {
// sess 是当前请求经过认证中间件注入的会话。
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return nil, false
}
// card 和 err 分别表示卡券组记录及其查询错误。
card, err := s.Store.Cards.Get(r.Context(), cardID)
if err != nil {
writeErr(w, http.StatusNotFound, "卡券不存在")
@@ -65,13 +102,17 @@ func (s *Server) requireCardOwner(w http.ResponseWriter, r *http.Request, cardID
return card, true
}
// requireChannelOwner 校验当前会话是否拥有通知渠道。
func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, channelID int64) bool {
// sess 是当前请求经过认证中间件注入的会话。
sess := auth.SessionFromContext(r.Context())
if sess == nil {
writeErr(w, http.StatusUnauthorized, "未授权访问")
return false
}
// exists 表示通知渠道是否由当前用户拥有。
var exists bool
// err 表示通知渠道所有权查询失败的原因。
err := s.Store.DB.QueryRowContext(r.Context(),
`SELECT EXISTS(SELECT 1 FROM notification_channels WHERE id=? AND user_id=?)`,
channelID, sess.UserID).Scan(&exists)
@@ -81,12 +122,3 @@ func (s *Server) requireChannelOwner(w http.ResponseWriter, r *http.Request, cha
}
return true
}
func (s *Server) cookieForUser(r *http.Request, userID int64, cookieID string) (string, bool) {
all, err := s.Store.Cookies.AllForUser(r.Context(), userID)
if err != nil {
return "", false
}
value, ok := all[cookieID]
return value, ok
}
+2 -2
View File
@@ -155,7 +155,7 @@ func (s *Server) listAIReply(w http.ResponseWriter, r *http.Request) {
func (s *Server) getAIReply(w http.ResponseWriter, r *http.Request) {
cid := chi.URLParam(r, "cookie_id")
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
cfg, err := s.Store.AIReply.Get(r.Context(), cid)
@@ -196,7 +196,7 @@ func (s *Server) setAIReply(w http.ResponseWriter, r *http.Request) {
writeErr(w, http.StatusBadRequest, "请求格式错误")
return
}
if _, ok := s.requireCookieOwner(w, r, cid); !ok {
if !s.requireCookieOwnership(w, r, cid) {
return
}
if req.MaxDiscountPercent < 0 || req.MaxDiscountPercent > 100 {