на оценку 4

This commit is contained in:
2026-11-22 23:33:11 +03:00
parent 20afc2c790
commit cc41f601e3
207 changed files with 22098 additions and 120 deletions
+126
View File
@@ -0,0 +1,126 @@
package domain
import (
"encoding/hex"
"fmt"
"strings"
"time"
"unicode"
"unicode/utf8"
)
const (
MaxAttachmentFilenameCodePoints = 255
MaxAttachmentSizeBytes = 10 * 1024 * 1024
MaxAttachmentPixels = 40_000_000
)
type AttachmentVariant struct {
Name string
ContentType string
SizeBytes int64
Width int
Height int
SHA256 string
ObjectKey string
PipelineVersion int
}
type AttachmentStatus string
const (
AttachmentStatusQueued AttachmentStatus = "queued"
AttachmentStatusProcessing AttachmentStatus = "processing"
AttachmentStatusReady AttachmentStatus = "ready"
AttachmentStatusFailed AttachmentStatus = "failed"
// Source-compatible alias for the lab4 reconciliation code.
AttachmentStatusPending = AttachmentStatusQueued
)
// Attachment contains metadata only. ObjectKey points to bytes in the
// private object store and must never be derived from Filename.
type Attachment struct {
ID string
ChatID string
OwnerID string
Filename string
ObjectKey string
ContentType string
SizeBytes int64
SHA256 string
Width int
Height int
StagingKey string
PipelineVersion int
Status AttachmentStatus
Variants []AttachmentVariant
ErrorCode *string
CreatedAt time.Time
UpdatedAt time.Time
}
func ValidateAttachmentFilename(filename string) error {
if !utf8.ValidString(filename) {
return fmt.Errorf("filename must be valid UTF-8")
}
filenameLength := utf8.RuneCountInString(filename)
if filenameLength < 1 || filenameLength > MaxAttachmentFilenameCodePoints {
return fmt.Errorf("filename length must be between 1 and %d code points", MaxAttachmentFilenameCodePoints)
}
if strings.TrimSpace(filename) == "" || filename == "." || filename == ".." {
return fmt.Errorf("filename is unsafe")
}
if strings.ContainsAny(filename, `/\\`) {
return fmt.Errorf("filename must not contain path separators")
}
for _, character := range filename {
if unicode.IsControl(character) {
return fmt.Errorf("filename must not contain control characters")
}
}
return nil
}
func ValidateAttachmentContentType(contentType string) error {
if contentType != "image/png" && contentType != "image/jpeg" {
return fmt.Errorf("content type must be image/png or image/jpeg")
}
return nil
}
// ValidateReadyAttachmentMetadata checks the bounded metadata produced after
// the upload stream has been identified, decoded and hashed. It deliberately
// does not trust an HTTP Content-Type header.
func ValidateReadyAttachmentMetadata(
filename string,
contentType string,
sizeBytes int64,
sha256Hex string,
width int,
height int,
) error {
if err := ValidateAttachmentFilename(filename); err != nil {
return err
}
if err := ValidateAttachmentContentType(contentType); err != nil {
return err
}
if sizeBytes < 1 || sizeBytes > MaxAttachmentSizeBytes {
return fmt.Errorf("attachment size must be between 1 and %d bytes", MaxAttachmentSizeBytes)
}
if width < 1 || height < 1 {
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
}
if int64(width) > int64(MaxAttachmentPixels)/int64(height) {
return fmt.Errorf("image dimensions must be positive and contain at most %d pixels", MaxAttachmentPixels)
}
if len(sha256Hex) != 64 || sha256Hex != strings.ToLower(sha256Hex) {
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
}
decodedHash, err := hex.DecodeString(sha256Hex)
if err != nil || len(decodedHash) != 32 {
return fmt.Errorf("sha256 must contain 64 lowercase hexadecimal characters")
}
return nil
}
+57
View File
@@ -0,0 +1,57 @@
package domain
import "time"
const AttachmentJobType = "attachment.process.v1"
type AttachmentJobStatus string
const (
AttachmentJobQueued AttachmentJobStatus = "queued"
AttachmentJobProcessing AttachmentJobStatus = "processing"
AttachmentJobSucceeded AttachmentJobStatus = "succeeded"
AttachmentJobFailed AttachmentJobStatus = "failed"
AttachmentJobSuperseded AttachmentJobStatus = "superseded"
)
type AttachmentJob struct {
SchemaVersion int
JobID string
Type string
AttachmentID string
PipelineVersion int
Attempt int
MaxAttempts int
Status AttachmentJobStatus
ErrorCode *string
AvailableAt time.Time
LeaseUntil *time.Time
LeasedBy *string
ReplayCount int
CreatedAt time.Time
UpdatedAt time.Time
TraceParent string
TraceState string
}
type AttachmentJobMessage struct {
SchemaVersion int `json:"schema_version"`
JobID string `json:"job_id"`
Type string `json:"type"`
AttachmentID string `json:"attachment_id"`
PipelineVersion int `json:"pipeline_version"`
Attempt int `json:"attempt"`
CreatedAt time.Time `json:"created_at"`
}
func (job AttachmentJob) Message() AttachmentJobMessage {
return AttachmentJobMessage{
SchemaVersion: job.SchemaVersion,
JobID: job.JobID,
Type: job.Type,
AttachmentID: job.AttachmentID,
PipelineVersion: job.PipelineVersion,
Attempt: job.Attempt,
CreatedAt: job.CreatedAt.UTC(),
}
}
+59
View File
@@ -0,0 +1,59 @@
package domain
import (
"math"
"strings"
"testing"
)
func TestValidateReadyAttachmentMetadata(t *testing.T) {
validHash := strings.Repeat("ab", 32)
testCases := []struct {
name string
filename string
contentType string
sizeBytes int64
sha256 string
width int
height int
wantError bool
}{
{name: "png", filename: "кот.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1},
{name: "jpeg at limits", filename: strings.Repeat("界", 255), contentType: "image/jpeg", sizeBytes: MaxAttachmentSizeBytes, sha256: validHash, width: 8_000, height: 5_000},
{name: "empty filename", filename: "", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "blank filename", filename: " ", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "dot segment", filename: "..", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "forward slash", filename: "folder/image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "backslash", filename: `folder\\image.png`, contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "control character", filename: "image\n.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "C1 control character", filename: "image\u0085.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "invalid UTF-8", filename: string([]byte{'x', 0xff, '.', 'p', 'n', 'g'}), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "filename too long", filename: strings.Repeat("a", 256), contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "unsupported MIME", filename: "image.gif", contentType: "image/gif", sizeBytes: 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "empty file", filename: "image.png", contentType: "image/png", sizeBytes: 0, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "file too large", filename: "image.png", contentType: "image/png", sizeBytes: MaxAttachmentSizeBytes + 1, sha256: validHash, width: 1, height: 1, wantError: true},
{name: "zero width", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 0, height: 1, wantError: true},
{name: "too many pixels", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: 8_001, height: 5_000, wantError: true},
{name: "dimension multiplication cannot overflow", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: validHash, width: math.MaxInt, height: math.MaxInt, wantError: true},
{name: "short hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: "ab", width: 1, height: 1, wantError: true},
{name: "uppercase hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.ToUpper(validHash), width: 1, height: 1, wantError: true},
{name: "non-hex hash", filename: "image.png", contentType: "image/png", sizeBytes: 1, sha256: strings.Repeat("zz", 32), width: 1, height: 1, wantError: true},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateReadyAttachmentMetadata(
testCase.filename,
testCase.contentType,
testCase.sizeBytes,
testCase.sha256,
testCase.width,
testCase.height,
)
if (err != nil) != testCase.wantError {
t.Fatalf("ValidateReadyAttachmentMetadata() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
+21
View File
@@ -0,0 +1,21 @@
package domain
import "time"
type Chat struct {
ID string
Title string
MemberIDs []string
CreatedAt time.Time
}
type ChatCursor struct {
CreatedAt time.Time
ChatID string
UserID string
}
type ChatPage struct {
Items []Chat
NextCursor *string
}
+8
View File
@@ -0,0 +1,8 @@
package domain
import "errors"
var (
ErrNotFound = errors.New("not found")
ErrConflict = errors.New("conflict")
)
+23
View File
@@ -0,0 +1,23 @@
package domain
import "time"
type Message struct {
ID string
ChatID string
SenderID string
Text string
AttachmentIDs []string
CreatedAt time.Time
}
type MessageCursor struct {
CreatedAt time.Time
MessageID string
ChatID string
}
type MessagePage struct {
Items []Message
NextCursor *string
}
+70
View File
@@ -0,0 +1,70 @@
package domain
import (
"strings"
"testing"
)
func TestValidateMessageInput(t *testing.T) {
validAttachment := "11111111-1111-4111-8111-111111111111"
testCases := []struct {
name string
text string
attachmentIDs []string
wantError bool
}{
{name: "text only", text: "hello"},
{name: "attachment only", attachmentIDs: []string{validAttachment}},
{name: "whitespace with attachment", text: " ", attachmentIDs: []string{validAttachment}},
{name: "empty", wantError: true},
{name: "whitespace only", text: " ", wantError: true},
{name: "text too long", text: strings.Repeat("界", 4001), wantError: true},
{name: "invalid attachment uuid", text: "hello", attachmentIDs: []string{"not-a-uuid"}, wantError: true},
{
name: "duplicate attachment uuid ignores case",
text: "hello",
attachmentIDs: []string{
"AAAAAAAA-AAAA-4AAA-8AAA-AAAAAAAAAAAA",
"aaaaaaaa-aaaa-4aaa-8aaa-aaaaaaaaaaaa",
},
wantError: true,
},
}
for _, testCase := range testCases {
t.Run(testCase.name, func(t *testing.T) {
err := ValidateMessageInput(testCase.text, testCase.attachmentIDs)
if (err != nil) != testCase.wantError {
t.Fatalf("ValidateMessageInput() error = %v, wantError %v", err, testCase.wantError)
}
})
}
}
func TestValidateMessageInputAttachmentLimit(t *testing.T) {
attachmentIDs := []string{
"00000000-0000-4000-8000-000000000001",
"00000000-0000-4000-8000-000000000002",
"00000000-0000-4000-8000-000000000003",
"00000000-0000-4000-8000-000000000004",
"00000000-0000-4000-8000-000000000005",
"00000000-0000-4000-8000-000000000006",
"00000000-0000-4000-8000-000000000007",
"00000000-0000-4000-8000-000000000008",
"00000000-0000-4000-8000-000000000009",
"00000000-0000-4000-8000-000000000010",
}
if err := ValidateMessageInput("", attachmentIDs); err != nil {
t.Fatalf("10 attachments must be accepted: %v", err)
}
attachmentIDs = append(
attachmentIDs,
"00000000-0000-4000-8000-000000000011",
)
if err := ValidateMessageInput("hello", attachmentIDs); err == nil {
t.Fatal("11 attachments must be rejected")
}
}
+10
View File
@@ -0,0 +1,10 @@
package domain
import "time"
type Session struct {
Token string
TokenType string
ExpiresAt time.Time
User User
}
+11
View File
@@ -0,0 +1,11 @@
package domain
import "time"
// User is the transport-independent representation of a messenger user.
type User struct {
ID string
Username string
DisplayName string
CreatedAt time.Time
}
+101
View File
@@ -0,0 +1,101 @@
package domain
import (
"fmt"
"regexp"
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
const MaxMessageAttachments = 10
var usernameRegex = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
func ValidateUser(username, displayName string) error {
if !usernameRegex.MatchString(username) {
return fmt.Errorf("username must match [a-z0-9_]{3,32}")
}
nameRunes := utf8.RuneCountInString(displayName)
if nameRunes < 1 || nameRunes > 100 {
return fmt.Errorf("display_name length must be between 1 and 100 code points")
}
if strings.TrimSpace(displayName) == "" {
return fmt.Errorf("display_name cannot be only whitespace")
}
return nil
}
// Validate remains as a compatibility convenience for existing callers.
func (u User) Validate() error {
return ValidateUser(u.Username, u.DisplayName)
}
func ValidateChatInput(title string, memberIDs []string, callerID string) error {
titleRunes := utf8.RuneCountInString(title)
if titleRunes < 1 || titleRunes > 100 || strings.TrimSpace(title) == "" {
return fmt.Errorf("invalid chat title")
}
if len(memberIDs) == 0 {
return fmt.Errorf("member_ids cannot be empty")
}
if len(memberIDs) > 100 {
return fmt.Errorf("member_ids must contain at most 100 users")
}
hasCaller := false
seen := make(map[string]struct{}, len(memberIDs))
for _, id := range memberIDs {
if _, err := uuid.Parse(id); err != nil {
return fmt.Errorf("invalid member uuid: %s", id)
}
if _, exists := seen[id]; exists {
return fmt.Errorf("duplicate member_id: %s", id)
}
seen[id] = struct{}{}
if id == callerID {
hasCaller = true
}
}
if !hasCaller {
return fmt.Errorf("caller must be in member_ids")
}
return nil
}
func ValidateMessageInput(text string, attachmentIDs []string) error {
textRunes := utf8.RuneCountInString(text)
if textRunes > 4000 {
return fmt.Errorf("message text length must be at most 4000 code points")
}
if len(attachmentIDs) > MaxMessageAttachments {
return fmt.Errorf("attachment_ids must contain at most %d items", MaxMessageAttachments)
}
seen := make(map[string]struct{}, len(attachmentIDs))
for _, attachmentID := range attachmentIDs {
parsedID, err := uuid.Parse(attachmentID)
if err != nil {
return fmt.Errorf("invalid attachment uuid: %s", attachmentID)
}
canonicalID := parsedID.String()
if _, exists := seen[canonicalID]; exists {
return fmt.Errorf("duplicate attachment_id: %s", attachmentID)
}
seen[canonicalID] = struct{}{}
}
if strings.TrimSpace(text) == "" && len(attachmentIDs) == 0 {
return fmt.Errorf("message must contain non-blank text or at least one attachment")
}
return nil
}
// ValidateMessageText remains for callers that create text-only messages.
func ValidateMessageText(text string) error {
return ValidateMessageInput(text, nil)
}