Перенесите реализацию ЛР 4 на стенд ЛР 5

This commit is contained in:
2026-11-18 15:33:31 +03:00
parent 276dbdad8a
commit 911d97a77a
153 changed files with 17451 additions and 1 deletions
+70
View File
@@ -0,0 +1,70 @@
package user
import (
"net/http"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/platform/httpx"
)
type Handler struct {
users *Service
}
func NewHandler(users *Service) *Handler {
return &Handler{users: users}
}
// Register mounts registration on the public router and the current-user
// endpoint on the router guarded by the authentication middleware.
func (h *Handler) Register(public, protected gin.IRouter) {
public.POST("/users", h.register)
protected.GET("/users/me", httpx.WithUser(h.me))
}
type createRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
type Response struct {
ID string `json:"id"`
Username string `json:"username"`
DisplayName string `json:"display_name"`
CreatedAt string `json:"created_at"`
}
func ToResponse(u User) Response {
return Response{
ID: u.ID.String(),
Username: u.Username,
DisplayName: u.DisplayName,
CreatedAt: httpx.Timestamp(u.CreatedAt),
}
}
func (h *Handler) register(c *gin.Context) {
var req createRequest
if err := httpx.DecodeJSON(c, &req); err != nil {
httpx.Error(c, err)
return
}
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName, req.Password)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusCreated, ToResponse(u))
}
func (h *Handler) me(c *gin.Context, actor uuid.UUID) {
u, err := h.users.GetByID(c.Request.Context(), actor)
if err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, ToResponse(u))
}
+24
View File
@@ -0,0 +1,24 @@
package user_test
import (
"context"
"fmt"
"os"
"testing"
"messenger/internal/testenv"
)
var db *testenv.DB
func TestMain(m *testing.M) {
var err error
db, err = testenv.StartPostgres(context.Background())
if err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
db.Close()
os.Exit(code)
}
+18
View File
@@ -0,0 +1,18 @@
package user
import (
"context"
"github.com/google/uuid"
)
type Repository interface {
// Create stores a new user or returns ErrUsernameTaken; the uniqueness
// check and the insert must be atomic.
Create(ctx context.Context, user User) error
GetByID(ctx context.Context, id uuid.UUID) (User, error)
GetByUsername(ctx context.Context, username string) (User, error)
// ExistingIDs returns the subset of ids that belong to registered users,
// in no particular order, in one round trip.
ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error)
}
+88
View File
@@ -0,0 +1,88 @@
package user
import (
"context"
"errors"
"fmt"
"sync"
"github.com/google/uuid"
"messenger/internal/platform/ident"
"messenger/internal/platform/password"
)
type Service struct {
repo Repository
}
func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
// Register validates every field before hashing, so invalid input never pays
// for the KDF.
func (s *Service) Register(ctx context.Context, username, displayName, plain string) (User, error) {
u, err := New(ident.New(), username, displayName)
if err != nil {
return User{}, err
}
if err := ValidatePassword(plain); err != nil {
return User{}, err
}
u.PasswordHash = password.Hash(plain)
if err := s.repo.Create(ctx, u); err != nil {
return User{}, err
}
return u, nil
}
// dummyHash is verified for unknown usernames, so a failed login takes the
// same time whether or not the user exists.
var dummyHash = sync.OnceValue(func() string {
return password.Hash("timing-equaliser-password")
})
// Authenticate returns the user whose password matches, or
// ErrInvalidCredentials for an unknown username and a wrong password alike.
// The username comes straight from the Basic header, so one that cannot
// exist (including NUL or invalid UTF-8, which the database would reject)
// is answered without a query, but after the same KDF work.
func (s *Service) Authenticate(ctx context.Context, username, plain string) (User, error) {
if !usernamePattern.MatchString(username) {
_, _ = password.Verify(dummyHash(), plain)
return User{}, ErrInvalidCredentials
}
u, err := s.repo.GetByUsername(ctx, username)
if errors.Is(err, ErrNotFound) {
_, _ = password.Verify(dummyHash(), plain)
return User{}, ErrInvalidCredentials
}
if err != nil {
return User{}, fmt.Errorf("find user: %w", err)
}
ok, err := password.Verify(u.PasswordHash, plain)
if err != nil {
return User{}, fmt.Errorf("verify password of user %s: %w", u.ID, err)
}
if !ok {
return User{}, ErrInvalidCredentials
}
return u, nil
}
func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (User, error) {
return s.repo.GetByID(ctx, id)
}
// ExistingIDs serves the chats module when it validates member lists.
func (s *Service) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
if len(ids) == 0 {
return []uuid.UUID{}, nil
}
found, err := s.repo.ExistingIDs(ctx, ids)
if err != nil {
return nil, fmt.Errorf("user lookup: %w", err)
}
return found, nil
}
+189
View File
@@ -0,0 +1,189 @@
package user_test
import (
"context"
"errors"
"strings"
"sync"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/user"
"messenger/internal/user/store"
)
const pw = "correct-horse-battery"
// newService wires the service to the real store over an empty database.
func newService(t *testing.T) *user.Service {
t.Helper()
db.Reset(t)
return user.NewService(store.NewUsers(db.Pool))
}
func TestRegisterStoresUserWithPasswordHash(t *testing.T) {
svc := newService(t)
ctx := context.Background()
u, err := svc.Register(ctx, "alice", "Алиса", pw)
if err != nil {
t.Fatalf("Register error: %v", err)
}
if u.ID.Version() != 7 {
t.Fatalf("id must be UUIDv7, got version %d", u.ID.Version())
}
if !strings.HasPrefix(u.PasswordHash, "$argon2id$") || strings.Contains(u.PasswordHash, pw) {
t.Fatalf("password must be stored as an Argon2id hash, got %q", u.PasswordHash)
}
got, err := svc.GetByID(ctx, u.ID)
if err != nil {
t.Fatalf("GetByID error: %v", err)
}
if got != u {
t.Fatalf("GetByID = %+v, want %+v", got, u)
}
}
func TestRegisterRejectsInvalidInputAndStoresNothing(t *testing.T) {
svc := newService(t)
ctx := context.Background()
cases := map[string][3]string{
"username": {"Bad Name", "x", pw},
"display_name": {"alice", " ", pw},
"password": {"alice", "Алиса", "short"},
}
for field, in := range cases {
_, err := svc.Register(ctx, in[0], in[1], in[2])
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), field) {
t.Errorf("%s: err = %v, want KindInvalid naming the field", field, err)
}
}
var n int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM users`).Scan(&n); err != nil || n != 0 {
t.Fatalf("users = %d, %v; invalid input must not be stored", n, err)
}
}
func TestRegisterReportsDuplicateAsConflict(t *testing.T) {
svc := newService(t)
ctx := context.Background()
if _, err := svc.Register(ctx, "alice", "A", pw); err != nil {
t.Fatal(err)
}
_, err := svc.Register(ctx, "alice", "B", pw)
if !errors.Is(err, user.ErrUsernameTaken) || apperr.KindOf(err) != apperr.KindConflict {
t.Fatalf("err = %v, want ErrUsernameTaken with KindConflict", err)
}
}
// Concurrent registrations of one username race on the unique constraint:
// exactly one wins and every other gets the conflict, never a 500.
func TestConcurrentRegistrationOfOneUsernameHasOneWinner(t *testing.T) {
svc := newService(t)
ctx := context.Background()
const attempts = 10
errs := make(chan error, attempts)
var start, done sync.WaitGroup
start.Add(1)
for range attempts {
done.Add(1)
go func() {
defer done.Done()
start.Wait()
_, err := svc.Register(ctx, "racer", "Racer", pw)
errs <- err
}()
}
start.Done()
done.Wait()
close(errs)
won, lost := 0, 0
for err := range errs {
switch {
case err == nil:
won++
case errors.Is(err, user.ErrUsernameTaken):
lost++
default:
t.Errorf("unexpected error: %v", err)
}
}
if won != 1 || lost != attempts-1 {
t.Fatalf("won = %d, lost = %d; want 1 and %d", won, lost, attempts-1)
}
var n int
if err := db.Pool.QueryRow(ctx, `SELECT count(*) FROM users WHERE username = 'racer'`).Scan(&n); err != nil || n != 1 {
t.Fatalf("rows = %d, %v; want exactly one", n, err)
}
}
func TestGetByIDUnknownIsNotFound(t *testing.T) {
svc := newService(t)
_, err := svc.GetByID(context.Background(), ident.New())
if !errors.Is(err, user.ErrNotFound) || apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("err = %v, want ErrNotFound with KindNotFound", err)
}
}
func TestExistingIDsReturnsOnlyRegistered(t *testing.T) {
svc := newService(t)
ctx := context.Background()
alice, _ := svc.Register(ctx, "alice", "A", pw)
bob, _ := svc.Register(ctx, "bob", "B", pw)
got, err := svc.ExistingIDs(ctx, []uuid.UUID{ident.New(), bob.ID, alice.ID})
if err != nil {
t.Fatal(err)
}
set := map[uuid.UUID]bool{}
for _, id := range got {
set[id] = true
}
if len(got) != 2 || !set[alice.ID] || !set[bob.ID] {
t.Fatalf("ExistingIDs = %v, want alice and bob", got)
}
if empty, err := svc.ExistingIDs(ctx, nil); err != nil || len(empty) != 0 {
t.Fatalf("ExistingIDs(nil) = %v, %v", empty, err)
}
}
func TestAuthenticateChecksPassword(t *testing.T) {
svc := newService(t)
ctx := context.Background()
const colonPassword = "пароль:с:двоеточием 👋"
alice, err := svc.Register(ctx, "alice", "Алиса", colonPassword)
if err != nil {
t.Fatal(err)
}
got, err := svc.Authenticate(ctx, "alice", colonPassword)
if err != nil || got != alice {
t.Fatalf("Authenticate = %+v, %v; want alice", got, err)
}
}
// A wrong password and an unknown username must be indistinguishable.
func TestAuthenticateFailuresLookTheSame(t *testing.T) {
svc := newService(t)
ctx := context.Background()
if _, err := svc.Register(ctx, "alice", "Алиса", pw); err != nil {
t.Fatal(err)
}
_, wrong := svc.Authenticate(ctx, "alice", pw+"!")
_, unknown := svc.Authenticate(ctx, "nobody", pw)
// Basic credentials are client bytes: a username the database cannot
// even compare must still be a plain credential failure.
_, nul := svc.Authenticate(ctx, "a\x00b", pw)
_, notUTF8 := svc.Authenticate(ctx, "\xff\xfe", pw)
for name, err := range map[string]error{
"wrong password": wrong, "unknown user": unknown, "nul username": nul, "invalid utf-8 username": notUTF8,
} {
if !errors.Is(err, user.ErrInvalidCredentials) || apperr.KindOf(err) != apperr.KindUnauthorized {
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
}
}
if wrong.Error() != unknown.Error() {
t.Fatalf("messages differ: %q vs %q", wrong, unknown)
}
}
+74
View File
@@ -0,0 +1,74 @@
// Package store holds the repository implementations of the users module.
// Errors pass through postgres.Classify, so an unreachable database surfaces
// as unavailability rather than as an internal error.
package store
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/jackc/pgx/v5"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/platform/postgres"
"messenger/internal/user"
)
type Users struct {
pool *pgxpool.Pool
}
var _ user.Repository = (*Users)(nil)
func NewUsers(pool *pgxpool.Pool) *Users {
return &Users{pool: pool}
}
// Create relies on the unique constraint rather than a prior lookup, so two
// concurrent registrations of one username cannot both succeed.
func (r *Users) Create(ctx context.Context, u user.User) error {
_, err := r.pool.Exec(ctx,
`INSERT INTO users (id, username, display_name, password_hash, created_at) VALUES ($1, $2, $3, $4, $5)`,
u.ID, u.Username, u.DisplayName, u.PasswordHash, u.CreatedAt)
if postgres.IsUniqueViolation(err, "users_username_key") {
return user.ErrUsernameTaken
}
if err != nil {
return fmt.Errorf("insert user: %w", postgres.Classify(err))
}
return nil
}
func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) {
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE id = $1`, id)
}
func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) {
return r.one(ctx, `SELECT id, username, display_name, password_hash, created_at FROM users WHERE username = $1`, username)
}
func (r *Users) ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
rows, err := r.pool.Query(ctx, `SELECT id FROM users WHERE id = ANY($1)`, ids)
if err != nil {
return nil, fmt.Errorf("select user ids: %w", postgres.Classify(err))
}
found, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
if err != nil {
return nil, fmt.Errorf("read user ids: %w", postgres.Classify(err))
}
return found, nil
}
func (r *Users) one(ctx context.Context, query string, arg any) (user.User, error) {
var u user.User
err := r.pool.QueryRow(ctx, query, arg).Scan(&u.ID, &u.Username, &u.DisplayName, &u.PasswordHash, &u.CreatedAt)
if errors.Is(err, pgx.ErrNoRows) {
return user.User{}, user.ErrNotFound
}
if err != nil {
return user.User{}, fmt.Errorf("select user: %w", postgres.Classify(err))
}
return u, nil
}
+75
View File
@@ -0,0 +1,75 @@
// Package user is the users module. The entity mirrors the table row and
// carries no behaviour; New only enforces input invariants and CreatedAt
// derives from the UUIDv7 id. The password itself is never kept: the service
// validates it and stores only its hash.
package user
import (
"fmt"
"regexp"
"strings"
"time"
"unicode/utf8"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
)
const (
MaxDisplayNameCodePoints = 100
MinPasswordCodePoints = 12
MaxPasswordCodePoints = 128
)
var (
ErrNotFound = apperr.NotFound("user not found")
ErrUsernameTaken = apperr.Conflict("username already taken")
// ErrInvalidCredentials covers an unknown username and a wrong password
// alike, so a login attempt cannot probe which usernames exist.
ErrInvalidCredentials = apperr.Unauthorized("invalid username or password")
)
var usernamePattern = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
type User struct {
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
CreatedAt time.Time
}
func New(id uuid.UUID, username, displayName string) (User, error) {
if !usernamePattern.MatchString(username) {
return User{}, apperr.Invalid("username must match [a-z0-9_]{3,32}")
}
if strings.TrimSpace(displayName) == "" {
return User{}, apperr.Invalid("display_name must not be blank")
}
if utf8.RuneCountInString(displayName) > MaxDisplayNameCodePoints {
return User{}, apperr.Invalid(fmt.Sprintf("display_name must be at most %d characters", MaxDisplayNameCodePoints))
}
// PostgreSQL text cannot hold U+0000.
if strings.ContainsRune(displayName, 0) {
return User{}, apperr.Invalid("display_name must not contain the NUL character")
}
return User{
ID: id,
Username: username,
DisplayName: displayName,
CreatedAt: ident.TimeOf(id),
}, nil
}
// ValidatePassword checks the contract length in Unicode code points.
func ValidatePassword(plain string) error {
if strings.TrimSpace(plain) == "" {
return apperr.Invalid("password must not be blank")
}
if n := utf8.RuneCountInString(plain); n < MinPasswordCodePoints || n > MaxPasswordCodePoints {
return apperr.Invalid(fmt.Sprintf("password must be %d to %d characters", MinPasswordCodePoints, MaxPasswordCodePoints))
}
return nil
}
+78
View File
@@ -0,0 +1,78 @@
package user_test
import (
"strings"
"testing"
"messenger/internal/platform/apperr"
"messenger/internal/platform/ident"
"messenger/internal/user"
)
func TestNewDerivesCreatedAtFromID(t *testing.T) {
id := ident.New()
u, err := user.New(id, "alice", "Алиса")
if err != nil {
t.Fatalf("New error: %v", err)
}
if u.ID != id || u.Username != "alice" || u.DisplayName != "Алиса" {
t.Fatalf("unexpected user %+v", u)
}
if !u.CreatedAt.Equal(ident.TimeOf(id)) {
t.Fatalf("CreatedAt = %v, want %v", u.CreatedAt, ident.TimeOf(id))
}
}
func TestNewValidatesUsername(t *testing.T) {
valid := []string{"abc", "a_1", strings.Repeat("a", 32), "user_2026"}
for _, name := range valid {
if _, err := user.New(ident.New(), name, "ok"); err != nil {
t.Errorf("username %q must be accepted: %v", name, err)
}
}
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "al ice", "алиса", "a-b", "a.b", " abc", "abc\n"}
for _, name := range invalid {
_, err := user.New(ident.New(), name, "ok")
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "username") {
t.Errorf("username %q must be rejected as invalid naming the field, got %v", name, err)
}
}
}
// The contract counts the password length in Unicode code points, not bytes.
func TestValidatePasswordCountsCodePoints(t *testing.T) {
valid := []string{
strings.Repeat("я", 12),
strings.Repeat("👋", 128),
"pass:word:with:colons",
" spaced but long enough ",
}
for _, p := range valid {
if err := user.ValidatePassword(p); err != nil {
t.Errorf("password of %d code points must be accepted: %v", len([]rune(p)), err)
}
}
invalid := []string{"", strings.Repeat(" ", 12), strings.Repeat("\t", 20), strings.Repeat("я", 11), strings.Repeat("👋", 129)}
for _, p := range invalid {
err := user.ValidatePassword(p)
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "password") {
t.Errorf("password %q must be rejected as invalid naming the field, got %v", p, err)
}
}
}
func TestNewValidatesDisplayNameByCodePoints(t *testing.T) {
valid := []string{"A", "Алиса", strings.Repeat("я", 100), "👋 hi"}
for _, name := range valid {
if _, err := user.New(ident.New(), "alice", name); err != nil {
t.Errorf("display_name %q must be accepted: %v", name, err)
}
}
invalid := []string{"", " ", "\t\n", strings.Repeat("я", 101), "nul\x00inside"}
for _, name := range invalid {
_, err := user.New(ident.New(), "alice", name)
if apperr.KindOf(err) != apperr.KindInvalid || !strings.Contains(err.Error(), "display_name") {
t.Errorf("display_name %q must be rejected as invalid naming the field, got %v", name, err)
}
}
}