diff --git a/go.mod b/go.mod index e6db6494..99bf2424 100644 --- a/go.mod +++ b/go.mod @@ -2,4 +2,16 @@ module messenger go 1.22.2 -require github.com/google/uuid v1.6.0 +require ( + github.com/google/uuid v1.6.0 + github.com/jackc/pgx/v5 v5.5.5 + golang.org/x/crypto v0.22.0 +) + +require ( + github.com/jackc/pgpassfile v1.0.0 // indirect + github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a // indirect + github.com/jackc/puddle/v2 v2.2.1 // indirect + golang.org/x/sync v0.1.0 // indirect + golang.org/x/text v0.14.0 // indirect +) diff --git a/go.sum b/go.sum index 7790d7c3..99d44c20 100644 --- a/go.sum +++ b/go.sum @@ -1,2 +1,30 @@ +github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= +github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/google/uuid v1.6.0 h1:NIvaJDMOsjHA8n1jAhLSgzrAzy1Hgr+hNrb57e+94F0= github.com/google/uuid v1.6.0/go.mod h1:TIyPZe4MgqvfeYDBFedMoGGpEw/LqOeaOT+nhxU+yHo= +github.com/jackc/pgpassfile v1.0.0 h1:/6Hmqy13Ss2zCq62VdNG8tM1wchn8zjSGOBJ6icpsIM= +github.com/jackc/pgpassfile v1.0.0/go.mod h1:CEx0iS5ambNFdcRtxPj5JhEz+xB6uRky5eyVu/W2HEg= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a h1:bbPeKD0xmW/Y25WS6cokEszi5g+S0QxI/d45PkRi7Nk= +github.com/jackc/pgservicefile v0.0.0-20221227161230-091c0ba34f0a/go.mod h1:5TJZWKEWniPve33vlWYSoGYefn3gLQRzjfDlhSJ9ZKM= +github.com/jackc/pgx/v5 v5.5.5 h1:amBjrZVmksIdNjxGW/IiIMzxMKZFelXbUoPNb+8sjQw= +github.com/jackc/pgx/v5 v5.5.5/go.mod h1:ez9gk+OAat140fv9ErkZDYFWmXLfV+++K0uAOiwgm1A= +github.com/jackc/puddle/v2 v2.2.1 h1:RhxXJtFG022u4ibrCSMSiu5aOq1i77R3OHKNJj77OAk= +github.com/jackc/puddle/v2 v2.2.1/go.mod h1:vriiEXHvEE654aYKXXjOvZM39qJ0q+azkZFrfEOc3H4= +github.com/pmezard/go-difflib v1.0.0 h1:4DBwDE0NGyQoBHbLQYPwSUPoCMWR5BEzIk/f1lZbAQM= +github.com/pmezard/go-difflib v1.0.0/go.mod h1:iKH77koFhYxTK1pcRnkKkqfTogsbg7gZNVY4sRDYZ/4= +github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= +github.com/stretchr/testify v1.3.0/go.mod h1:M5WIy9Dh21IEIfnGCwXGc5bZfKNJtfHm1UVUgZn+9EI= +github.com/stretchr/testify v1.7.0/go.mod h1:6Fq8oRcR53rry900zMqJjRRixrwX3KX962/h/Wwjteg= +github.com/stretchr/testify v1.8.1 h1:w7B6lhMri9wdJUVmEZPGGhZzrYTPvgJArz7wNPgYKsk= +github.com/stretchr/testify v1.8.1/go.mod h1:w2LPCIKwWwSfY2zedu0+kehJoqGctiVI29o6fzry7u4= +golang.org/x/crypto v0.22.0 h1:g1v0xeRhjcugydODzvb3mEM9SQ0HGp9s/nh3COQ/C30= +golang.org/x/crypto v0.22.0/go.mod h1:vr6Su+7cTlO45qkww3VDJlzDn0ctJvRgYbC2NvXHt+M= +golang.org/x/sync v0.1.0 h1:wsuoTGHzEhffawBOhz5CYhcrV4IdKZbEyZjBMuTp12o= +golang.org/x/sync v0.1.0/go.mod h1:RxMgew5VJxzue5/jJTE5uejpjVlOe/izrB70Jof72aM= +golang.org/x/text v0.14.0 h1:ScX5w1eTa3QqT8oi6+ziP7dTV1S2+ALU0bI+0zXKWiQ= +golang.org/x/text v0.14.0/go.mod h1:18ZOQIKpY8NJVqYksKHtTdi31H5itFRjB5/qKTNYzSU= +gopkg.in/check.v1 v0.0.0-20161208181325-20d25e280405/go.mod h1:Co6ibVJAznAaIkqp8huTwlJQCZ016jof/cbN4VW5Yz0= +gopkg.in/yaml.v3 v3.0.0-20200313102051-9f266ea9e77c/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= +gopkg.in/yaml.v3 v3.0.1 h1:fxVm/GzAzEWqLHuvctI91KS9hhNmmWOoWu0XTYJS7CA= +gopkg.in/yaml.v3 v3.0.1/go.mod h1:K4uyk7z7BCEPqu6E+C64Yfv1cQ7kz7rIZviUmN+EgEM= diff --git a/scripts/restart.sh b/scripts/restart.sh new file mode 100755 index 00000000..a29ccdc5 --- /dev/null +++ b/scripts/restart.sh @@ -0,0 +1,5 @@ +#!/bin/sh +set -eu +cd "$(dirname "$0")/.." +docker compose --env-file .env restart db api >/dev/null +docker compose --env-file .env up -d --wait >/dev/null diff --git a/src/chat.go b/src/chat.go index 7ef1833c..d7601788 100644 --- a/src/chat.go +++ b/src/chat.go @@ -1,10 +1,12 @@ package main import ( - "sync" + "context" + "errors" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" ) type Chat struct { @@ -15,43 +17,72 @@ type Chat struct { } type chatStore struct { - mu sync.RWMutex - byID map[string]Chat + db *pgxpool.Pool } -func newChatStore() *chatStore { - return &chatStore{ - byID: make(map[string]Chat), - } +func newChatStore(db *pgxpool.Pool) *chatStore { + return &chatStore{db: db} } -func (s *chatStore) create(title string, memberIDs []string) Chat { - s.mu.Lock() - defer s.mu.Unlock() +var errUnknownMember = errors.New("unknown member") - // Делаем копию, чтобы вызывающий код не мог изменить - // список участников после сохранения чата. +func (s *chatStore) create(ctx context.Context, title string, memberIDs []string) (Chat, error) { membersCopy := append([]string(nil), memberIDs...) - chat := Chat{ ID: uuid.New().String(), Title: title, MemberIDs: membersCopy, - CreatedAt: time.Now().UTC(), + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - s.byID[chat.ID] = chat - - return chat + tx, err := s.db.Begin(ctx) + if err != nil { + return Chat{}, err + } + defer tx.Rollback(ctx) + for _, id := range membersCopy { + var exists bool + if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM users WHERE id=$1)", id).Scan(&exists); err != nil { + return Chat{}, err + } + if !exists { + return Chat{}, errUnknownMember + } + } + if _, err = tx.Exec(ctx, "INSERT INTO chats(id,title,created_at) VALUES($1,$2,$3)", chat.ID, title, chat.CreatedAt); err != nil { + return Chat{}, err + } + for _, id := range membersCopy { + if _, err = tx.Exec(ctx, "INSERT INTO chat_members(chat_id,user_id) VALUES($1,$2)", chat.ID, id); err != nil { + return Chat{}, err + } + } + if err = tx.Commit(ctx); err != nil { + return Chat{}, err + } + return chat, nil } -func (s *chatStore) getByID(id string) (Chat, bool) { - s.mu.RLock() - defer s.mu.RUnlock() - - chat, exists := s.byID[id] - - return chat, exists +func (s *chatStore) getByID(ctx context.Context, id string) (Chat, error) { + var chat Chat + err := s.db.QueryRow(ctx, "SELECT id,title,created_at FROM chats WHERE id=$1", id).Scan(&chat.ID, &chat.Title, &chat.CreatedAt) + if err != nil { + return Chat{}, err + } + rows, err := s.db.Query(ctx, "SELECT user_id FROM chat_members WHERE chat_id=$1 ORDER BY user_id", id) + if err != nil { + return Chat{}, err + } + defer rows.Close() + chat.MemberIDs = []string{} + for rows.Next() { + var member string + if err = rows.Scan(&member); err != nil { + return Chat{}, err + } + chat.MemberIDs = append(chat.MemberIDs, member) + } + return chat, rows.Err() } func (s *chatStore) isMember(chat Chat, userID string) bool { @@ -64,20 +95,39 @@ func (s *chatStore) isMember(chat Chat, userID string) bool { return false } -func (s *chatStore) listForUser(userID string) []Chat { - s.mu.RLock() - defer s.mu.RUnlock() - - chats := make([]Chat, 0) - - for _, chat := range s.byID { - if !s.isMember(chat, userID) { - continue - } - - chat.MemberIDs = append([]string(nil), chat.MemberIDs...) - chats = append(chats, chat) +func (s *chatStore) listPageForUser(ctx context.Context, userID string, cursor *chatCursor, limit int) ([]Chat, bool, error) { + afterTime := time.Time{} + afterID := "00000000-0000-0000-0000-000000000000" + if cursor != nil { + afterTime = cursor.CreatedAt + afterID = cursor.ChatID } - - return chats + rows, err := s.db.Query(ctx, `SELECT c.id,c.title,c.created_at FROM chats c JOIN chat_members m ON m.chat_id=c.id WHERE m.user_id=$1 AND (c.created_at,c.id)>($2,$3::uuid) ORDER BY c.created_at,c.id LIMIT $4`, userID, afterTime, afterID, limit+1) + if err != nil { + return nil, false, err + } + defer rows.Close() + chats := []Chat{} + for rows.Next() { + var c Chat + if err = rows.Scan(&c.ID, &c.Title, &c.CreatedAt); err != nil { + return nil, false, err + } + chats = append(chats, c) + } + if err = rows.Err(); err != nil { + return nil, false, err + } + more := len(chats) > limit + if more { + chats = chats[:limit] + } + for i := range chats { + chat, err := s.getByID(ctx, chats[i].ID) + if err != nil { + return nil, false, err + } + chats[i] = chat + } + return chats, more, nil } diff --git a/src/chat_get_handler.go b/src/chat_get_handler.go index 3710ffa2..3d504890 100644 --- a/src/chat_get_handler.go +++ b/src/chat_get_handler.go @@ -28,20 +28,20 @@ func getChatHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -79,9 +79,9 @@ func getChatHandler( return } - chat, exists := chatStore.getByID(chatID) + chat, err := chatStore.getByID(r.Context(), chatID) - if !exists || !chatStore.isMember(chat, currentUserID) { + if err != nil || !chatStore.isMember(chat, currentUserID) { // Для неизвестного и чужого чата используется одинаковый 404. // Это не раскрывает постороннему пользователю наличие чата. writeError( diff --git a/src/chat_handler.go b/src/chat_handler.go index 5842cba5..7460c89c 100644 --- a/src/chat_handler.go +++ b/src/chat_handler.go @@ -2,6 +2,7 @@ package main import ( "encoding/json" + "errors" "log" "net/http" "strings" @@ -34,20 +35,20 @@ func createChatHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -145,7 +146,7 @@ func createChatHandler( seenMembers[memberID] = struct{}{} - if _, exists := userStore.getByID(memberID); !exists { + if _, err := userStore.getByID(r.Context(), memberID); err != nil { writeError( w, http.StatusBadRequest, @@ -168,10 +169,19 @@ func createChatHandler( return } - chat := chatStore.create( + chat, err := chatStore.create( + r.Context(), request.Title, request.MemberIDs, ) + if errors.Is(err, errUnknownMember) { + writeError(w, 400, "invalid_request", "all members must be existing users", requestID) + return + } + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) diff --git a/src/chat_list_handler.go b/src/chat_list_handler.go index 6d036828..fafe5915 100644 --- a/src/chat_list_handler.go +++ b/src/chat_list_handler.go @@ -4,7 +4,6 @@ import ( "encoding/base64" "encoding/json" "net/http" - "sort" "strconv" "time" ) @@ -69,20 +68,20 @@ func listChatsHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -151,36 +150,10 @@ func listChatsHandler( cursor = &decoded } - chats := chatStore.listForUser(currentUserID) - - sort.Slice(chats, func(i, j int) bool { - if chats[i].CreatedAt.Equal(chats[j].CreatedAt) { - return chats[i].ID < chats[j].ID - } - - return chats[i].CreatedAt.Before(chats[j].CreatedAt) - }) - - if cursor != nil { - filtered := make([]Chat, 0, len(chats)) - - for _, chat := range chats { - isAfterCursor := chat.CreatedAt.After(cursor.CreatedAt) || - (chat.CreatedAt.Equal(cursor.CreatedAt) && - chat.ID > cursor.ChatID) - - if isAfterCursor { - filtered = append(filtered, chat) - } - } - - chats = filtered - } - - pageItems := chats - - if len(pageItems) > limit { - pageItems = pageItems[:limit] + pageItems, hasMore, err := chatStore.listPageForUser(r.Context(), currentUserID, cursor, limit) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return } page := chatPage{ @@ -188,7 +161,7 @@ func listChatsHandler( NextCursor: nil, } - if len(chats) > limit { + if hasMore { last := pageItems[len(pageItems)-1] nextCursor, err := encodeChatCursor(chatCursor{ diff --git a/src/concurrency_test.go b/src/concurrency_test.go deleted file mode 100644 index 388b057d..00000000 --- a/src/concurrency_test.go +++ /dev/null @@ -1,221 +0,0 @@ -package main - -import ( - "bytes" - "encoding/json" - "fmt" - "io" - "net/http" - "net/http/httptest" - "strconv" - "sync" - "testing" -) - -func TestConcurrentMessageCreation(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - const clientsCount = 10 - const messagesPerClient = 10 - const expectedMessages = clientsCount * messagesPerClient - - memberIDs := make([]string, 0, clientsCount) - users := make([]User, 0, clientsCount) - - for i := range clientsCount { - user, created := userStore.create( - "user"+strconv.Itoa(i), - "Пользователь "+strconv.Itoa(i), - ) - - if !created { - t.Fatalf("failed to create test user %d", i) - } - - users = append(users, user) - memberIDs = append(memberIDs, user.ID) - } - - chat := chatStore.create( - "Конкурентный чат", - memberIDs, - ) - - mux := http.NewServeMux() - mux.Handle( - "/api/v1/chats/", - chatSubresourceHandler( - userStore, - chatStore, - messageStore, - ), - ) - - server := httptest.NewServer(mux) - defer server.Close() - - client := server.Client() - - var waitGroup sync.WaitGroup - messageIDs := make(chan string, expectedMessages) - errors := make(chan error, expectedMessages) - - for clientIndex := range clientsCount { - waitGroup.Add(1) - - go func(index int) { - defer waitGroup.Done() - - for messageIndex := range messagesPerClient { - body := fmt.Appendf(nil, - `{"text":"client-%d message-%d"}`, - index, - messageIndex, - ) - - request, err := http.NewRequest( - http.MethodPost, - server.URL+"/api/v1/chats/"+chat.ID+"/messages", - bytes.NewReader(body), - ) - if err != nil { - errors <- fmt.Errorf( - "client %d: create request: %w", - index, - err, - ) - continue - } - - request.Header.Set("Content-Type", "application/json") - request.Header.Set("X-User-Id", users[index].ID) - - response, err := client.Do(request) - if err != nil { - errors <- fmt.Errorf( - "client %d: send request: %w", - index, - err, - ) - continue - } - - responseBody, readErr := io.ReadAll(response.Body) - response.Body.Close() - - if readErr != nil { - errors <- fmt.Errorf( - "client %d: read response: %w", - index, - readErr, - ) - continue - } - - if response.StatusCode != http.StatusCreated { - errors <- fmt.Errorf( - "client %d: expected status %d, got %d; body: %s", - index, - http.StatusCreated, - response.StatusCode, - string(responseBody), - ) - continue - } - - var message Message - - if err := json.Unmarshal(responseBody, &message); err != nil { - errors <- fmt.Errorf( - "client %d: decode response: %w", - index, - err, - ) - continue - } - - if message.ID == "" { - errors <- fmt.Errorf( - "client %d: response contains empty message ID", - index, - ) - continue - } - - messageIDs <- message.ID - } - }(clientIndex) - } - - waitGroup.Wait() - - close(errors) - close(messageIDs) - - for err := range errors { - t.Error(err) - } - - createdIDs := make(map[string]bool) - - for messageID := range messageIDs { - if createdIDs[messageID] { - t.Fatalf("duplicate message ID returned: %s", messageID) - } - - createdIDs[messageID] = true - } - - if len(createdIDs) != expectedMessages { - t.Fatalf( - "expected %d unique created messages, got %d", - expectedMessages, - len(createdIDs), - ) - } - - // Дополнительно проверяем историю через HTTP API. - request, err := http.NewRequest( - http.MethodGet, - server.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=100", - nil, - ) - if err != nil { - t.Fatalf("create history request: %v", err) - } - - request.Header.Set("X-User-Id", users[0].ID) - - response, err := client.Do(request) - if err != nil { - t.Fatalf("request message history: %v", err) - } - defer response.Body.Close() - - if response.StatusCode != http.StatusOK { - body, _ := io.ReadAll(response.Body) - - t.Fatalf( - "expected history status %d, got %d; body: %s", - http.StatusOK, - response.StatusCode, - string(body), - ) - } - - var page messagePage - - if err := json.NewDecoder(response.Body).Decode(&page); err != nil { - t.Fatalf("decode message history: %v", err) - } - - if len(page.Items) != expectedMessages { - t.Fatalf( - "expected %d messages in history, got %d", - expectedMessages, - len(page.Items), - ) - } -} diff --git a/src/current_user_handler.go b/src/current_user_handler.go index ef0b6adb..f96f74e8 100644 --- a/src/current_user_handler.go +++ b/src/current_user_handler.go @@ -22,21 +22,21 @@ func currentUserHandler(store *userStore) http.HandlerFunc { return } - userID := r.Header.Get("X-User-Id") + userID := currentUserID(r) if userID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - user, exists := store.getByID(userID) - if !exists { + user, err := store.getByID(r.Context(), userID) + if err != nil { writeError( w, http.StatusUnauthorized, diff --git a/src/database.go b/src/database.go new file mode 100644 index 00000000..cd288127 --- /dev/null +++ b/src/database.go @@ -0,0 +1,102 @@ +package main + +import ( + "context" + "embed" + "errors" + "fmt" + "os" + "sort" + "strings" + "time" + + "github.com/jackc/pgx/v5/pgconn" + "github.com/jackc/pgx/v5/pgxpool" +) + +//go:embed migrations/*.sql +var migrationFiles embed.FS + +func databaseURL() (string, error) { + if path := os.Getenv("DATABASE_URL_FILE"); path != "" { + data, err := os.ReadFile(path) + if err != nil { + return "", err + } + return strings.TrimSpace(string(data)), nil + } + if url := os.Getenv("DATABASE_URL"); url != "" { + return url, nil + } + return "", errors.New("DATABASE_URL_FILE or DATABASE_URL is required") +} + +func openDatabase(ctx context.Context) (*pgxpool.Pool, error) { + url, err := databaseURL() + if err != nil { + return nil, err + } + cfg, err := pgxpool.ParseConfig(url) + if err != nil { + return nil, err + } + cfg.MaxConns = 10 + cfg.ConnConfig.ConnectTimeout = 5 * time.Second + db, err := pgxpool.NewWithConfig(ctx, cfg) + if err != nil { + return nil, err + } + if err = db.Ping(ctx); err != nil { + db.Close() + return nil, err + } + if err = applyMigrations(ctx, db); err != nil { + db.Close() + return nil, err + } + return db, nil +} + +func applyMigrations(ctx context.Context, db *pgxpool.Pool) error { + files, err := migrationFiles.ReadDir("migrations") + if err != nil { + return err + } + sort.Slice(files, func(i, j int) bool { return files[i].Name() < files[j].Name() }) + tx, err := db.Begin(ctx) + if err != nil { + return err + } + defer tx.Rollback(ctx) + if _, err = tx.Exec(ctx, "SELECT pg_advisory_xact_lock(20426002)"); err != nil { + return err + } + if _, err = tx.Exec(ctx, "CREATE TABLE IF NOT EXISTS schema_migrations (version text PRIMARY KEY)"); err != nil { + return err + } + for _, file := range files { + var exists bool + if err = tx.QueryRow(ctx, "SELECT EXISTS(SELECT 1 FROM schema_migrations WHERE version=$1)", file.Name()).Scan(&exists); err != nil { + return err + } + if exists { + continue + } + sql, readErr := migrationFiles.ReadFile("migrations/" + file.Name()) + if readErr != nil { + return readErr + } + if _, err = tx.Exec(ctx, string(sql)); err != nil { + return fmt.Errorf("migration %s: %w", file.Name(), err) + } + if _, err = tx.Exec(ctx, "INSERT INTO schema_migrations(version) VALUES($1)", file.Name()); err != nil { + return err + } + } + return tx.Commit(ctx) +} + +func uniqueViolation(err error) bool { + var pgerr *pgconn.PgError + return errors.As(err, &pgerr) && pgerr.Code == "23505" +} diff --git a/src/main.go b/src/main.go index 699b0608..e0d512cc 100644 --- a/src/main.go +++ b/src/main.go @@ -6,6 +6,7 @@ import ( "encoding/hex" "encoding/json" "errors" + "github.com/jackc/pgx/v5/pgxpool" "log" "net" "net/http" @@ -75,6 +76,25 @@ func healthHandler(w http.ResponseWriter, r *http.Request) { } } +func readyHandler(db *pgxpool.Pool) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodGet { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) + defer cancel() + if err := db.Ping(ctx); err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.Header().Set("Content-Type", "application/json") + json.NewEncoder(w).Encode(healthResponse{"ok"}) + } +} + func serverAddress() string { host := os.Getenv("APP_HOST") if host == "" { @@ -90,27 +110,40 @@ func serverAddress() string { } func main() { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() + ctx, cancel := context.WithTimeout(context.Background(), 20*time.Second) + db, err := openDatabase(ctx) + cancel() + if err != nil { + log.Fatalf("database initialization failed: %v", err) + } + defer db.Close() + userStore := newUserStore(db) + chatStore := newChatStore(db) + messageStore := newMessageStore(db) + sessions, err := newSessionStore(db) + if err != nil { + log.Fatal(err) + } mux := http.NewServeMux() mux.HandleFunc("/health/live", healthHandler) - mux.HandleFunc("/health/ready", healthHandler) + mux.HandleFunc("/health/ready", readyHandler(db)) mux.Handle("/api/v1/users", createUserHandler(userStore)) - mux.Handle("/api/v1/users/me", currentUserHandler(userStore)) + mux.Handle("/api/v1/auth/sessions", sessionHandler(userStore, sessions)) + mux.Handle("/api/v1/auth/sessions/current", authRequired(sessions, logoutHandler(sessions))) + mux.Handle("/api/v1/users/me", authRequired(sessions, currentUserHandler(userStore))) mux.Handle( "/api/v1/chats", - chatCollectionHandler(userStore, chatStore), + authRequired(sessions, chatCollectionHandler(userStore, chatStore)), ) mux.Handle( "/api/v1/chats/", - chatSubresourceHandler( + authRequired(sessions, chatSubresourceHandler( userStore, chatStore, messageStore, - ), + )), ) server := &http.Server{ diff --git a/src/message.go b/src/message.go index c8e0eeaa..ac812bb9 100644 --- a/src/message.go +++ b/src/message.go @@ -1,11 +1,11 @@ package main import ( - "sort" - "sync" + "context" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5/pgxpool" ) type Message struct { @@ -17,47 +17,29 @@ type Message struct { } type messageStore struct { - mu sync.RWMutex - byChatID map[string][]Message + db *pgxpool.Pool } -func newMessageStore() *messageStore { - return &messageStore{ - byChatID: make(map[string][]Message), - } +func newMessageStore(db *pgxpool.Pool) *messageStore { + return &messageStore{db: db} } func (s *messageStore) create( + ctx context.Context, chatID string, senderID string, text string, -) Message { - s.mu.Lock() - defer s.mu.Unlock() - +) (Message, error) { message := Message{ ID: uuid.New().String(), ChatID: chatID, SenderID: senderID, Text: text, - CreatedAt: time.Now().UTC(), + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - messages := s.byChatID[chatID] - insertAt := len(messages) - - if insertAt > 0 && messageLess(message, messages[insertAt-1]) { - insertAt = sort.Search(len(messages), func(index int) bool { - return !messageLess(messages[index], message) - }) - } - - messages = append(messages, Message{}) - copy(messages[insertAt+1:], messages[insertAt:]) - messages[insertAt] = message - s.byChatID[chatID] = messages - - return message + _, err := s.db.Exec(ctx, "INSERT INTO messages(id,chat_id,sender_id,text,created_at) VALUES($1,$2,$3,$4,$5)", message.ID, message.ChatID, message.SenderID, message.Text, message.CreatedAt) + return message, err } func messageLess(left Message, right Message) bool { @@ -74,38 +56,36 @@ func messageAfterCursor(message Message, cursor messageCursor) bool { } func (s *messageStore) listPageByChat( + ctx context.Context, chatID string, cursor *messageCursor, limit int, -) ([]Message, bool) { - s.mu.RLock() - defer s.mu.RUnlock() - - messages := s.byChatID[chatID] - start := 0 - +) ([]Message, bool, error) { + afterTime := time.Time{} + afterID := "00000000-0000-0000-0000-000000000000" if cursor != nil { - start = sort.Search(len(messages), func(index int) bool { - return messageAfterCursor(messages[index], *cursor) - }) + afterTime = cursor.CreatedAt + afterID = cursor.MessageID } - - remaining := len(messages) - start - pageLength := min(remaining, limit) - page := make([]Message, pageLength) - copy(page, messages[start:start+pageLength]) - - return page, remaining > limit -} - -func (s *messageStore) listByChat(chatID string) []Message { - s.mu.RLock() - defer s.mu.RUnlock() - - messages := s.byChatID[chatID] - - result := make([]Message, len(messages)) - copy(result, messages) - - return result + rows, err := s.db.Query(ctx, `SELECT id,chat_id,sender_id,text,created_at FROM messages WHERE chat_id=$1 AND (created_at,id)>($2,$3::uuid) ORDER BY created_at,id LIMIT $4`, chatID, afterTime, afterID, limit+1) + if err != nil { + return nil, false, err + } + defer rows.Close() + items := []Message{} + for rows.Next() { + var m Message + if err = rows.Scan(&m.ID, &m.ChatID, &m.SenderID, &m.Text, &m.CreatedAt); err != nil { + return nil, false, err + } + items = append(items, m) + } + if err = rows.Err(); err != nil { + return nil, false, err + } + more := len(items) > limit + if more { + items = items[:limit] + } + return items, more, nil } diff --git a/src/message_handler.go b/src/message_handler.go index 81c26d89..b50aaf10 100644 --- a/src/message_handler.go +++ b/src/message_handler.go @@ -34,20 +34,20 @@ func createMessageHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -81,9 +81,9 @@ func createMessageHandler( return } - chat, exists := chatStore.getByID(chatID) + chat, err := chatStore.getByID(r.Context(), chatID) - if !exists || !chatStore.isMember(chat, currentUserID) { + if err != nil || !chatStore.isMember(chat, currentUserID) { writeError( w, http.StatusNotFound, @@ -143,11 +143,16 @@ func createMessageHandler( return } - message := messageStore.create( + message, err := messageStore.create( + r.Context(), chatID, currentUserID, request.Text, ) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) diff --git a/src/message_handler_test.go b/src/message_handler_test.go deleted file mode 100644 index 90864933..00000000 --- a/src/message_handler_test.go +++ /dev/null @@ -1,291 +0,0 @@ -package main - -import ( - "encoding/json" - "net/http" - "net/http/httptest" - "net/url" - "strings" - "testing" -) - -func TestCreateMessageBlankText(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - user, created := userStore.create("alice", "Алиса") - if !created { - t.Fatal("expected user to be created") - } - - chat := chatStore.create( - "Тестовый чат", - []string{user.ID}, - ) - - handler := createMessageHandler( - userStore, - chatStore, - messageStore, - ) - - request := httptest.NewRequest( - http.MethodPost, - "/api/v1/chats/"+chat.ID+"/messages", - strings.NewReader(`{"text":" \t\n"}`), - ) - request.Header.Set("Content-Type", "application/json") - request.Header.Set("X-User-Id", user.ID) - - response := httptest.NewRecorder() - - handler.ServeHTTP(response, request) - - if response.Code != http.StatusBadRequest { - t.Fatalf( - "expected status %d, got %d; body: %s", - http.StatusBadRequest, - response.Code, - response.Body.String(), - ) - } - - if response.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - if !strings.Contains( - response.Body.String(), - `"code":"invalid_request"`, - ) { - t.Fatalf( - "expected invalid_request error code, got body: %s", - response.Body.String(), - ) - } - - messages := messageStore.listByChat(chat.ID) - - if len(messages) != 0 { - t.Fatalf( - "expected no messages to be stored, got %d", - len(messages), - ) - } -} -func TestCreateMessageFromChatOutsider(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - alice, created := userStore.create("alice", "Алиса") - if !created { - t.Fatal("expected Alice to be created") - } - - bob, created := userStore.create("bob", "Боб") - if !created { - t.Fatal("expected Bob to be created") - } - - chat := chatStore.create( - "Чат Алисы", - []string{alice.ID}, - ) - - handler := createMessageHandler( - userStore, - chatStore, - messageStore, - ) - - request := httptest.NewRequest( - http.MethodPost, - "/api/v1/chats/"+chat.ID+"/messages", - strings.NewReader(`{"text":"Сообщение чужому чату"}`), - ) - request.Header.Set("Content-Type", "application/json") - request.Header.Set("X-User-Id", bob.ID) - - response := httptest.NewRecorder() - - handler.ServeHTTP(response, request) - - if response.Code != http.StatusNotFound { - t.Fatalf( - "expected status %d, got %d; body: %s", - http.StatusNotFound, - response.Code, - response.Body.String(), - ) - } - - if response.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - if !strings.Contains( - response.Body.String(), - `"code":"not_found"`, - ) { - t.Fatalf( - "expected not_found error code, got body: %s", - response.Body.String(), - ) - } - - messages := messageStore.listByChat(chat.ID) - - if len(messages) != 0 { - t.Fatalf( - "expected no messages to be stored, got %d", - len(messages), - ) - } -} -func TestListMessagesPagination(t *testing.T) { - userStore := newUserStore() - chatStore := newChatStore() - messageStore := newMessageStore() - - user, created := userStore.create("alice", "Алиса") - if !created { - t.Fatal("expected user to be created") - } - - chat := chatStore.create( - "Тестовый чат", - []string{user.ID}, - ) - - first := messageStore.create(chat.ID, user.ID, "Первое сообщение") - second := messageStore.create(chat.ID, user.ID, "Второе сообщение") - third := messageStore.create(chat.ID, user.ID, "Третье сообщение") - - expectedIDs := map[string]bool{ - first.ID: true, - second.ID: true, - third.ID: true, - } - - handler := listMessagesHandler( - userStore, - chatStore, - messageStore, - ) - - // Запрашиваем только два сообщения из трёх. - firstRequest := httptest.NewRequest( - http.MethodGet, - "/api/v1/chats/"+chat.ID+"/messages?limit=2", - nil, - ) - firstRequest.Header.Set("X-User-Id", user.ID) - - firstResponse := httptest.NewRecorder() - - handler.ServeHTTP(firstResponse, firstRequest) - - if firstResponse.Code != http.StatusOK { - t.Fatalf( - "expected first page status %d, got %d; body: %s", - http.StatusOK, - firstResponse.Code, - firstResponse.Body.String(), - ) - } - - var firstPage messagePage - - if err := json.NewDecoder(firstResponse.Body).Decode(&firstPage); err != nil { - t.Fatalf("failed to decode first page: %v", err) - } - - if len(firstPage.Items) != 2 { - t.Fatalf( - "expected 2 messages on first page, got %d", - len(firstPage.Items), - ) - } - - if firstPage.NextCursor == nil || *firstPage.NextCursor == "" { - t.Fatal("expected non-empty next cursor on first page") - } - - // Проверяем, что сообщения на первой странице уникальны - // и принадлежат исходному набору. - seenIDs := make(map[string]bool) - - for _, message := range firstPage.Items { - if !expectedIDs[message.ID] { - t.Fatalf("unexpected message ID on first page: %s", message.ID) - } - - if seenIDs[message.ID] { - t.Fatalf("duplicate message on first page: %s", message.ID) - } - - seenIDs[message.ID] = true - } - - // Используем cursor первой страницы для получения второй. - secondRequest := httptest.NewRequest( - http.MethodGet, - "/api/v1/chats/"+chat.ID+"/messages?limit=2&cursor="+ - url.QueryEscape(*firstPage.NextCursor), - nil, - ) - secondRequest.Header.Set("X-User-Id", user.ID) - - secondResponse := httptest.NewRecorder() - - handler.ServeHTTP(secondResponse, secondRequest) - - if secondResponse.Code != http.StatusOK { - t.Fatalf( - "expected second page status %d, got %d; body: %s", - http.StatusOK, - secondResponse.Code, - secondResponse.Body.String(), - ) - } - - var secondPage messagePage - - if err := json.NewDecoder(secondResponse.Body).Decode(&secondPage); err != nil { - t.Fatalf("failed to decode second page: %v", err) - } - - if len(secondPage.Items) != 1 { - t.Fatalf( - "expected 1 message on second page, got %d", - len(secondPage.Items), - ) - } - - if secondPage.NextCursor != nil { - t.Fatalf("expected second page to be final, got cursor %q", *secondPage.NextCursor) - } - - // Проверяем, что вторая страница не повторяет первую. - for _, message := range secondPage.Items { - if seenIDs[message.ID] { - t.Fatalf("message repeated on second page: %s", message.ID) - } - - if !expectedIDs[message.ID] { - t.Fatalf("unexpected message ID on second page: %s", message.ID) - } - - seenIDs[message.ID] = true - } - - if len(seenIDs) != len(expectedIDs) { - t.Fatalf( - "pagination lost messages: expected %d unique messages, got %d", - len(expectedIDs), - len(seenIDs), - ) - } -} diff --git a/src/message_list_handler.go b/src/message_list_handler.go index f71b8b9a..15070aa5 100644 --- a/src/message_list_handler.go +++ b/src/message_list_handler.go @@ -69,20 +69,20 @@ func listMessagesHandler( return } - currentUserID := r.Header.Get("X-User-Id") + currentUserID := currentUserID(r) if currentUserID == "" { writeError( w, http.StatusUnauthorized, "unauthorized", - "valid X-User-Id header is required", + "valid Bearer session is required", requestID, ) return } - if _, exists := userStore.getByID(currentUserID); !exists { + if _, err := userStore.getByID(r.Context(), currentUserID); err != nil { writeError( w, http.StatusUnauthorized, @@ -105,9 +105,9 @@ func listMessagesHandler( return } - chat, exists := chatStore.getByID(chatID) + chat, err := chatStore.getByID(r.Context(), chatID) - if !exists || !chatStore.isMember(chat, currentUserID) { + if err != nil || !chatStore.isMember(chat, currentUserID) { writeError( w, http.StatusNotFound, @@ -176,11 +176,16 @@ func listMessagesHandler( cursor = &decoded } - pageItems, hasMore := messageStore.listPageByChat( + pageItems, hasMore, err := messageStore.listPageByChat( + r.Context(), chatID, cursor, limit, ) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } page := messagePage{ Items: pageItems, diff --git a/src/message_store_test.go b/src/message_store_test.go deleted file mode 100644 index 372a746e..00000000 --- a/src/message_store_test.go +++ /dev/null @@ -1,64 +0,0 @@ -package main - -import ( - "testing" - "time" -) - -func TestMessageLessUsesIDForEqualTimestamps(t *testing.T) { - createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) - first := Message{ID: "a", CreatedAt: createdAt} - second := Message{ID: "b", CreatedAt: createdAt} - - if !messageLess(first, second) { - t.Fatal("expected the smaller ID to sort first for equal timestamps") - } - - if messageLess(second, first) { - t.Fatal("expected the larger ID to sort last for equal timestamps") - } -} - -func TestListPageByChatUsesCursorAndLimit(t *testing.T) { - createdAt := time.Date(2026, 9, 18, 12, 0, 0, 0, time.UTC) - store := newMessageStore() - store.byChatID["chat-1"] = []Message{ - {ID: "a", ChatID: "chat-1", CreatedAt: createdAt}, - {ID: "b", ChatID: "chat-1", CreatedAt: createdAt}, - {ID: "c", ChatID: "chat-1", CreatedAt: createdAt.Add(time.Second)}, - {ID: "d", ChatID: "chat-1", CreatedAt: createdAt.Add(2 * time.Second)}, - } - - firstPage, hasMore := store.listPageByChat("chat-1", nil, 2) - if !hasMore { - t.Fatal("expected another page") - } - if len(firstPage) != 2 || firstPage[0].ID != "a" || firstPage[1].ID != "b" { - t.Fatalf("unexpected first page: %#v", firstPage) - } - - cursor := messageCursor{ - ChatID: "chat-1", - CreatedAt: firstPage[1].CreatedAt, - MessageID: firstPage[1].ID, - } - secondPage, hasMore := store.listPageByChat("chat-1", &cursor, 2) - if hasMore { - t.Fatal("did not expect another page") - } - if len(secondPage) != 2 || secondPage[0].ID != "c" || secondPage[1].ID != "d" { - t.Fatalf("unexpected second page: %#v", secondPage) - } -} - -func TestListPageByChatReturnsNonNilEmptyPage(t *testing.T) { - store := newMessageStore() - - page, hasMore := store.listPageByChat("missing", nil, 100) - if page == nil { - t.Fatal("expected a non-nil empty page") - } - if len(page) != 0 || hasMore { - t.Fatalf("unexpected empty page result: page=%#v hasMore=%v", page, hasMore) - } -} diff --git a/src/migrations/001_initial.sql b/src/migrations/001_initial.sql new file mode 100644 index 00000000..2962c554 --- /dev/null +++ b/src/migrations/001_initial.sql @@ -0,0 +1,33 @@ +CREATE TABLE users ( + id uuid PRIMARY KEY, + username varchar(32) NOT NULL UNIQUE CHECK (username ~ '^[a-z0-9_]{3,32}$'), + display_name text NOT NULL CHECK (char_length(display_name) BETWEEN 1 AND 100), + password_hash bytea NOT NULL, + password_salt bytea NOT NULL, + created_at timestamptz NOT NULL +); +CREATE TABLE chats ( + id uuid PRIMARY KEY, + title text NOT NULL CHECK (char_length(title) BETWEEN 1 AND 100), + created_at timestamptz NOT NULL +); +CREATE TABLE chat_members ( + chat_id uuid NOT NULL REFERENCES chats(id) ON DELETE CASCADE, + user_id uuid NOT NULL REFERENCES users(id), + PRIMARY KEY (chat_id,user_id) +); +CREATE INDEX chat_members_user_idx ON chat_members(user_id,chat_id); +CREATE TABLE messages ( + id uuid PRIMARY KEY, + chat_id uuid NOT NULL REFERENCES chats(id), + sender_id uuid NOT NULL REFERENCES users(id), + text text NOT NULL CHECK (char_length(text) BETWEEN 1 AND 4000), + created_at timestamptz NOT NULL +); +CREATE INDEX messages_history_idx ON messages(chat_id,created_at,id); +CREATE TABLE sessions ( + token_hash bytea PRIMARY KEY, + user_id uuid NOT NULL REFERENCES users(id), + expires_at timestamptz NOT NULL +); +CREATE INDEX sessions_expiry_idx ON sessions(expires_at); diff --git a/src/security_test.go b/src/security_test.go new file mode 100644 index 00000000..9e65f02b --- /dev/null +++ b/src/security_test.go @@ -0,0 +1,54 @@ +package main + +import ( + "bytes" + "net/http" + "net/http/httptest" + "testing" + "time" +) + +func TestPasswordKDFUsesSaltAndFullUTF8Password(t *testing.T) { + password := "длинный-пароль-с-эмодзи-🔒-0123456789" + first, err := derivePassword(password, bytes.Repeat([]byte{1}, 32)) + if err != nil { + t.Fatal(err) + } + same, err := derivePassword(password, bytes.Repeat([]byte{1}, 32)) + if err != nil { + t.Fatal(err) + } + changed, err := derivePassword(password, bytes.Repeat([]byte{2}, 32)) + if err != nil { + t.Fatal(err) + } + if !bytes.Equal(first, same) || bytes.Equal(first, changed) { + t.Fatal("password derivation lost salt or determinism") + } +} + +func TestBearerRequiredIgnoresXUserID(t *testing.T) { + handler := authRequired(&sessionStore{}, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { t.Fatal("business handler reached without bearer") })) + request := httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil) + request.Header.Set("X-User-Id", "11111111-1111-4111-8111-111111111111") + response := httptest.NewRecorder() + handler.ServeHTTP(response, request) + if response.Code != 401 || response.Header().Get("WWW-Authenticate") != `Bearer realm="messenger"` { + t.Fatalf("unexpected response: %d %v", response.Code, response.Header()) + } +} + +func TestMessageCursorPreservesPosition(t *testing.T) { + original := messageCursor{ChatID: "11111111-1111-4111-8111-111111111111", CreatedAt: time.Date(2026, 9, 23, 10, 0, 0, 123000, time.UTC), MessageID: "22222222-2222-4222-8222-222222222222"} + token, err := encodeMessageCursor(original) + if err != nil { + t.Fatal(err) + } + decoded, err := decodeMessageCursor(token) + if err != nil { + t.Fatal(err) + } + if decoded != original { + t.Fatalf("cursor changed: %+v", decoded) + } +} diff --git a/src/session.go b/src/session.go new file mode 100644 index 00000000..77838492 --- /dev/null +++ b/src/session.go @@ -0,0 +1,157 @@ +package main + +import ( + "context" + "crypto/rand" + "crypto/sha256" + "encoding/hex" + "encoding/json" + "errors" + "net/http" + "os" + "strconv" + "strings" + "time" + "unicode/utf8" + + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" +) + +type sessionStore struct { + db *pgxpool.Pool + ttl time.Duration +} + +type authenticatedUserKey struct{} + +func currentUserID(r *http.Request) string { + id, _ := r.Context().Value(authenticatedUserKey{}).(string) + return id +} + +func newSessionStore(db *pgxpool.Pool) (*sessionStore, error) { + seconds := 3600 + if value := os.Getenv("SESSION_TTL_SECONDS"); value != "" { + n, err := strconv.Atoi(value) + if err != nil || n < 1 { + return nil, errors.New("invalid SESSION_TTL_SECONDS") + } + seconds = n + } + return &sessionStore{db: db, ttl: time.Duration(seconds) * time.Second}, nil +} + +func (s *sessionStore) create(r *http.Request, userID string) (string, time.Time, error) { + raw := make([]byte, 32) + if _, err := rand.Read(raw); err != nil { + return "", time.Time{}, err + } + token := hex.EncodeToString(raw) + hash := sha256.Sum256([]byte(token)) + expires := time.Now().UTC().Add(s.ttl).Truncate(time.Microsecond) + _, err := s.db.Exec(r.Context(), "INSERT INTO sessions(token_hash,user_id,expires_at) VALUES($1,$2,$3)", hash[:], userID, expires) + return token, expires, err +} + +func (s *sessionStore) user(r *http.Request, token string) (User, error) { + hash := sha256.Sum256([]byte(token)) + var user User + err := s.db.QueryRow(r.Context(), `SELECT u.id,u.username,u.display_name,u.created_at FROM sessions s JOIN users u ON u.id=s.user_id WHERE s.token_hash=$1 AND s.expires_at>now()`, hash[:]).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, err +} + +func (s *sessionStore) revoke(r *http.Request, token string) error { + hash := sha256.Sum256([]byte(token)) + _, err := s.db.Exec(r.Context(), "DELETE FROM sessions WHERE token_hash=$1", hash[:]) + return err +} + +// authRequired replaces the lab1 X-User-Id trust model before any business handler runs. +func authRequired(s *sessionStore, next http.Handler) http.Handler { + return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { + authorization := r.Header.Get("Authorization") + if !strings.HasPrefix(authorization, "Bearer ") || strings.TrimSpace(strings.TrimPrefix(authorization, "Bearer ")) == "" { + unauthorized(w, "Bearer", newRequestID()) + return + } + token := strings.TrimPrefix(authorization, "Bearer ") + user, err := s.user(r, token) + if errors.Is(err, pgx.ErrNoRows) { + unauthorized(w, "Bearer", newRequestID()) + return + } + if err != nil { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), authenticatedUserKey{}, user.ID))) + }) +} + +func unauthorized(w http.ResponseWriter, scheme, requestID string) { + w.Header().Set("X-Request-Id", requestID) + if scheme == "Basic" { + w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`) + } else { + w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`) + } + writeError(w, 401, "unauthorized", "invalid credentials", requestID) +} + +func sessionHandler(users *userStore, sessions *sessionStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodPost { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + username, password, ok := r.BasicAuth() + if !ok || !usernamePattern.MatchString(username) || utf8.RuneCountInString(password) < 12 || utf8.RuneCountInString(password) > 128 || r.ContentLength > 0 { + unauthorized(w, "Basic", requestID) + return + } + user, valid, err := users.verifyPassword(r.Context(), username, password) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + if !valid { + unauthorized(w, "Basic", requestID) + return + } + token, expires, err := sessions.create(r, user.ID) + if err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.Header().Set("Content-Type", "application/json") + w.WriteHeader(201) + json.NewEncoder(w).Encode(struct { + Token string `json:"token"` + TokenType string `json:"token_type"` + ExpiresAt time.Time `json:"expires_at"` + User User `json:"user"` + }{token, "Bearer", expires, user}) + } +} + +func logoutHandler(sessions *sessionStore) http.HandlerFunc { + return func(w http.ResponseWriter, r *http.Request) { + requestID := newRequestID() + w.Header().Set("X-Request-Id", requestID) + if r.Method != http.MethodDelete { + writeError(w, 405, "method_not_allowed", "method not allowed", requestID) + return + } + token := strings.TrimPrefix(r.Header.Get("Authorization"), "Bearer ") + if err := sessions.revoke(r, token); err != nil { + writeError(w, 503, "unavailable", "database unavailable", requestID) + return + } + w.WriteHeader(204) + } +} diff --git a/src/user.go b/src/user.go index f9ec7f26..594f8e7a 100644 --- a/src/user.go +++ b/src/user.go @@ -1,10 +1,16 @@ package main import ( - "sync" + "context" + "crypto/rand" + "crypto/subtle" + "errors" "time" "github.com/google/uuid" + "github.com/jackc/pgx/v5" + "github.com/jackc/pgx/v5/pgxpool" + "golang.org/x/crypto/scrypt" ) type User struct { @@ -15,44 +21,56 @@ type User struct { } type userStore struct { - mu sync.RWMutex - byID map[string]User - byUsername map[string]string + db *pgxpool.Pool } -func newUserStore() *userStore { - return &userStore{ - byID: make(map[string]User), - byUsername: make(map[string]string), - } +func newUserStore(db *pgxpool.Pool) *userStore { + return &userStore{db: db} } -func (s *userStore) create(username string, displayName string) (User, bool) { - s.mu.Lock() - defer s.mu.Unlock() +func derivePassword(password string, salt []byte) ([]byte, error) { + return scrypt.Key([]byte(password), salt, 32768, 8, 1, 32) +} - if _, exists := s.byUsername[username]; exists { - return User{}, false +func (s *userStore) create(ctx context.Context, username, displayName, password string) (User, error) { + salt := make([]byte, 32) + if _, err := rand.Read(salt); err != nil { + return User{}, err + } + hash, err := derivePassword(password, salt) + if err != nil { + return User{}, err } - user := User{ ID: uuid.New().String(), Username: username, DisplayName: displayName, - CreatedAt: time.Now().UTC(), + CreatedAt: time.Now().UTC().Truncate(time.Microsecond), } - s.byID[user.ID] = user - s.byUsername[user.Username] = user.ID - - return user, true + _, err = s.db.Exec(ctx, "INSERT INTO users(id,username,display_name,password_hash,password_salt,created_at) VALUES($1,$2,$3,$4,$5,$6)", user.ID, user.Username, user.DisplayName, hash, salt, user.CreatedAt) + return user, err } -func (s *userStore) getByID(id string) (User, bool) { - s.mu.RLock() - defer s.mu.RUnlock() +func (s *userStore) getByID(ctx context.Context, id string) (User, error) { + var user User + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at FROM users WHERE id=$1", id).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt) + return user, err +} - user, exists := s.byID[id] - - return user, exists +func (s *userStore) verifyPassword(ctx context.Context, username, password string) (User, bool, error) { + var user User + var hash, salt []byte + err := s.db.QueryRow(ctx, "SELECT id,username,display_name,created_at,password_hash,password_salt FROM users WHERE username=$1", username).Scan(&user.ID, &user.Username, &user.DisplayName, &user.CreatedAt, &hash, &salt) + if errors.Is(err, pgx.ErrNoRows) { + return User{}, false, nil + } + if err != nil { + return User{}, false, err + } + actual, err := derivePassword(password, salt) + if err != nil { + return User{}, false, err + } + return user, subtle.ConstantTimeCompare(hash, actual) == 1, nil } diff --git a/src/user_handler.go b/src/user_handler.go index ec72c3e9..4f9e05fb 100644 --- a/src/user_handler.go +++ b/src/user_handler.go @@ -2,6 +2,9 @@ package main import ( "encoding/json" + "errors" + "fmt" + "github.com/jackc/pgx/v5/pgconn" "io" "log" "net/http" @@ -13,6 +16,7 @@ import ( type createUserRequest struct { Username string `json:"username"` DisplayName string `json:"display_name"` + Password string `json:"password"` } var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`) @@ -27,7 +31,10 @@ func decodeJSONBody(r *http.Request, destination any) error { var extra any if err := decoder.Decode(&extra); err != io.EOF { - return err + if err != nil { + return err + } + return fmt.Errorf("more than one JSON value") } return nil @@ -105,13 +112,19 @@ func createUserHandler(store *userStore) http.HandlerFunc { ) return } + if strings.TrimSpace(request.Password) == "" || utf8.RuneCountInString(request.Password) < 12 || utf8.RuneCountInString(request.Password) > 128 { + writeError(w, http.StatusBadRequest, "invalid_request", "password must contain 12-128 characters", requestID) + return + } - user, created := store.create( + user, err := store.create( + r.Context(), request.Username, request.DisplayName, + request.Password, ) - if !created { + if uniqueViolation(err) { writeError( w, http.StatusConflict, @@ -121,6 +134,15 @@ func createUserHandler(store *userStore) http.HandlerFunc { ) return } + if err != nil { + var pgerr *pgconn.PgError + if errors.As(err, &pgerr) && pgerr.Code == "23514" { + writeError(w, 400, "invalid_request", "invalid user fields", requestID) + } else { + writeError(w, 503, "unavailable", "database unavailable", requestID) + } + return + } w.Header().Set("Content-Type", "application/json") w.WriteHeader(http.StatusCreated) diff --git a/src/user_handler_test.go b/src/user_handler_test.go deleted file mode 100644 index d8c1277f..00000000 --- a/src/user_handler_test.go +++ /dev/null @@ -1,132 +0,0 @@ -package main - -import ( - "net/http" - "net/http/httptest" - "strings" - "testing" -) - -func TestCreateUserInvalidJSON(t *testing.T) { - store := newUserStore() - handler := createUserHandler(store) - - request := httptest.NewRequest( - http.MethodPost, - "/api/v1/users", - strings.NewReader(`{"username":`), - ) - request.Header.Set("Content-Type", "application/json") - - response := httptest.NewRecorder() - - handler.ServeHTTP(response, request) - - if response.Code != http.StatusBadRequest { - t.Fatalf( - "expected status %d, got %d; body: %s", - http.StatusBadRequest, - response.Code, - response.Body.String(), - ) - } - - if response.Header().Get("Content-Type") != "application/json" { - t.Fatalf( - "expected Content-Type application/json, got %q", - response.Header().Get("Content-Type"), - ) - } - - if response.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - body := response.Body.String() - - if !strings.Contains(body, `"code":"invalid_request"`) { - t.Fatalf( - "expected invalid_request error code, got body: %s", - body, - ) - } - - if !strings.Contains(body, "request_id") { - t.Fatalf( - "expected request_id in error body, got body: %s", - body, - ) - } -} - -func TestCreateUserDuplicateUsername(t *testing.T) { - store := newUserStore() - handler := createUserHandler(store) - - firstRequest := httptest.NewRequest( - http.MethodPost, - "/api/v1/users", - strings.NewReader(`{ - "username": "alice", - "display_name": "Алиса" - }`), - ) - firstRequest.Header.Set("Content-Type", "application/json") - - firstResponse := httptest.NewRecorder() - - handler.ServeHTTP(firstResponse, firstRequest) - - if firstResponse.Code != http.StatusCreated { - t.Fatalf( - "expected first request status %d, got %d; body: %s", - http.StatusCreated, - firstResponse.Code, - firstResponse.Body.String(), - ) - } - - secondRequest := httptest.NewRequest( - http.MethodPost, - "/api/v1/users", - strings.NewReader(`{ - "username": "alice", - "display_name": "Другая Алиса" - }`), - ) - secondRequest.Header.Set("Content-Type", "application/json") - - secondResponse := httptest.NewRecorder() - - handler.ServeHTTP(secondResponse, secondRequest) - - if secondResponse.Code != http.StatusConflict { - t.Fatalf( - "expected duplicate username status %d, got %d; body: %s", - http.StatusConflict, - secondResponse.Code, - secondResponse.Body.String(), - ) - } - - if secondResponse.Header().Get("X-Request-Id") == "" { - t.Fatal("expected non-empty X-Request-Id header") - } - - if !strings.Contains( - secondResponse.Body.String(), - `"code":"conflict"`, - ) { - t.Fatalf( - "expected conflict error code, got body: %s", - secondResponse.Body.String(), - ) - } - - if len(store.byID) != 1 { - t.Fatalf( - "expected exactly one user in store, got %d", - len(store.byID), - ) - } -}