fix: address lab2 review feedback

This commit is contained in:
Fedoroff
2026-10-27 20:03:08 +03:00
parent c251f2cb7d
commit f08011385a
11 changed files with 280 additions and 82 deletions
+64 -13
View File
@@ -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
}
+37
View File
@@ -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
}
+14 -25
View File
@@ -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
}
+46
View File
@@ -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")
}
}
+5
View File
@@ -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,
+1 -5
View File
@@ -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