forked from mtusi2026/mtusi2026lab4
перенос 3 лабы
This commit is contained in:
@@ -0,0 +1,55 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
func (s *Service) CreateChat(ctx context.Context, command CreateChatCommand) (domain.Chat, error) {
|
||||
if err := domain.ValidateChatInput(command.Title, command.MemberIDs, command.ActorID); err != nil {
|
||||
return domain.Chat{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
return s.repository.CreateChat(ctx, command.Title, command.MemberIDs)
|
||||
}
|
||||
|
||||
func (s *Service) GetChat(ctx context.Context, actorID, chatID string) (domain.Chat, error) {
|
||||
return s.repository.GetChatByID(ctx, chatID, actorID)
|
||||
}
|
||||
|
||||
func (s *Service) ListChats(
|
||||
ctx context.Context,
|
||||
actorID string,
|
||||
limit int,
|
||||
cursorToken string,
|
||||
) (domain.ChatPage, error) {
|
||||
var cursor *domain.ChatCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := s.cursors.DecodeChat(cursorToken, actorID)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, ErrInvalidCursor
|
||||
}
|
||||
cursor = decoded
|
||||
}
|
||||
|
||||
items, hasMore, err := s.repository.GetChatsForUser(ctx, actorID, limit, cursor)
|
||||
if err != nil {
|
||||
return domain.ChatPage{}, err
|
||||
}
|
||||
page := domain.ChatPage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Chat, 0)
|
||||
}
|
||||
if hasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
next, encodeErr := s.cursors.EncodeChat(domain.ChatCursor{
|
||||
CreatedAt: last.CreatedAt, ChatID: last.ID, UserID: actorID,
|
||||
})
|
||||
if encodeErr != nil {
|
||||
return domain.ChatPage{}, encodeErr
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,27 @@
|
||||
package application
|
||||
|
||||
type CreateUserCommand struct {
|
||||
Username string
|
||||
DisplayName string
|
||||
Password string
|
||||
}
|
||||
|
||||
type CreateSessionCommand struct {
|
||||
Username string
|
||||
Password string
|
||||
}
|
||||
|
||||
type CreateChatCommand struct {
|
||||
ActorID string
|
||||
Title string
|
||||
MemberIDs []string
|
||||
}
|
||||
|
||||
type SendMessageCommand struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
Method string
|
||||
CanonicalPath string
|
||||
IdempotencyKey string
|
||||
}
|
||||
@@ -0,0 +1,121 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
const cursorVersion = 1
|
||||
|
||||
type CursorCodec struct {
|
||||
key []byte
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
Version int `json:"v"`
|
||||
Kind string `json:"kind"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
ID string `json:"id"`
|
||||
ScopeID string `json:"scope_id"`
|
||||
}
|
||||
|
||||
func NewCursorCodec(key string) (*CursorCodec, error) {
|
||||
if len(key) < 32 {
|
||||
return nil, fmt.Errorf("cursor signing key must contain at least 32 bytes")
|
||||
}
|
||||
return &CursorCodec{key: []byte(key)}, nil
|
||||
}
|
||||
|
||||
func (c *CursorCodec) EncodeChat(cursor domain.ChatCursor) (string, error) {
|
||||
return c.encode(cursorPayload{
|
||||
Version: cursorVersion, Kind: "chat", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: cursor.ChatID, ScopeID: cursor.UserID,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *CursorCodec) DecodeChat(token, expectedUserID string) (*domain.ChatCursor, error) {
|
||||
payload, err := c.decode(token, "chat", expectedUserID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.ChatCursor{CreatedAt: payload.createdAt, ChatID: payload.id, UserID: payload.scopeID}, nil
|
||||
}
|
||||
|
||||
func (c *CursorCodec) EncodeMessage(cursor domain.MessageCursor) (string, error) {
|
||||
return c.encode(cursorPayload{
|
||||
Version: cursorVersion, Kind: "message", CreatedAt: cursor.CreatedAt.UTC().Format(time.RFC3339Nano),
|
||||
ID: cursor.MessageID, ScopeID: cursor.ChatID,
|
||||
})
|
||||
}
|
||||
|
||||
func (c *CursorCodec) DecodeMessage(token, expectedChatID string) (*domain.MessageCursor, error) {
|
||||
payload, err := c.decode(token, "message", expectedChatID)
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
return &domain.MessageCursor{CreatedAt: payload.createdAt, MessageID: payload.id, ChatID: payload.scopeID}, nil
|
||||
}
|
||||
|
||||
func (c *CursorCodec) encode(payload cursorPayload) (string, error) {
|
||||
encodedPayload, err := json.Marshal(payload)
|
||||
if err != nil {
|
||||
return "", fmt.Errorf("encode cursor payload: %w", err)
|
||||
}
|
||||
mac := hmac.New(sha256.New, c.key)
|
||||
_, _ = mac.Write(encodedPayload)
|
||||
return base64.RawURLEncoding.EncodeToString(encodedPayload) + "." +
|
||||
base64.RawURLEncoding.EncodeToString(mac.Sum(nil)), nil
|
||||
}
|
||||
|
||||
type decodedCursor struct {
|
||||
createdAt time.Time
|
||||
id string
|
||||
scopeID string
|
||||
}
|
||||
|
||||
func (c *CursorCodec) decode(token, expectedKind, expectedScopeID string) (decodedCursor, error) {
|
||||
parts := strings.Split(token, ".")
|
||||
if len(parts) != 2 {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
payloadBytes, err := base64.RawURLEncoding.DecodeString(parts[0])
|
||||
if err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
signature, err := base64.RawURLEncoding.DecodeString(parts[1])
|
||||
if err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
mac := hmac.New(sha256.New, c.key)
|
||||
_, _ = mac.Write(payloadBytes)
|
||||
if !hmac.Equal(signature, mac.Sum(nil)) {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
|
||||
var payload cursorPayload
|
||||
if err = json.Unmarshal(payloadBytes, &payload); err != nil ||
|
||||
payload.Version != cursorVersion || payload.Kind != expectedKind ||
|
||||
payload.ScopeID != expectedScopeID {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
createdAt, err := time.Parse(time.RFC3339Nano, payload.CreatedAt)
|
||||
if err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
if _, err = uuid.Parse(payload.ID); err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
if _, err = uuid.Parse(payload.ScopeID); err != nil {
|
||||
return decodedCursor{}, ErrInvalidCursor
|
||||
}
|
||||
return decodedCursor{createdAt: createdAt.UTC(), id: payload.ID, scopeID: payload.ScopeID}, nil
|
||||
}
|
||||
@@ -0,0 +1,70 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
const cursorTestKey = "cursor-test-key-with-more-than-thirty-two-bytes"
|
||||
|
||||
func TestCursorCodecRoundTrip(t *testing.T) {
|
||||
codec, err := NewCursorCodec(cursorTestKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
expected := domain.MessageCursor{
|
||||
CreatedAt: time.Date(2026, 10, 18, 12, 30, 0, 123, time.UTC),
|
||||
MessageID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
|
||||
ChatID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
|
||||
}
|
||||
token, err := codec.EncodeMessage(expected)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
actual, err := codec.DecodeMessage(token, expected.ChatID)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if *actual != expected {
|
||||
t.Fatalf("cursor changed after round trip: got %#v, want %#v", *actual, expected)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorCodecRejectsTamperingAndWrongScope(t *testing.T) {
|
||||
codec, err := NewCursorCodec(cursorTestKey)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
token, err := codec.EncodeChat(domain.ChatCursor{
|
||||
CreatedAt: time.Now().UTC(),
|
||||
ChatID: "42eea32e-d9b5-4bc6-b4fc-94e9b0477adf",
|
||||
UserID: "9fa3f49c-e62e-4209-8414-d6d5f69805bf",
|
||||
})
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
replacement := "A"
|
||||
if token[len(token)-1:] == replacement {
|
||||
replacement = "B"
|
||||
}
|
||||
tampered := token[:len(token)-1] + replacement
|
||||
if _, err = codec.DecodeChat(tampered, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
|
||||
t.Fatalf("tampered cursor: got %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
if _, err = codec.DecodeChat(token, "e6ca4af0-69ed-4784-8ce0-ee035299fe08"); !errors.Is(err, ErrInvalidCursor) {
|
||||
t.Fatalf("wrong scope: got %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
if _, err = codec.DecodeMessage(token, "9fa3f49c-e62e-4209-8414-d6d5f69805bf"); !errors.Is(err, ErrInvalidCursor) {
|
||||
t.Fatalf("wrong cursor kind: got %v, want ErrInvalidCursor", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCursorCodecRequiresStrongSharedKey(t *testing.T) {
|
||||
if _, err := NewCursorCodec("too-short"); err == nil {
|
||||
t.Fatal("expected short cursor signing key to be rejected")
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,11 @@
|
||||
package application
|
||||
|
||||
import "errors"
|
||||
|
||||
var (
|
||||
ErrInvalidCursor = errors.New("invalid cursor")
|
||||
ErrInvalidCredentials = errors.New("invalid credentials")
|
||||
ErrInvalidInput = errors.New("invalid input")
|
||||
ErrCredentialState = errors.New("invalid stored credential state")
|
||||
ErrIdempotencyConflict = errors.New("idempotency key is already used for another request")
|
||||
)
|
||||
@@ -0,0 +1,77 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/sha256"
|
||||
"encoding/json"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
type canonicalMessageRequest struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
func (s *Service) SendMessage(ctx context.Context, command SendMessageCommand) (domain.Message, error) {
|
||||
if err := domain.ValidateMessageText(command.Text); err != nil {
|
||||
return domain.Message{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
|
||||
canonicalBody, err := json.Marshal(canonicalMessageRequest{
|
||||
Text: command.Text,
|
||||
AttachmentIDs: make([]string, 0),
|
||||
})
|
||||
if err != nil {
|
||||
return domain.Message{}, fmt.Errorf("canonicalize message request: %w", err)
|
||||
}
|
||||
|
||||
return s.repository.CreateMessageIdempotently(ctx, IdempotentMessageWrite{
|
||||
ActorID: command.ActorID,
|
||||
ChatID: command.ChatID,
|
||||
Text: command.Text,
|
||||
Method: command.Method,
|
||||
CanonicalPath: command.CanonicalPath,
|
||||
Key: command.IdempotencyKey,
|
||||
RequestHash: sha256.Sum256(canonicalBody),
|
||||
TTL: s.idempotencyTTL,
|
||||
})
|
||||
}
|
||||
|
||||
func (s *Service) ListMessages(
|
||||
ctx context.Context,
|
||||
actorID string,
|
||||
chatID string,
|
||||
limit int,
|
||||
cursorToken string,
|
||||
) (domain.MessagePage, error) {
|
||||
var cursor *domain.MessageCursor
|
||||
if cursorToken != "" {
|
||||
decoded, err := s.cursors.DecodeMessage(cursorToken, chatID)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, ErrInvalidCursor
|
||||
}
|
||||
cursor = decoded
|
||||
}
|
||||
|
||||
items, hasMore, err := s.repository.GetMessages(ctx, chatID, actorID, limit, cursor)
|
||||
if err != nil {
|
||||
return domain.MessagePage{}, err
|
||||
}
|
||||
page := domain.MessagePage{Items: items}
|
||||
if page.Items == nil {
|
||||
page.Items = make([]domain.Message, 0)
|
||||
}
|
||||
if hasMore {
|
||||
last := page.Items[len(page.Items)-1]
|
||||
next, encodeErr := s.cursors.EncodeMessage(domain.MessageCursor{
|
||||
CreatedAt: last.CreatedAt, MessageID: last.ID, ChatID: chatID,
|
||||
})
|
||||
if encodeErr != nil {
|
||||
return domain.MessagePage{}, encodeErr
|
||||
}
|
||||
page.NextCursor = &next
|
||||
}
|
||||
return page, nil
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"time"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
)
|
||||
|
||||
type UserRepository interface {
|
||||
CreateUser(ctx context.Context, username, displayName, passwordHash string) (domain.User, error)
|
||||
GetUserByUsername(ctx context.Context, username string) (domain.User, string, error)
|
||||
}
|
||||
|
||||
type SessionRepository interface {
|
||||
CreateSession(ctx context.Context, tokenHash []byte, userID string, expiresAt time.Time) error
|
||||
GetUserBySession(ctx context.Context, tokenHash []byte) (domain.User, error)
|
||||
DeleteSession(ctx context.Context, tokenHash []byte) error
|
||||
}
|
||||
|
||||
type ChatRepository interface {
|
||||
CreateChat(ctx context.Context, title string, memberIDs []string) (domain.Chat, error)
|
||||
GetChatByID(ctx context.Context, chatID, callerID string) (domain.Chat, error)
|
||||
GetChatsForUser(ctx context.Context, userID string, limit int, cursor *domain.ChatCursor) ([]domain.Chat, bool, error)
|
||||
}
|
||||
|
||||
type IdempotentMessageWrite struct {
|
||||
ActorID string
|
||||
ChatID string
|
||||
Text string
|
||||
Method string
|
||||
CanonicalPath string
|
||||
Key string
|
||||
RequestHash [32]byte
|
||||
TTL time.Duration
|
||||
}
|
||||
|
||||
type MessageRepository interface {
|
||||
CreateMessageIdempotently(ctx context.Context, write IdempotentMessageWrite) (domain.Message, error)
|
||||
GetMessages(ctx context.Context, chatID, callerID string, limit int, cursor *domain.MessageCursor) ([]domain.Message, bool, error)
|
||||
}
|
||||
|
||||
type Repository interface {
|
||||
UserRepository
|
||||
SessionRepository
|
||||
ChatRepository
|
||||
MessageRepository
|
||||
}
|
||||
@@ -0,0 +1,53 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"time"
|
||||
)
|
||||
|
||||
const MinimumIdempotencyTTL = 24 * time.Hour
|
||||
|
||||
type ServiceOption func(*Service) error
|
||||
|
||||
type Service struct {
|
||||
repository Repository
|
||||
cursors *CursorCodec
|
||||
sessionTTL time.Duration
|
||||
idempotencyTTL time.Duration
|
||||
now func() time.Time
|
||||
}
|
||||
|
||||
func NewService(repository Repository, cursors *CursorCodec, sessionTTL time.Duration, options ...ServiceOption) (*Service, error) {
|
||||
if repository == nil {
|
||||
return nil, fmt.Errorf("repository is required")
|
||||
}
|
||||
if cursors == nil {
|
||||
return nil, fmt.Errorf("cursor codec is required")
|
||||
}
|
||||
if sessionTTL <= 0 {
|
||||
return nil, fmt.Errorf("session TTL must be positive")
|
||||
}
|
||||
service := &Service{
|
||||
repository: repository,
|
||||
cursors: cursors,
|
||||
sessionTTL: sessionTTL,
|
||||
idempotencyTTL: MinimumIdempotencyTTL,
|
||||
now: func() time.Time { return time.Now().UTC() },
|
||||
}
|
||||
for _, option := range options {
|
||||
if err := option(service); err != nil {
|
||||
return nil, err
|
||||
}
|
||||
}
|
||||
return service, nil
|
||||
}
|
||||
|
||||
func WithIdempotencyTTL(ttl time.Duration) ServiceOption {
|
||||
return func(service *Service) error {
|
||||
if ttl < MinimumIdempotencyTTL {
|
||||
return fmt.Errorf("idempotency TTL must be at least %s", MinimumIdempotencyTTL)
|
||||
}
|
||||
service.idempotencyTTL = ttl
|
||||
return nil
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,57 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
"mtusi2026lab4/internal/security"
|
||||
)
|
||||
|
||||
const dummyPasswordHash = "$argon2id$v=19$m=19456,t=2,p=1$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAA$" +
|
||||
"AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
|
||||
|
||||
func (s *Service) CreateSession(ctx context.Context, command CreateSessionCommand) (domain.Session, error) {
|
||||
user, passwordHash, err := s.repository.GetUserByUsername(ctx, command.Username)
|
||||
userNotFound := errors.Is(err, domain.ErrNotFound)
|
||||
if userNotFound {
|
||||
passwordHash = dummyPasswordHash
|
||||
} else if err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
|
||||
passwordMatches, verifyErr := security.VerifyPassword(command.Password, passwordHash)
|
||||
if verifyErr != nil {
|
||||
return domain.Session{}, fmt.Errorf("%w: %v", ErrCredentialState, verifyErr)
|
||||
}
|
||||
if userNotFound || !passwordMatches {
|
||||
return domain.Session{}, ErrInvalidCredentials
|
||||
}
|
||||
|
||||
token, tokenHash, err := security.GenerateSessionToken()
|
||||
if err != nil {
|
||||
return domain.Session{}, fmt.Errorf("generate session token: %w", err)
|
||||
}
|
||||
expiresAt := s.now().Add(s.sessionTTL)
|
||||
if err = s.repository.CreateSession(ctx, tokenHash, user.ID, expiresAt); err != nil {
|
||||
return domain.Session{}, err
|
||||
}
|
||||
return domain.Session{
|
||||
Token: token, TokenType: "Bearer", ExpiresAt: expiresAt, User: user,
|
||||
}, nil
|
||||
}
|
||||
|
||||
func (s *Service) Authenticate(ctx context.Context, token string) (domain.User, []byte, error) {
|
||||
tokenHash := security.HashSessionToken(token)
|
||||
user, err := s.repository.GetUserBySession(ctx, tokenHash)
|
||||
if err != nil {
|
||||
return domain.User{}, nil, err
|
||||
}
|
||||
return user, tokenHash, nil
|
||||
}
|
||||
|
||||
func (s *Service) DeleteSession(ctx context.Context, tokenHash []byte) error {
|
||||
return s.repository.DeleteSession(ctx, tokenHash)
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package application
|
||||
|
||||
import (
|
||||
"context"
|
||||
"fmt"
|
||||
|
||||
"mtusi2026lab4/internal/domain"
|
||||
"mtusi2026lab4/internal/security"
|
||||
)
|
||||
|
||||
func (s *Service) CreateUser(ctx context.Context, command CreateUserCommand) (domain.User, error) {
|
||||
if err := domain.ValidateUser(command.Username, command.DisplayName); err != nil {
|
||||
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
if err := security.ValidatePassword(command.Password); err != nil {
|
||||
return domain.User{}, fmt.Errorf("%w: %v", ErrInvalidInput, err)
|
||||
}
|
||||
|
||||
passwordHash, err := security.HashPassword(command.Password)
|
||||
if err != nil {
|
||||
return domain.User{}, fmt.Errorf("hash password: %w", err)
|
||||
}
|
||||
return s.repository.CreateUser(
|
||||
ctx,
|
||||
command.Username,
|
||||
command.DisplayName,
|
||||
passwordHash,
|
||||
)
|
||||
}
|
||||
Reference in New Issue
Block a user