package auth import ( "sync" "time" "git.t-juice.club/torjus/oubliette/internal/config" ) type credKey struct { Username string Password string } type Decision struct { Accepted bool Reason string // "static_credential", "threshold_reached", "remembered_credential", "rejected" } type Authenticator struct { mu sync.Mutex cfg config.AuthConfig failCounts map[string]int // IP -> consecutive failures rememberedCreds map[credKey]time.Time // (user,pass) -> expiry now func() time.Time // for testing } func NewAuthenticator(cfg config.AuthConfig) *Authenticator { return &Authenticator{ cfg: cfg, failCounts: make(map[string]int), rememberedCreds: make(map[credKey]time.Time), now: time.Now, } } func (a *Authenticator) Authenticate(ip, username, password string) Decision { a.mu.Lock() defer a.mu.Unlock() // 1. Check static credentials. for _, cred := range a.cfg.StaticCredentials { if cred.Username == username && cred.Password == password { a.failCounts[ip] = 0 return Decision{Accepted: true, Reason: "static_credential"} } } // 2. Check remembered credentials. key := credKey{Username: username, Password: password} if expiry, ok := a.rememberedCreds[key]; ok { if a.now().Before(expiry) { a.failCounts[ip] = 0 return Decision{Accepted: true, Reason: "remembered_credential"} } delete(a.rememberedCreds, key) } // 3. Increment fail count, check threshold. a.failCounts[ip]++ if a.failCounts[ip] >= a.cfg.AcceptAfter { a.failCounts[ip] = 0 a.rememberedCreds[key] = a.now().Add(a.cfg.CredentialTTLDuration) return Decision{Accepted: true, Reason: "threshold_reached"} } return Decision{Accepted: false, Reason: "rejected"} }