Implement lab 3 level 4 failover and idempotency

This commit is contained in:
2026-10-29 23:35:04 +03:00
parent 0ab3a341aa
commit a2cb1ad2ae
338 changed files with 37821 additions and 22 deletions
@@ -0,0 +1,32 @@
package auth_tests
import (
"net/http"
"net/http/httptest"
"strings"
"testing"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
)
func TestStorageAuthHandlerRejectsJSONBody(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
writes := f.redis.audit.writeCount()
auth := handler.NewAuthHandler(f.auth)
mid := middleware.NewMiddleware(f.auth, "auth-test")
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
request.SetBasicAuth(user.Username, password)
request.Header.Set("Content-Type", "application/json")
recorder := httptest.NewRecorder()
// Exercise the real handler independently of Router wiring.
// This component test does not replace the end-to-end login acceptance test.
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
if recorder.Code != http.StatusBadRequest {
t.Errorf("login with JSON body must return 400; received %d", recorder.Code)
}
if f.redis.audit.writeCount() != writes {
t.Error("login with forbidden JSON body attempted to create a session")
}
}
+209
View File
@@ -0,0 +1,209 @@
package auth_tests
import (
"context"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"os"
"strconv"
"testing"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"highload/internal/database"
"highload/internal/database/sqlc"
"highload/internal/repository"
"highload/internal/repository/postgres"
)
func operationBudget(t *testing.T) time.Duration {
t.Helper()
value := os.Getenv("AUTH_TEST_OPERATION_BUDGET_MS")
if value == "" {
t.Log("budget_policy=provisional_3000ms; teacher has no numeric threshold; approval remains pending")
return 3 * time.Second
}
n, err := strconv.Atoi(value)
if err != nil || n < 500 || n > 10000 {
t.Fatal("AUTH_TEST_OPERATION_BUDGET_MS must be 500..10000")
}
return time.Duration(n) * time.Millisecond
}
func applicationPool(t *testing.T, f *fixture) *pgxpool.Pool {
t.Helper()
u, err := url.Parse(os.Getenv("AUTH_TEST_DATABASE_URL"))
if err != nil {
t.Fatal("invalid test URL")
}
q := u.Query()
q.Set("search_path", f.config.ConnConfig.RuntimeParams["search_path"])
u.RawQuery = q.Encode()
// Actual production constructor: never inherit fixture statement_timeout.
pool, err := database.NewPostgres(f.ctx, u.String())
if err != nil {
t.Fatal("application pool unavailable")
}
f.pool.Close()
f.pool = pool
f.queries = sqlc.New(pool)
return pool
}
func blockOperation(t *testing.T, f *fixture, mode string) func() {
t.Helper()
if mode == "blocked_query" {
tx, err := f.admin.Begin(f.ctx)
if err != nil {
t.Fatal("lock transaction failed")
}
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "users"}.Sanitize()
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
t.Fatal("isolated table lock failed")
}
return func() {
ctx, c := context.WithTimeout(context.Background(), 2*time.Second)
defer c()
_ = tx.Rollback(ctx)
}
}
max := f.pool.Config().MaxConns
if max <= 0 || max > 128 {
t.Fatal("test refuses unbounded/oversized pool")
}
held := make([]*pgxpool.Conn, 0, max)
for range max {
conn, err := f.pool.Acquire(f.ctx)
if err != nil {
for _, h := range held {
h.Release()
}
t.Fatal("pool saturation failed")
}
held = append(held, conn)
}
return func() {
for _, h := range held {
h.Release()
}
}
}
func TestPostgresOperationsHaveBoundedWaits(t *testing.T) {
budget := operationBudget(t)
for _, mode := range []string{"blocked_query", "exhausted_pool"} {
for _, scenario := range []string{"application_budget", "shorter_caller_deadline", "released_before_budget"} {
t.Run(mode+"/"+scenario, func(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
session := f.session(t, user, password)
applicationPool(t, f)
release := blockOperation(t, f, mode)
released := false
defer func() {
if !released {
release()
}
}()
safety := budget + 2*time.Second
if scenario == "shorter_caller_deadline" {
safety = 150 * time.Millisecond
}
ctx, cancel := context.WithTimeout(context.Background(), safety)
defer cancel()
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil).WithContext(ctx)
request.Header.Set("Authorization", "Bearer "+session.Token)
recorder := httptest.NewRecorder()
done := make(chan struct{})
started := time.Now()
go func() { defer close(done); redisRouter(f, f.redis.client).ServeHTTP(recorder, request) }()
if scenario == "released_before_budget" {
time.Sleep(100 * time.Millisecond)
release()
released = true
}
<-done
elapsed := time.Since(started)
t.Logf("mode=%s scenario=%s elapsed_ms=%.3f caller_deadline_ms=%d budget_ms=%d caller_canceled=%t", mode, scenario, float64(elapsed)/float64(time.Millisecond), safety.Milliseconds(), budget.Milliseconds(), ctx.Err() != nil)
switch scenario {
case "application_budget":
if ctx.Err() != nil || elapsed > budget+250*time.Millisecond {
t.Error("application did not independently enforce its operation budget before test safety cancellation")
}
assertContractError(t, recorder, 503, "unavailable")
case "shorter_caller_deadline":
if elapsed > 750*time.Millisecond {
t.Error("short caller deadline was not honored")
}
assertContractError(t, recorder, 503, "unavailable")
case "released_before_budget":
if recorder.Code != 200 || elapsed >= budget {
t.Error("unblocked operation failed or missed the declared budget")
}
}
if !released {
release()
released = true
}
recovery := httptest.NewRecorder()
req := httptest.NewRequest("GET", "/api/v1/users/me", nil)
req.Header.Set("Authorization", "Bearer "+session.Token)
recoveryCtx, c := context.WithTimeout(context.Background(), 2*time.Second)
defer c()
redisRouter(f, f.redis.client).ServeHTTP(recovery, req.WithContext(recoveryCtx))
if recovery.Code != 200 {
t.Error("service did not recover after releasing lock/pool")
}
if f.pool.Stat().AcquiredConns() != 0 {
t.Error("application pool leaked an acquired connection")
}
})
}
}
}
func TestPostgresChatCancellationBeforeCommitIsAtomic(t *testing.T) {
f := newFixture(t)
user, _ := f.user(t)
applicationPool(t, f)
tx, err := f.admin.Begin(f.ctx)
if err != nil {
t.Fatal("cannot start membership blocker")
}
released := false
defer func() {
if !released {
_ = tx.Rollback(context.Background())
}
}()
table := pgx.Identifier{f.config.ConnConfig.RuntimeParams["search_path"], "chat_members"}.Sanitize()
if _, err = tx.Exec(f.ctx, "LOCK TABLE "+table+" IN ACCESS EXCLUSIVE MODE"); err != nil {
t.Fatal("cannot block membership insertion")
}
ctx, cancel := context.WithTimeout(context.Background(), 200*time.Millisecond)
defer cancel()
repo := postgres.NewChatRepository(f.queries, f.pool)
_, err = repo.CreateChat(ctx, "Canceled before membership", []string{user.ID})
if !errors.Is(err, repository.ErrServiceUnavailable) {
t.Errorf("want unavailable after controlled pre-commit cancellation, got category %v", err)
}
// The membership INSERT cannot finish while this lock is held, so COMMIT
// has not been reached. No ambiguous-commit inference is made here.
_ = tx.Rollback(context.Background())
released = true
for _, name := range []string{"chats", "chat_members"} {
var count int
if f.pool.QueryRow(f.ctx, "SELECT count(*) FROM "+name).Scan(&count) != nil || count != 0 {
t.Error("pre-commit cancellation left partial chat data")
}
}
if _, err = repo.CreateChat(f.ctx, "Works after cancellation", []string{user.ID}); err != nil {
t.Error("chat repository failed to recover")
}
if f.pool.Stat().AcquiredConns() != 0 {
t.Error("chat cancellation leaked a connection")
}
}
+273
View File
@@ -0,0 +1,273 @@
package auth_tests
import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
"io"
"log/slog"
"net"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"highload/internal/database/sqlc"
repository "highload/internal/repository/postgres"
"highload/internal/service"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/httputils"
"highload/internal/transport/http/middleware"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgtype"
)
func TestErrorDiagnosticsRecordedOnceAndPublicResponseIsSafe(t *testing.T) {
var output bytes.Buffer
original := slog.Default()
slog.SetDefault(slog.New(slog.NewJSONHandler(&output, nil)))
defer slog.SetDefault(original)
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: errors.New("synthetic-storage-diagnostic")})))
_, cause := users.GetUser(context.Background(), uuid.NewString())
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", "Bearer synthetic-secret-not-for-logs")
recorder := httptest.NewRecorder()
mid := middleware.NewMiddleware(nil, "auth-test")
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = httputils.WriteServiceError(w, cause, middleware.RequestIDFromContext(r.Context()))
})).ServeHTTP(recorder, request)
assertContractError(t, recorder, 500, "internal_error")
if strings.Contains(recorder.Body.String(), "synthetic-storage-diagnostic") {
t.Error("public response exposed internal cause")
}
if strings.Contains(output.String(), "synthetic-secret-not-for-logs") {
t.Error("server log exposed a Bearer credential")
}
var records []map[string]any
for _, line := range strings.Split(strings.TrimSpace(output.String()), "\n") {
if line == "" {
continue
}
var record map[string]any
if json.Unmarshal([]byte(line), &record) != nil {
t.Error("diagnostic log is not structured JSON")
continue
}
// Access records are not detailed duplicate error records.
if record["msg"] != "http request" {
records = append(records, record)
}
}
if len(records) != 1 {
t.Errorf("want exactly one detailed error at response boundary, got %d", len(records))
return
}
record := records[0]
if _, malformed := record["!BADKEY"]; malformed {
t.Error("structured error log contains !BADKEY: slog arguments are not valid key/value pairs")
}
if record["request_id"] != recorder.Header().Get("X-Request-Id") || record["status"] != float64(500) ||
(record["code"] != "internal_error" && record["error_code"] != "internal_error") {
t.Error("diagnostic is missing matching request_id/status/error code")
}
encoded, _ := json.Marshal(record)
if !bytes.Contains(encoded, []byte("synthetic-storage-diagnostic")) {
t.Error("diagnostic lost storage cause")
}
}
// Faults enter through sqlc's database interface, then pass through the real
// repository, service and HTTP error mapper. Driver causes are deliberately
// not required to survive: the public category and response are the contract.
type errorCase struct {
name string
cause error
want error
status int
code string
}
func databaseErrorCases() []errorCase {
cases := []errorCase{
{"no_rows", pgx.ErrNoRows, service.ErrNotFound, 404, "not_found"},
{"duplicate", &pgconn.PgError{Code: "23505"}, service.ErrAlreadyExists, 409, "conflict"},
{"eof", io.EOF, service.ErrServiceUnavailable, 503, "unavailable"},
{"deadline", context.DeadlineExceeded, service.ErrServiceUnavailable, 503, "unavailable"},
{"unexpected_eof", io.ErrUnexpectedEOF, service.ErrServiceUnavailable, 503, "unavailable"},
{"closed_connection", pgconn.ErrConnClosed, service.ErrServiceUnavailable, 503, "unavailable"},
{"connection_refused", unavailableRow{}.Scan(), service.ErrServiceUnavailable, 503, "unavailable"},
// Docker removes the stopped service from DNS. The real outage probe
// returned a ConnectError containing this error, without a net.OpError.
{"database_dns_missing", &net.DNSError{Err: "no such host", Name: "postgres", IsNotFound: true}, service.ErrServiceUnavailable, 503, "unavailable"},
{"sql_syntax", &pgconn.PgError{Code: "42601", Message: "private SQL diagnostic"}, service.ErrServerError, 500, "internal_error"},
{"unexpected", errors.New("private database diagnostic"), service.ErrServerError, 500, "internal_error"},
}
for _, code := range []string{"53300", "57P03", "08006", "08001", "57P01", "57P02"} {
cases = append(cases, errorCase{"sqlstate_" + code, &pgconn.PgError{Code: code}, service.ErrServiceUnavailable, 503, "unavailable"})
}
// Wrapping must not change how an existing error category is recognized.
originals := append([]errorCase(nil), cases...)
for _, tc := range originals {
tc.name = "wrapped_" + tc.name
tc.cause = fmt.Errorf("database operation: %w", tc.cause)
cases = append(cases, tc)
}
return cases
}
type faultRow struct{ cause error }
func (r faultRow) Scan(...any) error { return r.cause }
type faultDB struct {
unavailableDB
cause error
}
func (d faultDB) QueryRow(context.Context, string, ...any) pgx.Row {
return faultRow{d.cause}
}
func assertContractError(t *testing.T, recorder *httptest.ResponseRecorder, status int, code string) {
t.Helper()
if recorder.Code != status {
t.Fatalf("want HTTP %d, got %d", status, recorder.Code)
}
if recorder.Header().Get("Content-Type") != "application/json" {
t.Fatal("error response must have application/json content type")
}
var payload struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
decoder := json.NewDecoder(recorder.Body)
if err := decoder.Decode(&payload); err != nil {
t.Fatal("error response is not valid JSON")
}
if decoder.Decode(new(any)) != io.EOF {
t.Fatal("error response contains more than one JSON value")
}
if payload.Error.Code != code || payload.Error.RequestID == "" ||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
t.Fatal("error category or request ID violates the API contract")
}
if payload.Error.Message == "" || strings.Contains(payload.Error.Message, "private") {
t.Fatal("error message is empty or discloses internal diagnostics")
}
}
func TestErrorDatabaseCategoryReachesHTTP(t *testing.T) {
for _, tc := range databaseErrorCases() {
t.Run(tc.name, func(t *testing.T) {
users := service.NewUserService(repository.NewUserRepository(sqlc.New(faultDB{cause: tc.cause})))
_, err := users.GetUser(context.Background(), uuid.NewString())
if !errors.Is(err, tc.want) {
t.Fatalf("want category %v, got %v", tc.want, err)
}
if errors.Is(tc.cause, context.DeadlineExceeded) && !strings.Contains(err.Error(), context.DeadlineExceeded.Error()) {
t.Error("deadline diagnostic context lost between repository and service")
}
recorder := httptest.NewRecorder()
mid := middleware.NewMiddleware(nil, "auth-test")
mid.RequestID(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = httputils.WriteServiceError(w, err, middleware.RequestIDFromContext(r.Context()))
})).ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
assertContractError(t, recorder, tc.status, tc.code)
})
}
}
func TestErrorUnavailableSQLLoginKeepsCategory(t *testing.T) {
for _, tc := range databaseErrorCases() {
if tc.status != 503 {
continue
}
t.Run(tc.name, func(t *testing.T) {
queries := sqlc.New(faultDB{cause: tc.cause})
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
mid := middleware.NewMiddleware(auth, "auth-test")
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("synthetic_user", "Synthetic:password")
recorder := httptest.NewRecorder()
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
assertContractError(t, recorder, 503, "unavailable")
})
}
}
// The caller exists; the other member lookup fails. This isolates the service
// branch that used to replace the received err with ErrServerError.
type memberFaultDB struct {
unavailableDB
caller uuid.UUID
cause error
}
func (d memberFaultDB) QueryRow(_ context.Context, _ string, args ...any) pgx.Row {
id := uuid.UUID(args[0].(pgtype.UUID).Bytes)
if id == d.caller {
return memberUserRow{id}
}
return faultRow{d.cause}
}
type memberUserRow struct{ id uuid.UUID }
func (r memberUserRow) Scan(dst ...any) error {
*dst[0].(*pgtype.UUID) = pgtype.UUID{Bytes: [16]byte(r.id), Valid: true}
*dst[1].(*string) = "error_test_caller"
*dst[2].(*string) = "Error test caller"
*dst[3].(*string) = "unused password hash"
*dst[4].(*pgtype.Timestamptz) = pgtype.Timestamptz{Time: time.Unix(1, 0), Valid: true}
return nil
}
func TestErrorChatMemberLookupKeepsOperationMeaning(t *testing.T) {
for _, tc := range databaseErrorCases() {
if tc.status != 503 && tc.status != 404 && tc.status != 500 {
continue
}
t.Run(tc.name, func(t *testing.T) {
caller := uuid.New()
queries := sqlc.New(memberFaultDB{caller: caller, cause: tc.cause})
users := repository.NewUserRepository(queries)
// No writable repository: an invalid member list must never reach
// chat insertion. Accidentally continuing is a test failure.
chats := service.NewChatService(nil, users, service.NewUserService(users))
_, err := chats.Create(context.Background(), "Error regression", []string{caller.String(), uuid.NewString()}, caller.String())
want, status, code := tc.want, tc.status, tc.code
if tc.status == 404 {
// contracts/README.md:17: unknown members make POST /chats invalid.
want, status, code = service.ErrInvalidInput, 400, "invalid_request"
}
if !errors.Is(err, want) {
t.Fatalf("want category %v, got %v", want, err)
}
gotStatus, gotCode := httputils.ErrorFromService(err)
if gotStatus != status || gotCode != code {
t.Fatalf("want %d/%s, got %d/%s", status, code, gotStatus, gotCode)
}
})
}
}
func TestErrorMissingBasicPrecedesForbiddenBody(t *testing.T) {
mid := middleware.NewMiddleware(nil, "auth-test")
auth := handler.NewAuthHandler(nil)
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", strings.NewReader("{}"))
recorder := httptest.NewRecorder()
mid.RequestID(http.HandlerFunc(auth.CreateSession)).ServeHTTP(recorder, request)
assertContractError(t, recorder, 401, "unauthorized")
if recorder.Header().Get("WWW-Authenticate") != `Basic realm="messenger", charset="UTF-8"` {
t.Fatal("missing Basic challenge")
}
}
@@ -0,0 +1,202 @@
package auth_tests
import (
"context"
"encoding/json"
"errors"
"os"
"path/filepath"
"sync"
"testing"
"time"
"github.com/google/uuid"
redisclient "github.com/redis/go-redis/v9"
"highload/internal/repository"
)
type logoutObservationKey struct{}
type logoutObservation struct {
Group int `json:"clients"`
Round int `json:"round"`
PauseMS int `json:"pause_ms"`
ElapsedMS float64 `json:"elapsed_ms"`
WaitMS float64 `json:"waitaof_ms"`
DelID int64 `json:"del_connection_id"`
WaitID int64 `json:"wait_connection_id"`
Local *int64 `json:"local_fsynced"`
Replicas *int64 `json:"replicas_fsynced"`
Kind string `json:"kind"`
CommandError string `json:"command_error,omitempty"`
RepositoryError string `json:"repository_error,omitempty"`
}
type logoutAOFObservation struct{}
func (h logoutAOFObservation) DialHook(next redisclient.DialHook) redisclient.DialHook { return next }
func (h logoutAOFObservation) ProcessPipelineHook(next redisclient.ProcessPipelineHook) redisclient.ProcessPipelineHook {
return next
}
func (h logoutAOFObservation) ProcessHook(next redisclient.ProcessHook) redisclient.ProcessHook {
return func(ctx context.Context, cmd redisclient.Cmder) error {
started := time.Now()
err := next(ctx, cmd)
row, _ := ctx.Value(logoutObservationKey{}).(*logoutObservation)
if row == nil {
return err
}
name := cmd.Name()
if name != "del" && name != "waitaof" {
return err
}
if name == "waitaof" {
row.WaitMS = float64(time.Since(started)) / float64(time.Millisecond)
if err != nil {
row.CommandError = err.Error()
row.Kind = "command_error"
} else {
if value, ok := cmd.(*redisclient.Cmd); ok {
if reply, ok := value.Val().([]any); ok && len(reply) == 2 {
local, lok := reply[0].(int64)
replicas, rok := reply[1].(int64)
if lok && rok {
row.Local = &local
row.Replicas = &replicas
row.Kind = "acknowledged"
if local != 1 {
row.Kind = "unacknowledged"
}
}
}
}
if row.Local == nil {
row.Kind = "unexpected_reply"
}
}
}
if err == nil {
// next is bound to this Conn's processing path. The observation adds a
// read-only CLIENT ID on that same path; it never gets a second pool slot.
id := redisclient.NewIntCmd(ctx, "CLIENT", "ID")
if e := next(ctx, id); e == nil {
if name == "del" {
row.DelID = id.Val()
} else {
row.WaitID = id.Val()
}
}
}
return err
}
}
func TestRedisLogoutPersistenceDiagnostic(t *testing.T) {
f := newRedisFixture(t)
f.client.AddHook(logoutAOFObservation{})
before := f.client.PoolStats()
rows := []logoutObservation{}
var mu sync.Mutex
stop := make(chan struct{})
sampled := make(chan struct{})
poolSamples := []map[string]any{}
go func() {
defer close(sampled)
ticker := time.NewTicker(50 * time.Millisecond)
defer ticker.Stop()
for {
select {
case <-stop:
return
case <-ticker.C:
poolSamples = append(poolSamples, map[string]any{"at": time.Now().UTC().Format(time.RFC3339Nano), "stats": f.client.PoolStats()})
}
}
}()
defer func() {
close(stop)
<-sampled
deadline := time.Now().Add(time.Second)
for f.client.PoolStats().TotalConns != f.client.PoolStats().IdleConns && time.Now().Before(deadline) {
time.Sleep(10 * time.Millisecond)
}
after := f.client.PoolStats()
if after.TotalConns != after.IdleConns || after.PendingRequests != 0 {
t.Error("logout left acquired/pending pool connections")
}
report := map[string]any{"pool_before": before, "pool_after": after, "pool_samples": poolSamples, "samples": rows, "production_options": map[string]any{"read_timeout_ms": f.client.Options().ReadTimeout.Milliseconds(), "pool_size": f.client.Options().PoolSize, "pool_timeout_ms": f.client.Options().PoolTimeout.Milliseconds()}, "instrumentation": "read-only CLIENT ID after DEL and WAITAOF, on the pinned processing path"}
if directory := os.Getenv("AUTH_TEST_DIAGNOSTICS_DIR"); directory != "" {
_ = os.MkdirAll(directory, 0700)
data, _ := json.MarshalIndent(report, "", " ")
if os.WriteFile(filepath.Join(directory, "redis-logout.json"), data, 0600) != nil {
t.Error("cannot save Redis diagnostics")
}
}
t.Logf("logout samples=%d pool_wait_count=%d wait_ns=%d pool_timeouts=%d final_busy=%d", len(rows), after.WaitCount-before.WaitCount, after.WaitDurationNs-before.WaitDurationNs, after.Timeouts-before.Timeouts, after.TotalConns-after.IdleConns)
}()
run := func(clients, round, pause int) {
var workers sync.WaitGroup
start := make(chan struct{})
for range clients {
workers.Add(1)
go func() {
defer workers.Done()
// Two sessions for one synthetic identity: revoking one must leave the
// other valid, even while other workers revoke their own sessions.
first, other := f.trackSafe(uuid.NewString()), f.trackSafe(uuid.NewString())
user := uuid.NewString()
if _, err := f.repo.Create(f.ctx, first[:], user, time.Minute); err != nil {
t.Error("create logout fixture failed")
return
}
if _, err := f.repo.Create(f.ctx, other[:], user, time.Minute); err != nil {
t.Error("create independent fixture failed")
return
}
<-start
time.Sleep(time.Duration(pause) * time.Millisecond)
row := logoutObservation{Group: clients, Round: round, PauseMS: pause}
ctx := context.WithValue(f.ctx, logoutObservationKey{}, &row)
began := time.Now()
_, err := f.repo.RevokeSession(ctx, first[:])
row.ElapsedMS = float64(time.Since(began)) / float64(time.Millisecond)
if err != nil {
row.RepositoryError = err.Error()
t.Errorf("logout clients=%d kind=%s category=%v", clients, row.Kind, err)
}
if row.Kind == "unacknowledged" && !errors.Is(err, repository.ErrServiceUnavailable) {
t.Error("unacknowledged local fsync must preserve unavailable category")
}
if row.DelID == 0 || row.DelID != row.WaitID {
t.Error("DEL/WAITAOF connection identity not preserved")
}
if _, err = f.repo.GetSessionByTokenHash(f.ctx, other[:]); err != nil {
t.Error("concurrent logout affected independent session")
}
if _, err = f.repo.GetSessionByTokenHash(f.ctx, first[:]); !errors.Is(err, repository.ErrNotFound) {
t.Error("revoked session still available")
}
mu.Lock()
rows = append(rows, row)
mu.Unlock()
}()
}
close(start)
workers.Wait()
}
for i, pause := range []int{0, 137, 359, 613, 887, 1109} {
run(1, i+1, pause)
}
for _, clients := range []int{5, 10} {
for round := 1; round <= 3; round++ {
run(clients, round, 137*round)
}
}
}
// track modifies fixture cleanup bookkeeping; concurrent probes synchronize it.
var diagnosticTrackMu sync.Mutex
func (f *redisFixture) trackSafe(token string) [32]byte {
diagnosticTrackMu.Lock()
defer diagnosticTrackMu.Unlock()
return f.track(token)
}
+126
View File
@@ -0,0 +1,126 @@
package auth_tests
import (
"errors"
"strings"
"testing"
"highload/internal/security"
)
// These are tests of the selected Argon2id implementation, not a requirement
// that lab2 use particular parameters or a particular encoded hash format.
func TestPasswordRoundTripAndRandomSalt(t *testing.T) {
password := "Синтетический:пароль:😀"
first, err := security.HashPassword(password)
if err != nil {
t.Fatal("password hashing failed")
}
second, err := security.HashPassword(password)
if err != nil {
t.Fatal("password hashing failed")
}
if first == password || second == password || first == second {
t.Fatal("hash must differ from plaintext and have a fresh random salt")
}
if !strings.HasPrefix(first, "$argon2id$") {
t.Fatal("selected password implementation did not encode Argon2id")
}
for _, encoded := range []string{first, second} {
ok, err := security.VerifyPassword(password, encoded)
if err != nil || !ok {
t.Fatal("stored hash does not verify the original password")
}
ok, err = security.VerifyPassword(password+"x", encoded)
if err != nil || ok {
t.Fatal("wrong password was accepted or verifier failed")
}
}
}
func TestPasswordDoesNotTruncateLongUTF8(t *testing.T) {
// Both passwords share much more than bcrypt's 72-byte limit; each is
// within the lab's 128-code-point maximum.
password := strings.Repeat("😀", 127) + "A"
different := strings.Repeat("😀", 127) + "B"
encoded, err := security.HashPassword(password)
if err != nil {
t.Fatal("maximum-length UTF-8 password cannot be hashed")
}
ok, err := security.VerifyPassword(password, encoded)
if err != nil || !ok {
t.Fatal("maximum-length UTF-8 password cannot be verified")
}
ok, err = security.VerifyPassword(different, encoded)
if err != nil || ok {
t.Fatal("password suffix was truncated")
}
}
func TestPasswordWhitespaceIsSignificant(t *testing.T) {
password := " synthetic-password "
encoded, err := security.HashPassword(password)
if err != nil {
t.Fatal("password hashing failed")
}
ok, err := security.VerifyPassword(strings.TrimSpace(password), encoded)
if err != nil || ok {
t.Fatal("password whitespace was discarded")
}
}
func TestMalformedPasswordHashRejectedWithoutPanic(t *testing.T) {
valid, err := security.HashPassword("synthetic-password")
if err != nil {
t.Fatal("password hashing failed")
}
parts := strings.Split(valid, "$")
if len(parts) != 6 {
t.Fatal("unexpected encoded hash format")
}
cases := map[string]string{
"empty": "",
"plaintext": "synthetic-password",
"wrong_algorithm": strings.Replace(valid, "argon2id", "argon2i", 1),
"wrong_version": strings.Replace(valid, "$v=19$", "$v=999$", 1),
"missing_version": strings.Replace(valid, "$v=19$", "$19$", 1),
"extra_field": valid + "$extra",
}
for name, params := range map[string]string{
"zero_iterations": "m=65536,t=0,p=2",
"zero_threads": "m=65536,t=3,p=0",
"tiny_memory": "m=1,t=3,p=2",
"huge_memory": "m=4294967295,t=3,p=2",
"huge_iterations": "m=65536,t=4294967295,p=2",
"huge_threads": "m=65536,t=3,p=255",
"negative": "m=-1,t=3,p=2",
"non_numeric": "m=no,t=3,p=2",
"missing_param": "m=65536,t=3",
} {
copyParts := append([]string(nil), parts...)
copyParts[3] = params
cases[name] = strings.Join(copyParts, "$")
}
for name, field := range map[string]int{"salt": 4, "hash": 5} {
for label, value := range map[string]string{
"empty": "", "bad_base64": "!!!", "wrong_size": "YQ",
} {
copyParts := append([]string(nil), parts...)
copyParts[field] = value
cases[name+"_"+label] = strings.Join(copyParts, "$")
}
}
for name, encoded := range cases {
t.Run(name, func(t *testing.T) {
defer func() {
if recover() != nil {
t.Error("malformed stored hash caused a panic")
}
}()
ok, err := security.VerifyPassword("synthetic-password", encoded)
if ok || !errors.Is(err, security.ErrInvalidHash) {
t.Error("malformed stored hash was not rejected")
}
})
}
}
+455
View File
@@ -0,0 +1,455 @@
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")
}
})
}
}
@@ -0,0 +1,138 @@
package auth_tests
import (
"bytes"
"context"
"crypto/sha256"
"encoding/json"
"net/http"
"os"
"os/exec"
"strings"
"testing"
"time"
"github.com/google/uuid"
)
func TestRedisHTTPFullRestartKeepsDeadlineAndRevocation(t *testing.T) {
base, hook := os.Getenv("AUTH_TEST_BASE_URL"), os.Getenv("AUTH_TEST_STACK_RESTART_HOOK")
if base == "" || hook == "" {
t.Skip("set AUTH_TEST_BASE_URL and AUTH_TEST_STACK_RESTART_HOOK for a disposable API+stores stack")
}
for _, withLogout := range []bool{false, true} {
name := "active_only"
if withLogout {
name = "active_and_revoked"
}
t.Run(name, func(t *testing.T) {
f := newRedisFixture(t)
ctx, cancel := context.WithTimeout(context.Background(), 90*time.Second)
defer cancel()
client := &http.Client{Timeout: 5 * time.Second}
waitReady := func() {
t.Helper()
deadline := time.Now().Add(15 * time.Second)
for time.Now().Before(deadline) {
response, err := client.Get(strings.TrimRight(base, "/") + "/health/ready")
if err == nil {
response.Body.Close()
if response.StatusCode == http.StatusOK {
return
}
}
time.Sleep(100 * time.Millisecond)
}
t.Fatal("API did not regain readiness after restart")
}
waitReady()
username := "restart_" + strings.ReplaceAll(uuid.NewString(), "-", "")[:18]
password := "Synthetic:" + uuid.NewString()
call := func(method, path, token string, body any, basic bool, want int, dst any) {
t.Helper()
var data bytes.Buffer
if body != nil {
if json.NewEncoder(&data).Encode(body) != nil {
t.Fatal("cannot encode test request")
}
}
req, err := http.NewRequestWithContext(ctx, method, strings.TrimRight(base, "/")+path, &data)
if err != nil {
t.Fatal("cannot construct test request")
}
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if basic {
req.SetBasicAuth(username, password)
} else if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
response, err := client.Do(req)
if err != nil {
t.Fatal("restart HTTP request failed")
}
defer response.Body.Close()
if response.StatusCode != want {
t.Fatalf("%s %s: want %d, got %d", method, path, want, response.StatusCode)
}
if dst != nil && json.NewDecoder(response.Body).Decode(dst) != nil {
t.Fatal("invalid restart response JSON")
}
}
call("POST", "/api/v1/users", "", map[string]string{"username": username, "password": password, "display_name": "Restart fixture"}, false, 201, nil)
var active struct {
Token string `json:"token"`
ExpiresAt time.Time `json:"expires_at"`
}
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &active)
hash := f.track(active.Token)
before, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
if err != nil {
t.Fatal("cannot inspect issued session")
}
if !before.ExpiresAt.Equal(active.ExpiresAt) {
t.Fatal("HTTP and Redis expiry differ")
}
remaining := f.client.PTTL(ctx, f.keys[0]).Val()
if remaining < 2*time.Minute {
t.Fatal("normal restart suite requires long session TTL")
}
revoked := ""
if withLogout {
var other struct {
Token string `json:"token"`
}
call("POST", "/api/v1/auth/sessions", "", nil, true, 201, &other)
revoked = other.Token
f.track(revoked)
call("DELETE", "/api/v1/auth/sessions/current", revoked, nil, false, 204, nil)
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
}
if exec.CommandContext(ctx, hook).Run() != nil {
t.Fatal("real API+stores restart hook failed")
}
waitReady()
call("GET", "/health/live", "", nil, false, 200, nil)
call("GET", "/health/ready", "", nil, false, 200, nil)
call("GET", "/api/v1/users/me", active.Token, nil, false, 200, nil)
after, err := f.repo.GetSessionByTokenHash(ctx, hash[:])
if err != nil {
t.Fatal("restart lost session")
}
if !after.ExpiresAt.Equal(before.ExpiresAt) || after.UserID != before.UserID || !after.CreatedAt.Equal(before.CreatedAt) {
t.Fatal("actual API+Redis restart changed session identity/deadline")
}
if ttl := f.client.PTTL(ctx, f.keys[0]).Val(); ttl <= 0 || ttl >= remaining {
t.Fatal("restart reset/removed original TTL")
}
if revoked != "" {
call("GET", "/api/v1/users/me", revoked, nil, false, 401, nil)
revokedHash := sha256.Sum256([]byte(revoked))
if _, err = f.repo.GetSessionByTokenHash(ctx, revokedHash[:]); err == nil {
t.Fatal("revoked credential reappeared after restart")
}
}
})
}
}
+331
View File
@@ -0,0 +1,331 @@
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")
}
}
+163
View File
@@ -0,0 +1,163 @@
package auth_tests
import (
"context"
"encoding/json"
"io"
"net"
"net/http"
"net/http/httptest"
"strings"
"syscall"
"testing"
"time"
"highload/internal/database/sqlc"
repository "highload/internal/repository/postgres"
"highload/internal/service"
httptransport "highload/internal/transport/http"
"highload/internal/transport/http/handler"
"highload/internal/transport/http/middleware"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
)
type unavailableDB struct{}
type unavailableRow struct{}
func (unavailableRow) Scan(...any) error {
return &net.OpError{Op: "dial", Net: "tcp", Err: syscall.ECONNREFUSED}
}
func (unavailableDB) Exec(context.Context, string, ...any) (pgconn.CommandTag, error) {
return pgconn.CommandTag{}, unavailableRow{}.Scan()
}
func (unavailableDB) Query(context.Context, string, ...any) (pgx.Rows, error) {
return nil, unavailableRow{}.Scan()
}
func (unavailableDB) QueryRow(context.Context, string, ...any) pgx.Row {
return unavailableRow{}
}
func TestSQLUnavailableLoginStopsBeforeSessionCreation(t *testing.T) {
queries := sqlc.New(unavailableDB{})
auth := service.NewAuthService(repository.NewUserRepository(queries), nil, time.Hour)
mid := middleware.NewMiddleware(auth, "auth-test")
request := httptest.NewRequest(http.MethodPost, "/api/v1/auth/sessions", nil)
request.SetBasicAuth("synthetic_user", "Synthetic:password")
recorder := httptest.NewRecorder()
mid.RequestID(http.HandlerFunc(handler.NewAuthHandler(auth).CreateSession)).ServeHTTP(recorder, request)
assertContractError(t, recorder, 503, "unavailable")
}
func TestMiddlewareMalformedAuthWritesExactlyOneError(t *testing.T) {
// Invalid syntax must be rejected before asking an auth service or DB.
// A nil service deliberately makes an accidental dependency call visible.
mid := middleware.NewMiddleware(nil, "auth-test")
for _, header := range []string{"", "Basic invalid", "Bearer", "Bearer ",
"Bearer invalid token", "Digest invalid"} {
t.Run("malformed", func(t *testing.T) {
nextCalled := false
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { nextCalled = true })
request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil)
request.Header.Set("Authorization", header)
recorder := httptest.NewRecorder()
mid.RequestID(mid.Auth(next)).ServeHTTP(recorder, request)
if nextCalled || recorder.Code != http.StatusUnauthorized {
t.Fatal("malformed auth reached business handler or did not yield 401")
}
if recorder.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
t.Fatal("missing contract Bearer challenge")
}
var payload struct {
Error struct {
Code string `json:"code"`
RequestID string `json:"request_id"`
} `json:"error"`
}
decoder := json.NewDecoder(recorder.Body)
if err := decoder.Decode(&payload); err != nil {
t.Fatal("401 is not one valid JSON object")
}
if err := decoder.Decode(new(any)); err != io.EOF {
t.Fatal("middleware wrote more than one response after 401")
}
if payload.Error.Code != "unauthorized" || payload.Error.RequestID == "" ||
payload.Error.RequestID != recorder.Header().Get("X-Request-Id") {
t.Fatal("error request ID or code violates contract")
}
})
}
}
func TestStorageHTTPAuthRoutingAndLogout(t *testing.T) {
f := newFixture(t)
user, password := f.user(t)
userRepo := repository.NewUserRepository(f.queries)
chatRepo := repository.NewChatRepository(f.queries, f.pool)
chatService := service.NewChatService(chatRepo, userRepo, f.users)
messageService := service.NewMessageService(repository.NewMessageRepository(f.queries, f.pool), chatService, f.users)
router := httptransport.NewRouter(
middleware.NewMiddleware(f.auth, "auth-test"), handler.NewAuthHandler(f.auth),
handler.NewHealthHandler(f.pool, f.redis.client),
handler.NewChatHandler(chatService), handler.NewUserHandler(f.users),
handler.NewMessageHandler(messageService),
).Handler()
call := func(method, path, token string, login bool) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, path, nil)
if login {
request.SetBasicAuth(user.Username, password)
} else if token != "" {
request.Header.Set("Authorization", "Bearer "+token)
}
recorder := httptest.NewRecorder()
router.ServeHTTP(recorder, request)
if recorder.Header().Get("X-Request-Id") == "" {
t.Fatal("auth response missing X-Request-Id")
}
return recorder
}
defer func() {
if recover() != nil {
t.Error("auth router panicked; check constructor/handler wiring")
}
}()
response := call("POST", "/api/v1/auth/sessions", "", true)
if response.Code != 201 {
t.Fatal("Basic login route did not return 201")
}
var session struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
}
if err := json.Unmarshal(response.Body.Bytes(), &session); err != nil ||
session.Token == "" || session.TokenType != "Bearer" {
t.Fatal("login route returned invalid session")
}
other := f.session(t, user, password)
response = call("GET", "/api/v1/users/me", session.Token, false)
if response.Code != 200 || strings.Contains(response.Body.String(), "password") {
t.Fatal("Bearer user route failed or exposed password fields")
}
response = call("DELETE", "/api/v1/auth/sessions/current", session.Token, false)
if response.Code != 204 || response.Body.Len() != 0 {
t.Fatal("contract logout path must return empty 204")
}
for _, route := range [][2]string{
{"GET", "/api/v1/users/me"}, {"DELETE", "/api/v1/auth/sessions/current"},
} {
response = call(route[0], route[1], session.Token, false)
if response.Code != 401 || response.Header().Get("WWW-Authenticate") != "Bearer realm=\"messenger\"" {
t.Fatal("revoked token was accepted or challenged with wrong scheme")
}
}
if response := call("GET", "/api/v1/users/me", other.Token, false); response.Code != 200 {
t.Fatal("logout invalidated an independent session of the same user")
}
}