forked from mtusi2026/mtusi2026lab5
ЛР 5: асинхронная обработка изображений, уровень 5
This commit is contained in:
@@ -0,0 +1,70 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"strings"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
const (
|
||||
FilenameMinLen = 1
|
||||
FilenameMaxLen = 255
|
||||
|
||||
AttachmentIDsMax = 10
|
||||
)
|
||||
|
||||
// Filename проверяет отображаемое имя. Оно нигде не используется как путь, но попадает в заголовки
|
||||
// и к другим клиентам, поэтому разделители и невидимые управляющие символы запрещены.
|
||||
func Filename(s string) error {
|
||||
if !utf8.ValidString(s) {
|
||||
return newError("filename", "must be valid UTF-8")
|
||||
}
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("filename", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, FilenameMinLen, FilenameMaxLen) {
|
||||
return newError("filename", fmt.Sprintf("length must be in [%d, %d] code points", FilenameMinLen, FilenameMaxLen))
|
||||
}
|
||||
if s == "." || s == ".." {
|
||||
return newError("filename", "must not be a path component")
|
||||
}
|
||||
if strings.ContainsFunc(s, unsafeFilenameRune) {
|
||||
return newError("filename", "must not contain path separators or control characters")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func unsafeFilenameRune(r rune) bool {
|
||||
switch {
|
||||
case r == '/', r == '\\', unicode.IsControl(r):
|
||||
return true
|
||||
case r == '
', r == '
':
|
||||
return true
|
||||
case r >= '' && r <= '', r >= '' && r <= '':
|
||||
// Символы смены направления текста позволяют выдать evil.exe за безобидное имя.
|
||||
return true
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
// AttachmentIDs приводит ID к каноничному виду с сохранением порядка.
|
||||
func AttachmentIDs(ids []string) ([]string, error) {
|
||||
if len(ids) > AttachmentIDsMax {
|
||||
return nil, newError("attachment_ids", fmt.Sprintf("count must be at most %d", AttachmentIDsMax))
|
||||
}
|
||||
out := make([]string, 0, len(ids))
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
for i, raw := range ids {
|
||||
id, err := CanonicalUUID(fmt.Sprintf("attachment_ids[%d]", i), raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, newError("attachment_ids", "must not contain duplicates")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,42 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func ChatTitle(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("title", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, ChatTitleMinLen, ChatTitleMaxLen) {
|
||||
return newError("title", fmt.Sprintf("length must be in [%d, %d] code points", ChatTitleMinLen, ChatTitleMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func MemberIDs(ids []string, callerID string) ([]string, error) {
|
||||
if len(ids) < MemberIDsMin || len(ids) > MemberIDsMax {
|
||||
return nil, newError("member_ids", fmt.Sprintf("count must be in [%d, %d]", MemberIDsMin, MemberIDsMax))
|
||||
}
|
||||
|
||||
out := make([]string, 0, len(ids))
|
||||
seen := make(map[string]struct{}, len(ids))
|
||||
callerIn := false
|
||||
for i, raw := range ids {
|
||||
id, err := CanonicalUUID(fmt.Sprintf("member_ids[%d]", i), raw)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
return nil, newError("member_ids", "must not contain duplicates")
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
if id == callerID {
|
||||
callerIn = true
|
||||
}
|
||||
out = append(out, id)
|
||||
}
|
||||
|
||||
if !callerIn {
|
||||
return nil, newError("member_ids", "must contain caller")
|
||||
}
|
||||
return out, nil
|
||||
}
|
||||
@@ -0,0 +1,12 @@
|
||||
package validate
|
||||
|
||||
import "regexp"
|
||||
|
||||
var idempotencyKeyPattern = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
func IdempotencyKey(s string) error {
|
||||
if !idempotencyKeyPattern.MatchString(s) {
|
||||
return newError("Idempotency-Key", "must match [A-Za-z0-9._:-]{1,128}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
// MessageText: пустой или пробельный текст допустим, только если у сообщения есть вложения.
|
||||
func MessageText(s string, hasAttachments bool) error {
|
||||
if !hasAttachments && !notOnlyWhitespace(s) {
|
||||
return newError("text", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, 0, MessageTextMaxLen) {
|
||||
return newError("text", fmt.Sprintf("length must be at most %d code points", MessageTextMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
@@ -0,0 +1,80 @@
|
||||
package validate
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"regexp"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const (
|
||||
UsernameMinLen = 3
|
||||
UsernameMaxLen = 32
|
||||
|
||||
DisplayNameMinLen = 1
|
||||
DisplayNameMaxLen = 100
|
||||
|
||||
PasswordMinLen = 12
|
||||
PasswordMaxLen = 128
|
||||
|
||||
ChatTitleMinLen = 1
|
||||
ChatTitleMaxLen = 100
|
||||
|
||||
MessageTextMaxLen = 4000
|
||||
|
||||
MemberIDsMin = 1
|
||||
MemberIDsMax = 100
|
||||
|
||||
LimitMin = 1
|
||||
LimitMax = 100
|
||||
LimitDefault = 50
|
||||
)
|
||||
|
||||
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
|
||||
func CanonicalUUID(field, s string) (string, error) {
|
||||
if len(s) != 36 {
|
||||
return "", newError(field, "must be a valid UUID")
|
||||
}
|
||||
u, err := uuid.Parse(s)
|
||||
if err != nil {
|
||||
return "", newError(field, "must be a valid UUID")
|
||||
}
|
||||
return u.String(), nil
|
||||
}
|
||||
|
||||
func Limit(n int) error {
|
||||
if n < LimitMin || n > LimitMax {
|
||||
return newError("limit", fmt.Sprintf("must be in [%d, %d]", LimitMin, LimitMax))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func codePointsBetween(s string, min, max int) bool {
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func notOnlyWhitespace(s string) bool {
|
||||
return strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
type Error struct {
|
||||
Field string
|
||||
Reason string
|
||||
}
|
||||
|
||||
func (e *Error) Error() string {
|
||||
return e.Field + ": " + e.Reason
|
||||
}
|
||||
|
||||
func (e *Error) Is(target error) bool {
|
||||
_, ok := target.(*Error)
|
||||
return ok
|
||||
}
|
||||
|
||||
func newError(field, reason string) *Error {
|
||||
return &Error{Field: field, Reason: reason}
|
||||
}
|
||||
@@ -0,0 +1,30 @@
|
||||
package validate
|
||||
|
||||
import "fmt"
|
||||
|
||||
func Username(s string) error {
|
||||
if !usernamePattern.MatchString(s) {
|
||||
return newError("username", fmt.Sprintf("must match [a-z0-9_]{%d,%d}", UsernameMinLen, UsernameMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func DisplayName(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("display_name", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, DisplayNameMinLen, DisplayNameMaxLen) {
|
||||
return newError("display_name", fmt.Sprintf("length must be in [%d, %d] code points", DisplayNameMinLen, DisplayNameMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func Password(s string) error {
|
||||
if !notOnlyWhitespace(s) {
|
||||
return newError("password", "must not be empty or whitespace only")
|
||||
}
|
||||
if !codePointsBetween(s, PasswordMinLen, PasswordMaxLen) {
|
||||
return newError("password", fmt.Sprintf("length must be in [%d, %d] code points", PasswordMinLen, PasswordMaxLen))
|
||||
}
|
||||
return nil
|
||||
}
|
||||
Reference in New Issue
Block a user