Files
tamabox/internal/route/autoban.go
T
tamakyi e3e59e7c69 chore: baseline snapshot before moderation-strictness feature
Repo .git was damaged (refs/ missing, index truncated, object store near-empty).
Repaired via git init (rebuilt refs), stale index preserved as .git/index.corrupt-20260910.bak,
then full worktree committed as a rollback baseline.
2026-09-10 10:56:27 +08:00

46 lines
1.7 KiB
Go

package route
import (
"net/http"
"github.com/flamego/flamego"
"github.com/tamakyi/TamaBox/internal/security/autoban"
"github.com/tamakyi/TamaBox/internal/shared"
)
// autobanMiddleware 自动封禁中间件:挂载在静态黑名单之后、业务路由之前。
// - 已封禁 IP 直接 403,不再进入业务
// - 敏感路径命中 → 计入窗口统计(达到阈值触发临时封禁 + 邮件告警)
// - 真正的 404 探测由 f.NotFound 处理器单独计数(见 route.go),
// 不再把业务性的"302 → /"(语言切换 / 登出 / 投票不存在 / 黑名单跳转等)误判为扫描。
// - 核心检测逻辑见 internal/security/autoban(可独立测试);告警发送函数由本层注入。
func autobanMiddleware(b *autoban.Banner) flamego.Handler {
return func(ctx flamego.Context) {
// 经 shared.LimitKey 归一化后再计数与判定:IPv4 原样,IPv6 聚合到 /64。
// 否则攻击者可在单个 /64 内轮换地址,使每个键只命中一次而永不触发阈值。
// 记录与判定必须使用同一个键,否则封禁将无法命中。
ip := shared.LimitKey(shared.ResolveClientIP(ctx.Request().Request))
if ip == "" {
return
}
if b.IsBanned(ip) {
ctx.ResponseWriter().WriteHeader(http.StatusForbidden)
_, _ = ctx.ResponseWriter().Write([]byte("403 Forbidden"))
return
}
path := ctx.Request().URL.Path
kind := autoban.KindNone
if autoban.IsSensitivePath(path) {
kind = autoban.KindSensitive
}
if kind != autoban.KindNone {
defer b.Record(ip, path, kind)
}
// 让下游业务路由先执行,敏感路径的计数延后到响应返回后记录。
ctx.Next()
}
}