lab2 done
Skeleton contracts / contracts (pull_request) Canceled after 0s

This commit is contained in:
Khakimov Dmitrij
2026-10-06 22:38:28 +03:00
parent 47a3cd582d
commit 300ef7714e
74 changed files with 2785 additions and 112 deletions
+1 -1
View File
@@ -28,6 +28,6 @@ func createChatRequestToDomain(request dto.CreateChatRequest) domain.Chat {
func createChatResponseFromDomain(chat domain.Chat) dto.CreateChatResponse {
return dto.CreateChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
}
}
+1 -1
View File
@@ -37,6 +37,6 @@ func createMessageRequestToDomain(request dto.CreateMessageRequest) domain.Messa
func createMessageResponseFromDomain(message domain.Message) dto.CreateMessageResponse {
return dto.CreateMessageResponse{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: message.CreatedAt,
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
}
}
+2 -2
View File
@@ -14,7 +14,7 @@ func (h *Chat) createUser(c echo.Context) error {
if err := decodeJSON(c, &request); err != nil {
return h.jsonError(c, err)
}
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request))
user, err := h.useCase.CreateUser(c.Request().Context(), createUserRequestToDomain(request), request.Password)
if err != nil {
return h.useCaseError(c, err)
}
@@ -27,6 +27,6 @@ func createUserRequestToDomain(request dto.CreateUserRequest) domain.User {
func createUserResponseFromDomain(user domain.User) dto.CreateUserResponse {
return dto.CreateUserResponse{
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
}
}
+1 -1
View File
@@ -16,6 +16,6 @@ func (h *Chat) currentUser(c echo.Context) error {
func currentUserResponseFromDomain(user domain.User) dto.CurrentUserResponse {
return dto.CurrentUserResponse{
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: user.CreatedAt,
ID: user.ID, Username: user.Username, DisplayName: user.DisplayName, CreatedAt: dto.Timestamp(user.CreatedAt),
}
}
-9
View File
@@ -2,7 +2,6 @@ package chat
import (
"crypto/hmac"
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/json"
@@ -24,14 +23,6 @@ type cursorCodec struct {
secret [32]byte
}
func newCursorCodec() cursorCodec {
var codec cursorCodec
if _, err := rand.Read(codec.secret[:]); err != nil {
panic("cannot initialize cursor signing key: " + err.Error())
}
return codec
}
func (c cursorCodec) encode(scope, owner string, createdAt time.Time, id string) string {
payload, err := json.Marshal(cursorPayload{
Scope: scope,
+7
View File
@@ -33,10 +33,17 @@ func (h *Chat) useCaseError(c echo.Context, err error) error {
}
status := http.StatusInternalServerError
switch applicationError.Code {
case domain.ErrorUnavailable:
status = http.StatusServiceUnavailable
case domain.ErrorInvalid:
status = http.StatusBadRequest
case domain.ErrorUnauthorized:
status = http.StatusUnauthorized
challenge := `Bearer realm="messenger"`
if c.Path() == "/api/v1/auth/sessions" {
challenge = `Basic realm="messenger", charset="UTF-8"`
}
c.Response().Header().Set("WWW-Authenticate", challenge)
case domain.ErrorNotFound:
status = http.StatusNotFound
case domain.ErrorConflict:
+1 -1
View File
@@ -27,6 +27,6 @@ func getChatRequestToDomain(request dto.GetChatRequest) domain.Chat {
func getChatResponseFromDomain(chat domain.Chat) dto.GetChatResponse {
return dto.GetChatResponse{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
}
}
+1 -1
View File
@@ -46,7 +46,7 @@ func listChatsResponseFromDomain(page domain.ChatPage, nextCursor *string) dto.L
items := make([]dto.ListChatsItem, 0, len(page.Items))
for _, chat := range page.Items {
items = append(items, dto.ListChatsItem{
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: chat.CreatedAt,
ID: chat.ID, Title: chat.Title, MemberIDs: chat.MemberIDs, CreatedAt: dto.Timestamp(chat.CreatedAt),
})
}
return dto.ListChatsResponse{Items: items, NextCursor: nextCursor}
+1 -1
View File
@@ -63,7 +63,7 @@ func listMessagesResponseFromDomain(page domain.MessagePage, nextCursor *string)
for _, message := range page.Items {
items = append(items, dto.ListMessagesItem{
ID: message.ID, ChatID: message.ChatID, SenderID: message.SenderID,
Text: message.Text, CreatedAt: message.CreatedAt,
Text: message.Text, CreatedAt: dto.Timestamp(message.CreatedAt),
})
}
return dto.ListMessagesResponse{Items: items, NextCursor: nextCursor}
+1 -1
View File
@@ -23,7 +23,7 @@ func (h *Chat) requestIDMiddleware(next echo.HandlerFunc) echo.HandlerFunc {
func (h *Chat) authenticate(next echo.HandlerFunc) echo.HandlerFunc {
return func(c echo.Context) error {
user, err := h.useCase.Authenticate(c.Request().Context(), c.Request().Header.Get("X-User-Id"))
user, err := h.useCase.Authenticate(c.Request().Context(), bearerToken(c))
if err != nil {
return h.useCaseError(c, err)
}
+3
View File
@@ -9,5 +9,8 @@ import (
)
func (h *Chat) readiness(c echo.Context) error {
if err := h.useCase.Ready(c.Request().Context()); err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusOK, dto.ReadinessResponse{Status: "ok"})
}
+5 -2
View File
@@ -14,8 +14,8 @@ type Chat struct {
cursor cursorCodec
}
func NewChat(useCase UseCase) *Chat {
return &Chat{useCase: useCase, cursor: newCursorCodec()}
func NewChat(useCase UseCase, cursorKey [32]byte) *Chat {
return &Chat{useCase: useCase, cursor: cursorCodec{secret: cursorKey}}
}
func (h *Chat) Router() *echo.Echo {
@@ -60,8 +60,11 @@ func (h *Chat) Router() *echo.Echo {
e.GET("/swagger/*", swaggerUI)
e.POST("/api/v1/users", h.createUser)
e.POST("/api/v1/auth/sessions", h.createSession)
api := e.Group("/api/v1", h.authenticate)
api.GET("/users/me", h.currentUser)
api.DELETE("/auth/sessions/current", h.deleteSession)
api.POST("/chats", h.createChat)
api.GET("/chats", h.listChats)
api.GET("/chats/:chat_id", h.getChat)
+59 -6
View File
@@ -2,6 +2,8 @@ package chat_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
@@ -13,12 +15,14 @@ import (
"time"
chathandler "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/app/chat"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
type testAPI struct {
server *httptest.Server
tokens sync.Map
}
type userResponse struct {
@@ -47,8 +51,8 @@ type errorResponse struct {
func newTestAPI(t *testing.T) *testAPI {
t.Helper()
useCase := chatusecase.New(repository.NewMemory())
server := httptest.NewServer(chathandler.NewChat(useCase).Router())
useCase := chatusecase.New(repository.NewMemory(), &testSessions{values: map[string]domain.Session{}}, time.Hour)
server := httptest.NewServer(chathandler.NewChat(useCase, [32]byte{1}).Router())
t.Cleanup(server.Close)
return &testAPI{server: server}
}
@@ -63,7 +67,8 @@ func (a *testAPI) request(t *testing.T, client *http.Client, method, path, actor
request.Header.Set("Content-Type", "application/json")
}
if actorID != "" {
request.Header.Set("X-User-Id", actorID)
token, _ := a.tokens.Load(actorID)
request.Header.Set("Authorization", "Bearer "+token.(string))
}
response, err := client.Do(request)
if err != nil {
@@ -91,7 +96,27 @@ func (a *testAPI) createUser(t *testing.T, username string) userResponse {
t.Helper()
var user userResponse
a.request(t, http.DefaultClient, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":%q}`, username, username), http.StatusCreated, &user)
fmt.Sprintf(`{"username":%q,"display_name":%q,"password":"test-password-12345"}`, username, username), http.StatusCreated, &user)
req, err := http.NewRequest(http.MethodPost, a.server.URL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(username+":test-password-12345")))
response, err := http.DefaultClient.Do(req)
if err != nil {
t.Fatal(err)
}
defer response.Body.Close()
var login struct {
Token string `json:"token"`
}
if response.StatusCode != http.StatusCreated {
t.Fatalf("login status: %d", response.StatusCode)
}
if err = json.NewDecoder(response.Body).Decode(&login); err != nil {
t.Fatal(err)
}
a.tokens.Store(user.ID, login.Token)
return user
}
@@ -153,7 +178,7 @@ func TestRejectsDuplicateUsername(t *testing.T) {
api := newTestAPI(t)
api.createUser(t, "duplicate_user")
api.requestError(t, http.MethodPost, "/api/v1/users", "",
`{"username":"duplicate_user","display_name":"Duplicate"}`, http.StatusConflict, "conflict")
`{"username":"duplicate_user","display_name":"Duplicate","password":"test-password-12345"}`, http.StatusConflict, "conflict")
}
func TestPaginatesMessagesAcrossMultiplePages(t *testing.T) {
@@ -232,7 +257,8 @@ func TestConcurrentMessagesAreUnique(t *testing.T) {
return
}
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-User-Id", users[clientIndex].ID)
token, _ := api.tokens.Load(users[clientIndex].ID)
request.Header.Set("Authorization", "Bearer "+token.(string))
response, err := client.Do(request)
if err != nil {
errors <- err
@@ -294,3 +320,30 @@ func TestConcurrentMessagesAreUnique(t *testing.T) {
len(seenIDs), len(seenTexts), 10*10)
}
}
// Session fake is only used by HTTP unit tests; the server always uses Redis.
type testSessions struct {
mu sync.Mutex
values map[string]domain.Session
}
func (s *testSessions) Ready(context.Context) error { return nil }
func (s *testSessions) Put(_ context.Context, key string, value domain.Session) error {
s.mu.Lock()
defer s.mu.Unlock()
s.values[key] = value
return nil
}
func (s *testSessions) Get(_ context.Context, key string) (domain.Session, bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
value, ok := s.values[key]
return value, ok, nil
}
func (s *testSessions) Delete(_ context.Context, key string) (bool, error) {
s.mu.Lock()
defer s.mu.Unlock()
_, ok := s.values[key]
delete(s.values, key)
return ok, nil
}
+45
View File
@@ -0,0 +1,45 @@
package chat
import (
"io"
"net/http"
"strings"
"github.com/labstack/echo/v4"
"gitflic.ru/akselbant/mtusi2026lab1-fork/dto"
)
func bearerToken(c echo.Context) string {
parts := strings.Fields(c.Request().Header.Get("Authorization"))
if len(parts) != 2 || !strings.EqualFold(parts[0], "Bearer") {
return ""
}
return parts[1]
}
func (h *Chat) createSession(c echo.Context) error {
username, password, ok := c.Request().BasicAuth()
if !ok {
c.Response().Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
return h.writeError(c, http.StatusUnauthorized, "unauthorized", "Неверные учётные данные")
}
body, err := io.ReadAll(io.LimitReader(c.Request().Body, 1))
if err != nil || len(body) != 0 {
return h.invalid(c, "Тело запроса входа должно быть пустым")
}
login, err := h.useCase.CreateSession(c.Request().Context(), username, password)
if err != nil {
return h.useCaseError(c, err)
}
return c.JSON(http.StatusCreated, dto.CreateSessionResponse{
Token: login.Token, TokenType: "Bearer", ExpiresAt: dto.Timestamp(login.ExpiresAt), User: createUserResponseFromDomain(login.User),
})
}
func (h *Chat) deleteSession(c echo.Context) error {
if err := h.useCase.DeleteSession(c.Request().Context(), bearerToken(c)); err != nil {
return h.useCaseError(c, err)
}
return c.NoContent(http.StatusNoContent)
}
+5 -2
View File
@@ -8,8 +8,11 @@ import (
// UseCase is the application boundary required by the HTTP handler.
type UseCase interface {
Authenticate(ctx context.Context, rawUserID string) (domain.User, error)
CreateUser(ctx context.Context, user domain.User) (domain.User, error)
Ready(context.Context) error
CreateSession(context.Context, string, string) (domain.Login, error)
DeleteSession(context.Context, string) error
Authenticate(ctx context.Context, token string) (domain.User, error)
CreateUser(ctx context.Context, user domain.User, password string) (domain.User, error)
CreateChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
GetChat(ctx context.Context, callerID string, chat domain.Chat) (domain.Chat, error)
ListChats(ctx context.Context, callerID string, pagination domain.Pagination) (domain.ChatPage, error)
+100
View File
@@ -0,0 +1,100 @@
package config
import (
"encoding/hex"
"fmt"
"os"
"strconv"
"strings"
"time"
)
type Config struct {
Port string
PostgresHost string
PostgresPort uint16
PostgresUser string
PostgresDatabase string
PostgresPassword string
PostgresMaxConns int32
RedisAddr string
SessionTTL time.Duration
QueryTimeout time.Duration
CursorKey [32]byte
}
func value(name, fallback string) string {
if v := os.Getenv(name); v != "" {
return v
}
return fallback
}
func positive(name string, fallback, max int) (int, error) {
n, err := strconv.Atoi(value(name, strconv.Itoa(fallback)))
if err != nil || n < 1 || n > max {
return 0, fmt.Errorf("invalid %s", name)
}
return n, nil
}
func secret(name string) (string, error) {
if file := os.Getenv(name + "_FILE"); file != "" {
data, err := os.ReadFile(file)
if err != nil {
return "", fmt.Errorf("cannot read %s_FILE", name)
}
if s := strings.TrimSpace(string(data)); s != "" {
return s, nil
}
}
if s := os.Getenv(name); s != "" {
return s, nil
}
return "", fmt.Errorf("%s or %s_FILE is required", name, name)
}
func Load() (Config, error) {
var c Config
port, err := positive("PORT", 8080, 65535)
if err != nil {
return c, err
}
c.Port = strconv.Itoa(port)
pgPort, err := positive("POSTGRES_PORT", 5432, 65535)
if err != nil {
return c, err
}
c.PostgresPort = uint16(pgPort)
max, err := positive("POSTGRES_MAX_CONNS", 10, 100)
if err != nil {
return c, err
}
c.PostgresMaxConns = int32(max)
ttl, err := positive("SESSION_TTL_SECONDS", 3600, 86400*30)
if err != nil {
return c, err
}
c.SessionTTL = time.Duration(ttl) * time.Second
timeout, err := positive("QUERY_TIMEOUT_MS", 2000, 10000)
if err != nil {
return c, err
}
c.QueryTimeout = time.Duration(timeout) * time.Millisecond
c.PostgresHost = value("POSTGRES_HOST", "localhost")
c.PostgresUser = value("POSTGRES_USER", "messenger")
c.PostgresDatabase = value("POSTGRES_DB", "messenger")
c.RedisAddr = value("REDIS_ADDR", "localhost:6379")
c.PostgresPassword, err = secret("POSTGRES_PASSWORD")
if err != nil {
return c, err
}
key, err := secret("CURSOR_KEY")
if err != nil {
return c, err
}
decoded, err := hex.DecodeString(key)
if err != nil || len(decoded) != 32 {
return c, fmt.Errorf("CURSOR_KEY must be 32 random bytes encoded as hex")
}
copy(c.CursorKey[:], decoded)
return c, nil
}
+1
View File
@@ -5,6 +5,7 @@ import "errors"
type ErrorCode string
const (
ErrorUnavailable ErrorCode = "unavailable"
ErrorInvalid ErrorCode = "invalid_request"
ErrorUnauthorized ErrorCode = "unauthorized"
ErrorNotFound ErrorCode = "not_found"
+14
View File
@@ -0,0 +1,14 @@
package domain
import "time"
type Session struct {
UserID string `json:"user_id"`
ExpiresAt time.Time `json:"expires_at"`
}
type Login struct {
Token string
ExpiresAt time.Time
User User
}
+65
View File
@@ -0,0 +1,65 @@
package password
import (
"context"
"crypto/rand"
"crypto/subtle"
"encoding/base64"
"errors"
"strings"
"golang.org/x/crypto/argon2"
)
// Bound simultaneous KDF work to 4 * 19 MiB, including concurrent registrations.
var slots = make(chan struct{}, 4)
const prefix = "$argon2id$v=19$m=19456,t=2,p=1$"
func derive(ctx context.Context, password string, salt []byte) ([]byte, error) {
select {
case slots <- struct{}{}:
case <-ctx.Done():
return nil, ctx.Err()
}
defer func() { <-slots }()
if err := ctx.Err(); err != nil {
return nil, err
}
return argon2.IDKey([]byte(password), salt, 2, 19456, 1, 32), nil
}
func Hash(ctx context.Context, password string) (string, error) {
salt := make([]byte, 16)
if _, err := rand.Read(salt); err != nil {
return "", err
}
key, err := derive(ctx, password, salt)
if err != nil {
return "", err
}
return prefix + base64.RawStdEncoding.EncodeToString(salt) + "$" + base64.RawStdEncoding.EncodeToString(key), nil
}
func Verify(ctx context.Context, password, encoded string) (bool, error) {
if !strings.HasPrefix(encoded, prefix) {
return false, errors.New("unsupported password hash")
}
parts := strings.Split(strings.TrimPrefix(encoded, prefix), "$")
if len(parts) != 2 {
return false, errors.New("invalid password hash")
}
salt, err := base64.RawStdEncoding.DecodeString(parts[0])
if err != nil || len(salt) != 16 {
return false, errors.New("invalid salt")
}
expected, err := base64.RawStdEncoding.DecodeString(parts[1])
if err != nil || len(expected) != 32 {
return false, errors.New("invalid hash")
}
actual, err := derive(ctx, password, salt)
return subtle.ConstantTimeCompare(actual, expected) == 1, err
}
// A valid fixed encoding for equal-cost verification when username does not exist.
const DummyHash = prefix + "AAAAAAAAAAAAAAAAAAAAAA$AAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAAA"
+35
View File
@@ -0,0 +1,35 @@
package password_test
import (
"context"
"strings"
"testing"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/password"
)
func TestUnicodeAndSalt(t *testing.T) {
ctx := context.Background()
secret := strings.Repeat("🔑", 128)
first, err := password.Hash(ctx, secret)
if err != nil {
t.Fatal(err)
}
second, err := password.Hash(ctx, secret)
if err != nil {
t.Fatal(err)
}
if first == second {
t.Fatal("password hashes reused salt")
}
for _, hash := range []string{first, second} {
ok, err := password.Verify(ctx, secret, hash)
if err != nil || !ok {
t.Fatal("128-code-point UTF-8 password rejected")
}
ok, err = password.Verify(ctx, strings.Repeat("🔑", 127)+"x", hash)
if err != nil || ok {
t.Fatal("password suffix was ignored")
}
}
}
+12 -1
View File
@@ -16,6 +16,7 @@ import (
type Memory struct {
mu sync.RWMutex
users map[string]domain.User
hashes map[string]string
userByUsername map[string]string
chats map[string]domain.Chat
messages map[string][]domain.Message
@@ -26,13 +27,14 @@ var _ chatusecase.Repository = (*Memory)(nil)
func NewMemory() *Memory {
return &Memory{
users: make(map[string]domain.User),
hashes: make(map[string]string),
userByUsername: make(map[string]string),
chats: make(map[string]domain.Chat),
messages: make(map[string][]domain.Message),
}
}
func (m *Memory) CreateUser(_ context.Context, username, displayName string) (domain.User, error) {
func (m *Memory) CreateUser(_ context.Context, username, displayName, hash string) (domain.User, error) {
m.mu.Lock()
defer m.mu.Unlock()
@@ -46,6 +48,7 @@ func (m *Memory) CreateUser(_ context.Context, username, displayName string) (do
CreatedAt: now(),
}
m.users[user.ID] = user
m.hashes[user.ID] = hash
m.userByUsername[user.Username] = user.ID
return user, nil
}
@@ -178,3 +181,11 @@ func less(leftTime time.Time, leftID string, rightTime time.Time, rightID string
}
return leftTime.Before(rightTime)
}
func (m *Memory) Ready(context.Context) error { return nil }
func (m *Memory) UserByUsername(_ context.Context, username string) (domain.User, string, bool, error) {
m.mu.RLock()
defer m.mu.RUnlock()
id, ok := m.userByUsername[username]
return m.users[id], m.hashes[id], ok, nil
}
+78
View File
@@ -0,0 +1,78 @@
package postgres
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
func (s *Storage) CreateChat(ctx context.Context, title string, members []string) (domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
tx, err := s.pool.Begin(ctx)
if err != nil {
return domain.Chat{}, dbError(err)
}
defer tx.Rollback(context.WithoutCancel(ctx))
chat := domain.Chat{ID: uuid.NewString(), Title: title, MemberIDs: append([]string(nil), members...)}
err = tx.QueryRow(ctx, `INSERT INTO chats(id,title) VALUES($1,$2) RETURNING created_at`, chat.ID, title).Scan(&chat.CreatedAt)
if err != nil {
return domain.Chat{}, dbError(err)
}
for i, member := range members {
if _, err = tx.Exec(ctx, `INSERT INTO chat_members(chat_id,user_id,ordinal) VALUES($1,$2,$3)`, chat.ID, member, i); err != nil {
return domain.Chat{}, dbError(err)
}
}
if err = tx.Commit(ctx); err != nil {
return domain.Chat{}, dbError(err)
}
return chat, nil
}
const chatColumns = `c.id::text,c.title,c.created_at,ARRAY(SELECT m.user_id::text FROM chat_members m WHERE m.chat_id=c.id ORDER BY m.ordinal)`
func (s *Storage) ChatForUser(ctx context.Context, chatID, userID string) (domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var chat domain.Chat
err := s.pool.QueryRow(ctx, `SELECT `+chatColumns+` FROM chats c
WHERE c.id=$1 AND EXISTS(SELECT 1 FROM chat_members m WHERE m.chat_id=c.id AND m.user_id=$2)`, chatID, userID).
Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs)
if errors.Is(err, pgx.ErrNoRows) {
return chat, chatusecase.ErrChatNotFound
}
return chat, dbError(err)
}
func (s *Storage) ListChats(ctx context.Context, userID string, after *domain.Position, limit int) ([]domain.Chat, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `SELECT ` + chatColumns + ` FROM chats c JOIN chat_members member ON member.chat_id=c.id
WHERE member.user_id=$1`
args := []any{userID, limit}
if after != nil {
query += ` AND (c.created_at,c.id)>($3,$4)`
args = append(args, after.CreatedAt, after.ID)
}
query += ` ORDER BY c.created_at,c.id LIMIT $2`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
chats := make([]domain.Chat, 0)
for rows.Next() {
var chat domain.Chat
if err = rows.Scan(&chat.ID, &chat.Title, &chat.CreatedAt, &chat.MemberIDs); err != nil {
return nil, dbError(err)
}
chats = append(chats, chat)
}
return chats, dbError(rows.Err())
}
@@ -0,0 +1,44 @@
package postgres
import (
"context"
"github.com/google/uuid"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (s *Storage) CreateMessage(ctx context.Context, chatID, senderID, text string) (domain.Message, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
message := domain.Message{ID: uuid.NewString(), ChatID: chatID, SenderID: senderID, Text: text}
err := s.pool.QueryRow(ctx, `INSERT INTO messages(id,chat_id,sender_id,text) VALUES($1,$2,$3,$4) RETURNING created_at`,
message.ID, chatID, senderID, text).Scan(&message.CreatedAt)
return message, dbError(err)
}
func (s *Storage) ListMessages(ctx context.Context, chatID string, after *domain.Position, limit int) ([]domain.Message, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
query := `SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m WHERE m.chat_id=$1`
args := []any{chatID, limit}
if after != nil {
query += ` AND (m.created_at,m.id)>($3,$4)`
args = append(args, after.CreatedAt, after.ID)
}
query += ` ORDER BY m.created_at,m.id LIMIT $2`
rows, err := s.pool.Query(ctx, query, args...)
if err != nil {
return nil, dbError(err)
}
defer rows.Close()
messages := make([]domain.Message, 0)
for rows.Next() {
var m domain.Message
if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil {
return nil, dbError(err)
}
messages = append(messages, m)
}
return messages, dbError(rows.Err())
}
@@ -0,0 +1,51 @@
package postgres
import (
"context"
"errors"
"log"
"time"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgconn"
"github.com/jackc/pgx/v5/pgxpool"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
type Storage struct {
pool *pgxpool.Pool
timeout time.Duration
}
var _ chatusecase.Repository = (*Storage)(nil)
func New(pool *pgxpool.Pool, timeout time.Duration) *Storage {
return &Storage{pool: pool, timeout: timeout}
}
func (s *Storage) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return dbError(s.pool.Ping(ctx))
}
func dbError(err error) error {
if err == nil {
return nil
}
var pgErr *pgconn.PgError
if errors.As(err, &pgErr) {
switch pgErr.Code {
case "23505":
return chatusecase.ErrUsernameTaken
case "23503":
return chatusecase.ErrUserNotFound
}
log.Printf("postgres operation failed: sqlstate=%s", pgErr.Code)
} else if !errors.Is(err, pgx.ErrNoRows) {
log.Print("postgres operation failed")
}
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище недоступно")
}
@@ -0,0 +1,232 @@
package postgres_test
import (
"context"
"errors"
"net"
"net/url"
"os"
"os/exec"
"path/filepath"
"strconv"
"strings"
"sync"
"testing"
"time"
"github.com/google/uuid"
"github.com/jackc/pgx/v5/pgxpool"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/config"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/repository/postgres"
chatusecase "gitflic.ru/akselbant/mtusi2026lab1-fork/internal/usecase/chat"
)
func TestIntegration(t *testing.T) {
if os.Getenv("INTEGRATION_TESTS") != "1" {
t.Skip("run make test-integration against the Compose stack")
}
ctx := context.Background()
cfg, err := config.Load()
if err != nil {
t.Fatal(err)
}
pc, err := pgxpool.ParseConfig("sslmode=disable")
if err != nil {
t.Fatal(err)
}
pc.ConnConfig.Host = cfg.PostgresHost
pc.ConnConfig.Port = cfg.PostgresPort
pc.ConnConfig.User = cfg.PostgresUser
pc.ConnConfig.Database = cfg.PostgresDatabase
pc.ConnConfig.Password = cfg.PostgresPassword
pc.ConnConfig.RuntimeParams["timezone"] = "UTC"
pc.MaxConns = 4
admin, err := pgxpool.NewWithConfig(ctx, pc.Copy())
if err != nil {
t.Fatal("connect failed")
}
defer admin.Close()
// Identifier is generated by the test, never from an API request.
schema := "test_" + uuid.New().String()[:8]
if _, err = admin.Exec(ctx, `CREATE SCHEMA `+schema); err != nil {
t.Fatal(err)
}
defer admin.Exec(ctx, `DROP SCHEMA `+schema+` CASCADE`)
pc.ConnConfig.RuntimeParams["search_path"] = schema
pool, err := pgxpool.NewWithConfig(ctx, pc)
if err != nil {
t.Fatal(err)
}
defer pool.Close()
runGoose := func(t *testing.T, command string) {
t.Helper()
migrationDir := os.Getenv("GOOSE_MIGRATION_DIR")
if migrationDir == "" {
migrationDir, err = filepath.Abs("../../../../migrations")
if err != nil {
t.Fatal(err)
}
}
connection := url.URL{Scheme: "postgres", User: url.User(cfg.PostgresUser), Host: net.JoinHostPort(cfg.PostgresHost, strconv.Itoa(int(cfg.PostgresPort))), Path: cfg.PostgresDatabase}
connection.RawQuery = url.Values{"sslmode": {"disable"}, "search_path": {schema}, "connect_timeout": {"5"}}.Encode()
commandCtx, cancel := context.WithTimeout(ctx, 45*time.Second)
defer cancel()
commandExec := exec.CommandContext(commandCtx, "goose", "-env", "/dev/null", "-dir", migrationDir, "-timeout", "30s", command)
commandExec.Env = append(os.Environ(), "GOOSE_DRIVER=postgres", "GOOSE_DBSTRING="+connection.String(), "PGPASSWORD="+cfg.PostgresPassword)
output, err := commandExec.CombinedOutput()
if err != nil {
t.Fatalf("goose %s: %v: %s", command, err, strings.ReplaceAll(string(output), cfg.PostgresPassword, "[redacted]"))
}
t.Logf("goose %s: %s", command, output)
}
runGoose(t, "up")
runGoose(t, "up")
var versions int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM goose_db_version WHERE version_id=1 AND is_applied`).Scan(&versions); err != nil || versions != 1 {
t.Fatalf("migration versions=%d error=%v", versions, err)
}
repo := postgres.New(pool, 2*time.Second)
t.Run("registration_race", func(t *testing.T) {
const count = 12
results := make(chan error, count)
var wg sync.WaitGroup
start := make(chan struct{})
for i := 0; i < count; i++ {
wg.Add(1)
go func() {
defer wg.Done()
<-start
_, err := repo.CreateUser(ctx, "same_username", "Same", "test-hash")
results <- err
}()
}
close(start)
wg.Wait()
close(results)
successes, conflicts := 0, 0
for err := range results {
if err == nil {
successes++
} else if errors.Is(err, chatusecase.ErrUsernameTaken) {
conflicts++
} else {
t.Fatal(err)
}
}
if successes != 1 || conflicts != count-1 {
t.Fatalf("successes=%d conflicts=%d", successes, conflicts)
}
t.Logf("12 concurrent INSERTs: %d success, %d unique conflicts", successes, conflicts)
})
user, err := repo.CreateUser(ctx, "history_owner", "Owner", "test-hash")
if err != nil {
t.Fatal(err)
}
t.Run("rollback", func(t *testing.T) {
_, err := repo.CreateChat(ctx, "must rollback", []string{user.ID, uuid.NewString()})
if !errors.Is(err, chatusecase.ErrUserNotFound) {
t.Fatalf("unexpected error %v", err)
}
var chats, members int
if err = pool.QueryRow(ctx, `SELECT (SELECT count(*) FROM chats),(SELECT count(*) FROM chat_members)`).Scan(&chats, &members); err != nil {
t.Fatal(err)
}
if chats != 0 || members != 0 {
t.Fatalf("partial transaction: chats=%d members=%d", chats, members)
}
t.Log("failed second member INSERT left 0 chats and 0 members")
})
chat, err := repo.CreateChat(ctx, "History", []string{user.ID})
if err != nil {
t.Fatal(err)
}
_, err = pool.Exec(ctx, `INSERT INTO messages(id,chat_id,sender_id,text,created_at)
SELECT md5(i::text)::uuid,$1,$2,'synthetic message '||i,
timestamptz '2026-01-01 00:00:00+00' + (i / 10) * interval '1 millisecond'
FROM generate_series(1,10000) i`, chat.ID, user.ID)
if err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `ANALYZE messages`); err != nil {
t.Fatal(err)
}
t.Run("keyset_and_explain", func(t *testing.T) {
seen := make(map[string]bool)
var after *domain.Position
for {
page, err := repo.ListMessages(ctx, chat.ID, after, 97)
if err != nil {
t.Fatal(err)
}
if len(page) == 0 {
break
}
for _, message := range page {
if seen[message.ID] {
t.Fatal("duplicate on page boundary")
}
seen[message.ID] = true
}
last := page[len(page)-1]
after = &domain.Position{CreatedAt: last.CreatedAt, ID: last.ID}
}
if len(seen) != 10000 {
t.Fatalf("history count=%d", len(seen))
}
rows, err := pool.Query(ctx, `EXPLAIN (ANALYZE, BUFFERS)
SELECT m.id::text,m.chat_id::text,m.sender_id::text,m.text,m.created_at FROM messages m
WHERE m.chat_id=$1 AND (m.created_at,m.id)>($2,$3) ORDER BY m.created_at,m.id LIMIT $4`,
chat.ID, time.Date(2026, 1, 1, 0, 0, 0, 900000000, time.UTC), "00000000-0000-0000-0000-000000000000", 51)
if err != nil {
t.Fatal(err)
}
defer rows.Close()
t.Log("EXPLAIN on 10,000 messages, cursor near the end (9,000):")
for rows.Next() {
var line string
if err = rows.Scan(&line); err != nil {
t.Fatal(err)
}
t.Log(line)
}
if err = rows.Err(); err != nil {
t.Fatal(err)
}
t.Log("keyset traversal returned 10,000 distinct messages, including equal timestamps")
})
t.Run("goose_legacy_and_down", func(t *testing.T) {
// This is the disposable test schema, never the application's public schema.
const digestSQL = `SELECT md5(string_agg(ROW(id,chat_id,sender_id,text,created_at)::text,',' ORDER BY id)) FROM messages`
var before, after string
if err = pool.QueryRow(ctx, digestSQL).Scan(&before); err != nil {
t.Fatal(err)
}
if _, err = pool.Exec(ctx, `DROP TABLE goose_db_version;
CREATE TABLE schema_migrations(version text PRIMARY KEY,applied_at timestamptz NOT NULL DEFAULT now());
INSERT INTO schema_migrations(version) VALUES('001_initial.sql')`); err != nil {
t.Fatal(err)
}
runGoose(t, "up")
runGoose(t, "up")
if err = pool.QueryRow(ctx, digestSQL).Scan(&after); err != nil {
t.Fatal(err)
}
if before != after {
t.Fatal("legacy migration changed message data")
}
t.Log("adopted legacy schema: all 10,000 messages are unchanged")
runGoose(t, "down")
var tables int
if err = pool.QueryRow(ctx, `SELECT count(*) FROM information_schema.tables WHERE table_schema=$1 AND table_name IN ('users','chats','chat_members','messages','schema_migrations')`, schema).Scan(&tables); err != nil || tables != 0 {
t.Fatalf("down left %d application tables: %v", tables, err)
}
runGoose(t, "up")
if err = pool.QueryRow(ctx, `SELECT count(*) FROM messages`).Scan(&tables); err != nil || tables != 0 {
t.Fatalf("up after down failed: %v", err)
}
t.Log("down and up succeeded in isolated schema")
})
}
+46
View File
@@ -0,0 +1,46 @@
package postgres
import (
"context"
"errors"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
func (s *Storage) CreateUser(ctx context.Context, username, displayName, hash string) (domain.User, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user domain.User
err := s.pool.QueryRow(ctx, `INSERT INTO users(id,username,display_name,password_hash) VALUES($1,$2,$3,$4)
RETURNING id::text,username,display_name,created_at`, uuid.NewString(), username, displayName, hash).
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
return user, dbError(err)
}
func (s *Storage) User(ctx context.Context, id string) (domain.User, bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user domain.User
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at FROM users WHERE id=$1`, id).
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return user, false, nil
}
return user, err == nil, dbError(err)
}
func (s *Storage) UserByUsername(ctx context.Context, username string) (domain.User, string, bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var user domain.User
var hash string
err := s.pool.QueryRow(ctx, `SELECT id::text,username,display_name,created_at,password_hash FROM users WHERE username=$1`, username).
Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash)
if errors.Is(err, pgx.ErrNoRows) {
return user, "", false, nil
}
return user, hash, err == nil, dbError(err)
}
+71
View File
@@ -0,0 +1,71 @@
package session
import (
"context"
"encoding/json"
"errors"
"log"
"time"
"github.com/redis/go-redis/v9"
"gitflic.ru/akselbant/mtusi2026lab1-fork/internal/pkg/domain"
)
type Redis struct {
client *redis.Client
timeout time.Duration
}
func NewRedis(client *redis.Client, timeout time.Duration) *Redis {
return &Redis{client: client, timeout: timeout}
}
func unavailable(err error) error {
if err == nil {
return nil
}
log.Print("redis operation failed")
return domain.NewApplicationError(domain.ErrorUnavailable, "Хранилище сессий недоступно")
}
func (s *Redis) Ready(ctx context.Context) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
return unavailable(s.client.Ping(ctx).Err())
}
func (s *Redis) Put(ctx context.Context, key string, value domain.Session) error {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
data, err := json.Marshal(value)
if err != nil {
return err
}
// Absolute expiry prevents TTL extension by network delay or restart.
return unavailable(s.client.Do(ctx, "SET", "session:"+key, data, "PXAT", value.ExpiresAt.UnixMilli()).Err())
}
func (s *Redis) Get(ctx context.Context, key string) (domain.Session, bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
var value domain.Session
data, err := s.client.Get(ctx, "session:"+key).Bytes()
if errors.Is(err, redis.Nil) {
return value, false, nil
}
if err != nil {
return value, false, unavailable(err)
}
if err = json.Unmarshal(data, &value); err != nil {
return value, false, unavailable(err)
}
return value, time.Now().Before(value.ExpiresAt), nil
}
func (s *Redis) Delete(ctx context.Context, key string) (bool, error) {
ctx, cancel := context.WithTimeout(ctx, s.timeout)
defer cancel()
count, err := s.client.Del(ctx, "session:"+key).Result()
return count > 0, unavailable(err)
}
+3 -1
View File
@@ -16,7 +16,9 @@ var (
// Repository is the persistence port required by the chat use case.
type Repository interface {
CreateUser(ctx context.Context, username, displayName string) (domain.User, error)
Ready(ctx context.Context) error
UserByUsername(ctx context.Context, username string) (domain.User, string, bool, 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)
+16 -20
View File
@@ -3,41 +3,37 @@ package chat
import (
"context"
"errors"
"time"
"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) *UseCase {
return &UseCase{repository: repository}
func New(repository Repository, sessions Sessions, ttl time.Duration) *UseCase {
return &UseCase{repository: repository, sessions: sessions, sessionTTL: ttl}
}
func (u *UseCase) Authenticate(ctx context.Context, rawUserID string) (domain.User, error) {
userID, valid := normalizeUUID(rawUserID)
if !valid {
return domain.User{}, unauthorized()
}
user, exists, err := u.repository.User(ctx, userID)
if err != nil {
return domain.User{}, err
}
if !exists {
return domain.User{}, unauthorized()
}
return user, nil
}
func (u *UseCase) CreateUser(ctx context.Context, user domain.User) (domain.User, error) {
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 символов")
}
created, err := u.repository.CreateUser(ctx, user.Username, user.DisplayName)
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 уже существует")
}
@@ -154,7 +150,7 @@ func invalid(message string) error {
}
func unauthorized() error {
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительный X-User-Id")
return domain.NewApplicationError(domain.ErrorUnauthorized, "Требуется действительная сессия")
}
func notFound() error {
+102
View File
@@ -0,0 +1,102 @@
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()
}
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")
}
}
}