Перенести пользователей в PostgreSQL и добавить пароли

This commit is contained in:
2026-10-06 14:54:34 +03:00
parent 46c00436a0
commit 618d3919d1
17 changed files with 482 additions and 219 deletions
+24 -10
View File
@@ -1,4 +1,4 @@
// Command server starts the in-memory messenger API.
// Command server starts the messenger API over PostgreSQL.
package main
import (
@@ -12,6 +12,7 @@ import (
"messenger/internal/app"
"messenger/internal/platform/config"
"messenger/internal/platform/postgres"
"messenger/internal/server"
)
@@ -23,23 +24,36 @@ func main() {
}
log := newLogger(cfg)
ln, err := net.Listen("tcp", cfg.Addr())
if err != nil {
log.Error("listen failed", "addr", cfg.Addr(), "error", err.Error())
os.Exit(1)
}
ctx, stop := signal.NotifyContext(context.Background(), syscall.SIGTERM, syscall.SIGINT)
defer stop()
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(), "shutdown_timeout", cfg.ShutdownTimeout.String())
a := app.New(log, cfg.MaxBodyBytes)
if err := server.Run(ctx, log, ln, a.Engine, a.Health, cfg.ShutdownTimeout); err != nil {
if err := run(ctx, log, cfg); err != nil {
log.Error("server stopped with error", "error", err.Error())
os.Exit(1)
}
}
// run connects the dependencies before it listens, so the port accepts
// connections only once the schema is in place.
func run(ctx context.Context, log *slog.Logger, cfg config.Config) error {
pool, err := postgres.NewPool(ctx, cfg.DatabaseURL)
if err != nil {
return err
}
defer pool.Close()
if err := postgres.Migrate(ctx, pool); err != nil {
return err
}
ln, err := net.Listen("tcp", cfg.Addr())
if err != nil {
return fmt.Errorf("listen on %s: %w", cfg.Addr(), err)
}
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(), "shutdown_timeout", cfg.ShutdownTimeout.String())
a := app.New(app.Deps{Log: log, DB: pool, MaxBodyBytes: cfg.MaxBodyBytes})
return server.Run(ctx, log, ln, a.Engine, a.Health, cfg.ShutdownTimeout)
}
func newLogger(cfg config.Config) *slog.Logger {
opts := &slog.HandlerOptions{Level: cfg.LogLevel}
if cfg.Env == "dev" {
+14 -5
View File
@@ -1,12 +1,13 @@
// Package app is the composition root: it builds every module with its
// in-memory stores and mounts them on one HTTP engine. Both the server
// binary and the integration tests start from here.
// stores and mounts them on one HTTP engine. Both the server binary and the
// integration tests start from here.
package app
import (
"log/slog"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"messenger/internal/auth"
"messenger/internal/chat"
@@ -22,11 +23,19 @@ type App struct {
Health *health.Handler
}
func New(log *slog.Logger, maxBodyBytes int64) *App {
users := user.NewService(userstore.NewInMemUsers())
// Deps are the shared resources the modules are built on; their lifetime is
// owned by the caller.
type Deps struct {
Log *slog.Logger
DB *pgxpool.Pool
MaxBodyBytes int64
}
func New(d Deps) *App {
users := user.NewService(userstore.NewUsers(d.DB))
chats := chat.NewService(chatstore.NewInMemChats(), chatstore.NewInMemMessages(), users)
engine := httpx.NewEngine(log, maxBodyBytes)
engine := httpx.NewEngine(d.Log, d.MaxBodyBytes)
probes := health.New()
probes.Register(engine)
+26 -3
View File
@@ -2,6 +2,7 @@ package app_test
import (
"bytes"
"context"
"encoding/json"
"fmt"
"io"
@@ -9,6 +10,7 @@ import (
"net/http"
"net/http/httptest"
"net/url"
"os"
"sort"
"strings"
"sync"
@@ -17,9 +19,26 @@ import (
"messenger/internal/app"
"messenger/internal/chat"
"messenger/internal/platform/pagination"
"messenger/internal/testenv"
"messenger/internal/user"
)
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)
}
const testPassword = "correct-horse-battery"
// errorBody mirrors the contract error envelope.
type errorBody struct {
Error struct {
@@ -41,10 +60,12 @@ type tester struct {
a *app.App
}
// newTester assembles the application over an empty database.
func newTester(t *testing.T) *tester {
t.Helper()
db.Reset(t)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return &tester{t: t, a: app.New(log, 64*1024)}
return &tester{t: t, a: app.New(app.Deps{Log: log, DB: db.Pool, MaxBodyBytes: 64 * 1024})}
}
// do sends one request. A string body is sent verbatim, anything else is
@@ -127,7 +148,8 @@ func decode[T any](t *testing.T, res response) T {
func (ts *tester) user(username, display string) user.Response {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/users", "", map[string]string{"username": username, "display_name": display}, nil)
body := map[string]string{"username": username, "display_name": display, "password": testPassword}
res := ts.do(http.MethodPost, "/api/v1/users", "", body, nil)
ts.expect(res, http.StatusCreated, "")
return decode[user.Response](ts.t, res)
}
@@ -192,7 +214,8 @@ func TestRegisterUserShapeAndConflicts(t *testing.T) {
t.Fatalf("created_at = %q", alice.CreatedAt)
}
post := func(body any) response { return ts.do(http.MethodPost, "/api/v1/users", "", body, nil) }
ts.expect(post(map[string]string{"username": "alice", "display_name": "Other"}), http.StatusConflict, "conflict")
ts.expect(post(map[string]string{"username": "alice", "display_name": "Other", "password": testPassword}), http.StatusConflict, "conflict")
ts.expect(post(map[string]string{"username": "bob", "display_name": "Bob"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]string{"username": "Alice", "display_name": "x"}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]string{"username": "bob", "display_name": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(map[string]any{"username": "bob", "display_name": "x", "password": "no"}), http.StatusBadRequest, "invalid_request")
+28 -2
View File
@@ -1,12 +1,15 @@
// Package config reads the process configuration from the environment.
// Every setting has a default suited to the lab stand; an invalid value stops
// the process at start-up with a message naming the variable.
// Settings have defaults suited to the lab stand, except credentials, which
// are required and read from files named by *_FILE variables so that their
// values never appear in the environment. An invalid value stops the process
// at start-up with a message naming the variable, never the secret.
package config
import (
"fmt"
"log/slog"
"net"
"os"
"strconv"
"strings"
"time"
@@ -19,6 +22,7 @@ type Config struct {
LogLevel slog.Level
ShutdownTimeout time.Duration
MaxBodyBytes int64
DatabaseURL string
}
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
@@ -71,9 +75,31 @@ func Load(lookup Lookup) (Config, error) {
}
cfg.MaxBodyBytes = n
}
var err error
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
return Config{}, err
}
return cfg, nil
}
// secret reads the file named by the variable; surrounding whitespace,
// including the trailing newline editors add, is dropped.
func secret(lookup Lookup, key string) (string, error) {
path, ok := lookup(key)
if !ok || strings.TrimSpace(path) == "" {
return "", fmt.Errorf("%s must name a file with the value", key)
}
raw, err := os.ReadFile(path)
if err != nil {
return "", fmt.Errorf("%s: cannot read %s: %w", key, path, err)
}
value := strings.TrimSpace(string(raw))
if value == "" {
return "", fmt.Errorf("%s: file %s is empty", key, path)
}
return value, nil
}
func (c Config) Addr() string {
return net.JoinHostPort(c.Host, strconv.Itoa(c.Port))
}
+50 -4
View File
@@ -2,6 +2,9 @@ package config_test
import (
"log/slog"
"os"
"path/filepath"
"strings"
"testing"
"time"
@@ -15,8 +18,29 @@ func env(values map[string]string) func(string) (string, bool) {
}
}
func secretFile(t *testing.T, content string) string {
t.Helper()
path := filepath.Join(t.TempDir(), "secret")
if err := os.WriteFile(path, []byte(content), 0o600); err != nil {
t.Fatal(err)
}
return path
}
const databaseURL = "postgres://app:s3cret@db:5432/messenger"
// required holds the variables without defaults, merged with extra.
func required(t *testing.T, extra map[string]string) map[string]string {
t.Helper()
values := map[string]string{"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n")}
for k, v := range extra {
values[k] = v
}
return values
}
func TestDefaults(t *testing.T) {
cfg, err := config.Load(env(nil))
cfg, err := config.Load(env(required(t, nil)))
if err != nil {
t.Fatalf("Load error: %v", err)
}
@@ -29,17 +53,39 @@ func TestDefaults(t *testing.T) {
if cfg.ShutdownTimeout != 8*time.Second || cfg.MaxBodyBytes != 65536 {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.DatabaseURL != databaseURL {
t.Fatalf("DatabaseURL = %q, want the file content without the newline", cfg.DatabaseURL)
}
}
func TestSecretFilesAreRequiredAndNeverEchoed(t *testing.T) {
cases := map[string]map[string]string{
"unset": nil,
"empty path": {"DATABASE_URL_FILE": ""},
"no file": {"DATABASE_URL_FILE": filepath.Join(t.TempDir(), "missing")},
"blank file": {"DATABASE_URL_FILE": secretFile(t, " \r\n")},
}
for name, values := range cases {
_, err := config.Load(env(values))
if err == nil {
t.Errorf("%s: want error", name)
continue
}
if !strings.Contains(err.Error(), "DATABASE_URL_FILE") || strings.Contains(err.Error(), "s3cret") {
t.Errorf("%s: error must name the variable and hide the secret: %v", name, err)
}
}
}
func TestOverrides(t *testing.T) {
cfg, err := config.Load(env(map[string]string{
cfg, err := config.Load(env(required(t, map[string]string{
"APP_HOST": "127.0.0.1",
"APP_PORT": "9090",
"APP_ENV": "dev",
"APP_LOG_LEVEL": "debug",
"APP_SHUTDOWN_TIMEOUT": "3s",
"APP_MAX_BODY_BYTES": "1024",
}))
})))
if err != nil {
t.Fatalf("Load error: %v", err)
}
@@ -64,7 +110,7 @@ func TestInvalidValuesAreReported(t *testing.T) {
"empty host": {"APP_HOST": ""},
}
for name, values := range cases {
if _, err := config.Load(env(values)); err == nil {
if _, err := config.Load(env(required(t, values))); err == nil {
t.Errorf("%s: want error", name)
}
}
+2 -1
View File
@@ -27,6 +27,7 @@ func (h *Handler) Register(public, protected gin.IRouter) {
type createRequest struct {
Username string `json:"username"`
DisplayName string `json:"display_name"`
Password string `json:"password"`
}
type Response struct {
@@ -51,7 +52,7 @@ func (h *Handler) register(c *gin.Context) {
httpx.Error(c, err)
return
}
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName)
u, err := h.users.Register(c.Request.Context(), req.Username, req.DisplayName, req.Password)
if err != nil {
httpx.Error(c, err)
return
+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)
}
+2 -1
View File
@@ -11,7 +11,8 @@ type Repository interface {
// 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 input order, in one round trip.
// in no particular order, in one round trip.
ExistingIDs(ctx context.Context, ids []uuid.UUID) ([]uuid.UUID, error)
}
+37 -1
View File
@@ -2,11 +2,14 @@ package user
import (
"context"
"errors"
"fmt"
"sync"
"github.com/google/uuid"
"messenger/internal/platform/ident"
"messenger/internal/platform/password"
)
type Service struct {
@@ -17,17 +20,50 @@ func NewService(repo Repository) *Service {
return &Service{repo: repo}
}
func (s *Service) Register(ctx context.Context, username, displayName string) (User, error) {
// 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.
func (s *Service) Authenticate(ctx context.Context, username, plain string) (User, error) {
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)
}
+127 -23
View File
@@ -3,6 +3,8 @@ package user_test
import (
"context"
"errors"
"strings"
"sync"
"testing"
"github.com/google/uuid"
@@ -13,50 +15,116 @@ import (
"messenger/internal/user/store"
)
func newService() *user.Service {
return user.NewService(store.NewInMemUsers())
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 TestRegisterStoresUser(t *testing.T) {
svc := newService()
func TestRegisterStoresUserWithPasswordHash(t *testing.T) {
svc := newService(t)
ctx := context.Background()
u, err := svc.Register(ctx, "alice", "Алиса")
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 || got != u {
t.Fatalf("GetByID = %+v, %v; want %+v", got, err, u)
if err != nil {
t.Fatalf("GetByID error: %v", err)
}
if got != u {
t.Fatalf("GetByID = %+v, want %+v", got, u)
}
if ok, err := svc.Exists(ctx, u.ID); err != nil || !ok {
t.Fatalf("Exists = %v, %v; want true", ok, err)
}
}
func TestRegisterRejectsInvalidInput(t *testing.T) {
_, err := newService().Register(context.Background(), "Bad Name", "x")
if apperr.KindOf(err) != apperr.KindInvalid {
t.Fatalf("kind = %v, want KindInvalid (%v)", apperr.KindOf(err), err)
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()
svc := newService(t)
ctx := context.Background()
if _, err := svc.Register(ctx, "alice", "A"); err != nil {
if _, err := svc.Register(ctx, "alice", "A", pw); err != nil {
t.Fatal(err)
}
_, err := svc.Register(ctx, "alice", "B")
_, 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()
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)
@@ -66,20 +134,56 @@ func TestGetByIDUnknownIsNotFound(t *testing.T) {
}
}
func TestExistingIDsFiltersInOneCall(t *testing.T) {
svc := newService()
func TestExistingIDsReturnsOnlyRegistered(t *testing.T) {
svc := newService(t)
ctx := context.Background()
alice, _ := svc.Register(ctx, "alice", "A")
bob, _ := svc.Register(ctx, "bob", "B")
unknown := ident.New()
got, err := svc.ExistingIDs(ctx, []uuid.UUID{unknown, bob.ID, alice.ID})
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)
}
if len(got) != 2 || got[0] != bob.ID || got[1] != alice.ID {
t.Fatalf("ExistingIDs = %v, want bob then alice", got)
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)
for name, err := range map[string]error{"wrong password": wrong, "unknown user": unknown} {
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)
}
}
-63
View File
@@ -1,63 +0,0 @@
// Package store holds the repository implementations of the users module.
// inmem.go is the in-process one: state lives only in this process and
// disappears with it by design of the lab.
package store
import (
"context"
"sync"
"github.com/google/uuid"
"messenger/internal/user"
)
type InMemUsers struct {
mu sync.RWMutex
byID map[uuid.UUID]user.User
byUsername map[string]struct{}
}
var _ user.Repository = (*InMemUsers)(nil)
func NewInMemUsers() *InMemUsers {
return &InMemUsers{
byID: make(map[uuid.UUID]user.User),
byUsername: make(map[string]struct{}),
}
}
// Create checks and inserts under the same write lock, so concurrent
// registrations of one username admit exactly one winner.
func (r *InMemUsers) Create(_ context.Context, u user.User) error {
r.mu.Lock()
defer r.mu.Unlock()
if _, taken := r.byUsername[u.Username]; taken {
return user.ErrUsernameTaken
}
r.byUsername[u.Username] = struct{}{}
r.byID[u.ID] = u
return nil
}
func (r *InMemUsers) GetByID(_ context.Context, id uuid.UUID) (user.User, error) {
r.mu.RLock()
defer r.mu.RUnlock()
u, ok := r.byID[id]
if !ok {
return user.User{}, user.ErrNotFound
}
return u, nil
}
func (r *InMemUsers) ExistingIDs(_ context.Context, ids []uuid.UUID) ([]uuid.UUID, error) {
r.mu.RLock()
defer r.mu.RUnlock()
found := make([]uuid.UUID, 0, len(ids))
for _, id := range ids {
if _, ok := r.byID[id]; ok {
found = append(found, id)
}
}
return found, nil
}
-97
View File
@@ -1,97 +0,0 @@
package store_test
import (
"context"
"errors"
"sync"
"testing"
"github.com/google/uuid"
"messenger/internal/platform/ident"
"messenger/internal/user"
"messenger/internal/user/store"
)
func mustUser(t *testing.T, username string) user.User {
t.Helper()
u, err := user.New(ident.New(), username, "Display")
if err != nil {
t.Fatal(err)
}
return u
}
func TestCreateThenGetByID(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
u := mustUser(t, "alice")
if err := repo.Create(ctx, u); err != nil {
t.Fatalf("Create error: %v", err)
}
got, err := repo.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 TestGetByIDUnknownReturnsErrNotFound(t *testing.T) {
_, err := store.NewInMemUsers().GetByID(context.Background(), ident.New())
if !errors.Is(err, user.ErrNotFound) {
t.Fatalf("err = %v, want ErrNotFound", err)
}
}
func TestCreateRejectsDuplicateUsername(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
if err := repo.Create(ctx, mustUser(t, "alice")); err != nil {
t.Fatal(err)
}
err := repo.Create(ctx, mustUser(t, "alice"))
if !errors.Is(err, user.ErrUsernameTaken) {
t.Fatalf("err = %v, want ErrUsernameTaken", err)
}
}
func TestCreateIsAtomicUnderConcurrency(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
const workers = 50
var wg sync.WaitGroup
var mu sync.Mutex
created := 0
for i := 0; i < workers; i++ {
wg.Add(1)
go func() {
defer wg.Done()
if err := repo.Create(ctx, mustUser(t, "same_name")); err == nil {
mu.Lock()
created++
mu.Unlock()
}
}()
}
wg.Wait()
if created != 1 {
t.Fatalf("exactly one Create must win, got %d", created)
}
}
func TestExistingIDsReturnsOnlyKnownIDs(t *testing.T) {
repo := store.NewInMemUsers()
ctx := context.Background()
alice, bob := mustUser(t, "alice"), mustUser(t, "bob")
_ = repo.Create(ctx, alice)
_ = repo.Create(ctx, bob)
got, err := repo.ExistingIDs(ctx, []uuid.UUID{ident.New(), bob.ID, alice.ID, bob.ID})
if err != nil {
t.Fatal(err)
}
if len(got) != 3 || got[0] != bob.ID || got[1] != alice.ID || got[2] != bob.ID {
t.Fatalf("ExistingIDs must keep input order and drop unknown ids, got %v", got)
}
}
+75
View File
@@ -0,0 +1,75 @@
// Package store holds the repository implementations of the users module.
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"
)
const userColumns = `id, username, display_name, password_hash, created_at`
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 (`+userColumns+`) 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", err)
}
return nil
}
func (r *Users) GetByID(ctx context.Context, id uuid.UUID) (user.User, error) {
return r.one(ctx, `SELECT `+userColumns+` FROM users WHERE id = $1`, id)
}
func (r *Users) GetByUsername(ctx context.Context, username string) (user.User, error) {
return r.one(ctx, `SELECT `+userColumns+` 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", err)
}
found, err := pgx.CollectRows(rows, pgx.RowTo[uuid.UUID])
if err != nil {
return nil, fmt.Errorf("read user ids: %w", 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", err)
}
u.CreatedAt = u.CreatedAt.UTC()
return u, nil
}
+28 -8
View File
@@ -1,6 +1,7 @@
// Package user is the users module. The entity mirrors the future table row
// and carries no behaviour; New only enforces input invariants and CreatedAt
// derives from the UUIDv7 id.
// 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 (
@@ -16,20 +17,28 @@ import (
"messenger/internal/platform/ident"
)
const MaxDisplayNameCodePoints = 100
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
CreatedAt time.Time
ID uuid.UUID
Username string
DisplayName string
PasswordHash string
CreatedAt time.Time
}
func New(id uuid.UUID, username, displayName string) (User, error) {
@@ -49,3 +58,14 @@ func New(id uuid.UUID, username, displayName string) (User, error) {
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
}
+22
View File
@@ -39,6 +39,28 @@ func TestNewValidatesUsername(t *testing.T) {
}
}
// 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 {
+4
View File
@@ -121,6 +121,9 @@ func run(baseURL string, clients, perClient int) (Report, error) {
return report, nil
}
// clientPassword is shared by the synthetic clients of one run.
const clientPassword = "concurrency-check-password"
func registerClients(api *client, runID string, n int) ([]string, error) {
ids := make([]string, 0, n)
for i := range n {
@@ -128,6 +131,7 @@ func registerClients(api *client, runID string, n int) ([]string, error) {
body := map[string]string{
"username": fmt.Sprintf("load_%s_%d", runID, i),
"display_name": fmt.Sprintf("Load client %d", i),
"password": clientPassword,
}
if err := api.post("/api/v1/users", "", body, &created); err != nil {
return nil, fmt.Errorf("register client %d: %w", i, err)
+19 -1
View File
@@ -1,17 +1,35 @@
package main
import (
"context"
"fmt"
"io"
"log/slog"
"net/http/httptest"
"os"
"testing"
"messenger/internal/app"
"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)
}
func TestRunAgainstLiveServer(t *testing.T) {
log := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := httptest.NewServer(app.New(log, 64*1024).Engine)
srv := httptest.NewServer(app.New(app.Deps{Log: log, DB: db.Pool, MaxBodyBytes: 64 * 1024}).Engine)
defer srv.Close()
report, err := run(srv.URL, 10, 10)