fix(notifications): throttle failed-login alerts where they are published

Every failed login was published on the event bus, and the e-mail,
Telegram and Discord notifiers exempt login events from their cooldown
so that successful logins are never swallowed. An unauthenticated login
flood therefore filled each notifier's queue and crowded out every
other alert, a successful login, an Xray crash or a node going down.

UserLoginNotify now passes a failed attempt only for the first failure
of its source address in a minute, at most ten addresses per minute;
successful logins are always published.
This commit is contained in:
MHSanaei
2026-11-01 13:44:32 +01:00
parent 54339661a6
commit 846dfe3d74
2 changed files with 108 additions and 1 deletions
+36 -1
View File
@@ -208,7 +208,40 @@ func (t *Tgbot) prepareServerUsageInfo() string {
return info
}
// UserLoginNotify publishes a login event to the event bus.
const (
loginFailAlertWindow = 1 * time.Minute
// Distinct source addresses alerted per window; the address is the caller's
// to vary, so this ceiling keeps a broad flood below the notifier queue size.
loginFailAlertMaxSources = 10
)
var loginFailAlerts = &loginFailAlertGate{}
// loginFailAlertGate throttles failed-login alerts before they reach the bus: the
// notifiers exempt login events from their cooldown, so a flood crowds out every other alert.
type loginFailAlertGate struct {
mu sync.Mutex
windowStart time.Time
sources map[string]struct{}
}
// allow passes the first failure of each source address in a window.
func (g *loginFailAlertGate) allow(ip string, now time.Time) bool {
g.mu.Lock()
defer g.mu.Unlock()
if now.Sub(g.windowStart) >= loginFailAlertWindow {
g.windowStart = now
g.sources = make(map[string]struct{}, loginFailAlertMaxSources)
}
if _, seen := g.sources[ip]; seen || len(g.sources) >= loginFailAlertMaxSources {
return false
}
g.sources[ip] = struct{}{}
return true
}
// UserLoginNotify publishes a login event to the event bus. Successful logins
// are always published; failed ones are throttled by loginFailAlerts.
func (t *Tgbot) UserLoginNotify(attempt LoginAttempt) {
if attempt.Username == "" || attempt.IP == "" || attempt.Time == "" {
logger.Warning("UserLoginNotify failed, invalid info!")
@@ -222,6 +255,8 @@ func (t *Tgbot) UserLoginNotify(attempt LoginAttempt) {
status := "fail"
if attempt.Status == LoginSuccess {
status = "success"
} else if !loginFailAlerts.allow(attempt.IP, time.Now()) {
return
}
EventBus.Publish(eventbus.Event{