Files
mtusi2026lab3/student-tests/auth_tests/storage_test.go
T

332 lines
12 KiB
Go

package auth_tests
import (
"context"
"crypto/sha256"
"encoding/hex"
"errors"
"os"
"path/filepath"
"runtime"
"sort"
"strings"
"testing"
"time"
"highload/internal/database/sqlc"
"highload/internal/model"
repository "highload/internal/repository/postgres"
redisrepo "highload/internal/repository/redis"
"highload/internal/security"
"highload/internal/service"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
)
type fixture struct {
admin *pgxpool.Pool
pool *pgxpool.Pool
config *pgxpool.Config
queries *sqlc.Queries
users *service.UserService
auth *service.AuthService
redis *redisFixture
ctx context.Context
}
func newFixture(t *testing.T) *fixture {
t.Helper()
url := os.Getenv("AUTH_TEST_DATABASE_URL")
if url == "" {
t.Skip("storage not verified: set AUTH_TEST_DATABASE_URL for a dedicated test PostgreSQL")
}
ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second)
t.Cleanup(cancel)
config, err := pgxpool.ParseConfig(url)
if err != nil {
t.Fatal("cannot parse test PostgreSQL configuration (credentials suppressed)")
}
config.MaxConns = 4
config.MinConns = 0
config.ConnConfig.ConnectTimeout = 3 * time.Second
config.ConnConfig.RuntimeParams["statement_timeout"] = "5000"
admin, err := pgxpool.NewWithConfig(ctx, config)
if err != nil {
t.Fatal("cannot open test PostgreSQL pool")
}
t.Cleanup(admin.Close)
if err := admin.Ping(ctx); err != nil {
t.Fatal("test PostgreSQL is unavailable")
}
// Only this uniquely named schema is created and dropped. Existing tables
// and volumes are never removed. The role needs CREATE SCHEMA permission.
schema := "auth_test_" + strings.ReplaceAll(uuid.NewString(), "-", "")
quoted := pgx.Identifier{schema}.Sanitize()
if _, err := admin.Exec(ctx, "CREATE SCHEMA "+quoted); err != nil {
t.Fatal("cannot create isolated test schema")
}
t.Cleanup(func() {
cleanupCtx, done := context.WithTimeout(context.Background(), 5*time.Second)
defer done()
if _, err := admin.Exec(cleanupCtx, "DROP SCHEMA "+quoted+" CASCADE"); err != nil {
t.Error("isolated test schema cleanup failed")
}
})
config = config.Copy()
config.ConnConfig.RuntimeParams["search_path"] = schema
f := &fixture{admin: admin, config: config, ctx: ctx, redis: newRedisFixture(t)}
f.connect(t, time.Hour)
t.Cleanup(func() { f.pool.Close() })
_, source, _, ok := runtime.Caller(0)
if !ok {
t.Fatal("cannot locate migration files")
}
migrations, err := filepath.Glob(filepath.Join(filepath.Dir(source), "..", "..", "db", "migrations", "*.sql"))
if err != nil || len(migrations) == 0 {
t.Fatal("migration SQL is missing")
}
sort.Strings(migrations)
for _, path := range migrations {
data, err := os.ReadFile(path)
if err != nil {
t.Fatal("cannot read migration SQL")
}
// Current migrations are ordinary SQL with Goose Up/Down markers.
// This applies schema fixtures; it is NOT a test of Goose version tracking.
up, _, _ := strings.Cut(string(data), "-- +goose Down")
if !strings.Contains(up, "-- +goose Up") {
t.Fatal("test fixture expects SQL migrations with Goose Up/Down markers")
}
if _, err := f.pool.Exec(ctx, up, pgx.QueryExecModeSimpleProtocol); err != nil {
t.Fatal("migration cannot initialize isolated schema")
}
}
return f
}
func (f *fixture) connect(t *testing.T, ttl time.Duration) {
t.Helper()
pool, err := pgxpool.NewWithConfig(f.ctx, f.config.Copy())
if err != nil {
t.Fatal("cannot connect to isolated schema")
}
f.pool = pool
f.queries = sqlc.New(pool)
userRepo := repository.NewUserRepository(f.queries)
sessionRepo := redisrepo.NewSessionRepository(f.redis.client)
f.users = service.NewUserService(userRepo)
f.auth = service.NewAuthService(userRepo, sessionRepo, ttl)
}
func (f *fixture) user(t *testing.T) (*model.User, string) {
t.Helper()
password := "Synthetic:" + uuid.NewString()
username := "auth_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
user, err := f.users.CreateUser(f.ctx, username, "Auth storage", password)
if err != nil {
t.Fatal("cannot create synthetic user")
}
return user, password
}
func (f *fixture) session(t *testing.T, user *model.User, password string) *service.CreatedSession {
t.Helper()
session, err := f.auth.CreateSession(f.ctx, user.Username, password)
if err != nil {
t.Fatal("cannot create synthetic session")
}
return session
}
func TestStoragePasswordIsKDFAndDuplicateCannotOverwrite(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
stored, err := f.queries.GetUserByUsername(f.ctx, user.Username)
if err != nil || stored.PasswordHash == password || !strings.HasPrefix(stored.PasswordHash, "$argon2id$") {
t.Fatal("database did not preserve the selected password KDF")
}
ok, err := security.VerifyPassword(password, stored.PasswordHash)
if err != nil || !ok {
t.Fatal("stored password does not verify")
}
_, err = f.users.CreateUser(f.ctx, user.Username, "Overwrite", password+"x")
if !errors.Is(err, service.ErrAlreadyExists) {
t.Fatal("duplicate username was not rejected")
}
after, err := f.queries.GetUserByUsername(f.ctx, user.Username)
if err != nil || after.ID != stored.ID || after.PasswordHash != stored.PasswordHash ||
after.DisplayName != stored.DisplayName {
t.Fatal("failed duplicate registration changed the original user")
}
}
func TestStorageSessionHashAndReconnectPreserveDeadline(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
hash := sha256.Sum256([]byte(session.Token))
key := "session:" + hex.EncodeToString(hash[:])
row, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
value, getErr := f.redis.client.Get(f.ctx, key).Result()
if err != nil || getErr != nil || strings.Contains(key, session.Token) || strings.Contains(value, session.Token) {
t.Fatal("selected session storage did not use SHA-256 of the opaque token")
}
for _, ownedKey := range f.redis.audit.ownedKeys() {
storedValue, err := f.redis.client.Get(f.ctx, ownedKey).Result()
if err != nil || strings.Contains(ownedKey, session.Token) || strings.Contains(storedValue, session.Token) {
t.Fatal("raw session token was persisted in Redis")
}
}
if f.redis.client.Exists(f.ctx, "session:"+session.Token, session.Token).Val() != 0 {
t.Fatal("raw token was stored as a Redis key")
}
if ttl := f.redis.client.PTTL(f.ctx, key).Val(); ttl <= 0 || ttl > time.Hour {
t.Fatal("session must have a positive bounded Redis TTL")
}
if session.TokenType != "Bearer" || len(session.Token) < 32 || row.RevokedAt != nil ||
!row.ExpiresAt.Equal(session.ExpiresAt) || !row.ExpiresAt.After(row.CreatedAt) {
t.Fatal("invalid stored session metadata")
}
beforeDeadline := row.ExpiresAt
for range 3 {
id, err := f.auth.ValidateSession(f.ctx, session.Token)
if err != nil || id != user.ID {
t.Fatal("valid session rejected or mapped to another user")
}
}
f.pool.Close()
// A different process configuration must not reset already stored expiry.
f.connect(t, 24*time.Hour)
id, err := f.auth.ValidateSession(f.ctx, session.Token)
if err != nil || id != user.ID {
t.Fatal("new pool/services lost the existing session")
}
after, err := f.redis.repo.GetSessionByTokenHash(f.ctx, hash[:])
if err != nil || !after.ExpiresAt.Equal(beforeDeadline) {
t.Fatal("reads or reconnection extended session TTL")
}
}
func TestStorageWrongCredentialsNeverCreateSession(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
writes := f.redis.audit.writeCount()
for _, credentials := range [][2]string{
{user.Username, password + "x"}, {"unknown_auth_user", password},
} {
_, err := f.auth.CreateSession(f.ctx, credentials[0], credentials[1])
if !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("wrong credentials did not yield the same unauthorized error")
}
}
if f.redis.audit.writeCount() != writes {
t.Fatal("failed login created a session")
}
for _, token := range []string{"", uuid.NewString()} {
if _, err := f.auth.ValidateSession(f.ctx, token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("empty or unknown token accepted")
}
}
}
func TestStorageRevocationIsPersistentAndSessionSpecific(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
first, second := f.session(t, user, password), f.session(t, user, password)
if first.Token == second.Token {
t.Fatal("two logins reused the same token")
}
if err := f.auth.RevokeSession(f.ctx, first.Token); err != nil {
t.Fatal("logout failed")
}
f.pool.Close()
f.connect(t, time.Hour)
if _, err := f.auth.ValidateSession(f.ctx, first.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("revoked session revived after reconnect")
}
id, err := f.auth.ValidateSession(f.ctx, second.Token)
if err != nil || id != user.ID {
t.Fatal("logout affected another session")
}
}
func TestStorageExpiredSessionCannotRevive(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
hash := sha256.Sum256([]byte(session.Token))
key := "session:" + hex.EncodeToString(hash[:])
if err := f.redis.client.PExpire(f.ctx, key, time.Millisecond).Err(); err != nil {
t.Fatal("cannot set an expired fixture")
}
time.Sleep(20 * time.Millisecond)
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("expired session accepted")
}
f.pool.Close()
f.connect(t, 24*time.Hour)
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("new TTL configuration revived an expired session")
}
}
func TestStorageShortTTLExpiresAndReLoginWorks(t *testing.T) {
f := newFixture(t)
f.auth = service.NewAuthService(repository.NewUserRepository(f.queries),
redisrepo.NewSessionRepository(f.redis.client), 2*time.Second)
user, password := f.user(t)
session := f.session(t, user, password)
if remaining := time.Until(session.ExpiresAt); remaining <= 0 || remaining > 3*time.Second {
t.Fatal("two-second TTL was not used for the stored session")
}
if id, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil || id != user.ID {
t.Fatal("fresh short-lived session was rejected")
}
time.Sleep(max(0, time.Until(session.ExpiresAt)/2))
if _, err := f.auth.ValidateSession(f.ctx, session.Token); err != nil {
t.Fatal("session expired before its original deadline")
}
timer := time.NewTimer(max(0, time.Until(session.ExpiresAt)) + 100*time.Millisecond)
defer timer.Stop()
select {
case <-timer.C:
case <-f.ctx.Done():
t.Fatal("expiry fixture exceeded its deadline")
}
if _, err := f.auth.ValidateSession(f.ctx, session.Token); !errors.Is(err, service.ErrUnauthorized) {
t.Fatal("short-lived session was accepted after its stored deadline")
}
fresh := f.session(t, user, password)
if fresh.Token == session.Token {
t.Fatal("re-login reused the expired token")
}
if id, err := f.auth.ValidateSession(f.ctx, fresh.Token); err != nil || id != user.ID {
t.Fatal("re-login did not produce a usable session")
}
}
func TestStorageChatRollbackAfterMemberInsertFailure(t *testing.T) {
f := newFixture(t)
user, _ := f.user(t)
repo := repository.NewChatRepository(f.queries, f.pool)
// A valid first member is inserted before the nonexistent member fails.
// Calling the repository bypasses prevalidation and tests real rollback.
_, err := repo.CreateChat(f.ctx, "Must roll back", []string{user.ID, uuid.NewString()})
if err == nil {
t.Fatal("chat with nonexistent member unexpectedly committed")
}
for _, table := range []string{"chats", "chat_members"} {
var count int
err := f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+table).Scan(&count)
if err != nil || count != 0 {
t.Fatal("failed transaction left partial chat or membership rows")
}
}
created, err := repo.CreateChat(f.ctx, "Valid after rollback", []string{user.ID})
if err != nil || created == nil {
t.Fatal("rollback poisoned subsequent valid transaction")
}
}