Files
mtusi2026lab7/backend/internal/application/usecase/auth_security_test.go

169 lines
4.8 KiB
Go

package usecase
import (
"backend/internal/domain/model"
"backend/internal/domain/port"
"backend/internal/domain/repository"
"context"
"errors"
"github.com/google/uuid"
"sync"
"testing"
"time"
)
type securitySessions struct {
port.Sessions
attempts, created, rehashes int
replaced bool
allowError error
reads int
}
func (s *securitySessions) AllowLogin(context.Context, string) (bool, error) {
s.attempts++
return s.attempts <= 10, s.allowError
}
func (s *securitySessions) Credentials(context.Context, string) (uuid.UUID, string, error) {
s.reads++
hash := "old"
if s.reads > 1 && !s.replaced {
hash = "changed"
}
return uuid.MustParse("11111111-1111-1111-1111-111111111111"), hash, nil
}
func (s *securitySessions) RehashPassword(context.Context, uuid.UUID, string, string) (bool, error) {
s.rehashes++
return s.replaced, nil
}
func (s *securitySessions) CreateSession(context.Context, string, uuid.UUID, time.Time) error {
s.created++
return nil
}
type securityPasswords struct {
legacy bool
verified int
}
func (p *securityPasswords) Hash(string) (string, error) { return "new", nil }
func (p *securityPasswords) Verify(_ string, hash string) bool {
p.verified++
return hash != "changed"
}
func (p *securityPasswords) NeedsRehash(string) bool { return p.legacy }
type securityRepo struct{ repository.Repository }
func (securityRepo) GetUser(_ context.Context, id uuid.UUID) (model.User, error) {
return model.User{ID: id}, nil
}
func TestSharedLimitRunsBeforeKDF(t *testing.T) {
s := &securitySessions{replaced: true}
p := &securityPasswords{}
a := NewAuth(s, p, NewMessenger(securityRepo{}), time.Hour, time.Now)
b := NewAuth(s, p, NewMessenger(securityRepo{}), time.Hour, time.Now)
for i := 0; i < 10; i++ {
actor := a
if i%2 == 1 {
actor = b
}
if _, e := actor.Login(context.Background(), "synthetic", "password"); e != nil {
t.Fatal(e)
}
}
if _, e := b.Login(context.Background(), "synthetic", "password"); e == nil {
t.Fatal("replicas bypass shared attempt limit")
}
if p.verified != 10 || s.created != 10 {
t.Fatal("limited attempt reached KDF or session creation")
}
}
func TestLegacyRehashUsesCASBeforeSession(t *testing.T) {
for _, changed := range []bool{true, false} {
s := &securitySessions{replaced: changed}
p := &securityPasswords{legacy: true}
a := NewAuth(s, p, NewMessenger(securityRepo{}), time.Hour, time.Now)
_, e := a.Login(context.Background(), "synthetic", "password")
if s.rehashes != 1 {
t.Fatal("legacy password was not upgraded")
}
if changed && (e != nil || s.created != 1) {
t.Fatal("successful upgrade lost login")
}
if !changed && (!errors.Is(e, model.ErrUnauthorized) || s.created != 0) {
t.Fatal("concurrent password change issued stale session")
}
}
}
type racingRehashSessions struct {
port.Sessions
mu sync.Mutex
readers int
barrier chan struct{}
hash string
created int
}
func (s *racingRehashSessions) AllowLogin(context.Context, string) (bool, error) { return true, nil }
func (s *racingRehashSessions) Credentials(ctx context.Context, _ string) (uuid.UUID, string, error) {
s.mu.Lock()
hash := s.hash
s.readers++
n := s.readers
if n == 2 {
close(s.barrier)
}
s.mu.Unlock()
if n <= 2 {
select {
case <-s.barrier:
case <-ctx.Done():
return uuid.Nil, "", ctx.Err()
}
}
return uuid.MustParse("11111111-1111-1111-1111-111111111111"), hash, nil
}
func (s *racingRehashSessions) RehashPassword(_ context.Context, _ uuid.UUID, previous, replacement string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
if s.hash != previous {
return false, nil
}
s.hash = replacement
return true, nil
}
func (s *racingRehashSessions) CreateSession(context.Context, string, uuid.UUID, time.Time) error {
s.mu.Lock()
defer s.mu.Unlock()
s.created++
return nil
}
type racingPasswords struct{}
func (racingPasswords) Hash(string) (string, error) { return "new", nil }
func (racingPasswords) Verify(_ string, hash string) bool { return hash == "old" || hash == "new" }
func (racingPasswords) NeedsRehash(hash string) bool { return hash == "old" }
func TestConcurrentLegacyLoginsSurviveAnotherSuccessfulRehash(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Second)
defer cancel()
s := &racingRehashSessions{barrier: make(chan struct{}), hash: "old"}
results := make(chan error, 2)
for i := 0; i < 2; i++ {
a := NewAuth(s, racingPasswords{}, NewMessenger(securityRepo{}), time.Hour, time.Now)
go func() { _, e := a.Login(ctx, "synthetic", "password"); results <- e }()
}
for i := 0; i < 2; i++ {
if e := <-results; e != nil {
t.Fatal("concurrent benign rehash rejected valid login")
}
}
s.mu.Lock()
defer s.mu.Unlock()
if s.created != 2 || s.hash != "new" {
t.Fatal("concurrent upgrade did not preserve both logins")
}
}