Skip to content

Commit 4cea63e

Browse files
AchoArnoldCopilot
andcommitted
feat: add attachment count, size, and content-type validation
Co-authored-by: Copilot <223556219+Copilot@users.noreply.github.com>
1 parent 38a1175 commit 4cea63e

1 file changed

Lines changed: 47 additions & 1 deletion

File tree

api/pkg/validators/message_handler_validator.go

Lines changed: 47 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -2,6 +2,7 @@ package validators
22

33
import (
44
"context"
5+
"encoding/base64"
56
"fmt"
67
"net/url"
78
"strings"
@@ -46,6 +47,11 @@ func NewMessageHandlerValidator(
4647
}
4748
}
4849

50+
const (
51+
maxAttachmentCount = 10
52+
maxAttachmentSize = (3 * 1024 * 1024) / 2 // 1.5 MB
53+
)
54+
4955
// ValidateMessageReceive validates the requests.MessageReceive request
5056
func (validator MessageHandlerValidator) ValidateMessageReceive(_ context.Context, request requests.MessageReceive) url.Values {
5157
v := govalidator.New(govalidator.Options{
@@ -73,7 +79,47 @@ func (validator MessageHandlerValidator) ValidateMessageReceive(_ context.Contex
7379
},
7480
})
7581

76-
return v.ValidateStruct()
82+
errors := v.ValidateStruct()
83+
84+
if len(request.Attachments) > 0 {
85+
attachmentErrors := validator.validateAttachments(request.Attachments)
86+
for key, values := range attachmentErrors {
87+
for _, value := range values {
88+
errors.Add(key, value)
89+
}
90+
}
91+
}
92+
93+
return errors
94+
}
95+
96+
func (validator MessageHandlerValidator) validateAttachments(attachments []requests.MessageAttachment) url.Values {
97+
errors := url.Values{}
98+
allowedTypes := repositories.AllowedContentTypes()
99+
100+
if len(attachments) > maxAttachmentCount {
101+
errors.Add("attachments", fmt.Sprintf("attachment count [%d] exceeds maximum of [%d]", len(attachments), maxAttachmentCount))
102+
return errors
103+
}
104+
105+
for i, attachment := range attachments {
106+
if !allowedTypes[attachment.ContentType] {
107+
errors.Add("attachments", fmt.Sprintf("attachment [%d] has unsupported content type [%s]", i, attachment.ContentType))
108+
continue
109+
}
110+
111+
decoded, err := base64.StdEncoding.DecodeString(attachment.Content)
112+
if err != nil {
113+
errors.Add("attachments", fmt.Sprintf("attachment [%d] has invalid base64 content", i))
114+
continue
115+
}
116+
117+
if len(decoded) > maxAttachmentSize {
118+
errors.Add("attachments", fmt.Sprintf("attachment [%d] size [%d] exceeds maximum of [%d] bytes", i, len(decoded), maxAttachmentSize))
119+
}
120+
}
121+
122+
return errors
77123
}
78124

79125
// ValidateMessageSend validates the requests.MessageSend request

0 commit comments

Comments
 (0)