更新密码找回uniapp
This commit is contained in:
1 parent
7f9a66da0f
commit
3fdda89833
1304 files changed
+3503
-26132
No files matched your search
+2
-35
@@ -12,36 +12,21 @@ import (
|
||||
"github.com/beego/beego/v2/server/web/context"
|
||||
)
|
||||
|
||||
// 鉴权开关(app.conf: auth_enforce)
|
||||
// - off :完全不启用(等同改造前的行为)
|
||||
// - warn :观察模式,只记录「无 token / token 无效」的接口,不拦截(默认,零风险上线)
|
||||
// - on :真正拦截并返回 401
|
||||
//
|
||||
// 上线建议:先 warn 跑一段时间,用日志核对白名单是否遗漏,确认无误后再切 on。
|
||||
const (
|
||||
AuthModeOff = "off"
|
||||
AuthModeWarn = "warn"
|
||||
AuthModeOn = "on"
|
||||
)
|
||||
|
||||
// protectedPrefixes 需要鉴权的业务前缀。
|
||||
// 仅保护业务 API:官网(/ /site/ /index/…)、开放/登录器接口(/api/ 下的公开项)、
|
||||
// 静态资源与 ACME 验证路径均不在其中,避免误伤公开接口。
|
||||
// 移动端(uniapp)已并入 /api/,故显式列出其中需要鉴权的移动端前缀,
|
||||
// 而登录器公开接口(/api/getcard、/api/cursor/*、/api/softwareupgrade/check 等)
|
||||
// 不在下列前缀内,保持公开。
|
||||
var protectedPrefixes = []string{
|
||||
"/backend/", "/platform/",
|
||||
"/api/oa/", "/api/notebook/", "/api/schedule", "/api/currentUser",
|
||||
"/api/activity/", "/api/home", "/api/quick-menus",
|
||||
"/api/activity/", "/api/home", "/api/quick-menus", "/api/changePassword",
|
||||
}
|
||||
|
||||
// authWhitelist 受保护前缀内无需鉴权的路径(前缀匹配)
|
||||
var authWhitelist = []string{
|
||||
// 统一认证中心(P1 上线)
|
||||
"/auth/",
|
||||
|
||||
// backend 登录/注册/找回密码
|
||||
"/backend/login",
|
||||
"/backend/sendLoginCode",
|
||||
"/backend/register",
|
||||
@@ -51,7 +36,6 @@ var authWhitelist = []string{
|
||||
"/backend/verifyAccount",
|
||||
"/backend/logout",
|
||||
|
||||
// platform 登录/注册/找回密码
|
||||
"/platform/login",
|
||||
"/platform/sendLoginCode",
|
||||
"/platform/register",
|
||||
@@ -59,7 +43,6 @@ var authWhitelist = []string{
|
||||
"/platform/resetPassword",
|
||||
"/platform/logout",
|
||||
|
||||
// 移动端(/api)登录/注册/找回密码(/api/login 前缀同时覆盖 loginBySms、极验配置)
|
||||
"/api/login",
|
||||
"/api/sendLoginCode",
|
||||
"/api/register",
|
||||
@@ -68,14 +51,13 @@ var authWhitelist = []string{
|
||||
"/api/sendResetCode",
|
||||
"/api/verifyAccount",
|
||||
"/api/logout",
|
||||
// 登录器日程提醒确认(公开回调)
|
||||
"/api/schedule/reminder/ack",
|
||||
}
|
||||
|
||||
var (
|
||||
modeOnce sync.Once
|
||||
modeVal = AuthModeWarn
|
||||
warnSeen sync.Map // 观察模式下按 path 去重,避免日志刷屏
|
||||
warnSeen sync.Map
|
||||
)
|
||||
|
||||
func authMode() string {
|
||||
@@ -86,7 +68,6 @@ func authMode() string {
|
||||
modeVal = strings.ToLower(strings.TrimSpace(v))
|
||||
}
|
||||
}
|
||||
// 额外白名单:auth_whitelist = /backend/xxx,/app/yyy
|
||||
if extra, err := beego.AppConfig.String("auth_whitelist"); err == nil && strings.TrimSpace(extra) != "" {
|
||||
for _, p := range strings.Split(extra, ",") {
|
||||
if p = strings.TrimSpace(p); p != "" {
|
||||
@@ -99,7 +80,6 @@ func authMode() string {
|
||||
return modeVal
|
||||
}
|
||||
|
||||
// cleanPath 去掉 query / fragment 后返回纯路径
|
||||
func cleanPath(uri string) string {
|
||||
if i := strings.IndexAny(uri, "?#"); i >= 0 {
|
||||
return uri[:i]
|
||||
@@ -125,7 +105,6 @@ func isWhitelisted(path string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// warnLog 观察模式下记录一次「本会被拦截」的请求(按路径去重)
|
||||
func warnLog(path, reason string) {
|
||||
if _, loaded := warnSeen.LoadOrStore(path, struct{}{}); loaded {
|
||||
return
|
||||
@@ -133,14 +112,12 @@ func warnLog(path, reason string) {
|
||||
log.Printf("[auth][warn] 该接口在 enforce=on 时会被拦截: %s (%s)", path, reason)
|
||||
}
|
||||
|
||||
// JWTAuthMiddleware JWT认证中间件
|
||||
func JWTAuthMiddleware() beego.FilterFunc {
|
||||
return func(ctx *context.Context) {
|
||||
mode := authMode()
|
||||
if mode == AuthModeOff {
|
||||
return
|
||||
}
|
||||
// 预检请求直接放行
|
||||
if ctx.Input.Method() == http.MethodOptions {
|
||||
return
|
||||
}
|
||||
@@ -150,7 +127,6 @@ func JWTAuthMiddleware() beego.FilterFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// 失败处理:观察模式只记日志,强制模式才真正拦截
|
||||
reject := func(status int, message string) {
|
||||
if mode == AuthModeWarn {
|
||||
warnLog(path, message)
|
||||
@@ -163,21 +139,18 @@ func JWTAuthMiddleware() beego.FilterFunc {
|
||||
}, false, false)
|
||||
}
|
||||
|
||||
// 从请求头中获取Authorization
|
||||
authHeader := ctx.Request.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
reject(401, "未提供认证信息")
|
||||
return
|
||||
}
|
||||
|
||||
// 按空格分割
|
||||
authParts := strings.SplitN(authHeader, " ", 2)
|
||||
if !(len(authParts) == 2 && authParts[0] == "Bearer") {
|
||||
reject(401, "认证信息格式错误")
|
||||
return
|
||||
}
|
||||
|
||||
// 解析token
|
||||
claims, err := jwtutil.ParseToken(authParts[1])
|
||||
if err != nil {
|
||||
message := "无效的token"
|
||||
@@ -188,24 +161,18 @@ func JWTAuthMiddleware() beego.FilterFunc {
|
||||
return
|
||||
}
|
||||
|
||||
// 将用户信息存储在上下文
|
||||
ctx.Input.SetData("userId", claims.UserID)
|
||||
ctx.Input.SetData("username", claims.Username)
|
||||
ctx.Input.SetData("tenantId", claims.TenantId)
|
||||
// 兼容历史键名:部分控制器(menu / admin_user)读的是 uid / tid,
|
||||
// 且按 uint64 断言,这里补写一份,避免它们静默拿到 0。
|
||||
// 值语义与令牌一致:uid 为认证中心 identity_id。
|
||||
ctx.Input.SetData("uid", uint64(claims.UserID))
|
||||
ctx.Input.SetData("tid", uint64(claims.TenantId))
|
||||
|
||||
// 从token中获取用户类型(如果token中没有,则默认为"user")
|
||||
userType := claims.UserType
|
||||
if userType == "" {
|
||||
userType = "user"
|
||||
}
|
||||
ctx.Input.SetData("userType", userType)
|
||||
|
||||
// 认证中心扩展字段(旧 token 为空值,不影响现有逻辑)
|
||||
ctx.Input.SetData("clientId", claims.ClientID)
|
||||
ctx.Input.SetData("sid", claims.Sid)
|
||||
}
|
||||
|
||||
@@ -18,7 +18,6 @@ const (
|
||||
oplogReqBodyKey = "__oplog_req_body"
|
||||
)
|
||||
|
||||
// BeginOperationLog 在 BeforeRouter 采集请求信息
|
||||
func BeginOperationLog(ctx *context.Context) {
|
||||
url := ctx.Input.URL()
|
||||
method := ctx.Input.Method()
|
||||
@@ -26,7 +25,6 @@ func BeginOperationLog(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 解析用户信息(直接从 header 解析,不依赖 JWT 中间件设置的 context)
|
||||
var uid uint64
|
||||
var tid *uint64
|
||||
if auth := ctx.Request.Header.Get("Authorization"); auth != "" {
|
||||
@@ -42,13 +40,10 @@ func BeginOperationLog(ctx *context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// 匿名读请求不算操作:官网页面浏览和公开接口每次访问都落库,
|
||||
// 审计表会被 uid=0/module=unknown/action=查询 的流水淹掉。写操作仍照常记录。
|
||||
if method == "GET" && uid == 0 {
|
||||
return
|
||||
}
|
||||
|
||||
// 采集请求信息
|
||||
reqBody := ""
|
||||
if rb := ctx.Input.RequestBody; len(rb) > 0 {
|
||||
reqBody = truncateString(maskSensitive(string(rb)), 5000)
|
||||
@@ -61,9 +56,8 @@ func BeginOperationLog(ctx *context.Context) {
|
||||
ip := truncateString(ctx.Input.IP(), 50)
|
||||
userAgent := truncateString(ctx.Request.Header.Get("User-Agent"), 500)
|
||||
|
||||
// 异步写入数据库
|
||||
go func() {
|
||||
time.Sleep(100 * time.Millisecond) // 等待响应完成
|
||||
time.Sleep(100 * time.Millisecond)
|
||||
logRow := &models.SystemOperationLog{
|
||||
Tid: tid,
|
||||
UserID: uid,
|
||||
@@ -90,15 +84,11 @@ func strPtr(s string) *string {
|
||||
return &s
|
||||
}
|
||||
|
||||
// isMobileAppPath 判断是否属于移动端(/api/)功能接口前缀集合。
|
||||
// 登录器公开接口(/api/getcard、/api/cursor/*、/api/softwareupgrade/*、
|
||||
// /api/schedule/reminder/ack 等)不在此集合内。
|
||||
func isMobileAppPath(url string) bool {
|
||||
mobilePrefixes := []string{
|
||||
"/api/oa/", "/api/notebook/", "/api/currentUser",
|
||||
"/api/activity/", "/api/home", "/api/quick-menus",
|
||||
}
|
||||
// /api/schedule 需区分:/api/schedule/reminder/ack 属登录器,排除
|
||||
if strings.HasPrefix(url, "/api/schedule") {
|
||||
return !strings.HasPrefix(url, "/api/schedule/reminder/ack")
|
||||
}
|
||||
@@ -110,7 +100,6 @@ func isMobileAppPath(url string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// WriteDeleteLog 控制器删除后直接写操作日志(带标题)
|
||||
func WriteDeleteLog(userID uint64, tid int, module, title string) {
|
||||
moduleCN := oplogModuleLabel(module)
|
||||
desc := fmt.Sprintf("您删除了%s:【%s】", moduleCN, truncateString(title, 20))
|
||||
@@ -140,7 +129,6 @@ func oplogModuleLabel(m string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// FinishOperationLog 在 FinishRouter 统一落库到 yz_system_operation_log
|
||||
func FinishOperationLog(ctx *context.Context) {
|
||||
url := ctx.Input.URL()
|
||||
method := ctx.Input.Method()
|
||||
@@ -159,7 +147,6 @@ func FinishOperationLog(ctx *context.Context) {
|
||||
uid := parseUint64FromCtx(ctx.Input.GetData("userId"))
|
||||
tidVal := parseUint64FromCtx(ctx.Input.GetData("tenantId"))
|
||||
|
||||
// 如果 context 中没有用户信息,尝试从 Authorization header 解析
|
||||
if uid == 0 {
|
||||
if auth := ctx.Request.Header.Get("Authorization"); auth != "" {
|
||||
parts := strings.SplitN(auth, " ", 2)
|
||||
@@ -291,33 +278,27 @@ func shouldSkipLogging(method, url string) bool {
|
||||
}
|
||||
}
|
||||
|
||||
// 高频噪声接口:默认跳过(可按需再扩充)
|
||||
if method == "GET" {
|
||||
noisyExact := map[string]bool{
|
||||
"/platform/currentUser": true,
|
||||
"/platform/allmenu": true,
|
||||
"/platform/getOpenVerify": true, // 若未来改名/迁移可再调整
|
||||
"/platform/getOpenVerify": true,
|
||||
}
|
||||
if noisyExact[url] {
|
||||
return true
|
||||
}
|
||||
// 菜单详情/列表类:频率高且多为前端路由加载
|
||||
if strings.HasPrefix(url, "/platform/menu/") {
|
||||
return true
|
||||
}
|
||||
// 登录页极验配置轮询/获取(不影响关键业务)
|
||||
if strings.HasPrefix(url, "/platform/login/getGeetest") || strings.HasPrefix(url, "/platform/login/getOpenVerify") {
|
||||
return true
|
||||
}
|
||||
// 客户端高频版本检查
|
||||
if strings.HasPrefix(url, "/api/softwareupgrade/check") {
|
||||
return true
|
||||
}
|
||||
// 工作台天气实况(代理外部数据源,非业务写操作)
|
||||
if strings.HasPrefix(url, "/backend/weather/") {
|
||||
return true
|
||||
}
|
||||
// 移动端(已并入 /api/)读接口跳过(只记录写操作:POST/PUT/DELETE)
|
||||
if isMobileAppPath(url) {
|
||||
return true
|
||||
}
|
||||
@@ -353,7 +334,6 @@ func truncateString(s string, maxLen int) string {
|
||||
}
|
||||
|
||||
func maskSensitive(s string) string {
|
||||
// 尝试 JSON 脱敏(失败则返回原文)
|
||||
var obj interface{}
|
||||
if err := json.Unmarshal([]byte(s), &obj); err != nil {
|
||||
return s
|
||||
|
||||
@@ -7,14 +7,10 @@ import (
|
||||
"github.com/beego/beego/v2/server/web/context"
|
||||
)
|
||||
|
||||
// PermissionMiddleware 权限验证中间件
|
||||
// 根据路由的权限标识检查用户是否有访问权限
|
||||
func PermissionMiddleware() func(ctx *context.Context) {
|
||||
return func(ctx *context.Context) {
|
||||
// 获取当前请求的路径
|
||||
path := ctx.Input.URL()
|
||||
|
||||
// 不需要权限验证的路径列表
|
||||
publicPaths := []string{
|
||||
"/api/login",
|
||||
"/api/logout",
|
||||
@@ -24,23 +20,18 @@ func PermissionMiddleware() func(ctx *context.Context) {
|
||||
"/api/files/public",
|
||||
}
|
||||
|
||||
// 检查是否为公开路径
|
||||
for _, p := range publicPaths {
|
||||
if path == p {
|
||||
return
|
||||
}
|
||||
}
|
||||
|
||||
// 检查是否为公开预览接口
|
||||
if strings.HasPrefix(path, "/api/files/public-preview/") {
|
||||
return
|
||||
}
|
||||
|
||||
// 获取用户ID
|
||||
userIdData := ctx.Input.GetData("userId")
|
||||
if userIdData == nil {
|
||||
// 如果没有用户ID,说明未登录,这个应该在JWT中间件中处理
|
||||
// 这里直接返回,因为JWT中间件已经拦截了
|
||||
return
|
||||
}
|
||||
|
||||
@@ -53,15 +44,12 @@ func PermissionMiddleware() func(ctx *context.Context) {
|
||||
return
|
||||
}
|
||||
|
||||
// 获取当前路由对应的权限标识
|
||||
permission := getPermissionByPath(path, ctx.Input.Method())
|
||||
|
||||
// 如果没有权限标识,说明该接口不需要权限控制
|
||||
if permission == "" {
|
||||
return
|
||||
}
|
||||
|
||||
// 检查用户是否拥有该权限
|
||||
hasPermission, err := services.CheckUserPermission(userId, permission)
|
||||
if err != nil {
|
||||
ctx.Output.JSON(map[string]interface{}{
|
||||
@@ -83,13 +71,8 @@ func PermissionMiddleware() func(ctx *context.Context) {
|
||||
}
|
||||
}
|
||||
|
||||
// getPermissionByPath 根据路径和方法获取权限标识
|
||||
// 这是一个简化版本,实际应该从数据库中动态获取路由-权限映射关系
|
||||
func getPermissionByPath(path, method string) string {
|
||||
// 权限映射表(路径模式 -> 权限标识)
|
||||
// 这里只列举了部分示例,实际应该从数据库中加载
|
||||
permissionMap := map[string]string{
|
||||
// 用户管理
|
||||
"GET:/api/allUsers": "user:list",
|
||||
"GET:/api/user/:id": "user:detail",
|
||||
"POST:/api/addUser": "user:add",
|
||||
@@ -97,13 +80,11 @@ func getPermissionByPath(path, method string) string {
|
||||
"DELETE:/api/deleteUser/:id": "user:delete",
|
||||
"POST:/api/changePassword/:id": "user:changePassword",
|
||||
|
||||
// 菜单管理
|
||||
"GET:/api/allmenu": "menu:list",
|
||||
"POST:/api/menu": "menu:create",
|
||||
"PUT:/api/menu/:id": "menu:update",
|
||||
"DELETE:/api/menu/:id": "menu:delete",
|
||||
|
||||
// 文件管理
|
||||
"GET:/api/files": "file:list",
|
||||
"POST:/api/files": "file:upload",
|
||||
"GET:/api/files/my": "file:my",
|
||||
@@ -115,7 +96,6 @@ func getPermissionByPath(path, method string) string {
|
||||
"GET:/api/files/search": "file:search",
|
||||
"GET:/api/files/statistics": "file:statistics",
|
||||
|
||||
// 租户管理
|
||||
"GET:/api/tenant/list": "tenant:list",
|
||||
"POST:/api/tenant": "tenant:create",
|
||||
"PUT:/api/tenant/:id": "tenant:update",
|
||||
@@ -123,7 +103,6 @@ func getPermissionByPath(path, method string) string {
|
||||
"POST:/api/tenant/:id/audit": "tenant:audit",
|
||||
"GET:/api/tenant/:id": "tenant:detail",
|
||||
|
||||
// 知识库
|
||||
"GET:/api/knowledge/list": "knowledge:list",
|
||||
"GET:/api/knowledge/detail": "knowledge:detail",
|
||||
"POST:/api/knowledge/create": "knowledge:create",
|
||||
@@ -131,14 +110,11 @@ func getPermissionByPath(path, method string) string {
|
||||
"POST:/api/knowledge/delete": "knowledge:delete",
|
||||
}
|
||||
|
||||
// 匹配路径(简化版本,不支持动态参数匹配)
|
||||
key := method + ":" + path
|
||||
if perm, ok := permissionMap[key]; ok {
|
||||
return perm
|
||||
}
|
||||
|
||||
// 尝试匹配动态路由(简单的ID参数替换)
|
||||
// 例如:/api/user/123 -> /api/user/:id
|
||||
pathParts := strings.Split(path, "/")
|
||||
for pattern, perm := range permissionMap {
|
||||
parts := strings.Split(pattern, ":")
|
||||
@@ -161,7 +137,6 @@ func getPermissionByPath(path, method string) string {
|
||||
match := true
|
||||
for i, part := range patternParts {
|
||||
if strings.HasPrefix(part, ":") {
|
||||
// 动态参数,跳过
|
||||
continue
|
||||
}
|
||||
if part != pathParts[i] {
|
||||
@@ -175,6 +150,5 @@ func getPermissionByPath(path, method string) string {
|
||||
}
|
||||
}
|
||||
|
||||
// 如果没有找到匹配的权限标识,返回空字符串(表示不需要权限控制)
|
||||
return ""
|
||||
}
|
||||
@@ -15,21 +15,6 @@ import (
|
||||
"github.com/beego/beego/v2/server/web/context"
|
||||
)
|
||||
|
||||
// 模块套餐鉴权(PlanAuth)
|
||||
//
|
||||
// 把「接口前缀」映射到「功能模块编码」(yz_system_modules.code),
|
||||
// 当前租户生效套餐(含已开通的单品订单)未包含该模块时拒绝访问。
|
||||
//
|
||||
// 与 JWT 鉴权一致支持三档模式(app.conf: plan_enforce):
|
||||
// - off :完全不启用
|
||||
// - warn:观察模式,只记录「本会被拦截」的请求(默认,便于上线前核对映射)
|
||||
// - on :真正拦截,未开通返回 403
|
||||
//
|
||||
// 映射表(app.conf: plan_module_paths)示例:
|
||||
// plan_module_paths = /backend/crm:crm,/backend/erp:erp,/backend/oa:oa
|
||||
// 按最长前缀匹配;未出现在映射表中的接口不做模块校验(默认放行),
|
||||
// 因此可以按模块逐个灰度开启,不会误伤用户/角色/文件/日志等通用接口。
|
||||
|
||||
const planMappingSeparator = ":"
|
||||
|
||||
var (
|
||||
@@ -41,7 +26,6 @@ var (
|
||||
planRoutes []planRoute
|
||||
)
|
||||
|
||||
// planRoute 接口前缀 → 模块编码
|
||||
type planRoute struct {
|
||||
prefix string
|
||||
module string
|
||||
@@ -76,7 +60,6 @@ func planInit() {
|
||||
planRoutes = append(planRoutes, planRoute{prefix: prefix, module: module})
|
||||
}
|
||||
|
||||
// 最长前缀优先:/backend/crm/bidding 必须先于 /backend/crm 命中
|
||||
sort.Slice(planRoutes, func(i, j int) bool {
|
||||
return len(planRoutes[i].prefix) > len(planRoutes[j].prefix)
|
||||
})
|
||||
@@ -84,7 +67,6 @@ func planInit() {
|
||||
})
|
||||
}
|
||||
|
||||
// planModuleOf 返回路径归属的模块编码;未配置归属时返回空字符串
|
||||
func planModuleOf(path string) string {
|
||||
for _, r := range planRoutes {
|
||||
if strings.HasPrefix(path, r.prefix) {
|
||||
@@ -94,7 +76,6 @@ func planModuleOf(path string) string {
|
||||
return ""
|
||||
}
|
||||
|
||||
// PlanAuthMiddleware 模块套餐鉴权中间件
|
||||
func PlanAuthMiddleware() beego.FilterFunc {
|
||||
return func(ctx *context.Context) {
|
||||
planInit()
|
||||
@@ -117,7 +98,6 @@ func PlanAuthMiddleware() beego.FilterFunc {
|
||||
|
||||
claims, err := planClaims(ctx)
|
||||
if err != nil {
|
||||
// 未登录 / 令牌无效:交给 JWTAuthMiddleware 与各控制器按原逻辑处理
|
||||
return
|
||||
}
|
||||
if claims.TenantId <= 0 {
|
||||
@@ -141,7 +121,6 @@ func PlanAuthMiddleware() beego.FilterFunc {
|
||||
}
|
||||
}
|
||||
|
||||
// planClaims 解析 Authorization 头中的 JWT(仅用于本中间件的模块归属判断)
|
||||
func planClaims(ctx *context.Context) (*jwtutil.Claims, error) {
|
||||
authHeader := ctx.Request.Header.Get("Authorization")
|
||||
if authHeader == "" {
|
||||
|
||||
@@ -14,21 +14,6 @@ import (
|
||||
"github.com/beego/beego/v2/server/web/context"
|
||||
)
|
||||
|
||||
// security_probe.go 扫描器探针的日志降噪与泄露检测。
|
||||
//
|
||||
// 公网服务器每天都会收到大量针对 .env / config.js / credentials.json 等
|
||||
// 敏感文件的自动化探测。它们全部 404 时属于背景噪音,逐条打印访问日志只会淹没真正的告警。
|
||||
// 这里接管 Beego 的访问日志过滤器:
|
||||
// - 探针路径不再逐条打印;
|
||||
// - 持续探测但均未命中时,每 10 分钟汇总提示一次「未发现泄露」;
|
||||
// - 一旦探针路径返回 2xx(文件真实可访问),立即输出 [security][leak] 告警。
|
||||
//
|
||||
// 注意:该过滤器依赖 Beego 的 access log 流程,app.conf 中不要开启
|
||||
// EnableStaticLogs=true,否则 Beego 会跳过 DefaultAccessLogFilter。
|
||||
|
||||
// filterconsole 是带探针过滤的 console 日志适配器。
|
||||
// 在 main.go 里把 BConfig.Log.Outputs 指向它,既保留 Beego dev 模式原有的
|
||||
// `[D] router.go` 访问日志样式,又能把探针/根路径 404 从日志里过滤掉。
|
||||
func init() {
|
||||
logs.Register("filterconsole", func() logs.Logger {
|
||||
return &probeFilterLogger{inner: logs.NewConsole()}
|
||||
@@ -59,7 +44,6 @@ var (
|
||||
accessMethodPath = regexp.MustCompile(`\|\s*(GET|POST|PUT|DELETE|PATCH|HEAD|OPTIONS)\s+(\S+)`)
|
||||
)
|
||||
|
||||
// shouldSuppressAccessLogMsg 解析 Beego dev 访问日志行,过滤探针与根路径 404。
|
||||
func shouldSuppressAccessLogMsg(msg string) bool {
|
||||
clean := ansiColorRe.ReplaceAllString(msg, "")
|
||||
m := accessMethodPath.FindStringSubmatch(clean)
|
||||
@@ -83,7 +67,6 @@ func shouldSuppressAccessLogMsg(msg string) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// scannerProbeFiles 常见扫描器探测的完整文件名(小写)。
|
||||
var scannerProbeFiles = map[string]struct{}{
|
||||
".env": {},
|
||||
"env": {},
|
||||
@@ -118,7 +101,6 @@ var scannerProbeFiles = map[string]struct{}{
|
||||
"aws.json": {},
|
||||
}
|
||||
|
||||
// scannerProbeDirs 目录型探针(源代码/凭证/WordPress 目录)。
|
||||
var scannerProbeDirs = []string{
|
||||
"/.git",
|
||||
"/.svn",
|
||||
@@ -127,7 +109,6 @@ var scannerProbeDirs = []string{
|
||||
"/vendor/composer",
|
||||
"/wp-content",
|
||||
"/wp-admin",
|
||||
// Go 源码目录:日志里出现的 /middleware、/controllers、/routers 等
|
||||
"/middleware",
|
||||
"/routers",
|
||||
"/controllers",
|
||||
@@ -142,7 +123,6 @@ var scannerProbeDirs = []string{
|
||||
"/version",
|
||||
}
|
||||
|
||||
// IsScannerProbe 判断路径是否属于常见的敏感文件扫描探针。
|
||||
func IsScannerProbe(rawPath string) bool {
|
||||
p := strings.ToLower(path.Clean("/" + strings.TrimPrefix(rawPath, "/")))
|
||||
if p == "/" {
|
||||
@@ -152,7 +132,6 @@ func IsScannerProbe(rawPath string) bool {
|
||||
if _, ok := scannerProbeFiles[base]; ok {
|
||||
return true
|
||||
}
|
||||
// .env / .env.local / sendgrid.env / config.env 等变体
|
||||
if base == ".env" || base == "env" ||
|
||||
strings.HasPrefix(base, ".env.") || strings.HasSuffix(base, ".env") {
|
||||
return true
|
||||
@@ -162,12 +141,10 @@ func IsScannerProbe(rawPath string) bool {
|
||||
return true
|
||||
}
|
||||
}
|
||||
// 源码/配置文件后缀:/middleware/security_probe.go、/controllers/backend_reimburse.go 等
|
||||
switch path.Ext(base) {
|
||||
case ".go", ".vue", ".ts", ".sql", ".conf":
|
||||
return true
|
||||
}
|
||||
// WordPress 常见备份文件,如 wp-config.php.bak
|
||||
if strings.HasPrefix(base, "wp-") && strings.HasSuffix(base, ".bak") {
|
||||
return true
|
||||
}
|
||||
@@ -187,13 +164,10 @@ var probeLogState = struct {
|
||||
leakLogged: make(map[string]time.Time),
|
||||
}
|
||||
|
||||
// probeAccessLogFilter 包装 Beego 默认访问日志过滤器。
|
||||
// Filter 返回 true 时 Beego 跳过该请求的访问日志。
|
||||
type probeAccessLogFilter struct {
|
||||
fallback beego.FilterHandler
|
||||
}
|
||||
|
||||
// NewSecurityProbeLogFilter 创建扫描探针访问日志过滤器。
|
||||
func NewSecurityProbeLogFilter(fallback beego.FilterHandler) beego.FilterHandler {
|
||||
return &probeAccessLogFilter{fallback: fallback}
|
||||
}
|
||||
@@ -202,8 +176,6 @@ func (f *probeAccessLogFilter) Filter(ctx *context.Context) bool {
|
||||
p := path.Clean(ctx.Request.URL.Path)
|
||||
status := ctx.ResponseWriter.Status
|
||||
|
||||
// 当前进程只提供后端 API / 认证中心,根路径没有绑定站点;
|
||||
// 公网扫描器/爬虫大量请求 / 得到 404,单独聚合,不逐条刷日志。
|
||||
if p == "/" && status == 404 {
|
||||
recordRootNoise()
|
||||
return true
|
||||
@@ -216,20 +188,15 @@ func (f *probeAccessLogFilter) Filter(ctx *context.Context) bool {
|
||||
return false
|
||||
}
|
||||
|
||||
// 平台后台 SPA 对未知路径会兜底返回 index.html(200),
|
||||
// 这不代表敏感文件可访问,不能当成泄露。
|
||||
spaFallback, _ := ctx.Input.GetData("spa_fallback").(bool)
|
||||
contentType := strings.TrimSpace(ctx.ResponseWriter.Header().Get("Content-Type"))
|
||||
|
||||
// 只有「明确 2xx + 有内容类型」才判定为可访问资源。
|
||||
// status=0 或 Content-Type 为空多为 SPA 兜底/空响应,避免误报泄漏。
|
||||
if status >= 200 && status < 300 && !spaFallback && contentType != "" {
|
||||
recordProbeLeak(ctx, status, contentType)
|
||||
} else {
|
||||
recordProbeNoise()
|
||||
}
|
||||
|
||||
// 探针请求不进入常规访问日志
|
||||
return true
|
||||
}
|
||||
|
||||
|
||||
Reference in new issue
Block a user