ЛР 6 — БПИ2302 — Нурлыгаянова — на 3

This commit is contained in:
Nurlygayanova Ekaterina
2026-11-13 11:32:45 +03:00
parent 470d9d6f1e
commit 69a190be0e
164 changed files with 25947 additions and 29 deletions
+70
View File
@@ -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
}
+39
View File
@@ -0,0 +1,39 @@
package validate
import (
"strings"
"testing"
)
func TestFilename(t *testing.T) {
valid := []string{"photo.png", "фото отпуска.jpeg", "a", strings.Repeat("я", 255), "👋.png", "..hidden.png"}
for _, s := range valid {
if err := Filename(s); err != nil {
t.Errorf("Filename(%q) = %v", s, err)
}
}
invalid := []string{"", " ", ".", "..", "../etc/passwd", `a\b.png`, "a/b.png", "a\x00.png", "a\nb.png", "a\x7f.png",
"\xff.png", "evil‮gnp.exe", "a
b", strings.Repeat("я", 256)}
for _, s := range invalid {
if err := Filename(s); err == nil {
t.Errorf("Filename(%q) accepted", s)
}
}
}
func TestAttachmentIDs(t *testing.T) {
const a = "11111111-1111-4111-8111-111111111111"
got, err := AttachmentIDs([]string{strings.ToUpper(a)})
if err != nil || got[0] != a {
t.Errorf("canonical form: %v, %v", got, err)
}
if _, err := AttachmentIDs([]string{a, strings.ToUpper(a)}); err == nil {
t.Error("duplicates accepted after canonicalization")
}
if _, err := AttachmentIDs([]string{"not-a-uuid"}); err == nil {
t.Error("invalid UUID accepted")
}
if _, err := AttachmentIDs(make([]string, AttachmentIDsMax+1)); err == nil {
t.Error("too many IDs accepted")
}
}
+42
View File
@@ -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
}
+12
View File
@@ -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
}
+14
View File
@@ -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
}
+80
View File
@@ -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}
}
+30
View File
@@ -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
}