fix: validate message request fields

This commit is contained in:
2026-10-30 14:01:03 +03:00
parent 3815be3493
commit 05d9bb0ff2
3 changed files with 65 additions and 6 deletions
+4 -6
View File
@@ -208,18 +208,16 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
if !valid {
return invalidRequest()
}
var input struct {
Text string `json:"text"`
AttachmentIDs []string `json:"attachment_ids"`
}
var input createMessageRequest
if err := readJSON(w, r, &input); err != nil {
return err
}
if !validMessage(input.Text, input.AttachmentIDs) || !canonicalAttachmentIDs(input.AttachmentIDs) {
text, attachmentIDs, valid := input.values()
if !valid || !validMessage(text, attachmentIDs) || !canonicalAttachmentIDs(attachmentIDs) {
return invalidRequest()
}
message, replay, err := s.messageRepository.CreateMessage(
r.Context(), chatID, user.ID, input.Text, input.AttachmentIDs, key, s.idempotencyTTL,
r.Context(), chatID, user.ID, text, attachmentIDs, key, s.idempotencyTTL,
)
if errors.Is(err, model.ErrNotFound) {
return notFound()
+20
View File
@@ -20,6 +20,26 @@ const maxRequestBytes = 1 << 20
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
type createMessageRequest struct {
Text json.RawMessage `json:"text"`
AttachmentIDs json.RawMessage `json:"attachment_ids"`
}
func (r createMessageRequest) values() (string, []string, bool) {
var text *string
if len(r.Text) == 0 || json.Unmarshal(r.Text, &text) != nil || text == nil {
return "", nil, false
}
if len(r.AttachmentIDs) == 0 {
return *text, nil, true
}
var attachmentIDs *[]string
if json.Unmarshal(r.AttachmentIDs, &attachmentIDs) != nil || attachmentIDs == nil {
return "", nil, false
}
return *text, *attachmentIDs, true
}
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
+41
View File
@@ -259,6 +259,47 @@ func (s *MessengerSuite) TestMessageCreationValidatesIdempotencyKey() {
}
}
func (s *MessengerSuite) TestMessageCreationValidatesFieldPresenceAndTypes() {
store := messengerStoreStub{userByID: model.User{ID: "user-id"}}
server := s.newTestServer(store, sessionStub{userID: "user-id"}, passwordsStub{})
attachmentID := "00000000-0000-0000-0000-000000000002"
invalidBodies := []string{
`{"attachment_ids":["` + attachmentID + `"]}`,
`{"text":null,"attachment_ids":["` + attachmentID + `"]}`,
`{"text":"x","attachment_ids":null}`,
`{"text":1}`,
`{"text":"x","attachment_ids":{}}`,
}
for _, body := range invalidBodies {
response := createMessageRequestResponse(server, body)
s.Equal(http.StatusBadRequest, response.Code, body)
}
validBodies := []string{
`{"text":"message"}`,
`{"text":"message","attachment_ids":[]}`,
`{"text":"","attachment_ids":["` + attachmentID + `"]}`,
}
for _, body := range validBodies {
response := createMessageRequestResponse(server, body)
s.Equal(http.StatusCreated, response.Code, body)
}
}
func createMessageRequestResponse(server *Server, body string) *httptest.ResponseRecorder {
request := httptest.NewRequest(
http.MethodPost,
"/api/v1/chats/00000000-0000-0000-0000-000000000001/messages",
strings.NewReader(body),
)
request.Header.Set("Authorization", "Bearer valid-token")
request.Header.Set("Content-Type", "application/json")
request.Header.Set("Idempotency-Key", "message-key")
response := httptest.NewRecorder()
server.Handler().ServeHTTP(response, request)
return response
}
func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() {
t := s.T()
store := messengerStoreStub{