lab 7 done
Skeleton contracts / contracts (pull_request) Blocked by required conditions

This commit is contained in:
Khakimov Dmitrij
2026-11-29 21:59:16 +03:00
parent 20afc2c790
commit 2a7418fc45
170 changed files with 10332 additions and 96 deletions
+59
View File
@@ -0,0 +1,59 @@
package chat_test
import (
"context"
"testing"
"time"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
"golang.org/x/crypto/bcrypt"
)
type recordedSessions struct{ value domain.Session }
func (s *recordedSessions) Put(_ context.Context, _ string, value domain.Session) error {
s.value = value
return nil
}
func (*recordedSessions) Get(context.Context, string) (domain.Session, bool, error) {
return domain.Session{}, false, nil
}
func (*recordedSessions) Delete(context.Context, string) (bool, error) { return false, nil }
func (*recordedSessions) Ready(context.Context) error { return nil }
func TestPasswordUpgradeOnSuccessfulLogin(t *testing.T) {
ctx := context.Background()
repo := repository.NewMemory()
sessions := &recordedSessions{}
useCase := chat.New(repo, sessions, time.Minute)
const secret = "synthetic-legacy-password"
legacy, err := bcrypt.GenerateFromPassword([]byte(secret), bcrypt.MinCost)
if err != nil {
t.Fatal(err)
}
user, err := repo.CreateUser(ctx, "legacy", "Legacy", string(legacy))
if err != nil {
t.Fatal(err)
}
if _, err := useCase.CreateSession(ctx, user.Username, "synthetic-wrong-password"); err == nil {
t.Fatal("wrong password accepted")
}
if _, hash, _, _ := repo.UserByUsername(ctx, user.Username); hash != string(legacy) {
t.Fatal("failed login changed hash")
}
login, err := useCase.CreateSession(ctx, user.Username, secret)
if err != nil || login.Token == "" || sessions.value.UserID != user.ID {
t.Fatal("legacy login failed")
}
_, hash, _, _ := repo.UserByUsername(ctx, user.Username)
if password.NeedsRehash(hash) {
t.Fatal("successful login did not upgrade hash")
}
if ok, err := password.Verify(ctx, secret, hash); err != nil || !ok {
t.Fatal("replacement hash rejects original password")
}
}
+29
View File
@@ -0,0 +1,29 @@
package chat
import (
"context"
"errors"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
var (
ErrUsernameTaken = errors.New("username is already taken")
ErrUserNotFound = errors.New("user not found")
ErrChatNotFound = errors.New("chat not found")
ErrNotMember = errors.New("user is not a chat member")
)
// Repository is the persistence port required by the chat use case.
type Repository interface {
Ready(ctx context.Context) error
UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error)
UpdatePasswordHash(ctx context.Context, userID, oldHash, newHash string) error
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
User(ctx context.Context, id string) (domain.User, bool, error)
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error)
ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error)
CreateMessage(ctx context.Context, chatID, senderID, text, key string) (domain.Message, error)
ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error)
}
+182
View File
@@ -0,0 +1,182 @@
package chat
import (
"context"
"errors"
"strings"
"time"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
type UseCase struct {
repository Repository
sessions Sessions
sessionTTL time.Duration
}
func New(repository Repository, sessions Sessions, ttl time.Duration) *UseCase {
return &UseCase{repository: repository, sessions: sessions, sessionTTL: ttl}
}
func (u *UseCase) CreateUser(ctx context.Context, user domain.User, secret string) (domain.User, error) {
if !validUsername(user.Username) {
return domain.User{}, invalid("username должен соответствовать [a-z0-9_]{3,32}")
}
if !validRequiredText(user.DisplayName, 100) {
return domain.User{}, invalid("display_name должен содержать от 1 до 100 символов")
}
if !validPassword(secret) {
return domain.User{}, invalid("password должен содержать от 12 до 128 символов")
}
hash, err := password.Hash(ctx, secret)
if err != nil {
return domain.User{}, err
}
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName, hash)
if errors.Is(err, ErrUsernameTaken) {
return domain.User{}, domain.NewApplicationError(domain.ErrorConflict, "Пользователь с таким username уже существует")
}
return created, err
}
func (u *UseCase) CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
if !validRequiredText(chat.Title, 100) {
return domain.Chat{}, invalid("title должен содержать от 1 до 100 символов")
}
if len(chat.MemberIDs) < 1 || len(chat.MemberIDs) > 100 {
return domain.Chat{}, invalid("member_ids должен содержать от 1 до 100 участников")
}
normalizedIDs := make([]string, len(chat.MemberIDs))
seen := make(map[string]struct{}, len(chat.MemberIDs))
callerIncluded := false
for index, memberID := range chat.MemberIDs {
normalized, valid := normalizeUUID(memberID)
if !valid {
return domain.Chat{}, invalid("member_ids содержит некорректный UUID")
}
if _, duplicate := seen[normalized]; duplicate {
return domain.Chat{}, invalid("member_ids содержит повторяющиеся UUID")
}
normalizedIDs[index] = normalized
seen[normalized] = struct{}{}
callerIncluded = callerIncluded || normalized == callerID
}
if !callerIncluded {
return domain.Chat{}, invalid("текущий пользователь должен входить в member_ids")
}
created, err := u.repository.CreateChat(ctx, chat.Title, normalizedIDs)
if errors.Is(err, ErrUserNotFound) {
return domain.Chat{}, invalid("member_ids содержит неизвестного пользователя")
}
return created, err
}
func (u *UseCase) GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error) {
chatID, valid := normalizeUUID(chat.ID)
if !valid {
return domain.Chat{}, invalid("Некорректный chat_id")
}
return u.chatForUser(ctx, chatID, callerID)
}
func (u *UseCase) ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error) {
if pagination.Limit < 1 || pagination.Limit > 100 {
return domain.ChatPage{}, invalid("limit должен быть целым числом от 1 до 100")
}
items, err := u.repository.ListChats(ctx, callerID, pagination.After, pagination.Limit+1)
if err != nil {
return domain.ChatPage{}, err
}
page := domain.ChatPage{Items: items, HasMore: len(items) > pagination.Limit}
if page.HasMore {
page.Items = page.Items[:pagination.Limit]
}
return page, nil
}
func (u *UseCase) CreateMessage(ctx context.Context, callerID string, message domain.Message) (domain.Message, error) {
chatID, valid := normalizeUUID(message.ChatID)
if !valid {
return domain.Message{}, invalid("Некорректный chat_id")
}
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.Message{}, err
}
if !utf8.ValidString(message.Text) || utf8.RuneCountInString(message.Text) > 4000 || (strings.TrimSpace(message.Text) == "" && len(message.AttachmentIDs) == 0) {
return domain.Message{}, invalid("text должен содержать от 1 до 4000 символов")
}
if len(message.AttachmentIDs) > 10 {
return domain.Message{}, invalid("Не более 10 вложений")
}
seen := map[string]bool{}
for i, id := range message.AttachmentIDs {
normalized, ok := normalizeUUID(id)
if !ok || seen[normalized] {
return domain.Message{}, invalid("Некорректные или повторные attachment_ids")
}
seen[normalized] = true
message.AttachmentIDs[i] = normalized
}
var created domain.Message
var err error
if repository, ok := u.repository.(interface {
CreateMessageWithAttachments(context.Context, string, string, string, string, []string) (domain.Message, error)
}); ok {
created, err = repository.CreateMessageWithAttachments(ctx, chatID, callerID, message.Text, message.IdempotencyKey, message.AttachmentIDs)
} else if len(message.AttachmentIDs) > 0 {
return domain.Message{}, notFound()
} else {
created, err = u.repository.CreateMessage(ctx, chatID, callerID, message.Text, message.IdempotencyKey)
}
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Message{}, notFound()
}
return created, err
}
func (u *UseCase) ListMessages(ctx context.Context, callerID string, chat domain.Chat, pagination domain.Pagination) (domain.MessagePage, error) {
chatID, valid := normalizeUUID(chat.ID)
if !valid {
return domain.MessagePage{}, invalid("Некорректный chat_id")
}
if _, err := u.chatForUser(ctx, chatID, callerID); err != nil {
return domain.MessagePage{}, err
}
if pagination.Limit < 1 || pagination.Limit > 100 {
return domain.MessagePage{}, invalid("limit должен быть целым числом от 1 до 100")
}
items, err := u.repository.ListMessages(ctx, chatID, pagination.After, pagination.Limit+1)
if err != nil {
return domain.MessagePage{}, err
}
page := domain.MessagePage{Items: items, HasMore: len(items) > pagination.Limit}
if page.HasMore {
page.Items = page.Items[:pagination.Limit]
}
return page, nil
}
func (u *UseCase) chatForUser(ctx context.Context, chatID, callerID string) (domain.Chat, error) {
chat, err := u.repository.ChatForUser(ctx, chatID, callerID)
if errors.Is(err, ErrChatNotFound) || errors.Is(err, ErrNotMember) {
return domain.Chat{}, notFound()
}
return chat, err
}
func invalid(message string) error {
return domain.NewApplicationError(domain.ErrorInvalid, message)
}
func unauthorized() error {
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительная сессия")
}
func notFound() error {
return domain.NewApplicationError(domain.ErrorNotFound, "Объект не найден")
}
+111
View File
@@ -0,0 +1,111 @@
package chat
import (
"context"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"strings"
"time"
"unicode/utf8"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
type Sessions interface {
Put(context.Context, string, domain.Session) error
Get(context.Context, string) (domain.Session, bool, error)
Delete(context.Context, string) (bool, error)
Ready(context.Context) error
}
func validPassword(value string) bool {
n := utf8.RuneCountInString(value)
return utf8.ValidString(value) && n >= 12 && n <= 128 && strings.TrimSpace(value) != ""
}
func tokenKey(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
func (u *UseCase) Authenticate(ctx context.Context, token string) (domain.User, error) {
decoded, err := base64.RawURLEncoding.DecodeString(token)
if err != nil || len(decoded) != 32 {
return domain.User{}, unauthorized()
}
session, exists, err := u.sessions.Get(ctx, tokenKey(token))
if err != nil {
return domain.User{}, err
}
if !exists || !time.Now().Before(session.ExpiresAt) {
return domain.User{}, unauthorized()
}
user, exists, err := u.repository.User(ctx, session.UserID)
if err != nil {
return domain.User{}, err
}
if !exists {
return domain.User{}, unauthorized()
}
return user, nil
}
func (u *UseCase) CreateSession(ctx context.Context, username, secret string) (domain.Login, error) {
if !validUsername(username) || !validPassword(secret) {
return domain.Login{}, unauthorized()
}
user, hash, exists, err := u.repository.UserByUsername(ctx, username)
if err != nil {
return domain.Login{}, err
}
if !exists {
hash = password.DummyHash
}
valid, err := password.Verify(ctx, secret, hash)
if err != nil {
return domain.Login{}, err
}
if !valid || !exists {
return domain.Login{}, unauthorized()
}
if password.NeedsRehash(hash) {
replacement, err := password.Hash(ctx, secret)
if err != nil {
return domain.Login{}, err
}
if err := u.repository.UpdatePasswordHash(ctx, user.ID, hash, replacement); err != nil {
return domain.Login{}, err
}
}
var raw [32]byte
if _, err = rand.Read(raw[:]); err != nil {
return domain.Login{}, err
}
token := base64.RawURLEncoding.EncodeToString(raw[:])
expires := time.Now().UTC().Add(u.sessionTTL)
if err = u.sessions.Put(ctx, tokenKey(token), domain.Session{UserID: user.ID, ExpiresAt: expires}); err != nil {
return domain.Login{}, err
}
return domain.Login{Token: token, ExpiresAt: expires, User: user}, nil
}
func (u *UseCase) DeleteSession(ctx context.Context, token string) error {
deleted, err := u.sessions.Delete(ctx, tokenKey(token))
if err != nil {
return err
}
if !deleted {
return unauthorized()
}
return nil
}
func (u *UseCase) Ready(ctx context.Context) error {
if err := u.repository.Ready(ctx); err != nil {
return err
}
return u.sessions.Ready(ctx)
}
+19
View File
@@ -0,0 +1,19 @@
package chat
import (
"strings"
"testing"
)
func TestPasswordContract(t *testing.T) {
for _, value := range []string{"", "too-short", strings.Repeat(" ", 12), strings.Repeat("x", 129), strings.Repeat("x", 12) + string([]byte{0xff})} {
if validPassword(value) {
t.Fatal("invalid password accepted")
}
}
for _, value := range []string{strings.Repeat("🔑", 128), "valid:password", " password with spaces "} {
if !validPassword(value) {
t.Fatal("valid Unicode password rejected")
}
}
}
+37
View File
@@ -0,0 +1,37 @@
package chat
import (
"strings"
"unicode/utf8"
"github.com/google/uuid"
)
func normalizeUUID(value string) (string, bool) {
parsed, err := uuid.Parse(value)
if err != nil {
return "", false
}
normalized := parsed.String()
if !strings.EqualFold(value, normalized) {
return "", false
}
return normalized, true
}
func validUsername(value string) bool {
if len(value) < 3 || len(value) > 32 {
return false
}
for _, char := range value {
if char != '_' && (char < 'a' || char > 'z') && (char < '0' || char > '9') {
return false
}
}
return true
}
func validRequiredText(value string, maxRunes int) bool {
length := utf8.RuneCountInString(value)
return utf8.ValidString(value) && length >= 1 && length <= maxRunes && strings.TrimSpace(value) != ""
}