fix(security): 修复 P3 低危项(开放重定向/配额TOCTOU/safeJS/会话治理)
- Referer 开放重定向:safeRedirectPath 仅放行同站相对路径, 外部 URL/协议跳转一律回退 /inbox - 发信配额 TOCTOU:新增 TryReserveQuota 原子预扣 (UPDATE ... WHERE used_bytes + n <= quota_bytes),超配额即拒发; 附件保存失败按大小补偿回退 - 移除危险模板函数 safeHTML/safeJS:新增 jsonify(json.Marshal, < > & 转义为 \u003c 等,无法逃出 </script>),compose 页 quill.innerHTML 改用 jsonify;srcdoc 改回默认属性转义 - 会话治理:登录成功后 session.Clear() 清旧状态;记录 loginAt, 绝对过期 7 天 + 滑动续期(活跃会话 12h 写回刷新) - 确认 #15 Content-Disposition 编码随 P1 #4 已完成 - 新增 12 个测试:重定向路径矩阵、配额原子性(含超额不部分扣费)、 jsonify 逃逸防护、会话绝对过期/有效访问(签名会话构造) 至此 16 项安全审计项(P0-P3)全部修复完成。
This commit is contained in:
@@ -1,12 +1,40 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"time"
|
||||
|
||||
"mail_go/internal/store"
|
||||
|
||||
"github.com/gin-contrib/sessions"
|
||||
"github.com/gin-gonic/gin"
|
||||
)
|
||||
|
||||
const (
|
||||
// sessionAbsoluteMaxAge 会话绝对过期时间:超过后强制重新登录。
|
||||
sessionAbsoluteMaxAge = 7 * 24 * time.Hour
|
||||
// sessionSlidingRefresh 滑动续期阈值:距上次刷新超过该时长则更新
|
||||
// loginAt 并写回 cookie,保持活跃用户不中断(约 12 小时写回一次)。
|
||||
sessionSlidingRefresh = 12 * time.Hour
|
||||
)
|
||||
|
||||
// sessionInt64 兼容不同底层 session store 解码出的整数类型。
|
||||
func sessionInt64(v interface{}) (int64, bool) {
|
||||
switch n := v.(type) {
|
||||
case int64:
|
||||
return n, true
|
||||
case int:
|
||||
return int64(n), true
|
||||
case uint:
|
||||
return int64(n), true
|
||||
case uint64:
|
||||
return int64(n), true
|
||||
case float64:
|
||||
return int64(n), true
|
||||
default:
|
||||
return 0, false
|
||||
}
|
||||
}
|
||||
|
||||
// AuthMiddleware checks for a valid session and loads the current user
|
||||
// into the Gin context. If no valid session exists, it redirects to /login.
|
||||
func AuthMiddleware(stores *store.Stores) gin.HandlerFunc {
|
||||
@@ -19,6 +47,23 @@ func AuthMiddleware(stores *store.Stores) gin.HandlerFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// 会话绝对过期:登录超过 7 天强制重新登录;
|
||||
// 滑动续期:活跃会话每 12 小时刷新一次 loginAt。
|
||||
if loginAt, ok := sessionInt64(session.Get("loginAt")); ok {
|
||||
elapsed := time.Since(time.Unix(loginAt, 0))
|
||||
if elapsed > sessionAbsoluteMaxAge {
|
||||
session.Clear()
|
||||
session.Save()
|
||||
c.Redirect(302, "/login")
|
||||
c.Abort()
|
||||
return
|
||||
}
|
||||
if elapsed > sessionSlidingRefresh {
|
||||
session.Set("loginAt", time.Now().Unix())
|
||||
session.Save()
|
||||
}
|
||||
}
|
||||
|
||||
// userID is stored as uint in session, but sessions.Get returns interface{}
|
||||
// which may be stored as int or uint depending on the underlying store.
|
||||
var id uint
|
||||
|
||||
Reference in New Issue
Block a user