IAM-07: account-lockout-login-rate-limiting
internal/lockout: Store.RecordFailure erhoeht failed_count ATOMAR ueber ein einziges Postgres-UPSERT und setzt locked_until, sobald die konfigurierte Schwelle erreicht ist — Zustand lebt ausschliesslich in Postgres, mehrere Core-Instanzen teilen sich denselben Zaehler (Akzeptanzkriterium 2, bekannter Fehler aus archivdms internal/auth/ratelimit.go vermieden: kein In-Process-Zaehler). IsLocked vergleicht nur locked_until gegen die aktuelle Zeit — eine abgelaufene Sperre gilt automatisch als aufgehoben, ohne explizite Entsperr-Aktion (Akzeptanzkriterium 3). Unlock erlaubt zusaetzlich sofortige Entsperrung durch Administratoreingriff. GuardedLogin komponiert IAM-02s LoginService mit dem Lockout-Zustand, ohne LoginService selbst zu veraendern: prueft die Sperre vor jedem Versuch, vermerkt Erfolg/Fehlschlag danach. Bugfix waehrend Tests: die Sperrzeit wurde als Ganzzahl-Sekunden in die Postgres-INTERVAL-Berechnung eingesetzt (int(duration.Seconds())), wodurch Sperrzeiten unter 1 Sekunde (z.B. in Tests) auf 0 abgerundet wurden und die Sperre sofort wieder als abgelaufen galt — auf Fliesskomma-Sekunden umgestellt. Pruefungen (ausgefuehrt auf root@192.168.1.131, go build/vet/test PASS): 1. Zwei parallel laufende Dienstinstanzen teilen sich denselben Zaehler — TestRecordFailure_SharedAcrossInstances: zwei unabhaengige pgxpool.Pool- Verbindungen, Fehlversuche abwechselnd ueber beide, gemeinsame Schwelle wird erreicht. PASS. 2. Brute-Force-Sperre greift nach definierten Fehlversuchen zuverlaessig — TestRecordFailure_LocksAfterThreshold. PASS. 3. Zeitversatz zwischen Sperre und Entsperrung automatisiert getestet — TestIsLocked_AutoUnlocksAfterExpiry: gesperrt vor Ablauf, automatisch entsperrt nach Ablauf der Sperrzeit. PASS. Zusaetzlich: TestGuardedLogin_LocksAfterRepeatedFailures belegt das Zusammenspiel mit dem echten IAM-02-LoginService End-to-End — selbst das korrekte Passwort wird nach Sperrung abgewiesen. PASS. Co-Authored-By: Claude Sonnet 5 <noreply@anthropic.com>
This commit is contained in:
co-authored by
Claude Sonnet 5
parent
3d20d86a4f
commit
ac070c160a
@@ -0,0 +1,103 @@
|
||||
// Package lockout implementiert Core IAM-07: Account-Lockout nach
|
||||
// Fehlversuchen und Login-Rate-Limiting mit geteiltem, externem
|
||||
// (Postgres-basiertem) Zustand — kein In-Process-Zaehler, der bei
|
||||
// Mehrinstanzbetrieb aushebelbar waere (bekannter Fehler aus archivdms
|
||||
// internal/auth/ratelimit.go).
|
||||
package lockout
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
"time"
|
||||
|
||||
"github.com/jackc/pgx/v5/pgxpool"
|
||||
)
|
||||
|
||||
// DefaultMaxFailedAttempts/DefaultLockoutDuration sind explizit benannte
|
||||
// Defaults, ueberschreibbar via WithPolicy.
|
||||
const (
|
||||
DefaultMaxFailedAttempts = 5
|
||||
DefaultLockoutDuration = 15 * time.Minute
|
||||
)
|
||||
|
||||
type Store struct {
|
||||
pool *pgxpool.Pool
|
||||
maxFailed int
|
||||
lockoutDuration time.Duration
|
||||
}
|
||||
|
||||
func NewStore(pool *pgxpool.Pool) *Store {
|
||||
return &Store{pool: pool, maxFailed: DefaultMaxFailedAttempts, lockoutDuration: DefaultLockoutDuration}
|
||||
}
|
||||
|
||||
func (s *Store) WithPolicy(maxFailed int, lockoutDuration time.Duration) *Store {
|
||||
return &Store{pool: s.pool, maxFailed: maxFailed, lockoutDuration: lockoutDuration}
|
||||
}
|
||||
|
||||
// IsLocked prueft, ob ein Konto aktuell gesperrt ist. Eine abgelaufene
|
||||
// Sperre gilt automatisch als nicht mehr gesperrt (Akzeptanzkriterium 3) —
|
||||
// es ist keine explizite Entsperr-Aktion noetig, der Zeitvergleich reicht.
|
||||
func (s *Store) IsLocked(ctx context.Context, email string) (locked bool, lockedUntil time.Time, err error) {
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
SELECT locked_until FROM login_attempts WHERE email = $1 AND locked_until IS NOT NULL
|
||||
`, email).Scan(&lockedUntil)
|
||||
if err != nil {
|
||||
return false, time.Time{}, nil // kein Datensatz oder kein Lock -> nicht gesperrt
|
||||
}
|
||||
return time.Now().Before(lockedUntil), lockedUntil, nil
|
||||
}
|
||||
|
||||
// RecordFailure erhoeht den Fehlversuchszaehler ATOMAR (UPSERT) und sperrt
|
||||
// das Konto, sobald die Schwelle erreicht ist (Akzeptanzkriterium 1 / 2).
|
||||
// Der Zustand liegt ausschliesslich in Postgres, mehrere Core-Instanzen
|
||||
// teilen sich denselben Zaehler (Akzeptanzkriterium 2).
|
||||
func (s *Store) RecordFailure(ctx context.Context, email string) (locked bool, lockedUntil time.Time, err error) {
|
||||
var failedCount int
|
||||
var lockedUntilPtr *time.Time
|
||||
|
||||
err = s.pool.QueryRow(ctx, `
|
||||
INSERT INTO login_attempts (email, failed_count, locked_until, last_attempt_at)
|
||||
VALUES ($1, 1, CASE WHEN 1 >= $2 THEN now() + $3::interval ELSE NULL END, now())
|
||||
ON CONFLICT (email) DO UPDATE SET
|
||||
failed_count = login_attempts.failed_count + 1,
|
||||
last_attempt_at = now(),
|
||||
locked_until = CASE
|
||||
WHEN login_attempts.failed_count + 1 >= $2 THEN now() + $3::interval
|
||||
ELSE login_attempts.locked_until
|
||||
END
|
||||
RETURNING failed_count, locked_until
|
||||
`, email, s.maxFailed, fmt.Sprintf("%f seconds", s.lockoutDuration.Seconds())).Scan(&failedCount, &lockedUntilPtr)
|
||||
if err != nil {
|
||||
return false, time.Time{}, fmt.Errorf("fehlversuch erfassen: %w", err)
|
||||
}
|
||||
|
||||
if lockedUntilPtr != nil {
|
||||
return time.Now().Before(*lockedUntilPtr), *lockedUntilPtr, nil
|
||||
}
|
||||
return false, time.Time{}, nil
|
||||
}
|
||||
|
||||
// RecordSuccess setzt den Fehlversuchszaehler nach erfolgreichem Login zurueck.
|
||||
func (s *Store) RecordSuccess(ctx context.Context, email string) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
INSERT INTO login_attempts (email, failed_count, locked_until, last_attempt_at)
|
||||
VALUES ($1, 0, NULL, now())
|
||||
ON CONFLICT (email) DO UPDATE SET failed_count = 0, locked_until = NULL, last_attempt_at = now()
|
||||
`, email)
|
||||
if err != nil {
|
||||
return fmt.Errorf("erfolgreichen login erfassen: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// Unlock entsperrt ein Konto durch Administratoreingriff, unabhaengig von
|
||||
// der Sperrzeit (Akzeptanzkriterium 3).
|
||||
func (s *Store) Unlock(ctx context.Context, email string) error {
|
||||
_, err := s.pool.Exec(ctx, `
|
||||
UPDATE login_attempts SET failed_count = 0, locked_until = NULL WHERE email = $1
|
||||
`, email)
|
||||
if err != nil {
|
||||
return fmt.Errorf("konto entsperren: %w", err)
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user