forked from mtusi2026/mtusi2026lab5
chore(migrate) moved codebase from lab4
This commit is contained in:
@@ -0,0 +1,64 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestValidateFilename(t *testing.T) {
|
||||
valid := []string{"photo.png", "фото 1.jpeg", "a", strings.Repeat("a", 255)}
|
||||
for _, name := range valid {
|
||||
if err := ValidateFilename(name); err != nil {
|
||||
t.Errorf("ValidateFilename(%q) = %v, want nil", name, err)
|
||||
}
|
||||
}
|
||||
|
||||
invalid := []string{
|
||||
"", " ", ".", "..", "dir/photo.png", `dir\photo.png`,
|
||||
"nul\x00byte", "line\nbreak", strings.Repeat("a", 256),
|
||||
}
|
||||
for _, name := range invalid {
|
||||
if err := ValidateFilename(name); err == nil {
|
||||
t.Errorf("ValidateFilename(%q) = nil, want error", name)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateAttachmentIDs(t *testing.T) {
|
||||
ids := make([]uuid.UUID, 10)
|
||||
for index := range ids {
|
||||
ids[index] = uuid.New()
|
||||
}
|
||||
if err := ValidateAttachmentIDs(ids); err != nil {
|
||||
t.Fatalf("ten unique ids rejected: %v", err)
|
||||
}
|
||||
if err := ValidateAttachmentIDs(append(ids, uuid.New())); err == nil {
|
||||
t.Fatal("eleven ids accepted")
|
||||
}
|
||||
if err := ValidateAttachmentIDs([]uuid.UUID{ids[0], ids[0]}); err == nil {
|
||||
t.Fatal("duplicate ids accepted")
|
||||
}
|
||||
if err := ValidateAttachmentIDs(nil); err != nil {
|
||||
t.Fatalf("empty list rejected: %v", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestValidateMessageText(t *testing.T) {
|
||||
if err := ValidateMessageText("", 1); err != nil {
|
||||
t.Fatalf("empty text with attachment rejected: %v", err)
|
||||
}
|
||||
if err := ValidateMessageText(" ", 1); err != nil {
|
||||
t.Fatalf("blank text with attachment rejected: %v", err)
|
||||
}
|
||||
if err := ValidateMessageText("", 0); err == nil {
|
||||
t.Fatal("empty text without attachment accepted")
|
||||
}
|
||||
if err := ValidateMessageText(strings.Repeat("ж", 4000), 0); err != nil {
|
||||
t.Fatalf("4000 code points rejected: %v", err)
|
||||
}
|
||||
if err := ValidateMessageText(strings.Repeat("ж", 4001), 1); err == nil {
|
||||
t.Fatal("4001 code points accepted")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,63 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"strings"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
)
|
||||
|
||||
// ReadBodyLimited reads at most limit bytes from the request body. The caller
|
||||
// must use it instead of c.Body() when the endpoint has a smaller budget than
|
||||
// the process-wide Fiber.BodyLimit. The limit itself belongs to the caller
|
||||
// (config.MaxJSONBodyBytes for JSON endpoints).
|
||||
//
|
||||
// with StreamRequestBody enabled fasthttp exposes the network body as a
|
||||
// stream, so io.ReadAll over a LimitReader allocates only the bytes the
|
||||
// endpoint actually accepts instead of the whole upload limit.
|
||||
func ReadBodyLimited(c fiber.Ctx, limit int64) ([]byte, error) {
|
||||
var reader io.Reader = c.Request().BodyStream()
|
||||
if reader == nil {
|
||||
reader = bytes.NewReader(c.Body())
|
||||
}
|
||||
|
||||
data, err := io.ReadAll(io.LimitReader(reader, limit+1))
|
||||
if err != nil {
|
||||
return nil, BadRequest("incomplete request body")
|
||||
}
|
||||
if int64(len(data)) > limit {
|
||||
return nil, PayloadTooLarge("request body is too large")
|
||||
}
|
||||
|
||||
return data, nil
|
||||
}
|
||||
|
||||
func BindJSON(c fiber.Ctx, dst any, limit int64) error {
|
||||
if contentType := c.Get(fiber.HeaderContentType); !strings.HasPrefix(contentType, "application/json") {
|
||||
return UnsupportedMedia("invalid JSON body")
|
||||
}
|
||||
|
||||
body, err := ReadBodyLimited(c, limit)
|
||||
if err != nil {
|
||||
return err
|
||||
}
|
||||
if len(body) == 0 {
|
||||
return BadRequest("request body is empty")
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
|
||||
if err := decoder.Decode(dst); err != nil {
|
||||
return BadRequest("invalid JSON body")
|
||||
}
|
||||
|
||||
var extra json.RawMessage
|
||||
if err := decoder.Decode(&extra); err != io.EOF {
|
||||
return BadRequest("request body has extra trailing bytes")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,142 @@
|
||||
// Package common contains cross-cutting HTTP helpers: contract errors, JSON
|
||||
// binding, validation, cursor pagination and timestamp formatting.
|
||||
package common
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/gofiber/fiber/v3/middleware/requestid"
|
||||
)
|
||||
|
||||
const (
|
||||
ErrorCodeInvalidRequest = "invalid_request"
|
||||
ErrorCodeUnauthorized = "unauthorized"
|
||||
ErrorCodeNotFound = "not_found"
|
||||
ErrorCodeConflict = "conflict"
|
||||
ErrorCodePayloadTooLarge = "payload_too_large"
|
||||
ErrorCodeUnsupportedMedia = "unsupported_media_type"
|
||||
ErrorCodeRateLimited = "rate_limited"
|
||||
ErrorCodeUnavailable = "unavailable"
|
||||
ErrorCodeInternal = "internal_error"
|
||||
)
|
||||
|
||||
type APIErrorResponse struct {
|
||||
Error APIError `json:"error"`
|
||||
}
|
||||
|
||||
type APIError struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
func NewError(code, message, requestID string) APIErrorResponse {
|
||||
return APIErrorResponse{
|
||||
Error: APIError{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestID,
|
||||
},
|
||||
}
|
||||
}
|
||||
|
||||
// AppError is the single contract error type. Handlers and the store return it;
|
||||
// the Fiber error handler is the only place that turns it into a response.
|
||||
type AppError struct {
|
||||
Status int
|
||||
Code string
|
||||
Message string
|
||||
Challenge string // WWW-Authenticate value, set for 401 responses
|
||||
}
|
||||
|
||||
func (e *AppError) Error() string {
|
||||
return e.Message
|
||||
}
|
||||
|
||||
func NewAppError(status int, code, message string) *AppError {
|
||||
return &AppError{
|
||||
Status: status,
|
||||
Code: code,
|
||||
Message: message,
|
||||
}
|
||||
}
|
||||
|
||||
func BadRequest(message string) *AppError {
|
||||
return NewAppError(http.StatusBadRequest, ErrorCodeInvalidRequest, message)
|
||||
}
|
||||
|
||||
func NotFound(message string) *AppError {
|
||||
return NewAppError(http.StatusNotFound, ErrorCodeNotFound, message)
|
||||
}
|
||||
|
||||
func Conflict(message string) *AppError {
|
||||
return NewAppError(http.StatusConflict, ErrorCodeConflict, message)
|
||||
}
|
||||
|
||||
func UnsupportedMedia(message string) *AppError {
|
||||
return NewAppError(http.StatusUnsupportedMediaType, ErrorCodeUnsupportedMedia, message)
|
||||
}
|
||||
|
||||
func PayloadTooLarge(message string) *AppError {
|
||||
return NewAppError(http.StatusRequestEntityTooLarge, ErrorCodePayloadTooLarge, message)
|
||||
}
|
||||
|
||||
func Internal() *AppError {
|
||||
return NewAppError(http.StatusInternalServerError, ErrorCodeInternal, "Internal server error")
|
||||
}
|
||||
|
||||
func Unavailable(message string) *AppError {
|
||||
return NewAppError(http.StatusServiceUnavailable, ErrorCodeUnavailable, message)
|
||||
}
|
||||
|
||||
// NewChallenge builds the 401 that carries a WWW-Authenticate header.
|
||||
func NewChallenge(challenge, message string) *AppError {
|
||||
return &AppError{
|
||||
Status: http.StatusUnauthorized,
|
||||
Code: ErrorCodeUnauthorized,
|
||||
Message: message,
|
||||
Challenge: challenge,
|
||||
}
|
||||
}
|
||||
|
||||
// IsCode reports whether err is an AppError with the given contract code.
|
||||
func IsCode(err error, code string) bool {
|
||||
appErr, ok := errors.AsType[*AppError](err)
|
||||
return ok && appErr.Code == code
|
||||
}
|
||||
|
||||
func ErrorCodeFromStatus(status int) string {
|
||||
switch status {
|
||||
case http.StatusBadRequest:
|
||||
return ErrorCodeInvalidRequest
|
||||
case http.StatusUnauthorized:
|
||||
return ErrorCodeUnauthorized
|
||||
case http.StatusNotFound:
|
||||
return ErrorCodeNotFound
|
||||
case http.StatusConflict:
|
||||
return ErrorCodeConflict
|
||||
case http.StatusRequestEntityTooLarge:
|
||||
return ErrorCodePayloadTooLarge
|
||||
case http.StatusUnsupportedMediaType:
|
||||
return ErrorCodeUnsupportedMedia
|
||||
case http.StatusTooManyRequests:
|
||||
return ErrorCodeRateLimited
|
||||
case http.StatusServiceUnavailable:
|
||||
return ErrorCodeUnavailable
|
||||
default:
|
||||
return ErrorCodeInternal
|
||||
}
|
||||
}
|
||||
|
||||
func getRequestID(c fiber.Ctx) string {
|
||||
if id := string(c.Response().Header.Peek("X-Request-Id")); id != "" {
|
||||
return id
|
||||
}
|
||||
return requestid.FromContext(c)
|
||||
}
|
||||
|
||||
func SendError(c fiber.Ctx, status int, code, message string) error {
|
||||
return c.Status(status).JSON(NewError(code, message, getRequestID(c)))
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestValidateIdempotencyKey(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
key string
|
||||
ok bool
|
||||
}{
|
||||
{name: "hex", key: "4f8c2d1e", ok: true},
|
||||
{name: "allowed punctuation", key: "load-1_a.b:c", ok: true},
|
||||
{name: "empty", key: "", ok: false},
|
||||
{name: "space", key: "two words", ok: false},
|
||||
{name: "slash", key: "a/b", ok: false},
|
||||
{name: "too long", key: strings.Repeat("a", 129), ok: false},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
got := ValidateIdempotencyKey(test.key) == nil
|
||||
if got != test.ok {
|
||||
t.Fatalf("ValidateIdempotencyKey(%q) valid = %v, want %v", test.key, got, test.ok)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,39 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
KeyUserID = "userID"
|
||||
KeySessionToken = "sessionToken"
|
||||
)
|
||||
|
||||
func UserID(c fiber.Ctx) (uuid.UUID, bool) {
|
||||
userID, ok := c.Locals(KeyUserID).(uuid.UUID)
|
||||
return userID, ok
|
||||
}
|
||||
|
||||
func MustUserID(c fiber.Ctx) uuid.UUID {
|
||||
userID, ok := UserID(c)
|
||||
if !ok {
|
||||
panic("common: authenticated user ID is missing from the request context")
|
||||
}
|
||||
return userID
|
||||
}
|
||||
|
||||
func SessionToken(c fiber.Ctx) (string, bool) {
|
||||
token, ok := c.Locals(KeySessionToken).(string)
|
||||
return token, ok && token != ""
|
||||
}
|
||||
|
||||
// PathUUID parses a UUID path parameter. A malformed value is a contract
|
||||
// invalid_request, not a lookup failure.
|
||||
func PathUUID(c fiber.Ctx, name string) (uuid.UUID, error) {
|
||||
id, err := uuid.Parse(c.Params(name))
|
||||
if err != nil {
|
||||
return uuid.Nil, BadRequest("invalid " + name + " format")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,102 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/base64"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/gofiber/fiber/v3"
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type CursorKeyCtx struct {
|
||||
Time time.Time
|
||||
ID uuid.UUID
|
||||
ContextID uuid.UUID
|
||||
}
|
||||
|
||||
type Page[T any] struct {
|
||||
Items []T `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
func ParseLimit(c fiber.Ctx, defaultLimit int) (int, error) {
|
||||
limitStr, exists := c.Queries()["limit"]
|
||||
if !exists {
|
||||
return defaultLimit, nil
|
||||
}
|
||||
if strings.TrimSpace(limitStr) == "" {
|
||||
return 0, BadRequest("limit param declared but empty")
|
||||
}
|
||||
|
||||
limit, err := strconv.Atoi(limitStr)
|
||||
if err != nil || limit < 1 || limit > 100 {
|
||||
return 0, BadRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
return limit, nil
|
||||
}
|
||||
|
||||
func ParseCursor(c fiber.Ctx) (*CursorKeyCtx, error) {
|
||||
cursorStr, exists := c.Queries()["cursor"]
|
||||
if !exists {
|
||||
return nil, nil
|
||||
}
|
||||
if strings.TrimSpace(cursorStr) == "" {
|
||||
return nil, BadRequest("cursor param declared but empty")
|
||||
}
|
||||
|
||||
cursor, ok := DecodeCursor(cursorStr)
|
||||
if !ok {
|
||||
return nil, BadRequest("invalid cursor format")
|
||||
}
|
||||
return cursor, nil
|
||||
}
|
||||
|
||||
func EncodeCursor(key CursorKeyCtx) string {
|
||||
raw := key.Time.UTC().Format(time.RFC3339Nano) + "|" + key.ID.String() + "|" + key.ContextID.String()
|
||||
return base64.RawURLEncoding.EncodeToString([]byte(raw))
|
||||
}
|
||||
|
||||
func DecodeCursor(cursor string) (*CursorKeyCtx, bool) {
|
||||
data, err := base64.RawURLEncoding.DecodeString(cursor)
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parts := strings.SplitN(string(data), "|", 3)
|
||||
if len(parts) != 3 {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
parsedTime, err := time.Parse(time.RFC3339Nano, parts[0])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
parsedID, err := uuid.Parse(parts[1])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
parsedContext, err := uuid.Parse(parts[2])
|
||||
if err != nil {
|
||||
return nil, false
|
||||
}
|
||||
|
||||
return &CursorKeyCtx{Time: parsedTime, ID: parsedID, ContextID: parsedContext}, true
|
||||
}
|
||||
|
||||
func NextCursor[T interface {
|
||||
GetID() uuid.UUID
|
||||
GetCreatedAt() time.Time
|
||||
}](items []T, hasMore bool, contextID uuid.UUID) *string {
|
||||
if !hasMore || len(items) == 0 {
|
||||
return nil
|
||||
}
|
||||
last := items[len(items)-1]
|
||||
encoded := EncodeCursor(CursorKeyCtx{
|
||||
Time: last.GetCreatedAt(),
|
||||
ID: last.GetID(),
|
||||
ContextID: contextID,
|
||||
})
|
||||
return &encoded
|
||||
}
|
||||
@@ -0,0 +1,31 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
func TestCursorRoundTrip(t *testing.T) {
|
||||
want := CursorKeyCtx{
|
||||
Time: time.Date(2026, 10, 20, 12, 30, 45, 123456789, time.UTC),
|
||||
ID: uuid.MustParse("11111111-1111-4111-8111-111111111111"),
|
||||
ContextID: uuid.MustParse("22222222-2222-4222-8222-222222222222"),
|
||||
}
|
||||
|
||||
encoded := EncodeCursor(want)
|
||||
got, ok := DecodeCursor(encoded)
|
||||
if !ok {
|
||||
t.Fatal("cursor did not decode")
|
||||
}
|
||||
if !got.Time.Equal(want.Time) || got.ID != want.ID || got.ContextID != want.ContextID {
|
||||
t.Fatalf("cursor round trip changed the key: %+v", got)
|
||||
}
|
||||
|
||||
for _, invalid := range []string{"not-base64!", "", "aGVsbG8"} {
|
||||
if _, ok := DecodeCursor(invalid); ok {
|
||||
t.Fatalf("invalid cursor %q was accepted", invalid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,21 @@
|
||||
package common
|
||||
|
||||
import "testing"
|
||||
|
||||
func TestValidatePasswordRange(t *testing.T) {
|
||||
cases := []struct {
|
||||
password string
|
||||
valid bool
|
||||
}{
|
||||
{"short", false},
|
||||
{"12345678901", false},
|
||||
{"123456789012", true},
|
||||
{"пароль-из-двенадцати", true},
|
||||
{"😀", false},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
if got := ValidatePassword(tc.password) == nil; got != tc.valid {
|
||||
t.Fatalf("ValidatePassword(%q) valid=%v, want %v", tc.password, got, tc.valid)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"time"
|
||||
)
|
||||
|
||||
// PostgreSQL stores microseconds, so keeping the same boundary in Go
|
||||
// prevents a create response from showing more precision
|
||||
// than a later read can reproduce.
|
||||
const storageTimePrecision = time.Microsecond
|
||||
|
||||
type RFCFormTime time.Time
|
||||
|
||||
func (t RFCFormTime) MarshalJSON() ([]byte, error) {
|
||||
// RFC 3339 permits an optional fractional second.
|
||||
utc := time.Time(t).UTC().Truncate(storageTimePrecision)
|
||||
layout := "2006-01-02T15:04:05Z"
|
||||
if utc.Nanosecond() != 0 {
|
||||
layout = "2006-01-02T15:04:05.000000Z"
|
||||
}
|
||||
return json.Marshal(utc.Format(layout))
|
||||
}
|
||||
|
||||
func NowUTC() RFCFormTime {
|
||||
return RFCFormTime(time.Now().UTC().Truncate(storageTimePrecision))
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"testing"
|
||||
"time"
|
||||
)
|
||||
|
||||
func TestNowUTCHasMicrosecondPrecision(t *testing.T) {
|
||||
now := time.Time(NowUTC())
|
||||
if now.Nanosecond()%1000 != 0 {
|
||||
t.Fatalf("NowUTC() kept precision below a microsecond: %v", now)
|
||||
}
|
||||
if now.Location() != time.UTC {
|
||||
t.Fatalf("NowUTC() location = %v, want UTC", now.Location())
|
||||
}
|
||||
}
|
||||
|
||||
func TestRFCFormTimeSerializesFractionalSeconds(t *testing.T) {
|
||||
cases := []struct {
|
||||
name string
|
||||
value time.Time
|
||||
want string
|
||||
}{
|
||||
{
|
||||
name: "microseconds",
|
||||
value: time.Date(2026, 10, 26, 12, 34, 56, 123456789, time.UTC),
|
||||
want: `"2026-10-26T12:34:56.123456Z"`,
|
||||
},
|
||||
{
|
||||
name: "exact second",
|
||||
value: time.Date(2026, 10, 26, 12, 34, 56, 0, time.UTC),
|
||||
want: `"2026-10-26T12:34:56Z"`,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
encoded, err := json.Marshal(RFCFormTime(tc.value))
|
||||
if err != nil {
|
||||
t.Fatalf("marshal RFC form time: %v", err)
|
||||
}
|
||||
if string(encoded) != tc.want {
|
||||
t.Fatalf("RFC form time = %s, want %s", encoded, tc.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,149 @@
|
||||
package common
|
||||
|
||||
import (
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
var (
|
||||
usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
idempotencyKeyRegex = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
)
|
||||
|
||||
func blank(s string) bool {
|
||||
return strings.TrimSpace(s) == ""
|
||||
}
|
||||
|
||||
func strLenBetween(s string, min, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func ValidateCreateUser(username, displayName string) error {
|
||||
if !usernameRegex.MatchString(username) {
|
||||
return BadRequest("username must match ^[a-z0-9_]{3,32}$")
|
||||
}
|
||||
|
||||
if blank(displayName) {
|
||||
return BadRequest("display_name must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(displayName, 1, 100) {
|
||||
return BadRequest("display_name must be between 1 and 100 Unicode code points")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidatePassword(password string) error {
|
||||
if blank(password) {
|
||||
return BadRequest("password must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(password, 12, 128) {
|
||||
return BadRequest("password must be between 12 and 128 Unicode code points")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateChatTitle(title string) error {
|
||||
if blank(title) {
|
||||
return BadRequest("title must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(title, 1, 100) {
|
||||
return BadRequest("title must be between 1 and 100 Unicode code points")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMessageText(text string, attachmentCount int) error {
|
||||
if attachmentCount == 0 && blank(text) {
|
||||
return BadRequest("text must not be empty or only whitespace")
|
||||
}
|
||||
|
||||
if !strLenBetween(text, 0, 4000) {
|
||||
return BadRequest("text must be between 0 and 4000 Unicode code points")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateAttachmentIDs(ids []uuid.UUID) error {
|
||||
if len(ids) > 10 {
|
||||
return BadRequest("attachment_ids must contain at most 10 items")
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return BadRequest("attachment_ids must not contain duplicates")
|
||||
}
|
||||
seen[id] = true
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateFilename(filename string) error {
|
||||
if !strLenBetween(filename, 1, 255) {
|
||||
return BadRequest("filename must be between 1 and 255 Unicode code points")
|
||||
}
|
||||
if blank(filename) {
|
||||
return BadRequest("filename must not be empty or only whitespace")
|
||||
}
|
||||
if filename == "." || filename == ".." {
|
||||
return BadRequest("filename is not allowed")
|
||||
}
|
||||
|
||||
for _, r := range filename {
|
||||
if r == '/' || r == '\\' || r == 0 || unicode.IsControl(r) {
|
||||
return BadRequest("filename contains a forbidden character")
|
||||
}
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateIdempotencyKey(key string) error {
|
||||
if key == "" {
|
||||
return BadRequest("Idempotency-Key header is required")
|
||||
}
|
||||
if !idempotencyKeyRegex.MatchString(key) {
|
||||
return BadRequest("Idempotency-Key must match ^[A-Za-z0-9._:-]{1,128}$")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func ValidateMemberIDs(ids []uuid.UUID, callerID uuid.UUID) error {
|
||||
if len(ids) < 1 || len(ids) > 100 {
|
||||
return BadRequest("member_ids must contain between 1 and 100 members")
|
||||
}
|
||||
|
||||
seen := make(map[uuid.UUID]bool, len(ids))
|
||||
callerFound := false
|
||||
|
||||
for _, id := range ids {
|
||||
if seen[id] {
|
||||
return BadRequest("member_ids must not contain duplicates")
|
||||
}
|
||||
|
||||
seen[id] = true
|
||||
|
||||
if id == callerID {
|
||||
callerFound = true
|
||||
}
|
||||
}
|
||||
|
||||
if !callerFound {
|
||||
return BadRequest("caller must be included in member_ids")
|
||||
}
|
||||
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user