forked from mtusi2026/mtusi2026lab3
Implement lab 3 level 4 failover and idempotency
This commit is contained in:
@@ -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")
|
||||
}
|
||||
|
||||
}
|
||||
Reference in New Issue
Block a user