From f08011385a156c45ca77153d30b17e06e610b3a8 Mon Sep 17 00:00:00 2001 From: Fedoroff Date: Tue, 27 Oct 2026 20:03:08 +0300 Subject: [PATCH] fix: address lab2 review feedback --- cmd/server/main.go | 16 +++++- internal/handler/chat.go | 77 ++++++++++++++++++++++++----- internal/handler/json_validation.go | 37 ++++++++++++++ internal/handler/message.go | 39 ++++++--------- internal/handler/regression_test.go | 46 +++++++++++++++++ internal/handler/session.go | 5 ++ internal/handler/user.go | 6 +-- internal/storage/auth_postgres.go | 14 ++++++ internal/storage/chat_postgres.go | 40 +++++++++++++++ internal/storage/session_cache.go | 32 ++++++------ internal/storage/session_service.go | 50 ++++++++++--------- 11 files changed, 280 insertions(+), 82 deletions(-) create mode 100644 internal/handler/json_validation.go create mode 100644 internal/handler/regression_test.go diff --git a/cmd/server/main.go b/cmd/server/main.go index 77e18ba6..6cdcdaff 100644 --- a/cmd/server/main.go +++ b/cmd/server/main.go @@ -147,7 +147,7 @@ func main() { server := &http.Server{ Addr: host + ":" + port, - Handler: middleware.RequestID(mux), + Handler: middleware.RequestID(databaseDeadline(mux)), ReadHeaderTimeout: 5 * time.Second, ReadTimeout: 15 * time.Second, WriteTimeout: 15 * time.Second, @@ -189,3 +189,17 @@ func writeHealthOK(w http.ResponseWriter) { w.WriteHeader(http.StatusOK) _, _ = w.Write([]byte(`{"status":"ok"}`)) } + +// databaseDeadline bounds every API request, including queries on already-open +// PostgreSQL connections. The handler maps context/driver errors to HTTP 503. +func databaseDeadline(next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + if r.URL.Path == "/health/live" { + next.ServeHTTP(w, r) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 5*time.Second) + defer cancel() + next.ServeHTTP(w, r.WithContext(ctx)) + }) +} diff --git a/internal/handler/chat.go b/internal/handler/chat.go index 866331f7..280d4539 100644 --- a/internal/handler/chat.go +++ b/internal/handler/chat.go @@ -1,9 +1,11 @@ package handler import ( - "encoding/json" + "encoding/base64" "errors" + "fmt" "net/http" + "strconv" "strings" "time" "unicode/utf8" @@ -42,10 +44,7 @@ func (h *ChatHandler) Create(w http.ResponseWriter, r *http.Request) { } var req createChatRequest - decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - - if err := decoder.Decode(&req); err != nil { + if err := decodeOneObject(r, &req); err != nil { writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid request body") return @@ -132,17 +131,45 @@ func (h *ChatHandler) List(w http.ResponseWriter, r *http.Request) { return } - chats, err := h.store.ListChatsForUser(r.Context(), currentUser.ID) + limit := 50 + if values, exists := r.URL.Query()["limit"]; exists { + if len(values) != 1 { + writeError(w, r, 400, "invalid_request", "invalid limit") + return + } + n, err := strconv.Atoi(values[0]) + if err != nil || n < 1 || n > 100 { + writeError(w, r, 400, "invalid_request", "limit must be between 1 and 100") + return + } + limit = n + } + var cursorTime *time.Time + var cursorID *uuid.UUID + if values, exists := r.URL.Query()["cursor"]; exists { + if len(values) != 1 || values[0] == "" { + writeError(w, r, 400, "invalid_request", "invalid cursor") + return + } + t, id, err := decodeChatCursor(values[0], currentUser.ID) + if err != nil { + writeError(w, r, 400, "invalid_request", "invalid cursor") + return + } + cursorTime = &t + cursorID = &id + } + chats, more, err := h.store.ListChatsPage(r.Context(), currentUser.ID, limit, cursorTime, cursorID) if err != nil { - writeError(w, r, http.StatusServiceUnavailable, - "unavailable", "service unavailable") + writeError(w, r, 503, "unavailable", "service unavailable") return } - - writeJSON(w, http.StatusOK, chatPage{ - Items: chats, - NextCursor: nil, - }) + var next *string + if more && len(chats) > 0 { + c := encodeChatCursor(currentUser.ID, chats[len(chats)-1]) + next = &c + } + writeJSON(w, 200, chatPage{Items: chats, NextCursor: next}) } func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { @@ -176,3 +203,27 @@ func (h *ChatHandler) Get(w http.ResponseWriter, r *http.Request) { writeJSON(w, http.StatusOK, chat) } + +func encodeChatCursor(userID uuid.UUID, chat model.Chat) string { + value := fmt.Sprintf("%s|%s|%s", userID, chat.CreatedAt.Format(time.RFC3339Nano), chat.ID) + return base64.RawURLEncoding.EncodeToString([]byte(value)) +} +func decodeChatCursor(cursor string, userID uuid.UUID) (time.Time, uuid.UUID, error) { + data, err := base64.RawURLEncoding.DecodeString(cursor) + if err != nil { + return time.Time{}, uuid.Nil, err + } + parts := strings.Split(string(data), "|") + if len(parts) != 3 || parts[0] != userID.String() { + return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor") + } + t, err := time.Parse(time.RFC3339Nano, parts[1]) + if err != nil { + return time.Time{}, uuid.Nil, err + } + id, err := uuid.Parse(parts[2]) + if err != nil { + return time.Time{}, uuid.Nil, err + } + return t, id, nil +} diff --git a/internal/handler/json_validation.go b/internal/handler/json_validation.go new file mode 100644 index 00000000..e7025e70 --- /dev/null +++ b/internal/handler/json_validation.go @@ -0,0 +1,37 @@ +package handler + +import ( + "encoding/json" + "errors" + "io" + "net/http" +) + +// decodeOneObject rejects a second JSON value, trailing garbage and unknown fields. +func decodeOneObject(r *http.Request, target any) error { + dec := json.NewDecoder(io.LimitReader(r.Body, 1<<20)) + dec.DisallowUnknownFields() + if err := dec.Decode(target); err != nil { + return err + } + var extra any + if err := dec.Decode(&extra); !errors.Is(err, io.EOF) { + if err != nil { + return err + } + return errors.New("multiple JSON values") + } + return nil +} + +func requireEmptyBody(r *http.Request) error { + // A whitespace-only body is accepted as empty; any JSON or other bytes are not. + data, err := io.ReadAll(io.LimitReader(r.Body, 2)) + if err != nil { + return err + } + if len(data) != 0 { + return errors.New("request body must be empty") + } + return nil +} diff --git a/internal/handler/message.go b/internal/handler/message.go index 3827fdbd..10e46397 100644 --- a/internal/handler/message.go +++ b/internal/handler/message.go @@ -2,7 +2,6 @@ package handler import ( "encoding/base64" - "encoding/json" "errors" "fmt" "net/http" @@ -86,17 +85,14 @@ func (h *MessageHandler) Create(w http.ResponseWriter, r *http.Request) { currentUser, _ := middleware.GetCurrentUser(r.Context()) var req createMessageRequest - decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - - if err := decoder.Decode(&req); err != nil { + if err := decodeOneObject(r, &req); err != nil { writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid request body") return } textLength := utf8.RuneCountInString(req.Text) - if textLength < 1 || textLength > 4000 { + if strings.TrimSpace(req.Text) == "" || textLength > 4000 { writeError(w, r, http.StatusBadRequest, "invalid_request", "text must contain from 1 to 4000 characters") return @@ -146,7 +142,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { var cursorID *uuid.UUID if raw := r.URL.Query().Get("cursor"); raw != "" { - t, id, err := decodeCursor(raw) + t, id, err := decodeMessageCursor(raw, chatID) if err != nil { writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid cursor") @@ -167,7 +163,7 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { var nextCursor *string if hasMore && len(items) > 0 { - cursor := encodeCursor(items[len(items)-1]) + cursor := encodeMessageCursor(items[len(items)-1]) nextCursor = &cursor } @@ -177,35 +173,28 @@ func (h *MessageHandler) List(w http.ResponseWriter, r *http.Request) { }) } -func encodeCursor(message model.Message) string { - value := fmt.Sprintf( - "%s|%s", - message.CreatedAt.Format(time.RFC3339Nano), - message.ID.String(), - ) +// Cursor contains the chat UUID to prevent cross-chat replay. +func encodeMessageCursor(message model.Message) string { + value := fmt.Sprintf("%s|%s|%s", message.ChatID, message.CreatedAt.Format(time.RFC3339Nano), message.ID) return base64.RawURLEncoding.EncodeToString([]byte(value)) } -func decodeCursor(cursor string) (time.Time, uuid.UUID, error) { +func decodeMessageCursor(cursor string, chatID uuid.UUID) (time.Time, uuid.UUID, error) { data, err := base64.RawURLEncoding.DecodeString(cursor) if err != nil { return time.Time{}, uuid.Nil, err } - - parts := strings.SplitN(string(data), "|", 2) - if len(parts) != 2 { - return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor") + parts := strings.Split(string(data), "|") + if len(parts) != 3 || parts[0] != chatID.String() { + return time.Time{}, uuid.Nil, fmt.Errorf("invalid cursor for chat") } - - createdAt, err := time.Parse(time.RFC3339Nano, parts[0]) + t, err := time.Parse(time.RFC3339Nano, parts[1]) if err != nil { return time.Time{}, uuid.Nil, err } - - id, err := uuid.Parse(parts[1]) + id, err := uuid.Parse(parts[2]) if err != nil { return time.Time{}, uuid.Nil, err } - - return createdAt, id, nil + return t, id, nil } diff --git a/internal/handler/regression_test.go b/internal/handler/regression_test.go new file mode 100644 index 00000000..3f7c2036 --- /dev/null +++ b/internal/handler/regression_test.go @@ -0,0 +1,46 @@ +package handler + +import ( + "github.com/google/uuid" + "mtusi2026lab2/internal/model" + "net/http/httptest" + "strings" + "testing" + "time" +) + +func TestStrictJSON(t *testing.T) { + for _, body := range []string{`{"text":"hello"} garbage`, `{"text":"hello"}{"text":"again"}`} { + req := httptest.NewRequest("POST", "/", strings.NewReader(body)) + var v createMessageRequest + if err := decodeOneObject(req, &v); err == nil { + t.Fatalf("accepted trailing JSON: %q", body) + } + } +} +func TestMessageCursorBoundToChat(t *testing.T) { + chatA, chatB := uuid.New(), uuid.New() + cursor := encodeMessageCursor(model.Message{ID: uuid.New(), ChatID: chatA, CreatedAt: time.Now().UTC()}) + if _, _, err := decodeMessageCursor(cursor, chatA); err != nil { + t.Fatal(err) + } + if _, _, err := decodeMessageCursor(cursor, chatB); err == nil { + t.Fatal("accepted cursor for another chat") + } +} +func TestChatCursorBoundToUser(t *testing.T) { + a, b := uuid.New(), uuid.New() + cursor := encodeChatCursor(a, model.Chat{ID: uuid.New(), CreatedAt: time.Now().UTC()}) + if _, _, err := decodeChatCursor(cursor, a); err != nil { + t.Fatal(err) + } + if _, _, err := decodeChatCursor(cursor, b); err == nil { + t.Fatal("accepted cursor for another user") + } +} +func TestEmptyLoginBody(t *testing.T) { + req := httptest.NewRequest("POST", "/", strings.NewReader(`{"ignored":true}`)) + if err := requireEmptyBody(req); err == nil { + t.Fatal("accepted login body") + } +} diff --git a/internal/handler/session.go b/internal/handler/session.go index e838a305..8c474fd7 100644 --- a/internal/handler/session.go +++ b/internal/handler/session.go @@ -53,6 +53,11 @@ func (h *SessionHandler) Create(w http.ResponseWriter, r *http.Request) { `Basic realm="messenger", charset="UTF-8"`, ) + if err := requireEmptyBody(r); err != nil { + writeError(w, r, http.StatusBadRequest, "invalid_request", "request body must be empty") + return + } + username, password, ok := r.BasicAuth() if !ok || username == "" || password == "" { writeError(w, r, http.StatusUnauthorized, diff --git a/internal/handler/user.go b/internal/handler/user.go index 23523fa4..af00e1f3 100644 --- a/internal/handler/user.go +++ b/internal/handler/user.go @@ -4,7 +4,6 @@ import ( "crypto/rand" "crypto/subtle" "encoding/base64" - "encoding/json" "errors" "net/http" "regexp" @@ -87,10 +86,7 @@ func VerifyPassword(password, encoded string) bool { func (h *UserHandler) Create(w http.ResponseWriter, r *http.Request) { var req createUserRequest - decoder := json.NewDecoder(r.Body) - decoder.DisallowUnknownFields() - - if err := decoder.Decode(&req); err != nil { + if err := decodeOneObject(r, &req); err != nil { writeError(w, r, http.StatusBadRequest, "invalid_request", "invalid request body") return diff --git a/internal/storage/auth_postgres.go b/internal/storage/auth_postgres.go index 5321c602..7b94dc99 100644 --- a/internal/storage/auth_postgres.go +++ b/internal/storage/auth_postgres.go @@ -199,3 +199,17 @@ func (s *AuthStore) RevokeSession( } return nil } + +// GetActiveSessionUserID is the authoritative expiry/revocation check. +// Redis only caches the public user profile; it never grants access on its own. +func (s *AuthStore) GetActiveSessionUserID(ctx context.Context, token string) (uuid.UUID, error) { + var userID uuid.UUID + err := s.pool.QueryRow(ctx, `SELECT user_id FROM sessions WHERE token_hash=$1 AND expires_at>NOW()`, tokenHash(token)).Scan(&userID) + if errors.Is(err, pgx.ErrNoRows) { + return uuid.Nil, ErrSessionNotFound + } + if err != nil { + return uuid.Nil, fmt.Errorf("validate session: %w", err) + } + return userID, nil +} diff --git a/internal/storage/chat_postgres.go b/internal/storage/chat_postgres.go index 2399cbab..054b7838 100644 --- a/internal/storage/chat_postgres.go +++ b/internal/storage/chat_postgres.go @@ -203,3 +203,43 @@ func (s *ChatStore) ExistsUser( // Kept here to document that chat timestamps are stored in UTC. var _ = time.UTC + +// ListChatsPage uses (created_at,id) keyset pagination and fetches limit+1. +func (s *ChatStore) ListChatsPage(ctx context.Context, userID uuid.UUID, limit int, cursorTime *time.Time, cursorID *uuid.UUID) ([]model.Chat, bool, error) { + var rows pgx.Rows + var err error + if cursorTime == nil || cursorID == nil { + rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 ORDER BY c.created_at,c.id LIMIT $2`, userID, limit+1) + } else { + rows, err = s.pool.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members cm ON cm.chat_id=c.id WHERE cm.user_id=$1 AND (c.created_at,c.id)>($2,$3) ORDER BY c.created_at,c.id LIMIT $4`, userID, *cursorTime, *cursorID, limit+1) + } + if err != nil { + return nil, false, fmt.Errorf("list chats: %w", err) + } + chats := make([]model.Chat, 0, limit+1) + for rows.Next() { + var c model.Chat + if err := rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + rows.Close() + return nil, false, err + } + chats = append(chats, c) + } + if err := rows.Err(); err != nil { + rows.Close() + return nil, false, err + } + rows.Close() + more := len(chats) > limit + if more { + chats = chats[:limit] + } + for i := range chats { + members, err := s.getMemberIDs(ctx, chats[i].ID) + if err != nil { + return nil, false, err + } + chats[i].MemberIDs = members + } + return chats, more, nil +} diff --git a/internal/storage/session_cache.go b/internal/storage/session_cache.go index 6e38d00d..9a713413 100644 --- a/internal/storage/session_cache.go +++ b/internal/storage/session_cache.go @@ -4,11 +4,13 @@ import ( "context" "crypto/sha256" "encoding/hex" + "encoding/json" "errors" "fmt" "time" - "github.com/google/uuid" + "mtusi2026lab2/internal/model" + "github.com/redis/go-redis/v9" ) @@ -48,7 +50,7 @@ func cacheKey(token string) string { func (c *SessionCache) Set( ctx context.Context, token string, - userID uuid.UUID, + user model.User, expiresAt time.Time, ) error { ttl := time.Until(expiresAt) @@ -56,33 +58,31 @@ func (c *SessionCache) Set( return nil } - return c.client.Set( - ctx, - cacheKey(token), - userID.String(), - ttl, - ).Err() + payload, err := json.Marshal(user) + if err != nil { + return err + } + return c.client.Set(ctx, cacheKey(token), payload, ttl).Err() } func (c *SessionCache) Get( ctx context.Context, token string, -) (uuid.UUID, bool, error) { +) (model.User, bool, error) { value, err := c.client.Get(ctx, cacheKey(token)).Result() if errors.Is(err, redis.Nil) { - return uuid.Nil, false, nil + return model.User{}, false, nil } if err != nil { - return uuid.Nil, false, err + return model.User{}, false, err } - userID, err := uuid.Parse(value) - if err != nil { - return uuid.Nil, false, err + var user model.User + if err := json.Unmarshal([]byte(value), &user); err != nil { + return model.User{}, false, err } - - return userID, true, nil + return user, true, nil } func (c *SessionCache) Delete( diff --git a/internal/storage/session_service.go b/internal/storage/session_service.go index 84c7084f..ffcc2a4b 100644 --- a/internal/storage/session_service.go +++ b/internal/storage/session_service.go @@ -37,38 +37,44 @@ func (s *SessionService) CreateSession( return err } + // Populate the profile cache best-effort after the authoritative INSERT. if s.cache != nil { - cacheCtx, cancel := context.WithTimeout( - context.Background(), 2*time.Second, - ) - defer cancel() - - _ = s.cache.Set(cacheCtx, token, userID, expiresAt) + user, err := s.db.GetUserByID(ctx, userID) + if err == nil { + cacheCtx, cancel := context.WithTimeout(context.Background(), 250*time.Millisecond) + _ = s.cache.Set(cacheCtx, token, user, expiresAt) + cancel() + } } return nil } -func (s *SessionService) GetSessionUser( - ctx context.Context, - token string, -) (model.User, error) { - // PostgreSQL remains the source of truth. - user, err := s.db.GetSessionUser(ctx, token) +func (s *SessionService) GetSessionUser(ctx context.Context, token string) (model.User, error) { + // A cheap indexed PostgreSQL check on EVERY request enforces expiry and logout, + // even if Redis contains a stale value or its deletion fails. + userID, err := s.db.GetActiveSessionUserID(ctx, token) if err != nil { return model.User{}, err } - - // Redis is best-effort and cannot extend a session. if s.cache != nil { - cacheCtx, cancel := context.WithTimeout( - context.Background(), 2*time.Second, - ) - defer cancel() - - _, _, _ = s.cache.Get(cacheCtx, token) + cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond) + cached, hit, err := s.cache.Get(cacheCtx, token) + cancel() + if err == nil && hit && cached.ID == userID { + return cached, nil + } + } + user, err := s.db.GetUserByID(ctx, userID) + if err != nil { + return model.User{}, err + } + if s.cache != nil { + cacheCtx, cancel := context.WithTimeout(ctx, 250*time.Millisecond) + // Conservative short TTL on read-through; session lifetime is still checked in PostgreSQL. + _ = s.cache.Set(cacheCtx, token, user, time.Now().Add(30*time.Second)) + cancel() } - return user, nil } @@ -82,7 +88,7 @@ func (s *SessionService) RevokeSession( if s.cache != nil { cacheCtx, cancel := context.WithTimeout( - context.Background(), 2*time.Second, + context.Background(), 250*time.Millisecond, ) defer cancel()