package auth_tests import ( "context" "crypto/sha256" "encoding/hex" "errors" "net" "net/http" "net/http/httptest" "os" "os/exec" "path/filepath" "runtime" "strings" "sync" "syscall" "testing" "time" "highload/internal/config" "highload/internal/database" repoerrors "highload/internal/repository" "highload/internal/repository/postgres" redisrepo "highload/internal/repository/redis" "highload/internal/service" httptransport "highload/internal/transport/http" "highload/internal/transport/http/handler" "highload/internal/transport/http/middleware" "github.com/google/uuid" redisclient "github.com/redis/go-redis/v9" ) func TestRedisAddressIsAnAddressNotAFile(t *testing.T) { path := filepath.Join(t.TempDir(), "postgres_url") if err := os.WriteFile(path, []byte("postgres://fixture:fixture@postgres/messenger"), 0600); err != nil { t.Fatal("cannot create synthetic config fixture") } t.Setenv("DATABASE_URL_FILE", path) t.Setenv("REDIS_ADDR", "redis:6379") t.Setenv("SESSION_TTL_SECONDS", "3600") t.Setenv("SESSION_STORE", "redis") cfg, err := config.Load() if err != nil { t.Fatal("REDIS_ADDR must be read as an address, not opened as a file") } if cfg.Database.RedisAddr != "redis:6379" { t.Fatal("REDIS_ADDR did not reach the Redis configuration") } } type redisFixture struct { ctx context.Context client *redisclient.Client repo *redisrepo.SessionRepository keys []string audit *sessionWriteAudit } // Only observe writes through this test's client. No global key counting or // FLUSH commands: other clients' sessions must not affect assertions/cleanup. type sessionWriteAudit struct { sync.Mutex keys map[string]bool writes int } func (a *sessionWriteAudit) DialHook(next redisclient.DialHook) redisclient.DialHook { return next } func (a *sessionWriteAudit) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook { return next } func (a *sessionWriteAudit) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook { return func(ctx context.Context, cmd redisclient.Cmder) error { if cmd.Name() == "set" && len(cmd.Args()) > 1 { if key, ok := cmd.Args()[1].(string); ok { a.Lock() a.keys[key] = true a.writes++ a.Unlock() } } return next(ctx, cmd) } } func (a *sessionWriteAudit) writeCount() int { a.Lock(); defer a.Unlock(); return a.writes } func (a *sessionWriteAudit) ownedKeys() []string { a.Lock() defer a.Unlock() keys := make([]string, 0, len(a.keys)) for key := range a.keys { keys = append(keys, key) } return keys } type aofReplyHook struct { reply any err error } func (h aofReplyHook) DialHook(next redisclient.DialHook) redisclient.DialHook { return next } func (h aofReplyHook) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook { return next } func (h aofReplyHook) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook { return func(ctx context.Context, cmd redisclient.Cmder) error { if cmd.Name() == "waitaof" { // DEL still runs on the real test Redis. Only its persistence // acknowledgement is fault-injected deterministically. value := cmd.(*redisclient.Cmd) value.SetVal(h.reply) value.SetErr(h.err) return h.err } return next(ctx, cmd) } } func TestRedisUnconfirmedAOFNeverReturnsSuccessfulLogout(t *testing.T) { for _, tc := range []struct { name string reply any err error }{ {"local_not_fsynced", []any{int64(0), int64(0)}, nil}, {"only_replica_fsynced", []any{int64(0), int64(1)}, nil}, {"malformed_reply", []any{int64(1)}, nil}, {"command_failure", nil, errors.New("synthetic acknowledgement failure")}, } { t.Run(tc.name, func(t *testing.T) { f := newFixture(t) user, password := f.user(t) session := f.session(t, user, password) f.redis.client.AddHook(aofReplyHook{tc.reply, tc.err}) request := httptest.NewRequest(http.MethodDelete, "/api/v1/auth/sessions/current", nil) request.Header.Set("Authorization", "Bearer "+session.Token) recorder := httptest.NewRecorder() redisRouter(f, f.redis.client).ServeHTTP(recorder, request) if recorder.Code != 500 && recorder.Code != 503 { t.Fatalf("unconfirmed persistence must fail logout, got HTTP %d", recorder.Code) } if (tc.name == "local_not_fsynced" || tc.name == "only_replica_fsynced") && recorder.Code != 503 { t.Errorf("valid reply without local acknowledgement must be HTTP 503, got %d", recorder.Code) } code := "internal_error" if recorder.Code == 503 { code = "unavailable" } assertContractError(t, recorder, recorder.Code, code) hash := sha256.Sum256([]byte(session.Token)) if f.redis.client.Exists(f.ctx, "session:"+hex.EncodeToString(hash[:])).Val() != 0 { t.Fatal("fault fixture did not actually execute DEL before WAITAOF") } }) } } func newRedisFixture(t *testing.T) *redisFixture { t.Helper() addr := os.Getenv("AUTH_TEST_REDIS_ADDR") if addr == "" { t.Skip("Redis not verified: set AUTH_TEST_REDIS_ADDR to a dedicated test Redis with AOF") } ctx, cancel := context.WithTimeout(context.Background(), 45*time.Second) t.Cleanup(cancel) client, err := database.NewRedis(ctx, addr) if err != nil { t.Fatal("dedicated test Redis is unavailable") } audit := &sessionWriteAudit{keys: make(map[string]bool)} client.AddHook(audit) f := &redisFixture{ctx: ctx, client: client, repo: redisrepo.NewSessionRepository(client), audit: audit} t.Cleanup(func() { cleanup, done := context.WithTimeout(context.Background(), 3*time.Second) defer done() // No FLUSHDB/FLUSHALL: delete only this test's own random token keys. keys := append(f.audit.ownedKeys(), f.keys...) if len(keys) > 0 { if err := client.Del(cleanup, keys...).Err(); err != nil { t.Error("test-owned Redis key cleanup failed") } } _ = client.Close() }) return f } func (f *redisFixture) track(token string) [32]byte { hash := sha256.Sum256([]byte(token)) f.keys = append(f.keys, "session:"+hex.EncodeToString(hash[:])) return hash } func TestRedisSessionHasTTLAndReadsDoNotExtendIt(t *testing.T) { f := newRedisFixture(t) hash := f.track("synthetic-" + uuid.NewString()) created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 5*time.Second) if err != nil { t.Fatal("cannot create Redis session") } key := f.keys[0] before := f.client.PTTL(f.ctx, key).Val() if before <= 0 || before > 5*time.Second { t.Fatal("session key has no bounded positive TTL") } time.Sleep(120 * time.Millisecond) loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]) if err != nil || loaded == nil { t.Fatal("cannot read Redis session") } if loaded.UserID != created.UserID || !loaded.ExpiresAt.Equal(created.ExpiresAt) || !loaded.CreatedAt.Equal(created.CreatedAt) { t.Fatal("session identity or original timestamps changed on read") } after := f.client.PTTL(f.ctx, key).Val() if after <= 0 || after >= before { t.Fatal("reading refreshed or removed the session TTL") } } func TestRedisExpiredAndUnknownSessionsAreNotFound(t *testing.T) { f := newRedisFixture(t) hash := f.track(uuid.NewString()) if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) { t.Fatal("unknown session must be not found") } if _, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 200*time.Millisecond); err != nil { t.Fatal("cannot create short-lived test session") } time.Sleep(350 * time.Millisecond) if _, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]); !errors.Is(err, repoerrors.ErrNotFound) { t.Fatal("expired Redis session is still available") } } func TestRedisLogoutOnlyRemovesSelectedSession(t *testing.T) { f := newRedisFixture(t) first, second := f.track(uuid.NewString()), f.track(uuid.NewString()) userID := uuid.NewString() for _, hash := range [][32]byte{first, second} { if _, err := f.repo.Create(f.ctx, hash[:], userID, time.Minute); err != nil { t.Fatal("cannot create independent sessions") } } count, err := f.repo.RevokeSession(f.ctx, first[:]) if err != nil || count != 1 { t.Fatal("logout failed to remove exactly one session or acknowledge persistence") } if _, err := f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repoerrors.ErrNotFound) { t.Fatal("revoked session is still readable") } if _, err := f.repo.GetSessionByTokenHash(f.ctx, second[:]); err != nil { t.Fatal("logout removed another session") } } func TestRedisSessionsSurviveActualRestartWithoutExtendingTTL(t *testing.T) { hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK") if hook == "" { t.Skip("Redis restart not verified: set an explicit dedicated test restart hook") } f := newRedisFixture(t) active, revoked := f.track(uuid.NewString()), f.track(uuid.NewString()) created, err := f.repo.Create(f.ctx, active[:], uuid.NewString(), 30*time.Second) if err != nil { t.Fatal("cannot create active session") } if _, err := f.repo.Create(f.ctx, revoked[:], created.UserID, time.Minute); err != nil { t.Fatal("cannot create revocation fixture") } if _, err := f.repo.RevokeSession(f.ctx, revoked[:]); err != nil { t.Fatal("cannot persist logout before restart") } before := f.client.PTTL(f.ctx, f.keys[0]).Val() if err := exec.CommandContext(f.ctx, hook).Run(); err != nil { t.Fatal("explicit Redis restart hook failed (private output suppressed)") } deadline := time.Now().Add(5 * time.Second) for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) { time.Sleep(50 * time.Millisecond) } loaded, err := f.repo.GetSessionByTokenHash(f.ctx, active[:]) if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) { t.Fatal("restart lost active session or changed its original deadline") } if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before { t.Fatal("restart extended or lost remaining TTL") } if _, err := f.repo.GetSessionByTokenHash(f.ctx, revoked[:]); !errors.Is(err, repoerrors.ErrNotFound) { t.Fatal("restart revived a revoked session") } } func TestRedisActiveSessionSurvivesRestartIndependentlyOfLogout(t *testing.T) { hook := os.Getenv("AUTH_TEST_REDIS_RESTART_HOOK") if hook == "" { t.Skip("Redis restart not verified: set an explicit dedicated test restart hook") } f := newRedisFixture(t) hash := f.track(uuid.NewString()) created, err := f.repo.Create(f.ctx, hash[:], uuid.NewString(), 30*time.Second) if err != nil { t.Fatal("cannot create active session") } before := f.client.PTTL(f.ctx, f.keys[0]).Val() if err := exec.CommandContext(f.ctx, hook).Run(); err != nil { t.Fatal("explicit Redis restart hook failed (private output suppressed)") } deadline := time.Now().Add(5 * time.Second) for f.client.Ping(f.ctx).Err() != nil && time.Now().Before(deadline) { time.Sleep(50 * time.Millisecond) } loaded, err := f.repo.GetSessionByTokenHash(f.ctx, hash[:]) if err != nil || loaded == nil || !loaded.ExpiresAt.Equal(created.ExpiresAt) || loaded.UserID != created.UserID { t.Fatal("restart lost active session identity or changed its deadline") } if after := f.client.PTTL(f.ctx, f.keys[0]).Val(); after <= 0 || after >= before { t.Fatal("restart extended or removed the session TTL") } } func refusedRedis(t *testing.T) *redisclient.Client { t.Helper() client := redisclient.NewClient(&redisclient.Options{ Addr: "synthetic-unavailable:6379", MaxRetries: -1, Dialer: func(context.Context, string, string) (net.Conn, error) { return nil, &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED} }, }) t.Cleanup(func() { _ = client.Close() }) return client } func TestRedisUnavailableKeepsUnavailableCategory(t *testing.T) { repo := redisrepo.NewSessionRepository(refusedRedis(t)) hash := sha256.Sum256([]byte("synthetic-failed-token")) t.Run("create", func(t *testing.T) { _, err := repo.Create(context.Background(), hash[:], uuid.NewString(), time.Minute) if !errors.Is(err, repoerrors.ErrServiceUnavailable) { t.Fatalf("want service unavailable, got %v", err) } if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) { t.Error("Redis network diagnostic context was lost") } }) t.Run("read", func(t *testing.T) { _, err := repo.GetSessionByTokenHash(context.Background(), hash[:]) if !errors.Is(err, repoerrors.ErrServiceUnavailable) { t.Fatalf("want service unavailable, got %v", err) } if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) { t.Error("Redis network diagnostic context was lost") } }) t.Run("logout", func(t *testing.T) { _, err := repo.RevokeSession(context.Background(), hash[:]) if !errors.Is(err, repoerrors.ErrServiceUnavailable) { t.Fatalf("want service unavailable, got %v", err) } if err != nil && !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) { t.Error("Redis network diagnostic context was lost") } }) auth := service.NewAuthService(nil, repo, time.Hour) _, err := auth.ValidateSession(context.Background(), "synthetic-error-context") if !errors.Is(err, service.ErrServiceUnavailable) || !strings.Contains(err.Error(), syscall.ECONNREFUSED.Error()) { t.Error("service lost Redis unavailable category or diagnostic context") } } func redisRouter(f *fixture, client *redisclient.Client) http.Handler { users := postgres.NewUserRepository(f.queries) auth := service.NewAuthService(users, redisrepo.NewSessionRepository(client), time.Hour) userService := service.NewUserService(users) chats := service.NewChatService(postgres.NewChatRepository(f.queries, f.pool), users, userService) messages := service.NewMessageService(postgres.NewMessageRepository(f.queries, f.pool), chats, userService) return httptransport.NewRouter(middleware.NewMiddleware(auth, "auth-test"), handler.NewAuthHandler(auth), handler.NewHealthHandler(f.pool, client), handler.NewChatHandler(chats), handler.NewUserHandler(userService), handler.NewMessageHandler(messages)).Handler() } func TestRedisCriticalOutageHTTPAndReadiness(t *testing.T) { f := newFixture(t) router := redisRouter(f, refusedRedis(t)) for _, tc := range []struct { name, path string status int }{ {"liveness", "/health/live", 200}, {"readiness", "/health/ready", 503}, {"protected_request", "/api/v1/users/me", 503}, } { t.Run(tc.name, func(t *testing.T) { request := httptest.NewRequest(http.MethodGet, tc.path, nil) request.Header.Set("Authorization", "Bearer synthetic-outage-token") recorder := httptest.NewRecorder() router.ServeHTTP(recorder, request) if recorder.Code != tc.status { t.Fatalf("want HTTP %d, got %d", tc.status, recorder.Code) } if tc.status == 503 { assertContractError(t, recorder, 503, "unavailable") } }) } } func TestRedisPublicHTTPContractIsUnchanged(t *testing.T) { f := newFixture(t) r := newRedisFixture(t) server := httptest.NewServer(redisRouter(f, r.client)) t.Cleanup(server.Close) _, source, _, _ := runtime.Caller(0) root := filepath.Clean(filepath.Join(filepath.Dir(source), "..", "..")) // The full acceptance suite performs many Argon2id operations. Under -race // it needs its own budget rather than the 45-second SQL fixture budget. for _, tc := range []struct { name string args []string }{ {"teacher_smoke", []string{filepath.Join(root, "tests/smoke.py"), "--base-url", server.URL}}, {"auth_normal", []string{filepath.Join(root, "student-tests/auth_contract.py"), "--base-url", server.URL, "--ttl", "3600"}}, } { t.Run(tc.name, func(t *testing.T) { // Each independent subprocess gets the full acceptance budget. A smoke // run must not consume part of the following auth suite's allowance. acceptanceCtx, cancel := context.WithTimeout(context.Background(), 300*time.Second) defer cancel() cmd := exec.CommandContext(acceptanceCtx, "python3", tc.args...) cmd.Dir = root output, err := cmd.CombinedOutput() if err != nil { for _, line := range strings.Split(string(output), "\n") { if strings.HasPrefix(line, "test_") { // Only method names: never print credentials or subtest values. name, _, _ := strings.Cut(line, " ") t.Log("acceptance progress: " + name) } } if acceptanceCtx.Err() != nil { t.Fatal("HTTP acceptance subprocess exceeded its own execution budget; application operation budgets are unchanged") } // Public clients keep tokens in memory. Show only status diagnostics. for _, line := range strings.Split(string(output), "\n") { if strings.Contains(line, "expected [") && strings.Contains(line, "received") { t.Log(line) } } t.Fatal("HTTP acceptance contract failed with Redis-backed sessions") } }) } }