forked from mtusi2026/mtusi2026lab5
fix: validate message request fields
This commit is contained in:
@@ -208,18 +208,16 @@ func (s *Server) messages(w http.ResponseWriter, r *http.Request) *apiError {
|
|||||||
if !valid {
|
if !valid {
|
||||||
return invalidRequest()
|
return invalidRequest()
|
||||||
}
|
}
|
||||||
var input struct {
|
var input createMessageRequest
|
||||||
Text string `json:"text"`
|
|
||||||
AttachmentIDs []string `json:"attachment_ids"`
|
|
||||||
}
|
|
||||||
if err := readJSON(w, r, &input); err != nil {
|
if err := readJSON(w, r, &input); err != nil {
|
||||||
return err
|
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()
|
return invalidRequest()
|
||||||
}
|
}
|
||||||
message, replay, err := s.messageRepository.CreateMessage(
|
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) {
|
if errors.Is(err, model.ErrNotFound) {
|
||||||
return notFound()
|
return notFound()
|
||||||
|
|||||||
@@ -20,6 +20,26 @@ const maxRequestBytes = 1 << 20
|
|||||||
|
|
||||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
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 {
|
func readJSON(w http.ResponseWriter, r *http.Request, target any) *apiError {
|
||||||
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
mediaType, params, err := mime.ParseMediaType(r.Header.Get("Content-Type"))
|
||||||
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
if err != nil || mediaType != "application/json" || (params["charset"] != "" && !strings.EqualFold(params["charset"], "utf-8")) {
|
||||||
|
|||||||
@@ -263,6 +263,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() {
|
func (s *MessengerSuite) TestMessageCreationReturnsConflictForReusedKeyWithDifferentBody() {
|
||||||
t := s.T()
|
t := s.T()
|
||||||
store := messengerStoreStub{
|
store := messengerStoreStub{
|
||||||
|
|||||||
Reference in New Issue
Block a user