285 lines
6.9 KiB
Go
285 lines
6.9 KiB
Go
//go:build integration
|
|
|
|
package redis_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/hex"
|
|
"os"
|
|
"strconv"
|
|
"sync"
|
|
"testing"
|
|
"time"
|
|
|
|
"github.com/google/uuid"
|
|
goredis "github.com/redis/go-redis/v9"
|
|
"github.com/stretchr/testify/suite"
|
|
|
|
"mtusi-messenger/internal/domain"
|
|
"mtusi-messenger/internal/platform/cache"
|
|
storageredis "mtusi-messenger/internal/storage/redis"
|
|
)
|
|
|
|
const testRedisDB = 1
|
|
|
|
func redisEnv(key, fallback string) string {
|
|
if value := os.Getenv(key); value != "" {
|
|
return value
|
|
}
|
|
|
|
return fallback
|
|
}
|
|
|
|
func redisEnvInt(key string, fallback int) int {
|
|
value := os.Getenv(key)
|
|
if value == "" {
|
|
return fallback
|
|
}
|
|
|
|
parsed, err := strconv.Atoi(value)
|
|
if err != nil {
|
|
return fallback
|
|
}
|
|
|
|
return parsed
|
|
}
|
|
|
|
func testRedisConfig() cache.RedisConfig {
|
|
return cache.RedisConfig{
|
|
Host: redisEnv("TEST_REDIS_HOST", "localhost"),
|
|
Port: redisEnvInt("TEST_REDIS_PORT", 6379),
|
|
Password: os.Getenv("TEST_REDIS_PASSWORD"),
|
|
DB: redisEnvInt("TEST_REDIS_DB", testRedisDB),
|
|
MaxRetries: 3,
|
|
DialTimeout: 5 * time.Second,
|
|
ReadTimeout: 3 * time.Second,
|
|
WriteTimeout: 3 * time.Second,
|
|
PoolSize: 5,
|
|
}
|
|
}
|
|
|
|
type SessionRepositorySuite struct {
|
|
suite.Suite
|
|
|
|
cache *cache.RedisCache
|
|
client *goredis.Client
|
|
source *fakeSource
|
|
repo *storageredis.SessionRepository
|
|
}
|
|
|
|
func TestSessionRepositorySuite(t *testing.T) {
|
|
suite.Run(t, new(SessionRepositorySuite))
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) SetupSuite() {
|
|
cfg := testRedisConfig()
|
|
|
|
var err error
|
|
|
|
s.cache, err = cache.NewRedis(cfg)
|
|
s.Require().NoError(err)
|
|
|
|
s.client = goredis.NewClient(&goredis.Options{
|
|
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
|
Password: cfg.Password,
|
|
DB: cfg.DB,
|
|
})
|
|
|
|
s.Require().NoError(s.client.Ping(s.T().Context()).Err())
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TearDownSuite() {
|
|
if s.client != nil {
|
|
s.Require().NoError(s.client.Close())
|
|
}
|
|
|
|
if s.cache != nil {
|
|
s.Require().NoError(s.cache.Close())
|
|
}
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) SetupTest() {
|
|
s.Require().NoError(s.client.FlushDB(s.T().Context()).Err())
|
|
|
|
s.source = newFakeSource()
|
|
s.repo = storageredis.NewSessionRepository(
|
|
s.source,
|
|
s.cache,
|
|
5*time.Minute,
|
|
nil,
|
|
)
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TestCacheTTLCapAndSessionExpiry() {
|
|
ctx := s.T().Context()
|
|
for _, remaining := range []time.Duration{time.Hour, time.Minute} {
|
|
hash := []byte(uuid.NewString())
|
|
s.source.seed(hash, uuid.New(), time.Now().Add(remaining))
|
|
_, err := s.repo.Resolve(ctx, hash)
|
|
s.Require().NoError(err)
|
|
|
|
ttl, err := s.client.PTTL(ctx, sessionCacheKey(hash)).Result()
|
|
s.Require().NoError(err)
|
|
s.Positive(ttl)
|
|
s.LessOrEqual(ttl, min(remaining, 5*time.Minute))
|
|
}
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TestResolvePopulatesCacheAndServesFromIt() {
|
|
ctx := s.T().Context()
|
|
tokenHash := []byte("hash-populate")
|
|
session := s.source.seed(tokenHash, uuid.New(), time.Now().UTC().Add(time.Hour))
|
|
|
|
first, err := s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().NoError(err)
|
|
s.Equal(session.User.ID, first.User.ID)
|
|
s.Equal(1, s.source.resolveCount())
|
|
|
|
second, err := s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().NoError(err)
|
|
s.Equal(session.User.ID, second.User.ID)
|
|
s.Equal(1, s.source.resolveCount(), "second resolve must be served from cache")
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TestResolveFallsBackToSourceOnMiss() {
|
|
ctx := s.T().Context()
|
|
|
|
_, err := s.repo.Resolve(ctx, []byte("unknown"))
|
|
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
|
s.Equal(1, s.source.resolveCount(), "cache miss loads from source")
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TestRevokeEvictsCacheAndSource() {
|
|
ctx := s.T().Context()
|
|
userID := uuid.New()
|
|
tokenHash := []byte("hash-revoke")
|
|
s.source.seed(tokenHash, userID, time.Now().UTC().Add(time.Hour))
|
|
|
|
_, err := s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().NoError(err)
|
|
|
|
s.Require().NoError(s.repo.Revoke(ctx, userID, tokenHash))
|
|
|
|
_, err = s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
|
s.Equal(2, s.source.resolveCount(), "revoked token must not be served from cache")
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TestEvictedCacheEntryReloadsFromSource() {
|
|
ctx := s.T().Context()
|
|
tokenHash := []byte("hash-evicted")
|
|
s.source.seed(tokenHash, uuid.New(), time.Now().UTC().Add(time.Hour))
|
|
|
|
_, err := s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().NoError(err)
|
|
s.Equal(1, s.source.resolveCount())
|
|
|
|
// Simulate a Redis flush/restart by dropping the cache entry.
|
|
s.Require().NoError(s.client.Del(ctx, sessionCacheKey(tokenHash)).Err())
|
|
|
|
_, err = s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().NoError(err)
|
|
s.Equal(2, s.source.resolveCount(), "evicted entry must be reloaded from source")
|
|
}
|
|
|
|
func (s *SessionRepositorySuite) TestExpiredSessionIsRejected() {
|
|
ctx := s.T().Context()
|
|
tokenHash := []byte("hash-expired")
|
|
s.source.seed(tokenHash, uuid.New(), time.Now().UTC().Add(-time.Minute))
|
|
|
|
_, err := s.repo.Resolve(ctx, tokenHash)
|
|
s.Require().ErrorIs(err, domain.ErrUnauthenticated)
|
|
s.Equal(1, s.source.resolveCount())
|
|
}
|
|
|
|
func sessionCacheKey(tokenHash []byte) string {
|
|
return "session:" + hex.EncodeToString(tokenHash)
|
|
}
|
|
|
|
func flushRedisDB(ctx context.Context) error {
|
|
cfg := testRedisConfig()
|
|
|
|
client := goredis.NewClient(&goredis.Options{
|
|
Addr: cfg.Host + ":" + strconv.Itoa(cfg.Port),
|
|
Password: cfg.Password,
|
|
DB: cfg.DB,
|
|
})
|
|
|
|
defer func() { _ = client.Close() }()
|
|
|
|
return client.FlushDB(ctx).Err()
|
|
}
|
|
|
|
// fakeSource is an in-memory SessionSource used to observe cache behaviour.
|
|
type fakeSource struct {
|
|
mu sync.Mutex
|
|
sessions map[string]domain.Session
|
|
resolves int
|
|
}
|
|
|
|
func newFakeSource() *fakeSource {
|
|
return &fakeSource{sessions: make(map[string]domain.Session)}
|
|
}
|
|
|
|
func (f *fakeSource) seed(tokenHash []byte, userID uuid.UUID, expiresAt time.Time) domain.Session {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
|
|
session := domain.Session{
|
|
ExpiresAt: expiresAt,
|
|
User: domain.User{
|
|
ID: userID,
|
|
Username: "alice",
|
|
DisplayName: "Алиса",
|
|
CreatedAt: time.Now().UTC(),
|
|
},
|
|
}
|
|
f.sessions[string(tokenHash)] = session
|
|
|
|
return session
|
|
}
|
|
|
|
func (f *fakeSource) resolveCount() int {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
|
|
return f.resolves
|
|
}
|
|
|
|
func (f *fakeSource) Credentials(_ context.Context, _ string) (domain.UserCredentials, error) {
|
|
return domain.UserCredentials{}, domain.ErrUnauthenticated
|
|
}
|
|
|
|
func (f *fakeSource) Create(_ context.Context, session domain.NewSession) (domain.Session, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
|
|
stored := domain.Session{ExpiresAt: session.ExpiresAt}
|
|
f.sessions[string(session.TokenHash)] = stored
|
|
|
|
return stored, nil
|
|
}
|
|
|
|
func (f *fakeSource) Resolve(_ context.Context, tokenHash []byte) (domain.Session, error) {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
|
|
f.resolves++
|
|
|
|
session, ok := f.sessions[string(tokenHash)]
|
|
if !ok || time.Now().UTC().After(session.ExpiresAt) {
|
|
return domain.Session{}, domain.ErrUnauthenticated
|
|
}
|
|
|
|
return session, nil
|
|
}
|
|
|
|
func (f *fakeSource) Revoke(_ context.Context, _ uuid.UUID, tokenHash []byte) error {
|
|
f.mu.Lock()
|
|
defer f.mu.Unlock()
|
|
|
|
delete(f.sessions, string(tokenHash))
|
|
|
|
return nil
|
|
}
|