feat: persist data in PostgreSQL and add Basic/Bearer sessions in Redis

This commit is contained in:
2026-10-30 01:34:50 +03:00
parent 196e118ede
commit f68710818d
27 changed files with 1229 additions and 214 deletions
+53
View File
@@ -0,0 +1,53 @@
package handler
import (
"encoding/base64"
"errors"
"net/http"
"strings"
"unicode/utf8"
"messenger/internal/domain"
)
func (h *Handler) CreateSession(w http.ResponseWriter, r *http.Request) {
username, password, ok := basicCredentials(r)
if !ok {
h.failLogin(w, r, domain.ErrUnauthorized)
return
}
session, err := h.auth.Login(r.Context(), username, password)
if err != nil {
h.failLogin(w, r, err)
return
}
writeJSON(w, http.StatusCreated, toSessionResponse(session))
}
func (h *Handler) failLogin(w http.ResponseWriter, r *http.Request, err error) {
if errors.Is(err, domain.ErrUnauthorized) {
w.Header().Set(headerWWWAuthenticate, basicChallenge)
}
h.fail(w, r, err)
}
func (h *Handler) DeleteSession(w http.ResponseWriter, r *http.Request) {
if err := h.auth.Logout(r.Context(), current(r).token); err != nil {
h.fail(w, r, err)
return
}
w.WriteHeader(http.StatusNoContent)
}
func basicCredentials(r *http.Request) (string, string, bool) {
encoded, ok := authCredentials(r, "Basic")
if !ok {
return "", "", false
}
raw, err := base64.StdEncoding.DecodeString(encoded)
if err != nil || !utf8.Valid(raw) {
return "", "", false
}
username, password, ok := strings.Cut(string(raw), ":")
return username, password, ok
}
+102
View File
@@ -0,0 +1,102 @@
package handler_test
import (
"net/http"
"strings"
"testing"
"time"
)
const (
deadDatabaseURL = "postgres://messenger:x@127.0.0.1:1/messenger?sslmode=disable"
deadRedisURL = "redis://127.0.0.1:1/0"
)
func TestSessionExpiry(t *testing.T) {
dbURL, redisURL := testURLs(t)
srv := newStack(t, dbURL, redisURL, 2*time.Second)
alice := createUser(t, srv, "alice")
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusOK {
t.Fatalf("fresh session: got %d, want 200", status)
}
time.Sleep(3 * time.Second)
resp := request(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, "")
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Fatalf("expired session: got %d, want 401", resp.StatusCode)
}
if got := resp.Header.Get("WWW-Authenticate"); !strings.HasPrefix(got, "Bearer") {
t.Errorf("WWW-Authenticate = %q, want Bearer challenge", got)
}
}
func TestLogout(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
resp := request(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, "")
resp.Body.Close()
if resp.StatusCode != http.StatusNoContent {
t.Fatalf("logout: got %d, want 204", resp.StatusCode)
}
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusUnauthorized {
t.Errorf("revoked token on /users/me: got %d, want 401", status)
}
if status, _ := do(t, srv, http.MethodDelete, "/api/v1/auth/sessions/current", alice.Token, ""); status != http.StatusUnauthorized {
t.Errorf("repeated logout: got %d, want 401", status)
}
}
func TestWrongPassword(t *testing.T) {
srv := newServer(t)
alice := createUser(t, srv, "alice")
for name, password := range map[string]string{"wrong password": "Wrong-password-123", "unknown user": alice.Password} {
username := alice.Username
if name == "unknown user" {
username = "nobody_" + alice.Username[:10]
}
resp := login(t, srv, username, password)
resp.Body.Close()
if resp.StatusCode != http.StatusUnauthorized {
t.Errorf("%s: got %d, want 401", name, resp.StatusCode)
}
if got := resp.Header.Get("WWW-Authenticate"); got != `Basic realm="messenger", charset="UTF-8"` {
t.Errorf("%s: WWW-Authenticate = %q", name, got)
}
}
}
func TestRedisUnavailable(t *testing.T) {
dbURL, _ := testURLs(t)
srv := newStack(t, dbURL, deadRedisURL, time.Hour)
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", "some-token-from-before-the-outage", ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
t.Errorf("bearer request: got %d %q, want 503 unavailable", status, errorCode(body))
}
if status, _ := do(t, srv, http.MethodGet, "/api/v1/users/me", "", ""); status != http.StatusUnauthorized {
t.Errorf("anonymous request: got %d, want 401", status)
}
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
t.Errorf("ready: got %d, want 503", status)
}
}
func TestDatabaseUnavailable(t *testing.T) {
dbURL, redisURL := testURLs(t)
healthy := newStack(t, dbURL, redisURL, time.Hour)
alice := createUser(t, healthy, "alice")
srv := newStack(t, deadDatabaseURL, redisURL, time.Hour)
if status, body := do(t, srv, http.MethodGet, "/api/v1/users/me", alice.Token, ""); status != http.StatusServiceUnavailable || errorCode(body) != "unavailable" {
t.Errorf("valid session: got %d %q, want 503 unavailable", status, errorCode(body))
}
if status, _ := do(t, srv, http.MethodPost, "/api/v1/users", "",
`{"username":"db_down_user","display_name":"X","password":"long-enough-pass"}`); status != http.StatusServiceUnavailable {
t.Errorf("register: got %d, want 503", status)
}
if status, _ := do(t, srv, http.MethodGet, "/health/ready", "", ""); status != http.StatusServiceUnavailable {
t.Errorf("ready: got %d, want 503", status)
}
}
+17
View File
@@ -9,6 +9,7 @@ import (
type createUserRequest struct {
Username *string `json:"username"`
DisplayName *string `json:"display_name"`
Password *string `json:"password"`
}
type createChatRequest struct {
@@ -47,6 +48,13 @@ type pageResponse[T any] struct {
NextCursor *string `json:"next_cursor"`
}
type sessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User userResponse `json:"user"`
}
type healthResponse struct {
Status string `json:"status"`
}
@@ -74,6 +82,15 @@ func toUserResponse(u domain.User) userResponse {
}
}
func toSessionResponse(s domain.Session) sessionResponse {
return sessionResponse{
Token: s.Token,
TokenType: "Bearer",
ExpiresAt: formatTime(s.ExpiresAt),
User: toUserResponse(s.User),
}
}
func toChatResponse(c domain.Chat) chatResponse {
members := make([]string, len(c.MemberIDs))
for i, id := range c.MemberIDs {
+8 -1
View File
@@ -35,11 +35,18 @@ func (h *Handler) fail(w http.ResponseWriter, r *http.Request, err error) {
case errors.Is(err, domain.ErrInvalidInput):
writeError(w, http.StatusBadRequest, "invalid_request", err.Error())
case errors.Is(err, domain.ErrUnauthorized):
writeError(w, http.StatusUnauthorized, "unauthorized", "valid X-User-Id header is required")
if w.Header().Get(headerWWWAuthenticate) == "" {
w.Header().Set(headerWWWAuthenticate, bearerChallenge)
}
writeError(w, http.StatusUnauthorized, "unauthorized", "valid authentication is required")
case errors.Is(err, domain.ErrNotFound):
writeError(w, http.StatusNotFound, "not_found", "resource not found")
case errors.Is(err, domain.ErrConflict):
writeError(w, http.StatusConflict, "conflict", "username is already taken")
case errors.Is(err, domain.ErrUnavailable):
h.log.Error("dependency unavailable", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
writeError(w, http.StatusServiceUnavailable, "unavailable", "service temporarily unavailable")
default:
h.log.Error("unexpected error", "request_id", w.Header().Get(headerRequestID),
"method", r.Method, "path", r.URL.Path, "err", err)
+8 -2
View File
@@ -1,21 +1,27 @@
package handler
import (
"context"
"log/slog"
"net/http"
"messenger/internal/service"
)
type Pinger func(ctx context.Context) error
type Handler struct {
users *service.UserService
auth *service.AuthService
chats *service.ChatService
messages *service.MessageService
deps []Pinger
log *slog.Logger
}
func New(users *service.UserService, chats *service.ChatService, messages *service.MessageService, log *slog.Logger) *Handler {
return &Handler{users: users, chats: chats, messages: messages, log: log}
func New(users *service.UserService, auth *service.AuthService, chats *service.ChatService,
messages *service.MessageService, deps []Pinger, log *slog.Logger) *Handler {
return &Handler{users: users, auth: auth, chats: chats, messages: messages, deps: deps, log: log}
}
func (h *Handler) NotFound(w http.ResponseWriter, _ *http.Request) {
+113 -29
View File
@@ -1,33 +1,75 @@
package handler_test
import (
"context"
"encoding/base64"
"encoding/json"
"fmt"
"log/slog"
"net/http"
"net/http/httptest"
"os"
"strings"
"sync"
"testing"
"time"
"uuid"
"messenger/internal/handler"
"messenger/internal/repository/memory"
"messenger/internal/repository/postgres"
"messenger/internal/repository/redis"
"messenger/internal/router"
"messenger/internal/service"
)
func testURLs(t *testing.T) (string, string) {
t.Helper()
dbURL, redisURL := os.Getenv("TEST_DATABASE_URL"), os.Getenv("TEST_REDIS_URL")
if dbURL == "" || redisURL == "" {
t.Skip("TEST_DATABASE_URL and TEST_REDIS_URL are required")
}
return dbURL, redisURL
}
func newServer(t *testing.T) *httptest.Server {
t.Helper()
store := memory.New()
dbURL, redisURL := testURLs(t)
return newStack(t, dbURL, redisURL, time.Hour)
}
func newStack(t *testing.T, dbURL, redisURL string, ttl time.Duration) *httptest.Server {
t.Helper()
pool, err := postgres.NewPool(context.Background(), dbURL)
if err != nil {
t.Fatal(err)
}
t.Cleanup(pool.Close)
store := postgres.New(pool)
client, err := redis.NewClient(redisURL)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() { client.Close() })
sessions := redis.NewSessionStore(client)
users := service.NewUserService(store)
auth := service.NewAuthService(store, sessions, ttl)
chats := service.NewChatService(store)
messages := service.NewMessageService(chats, store)
srv := httptest.NewServer(router.New(handler.New(users, chats, messages, slog.New(slog.DiscardHandler))))
h := handler.New(users, auth, chats, messages, []handler.Pinger{store.Ping, sessions.Ping}, slog.New(slog.DiscardHandler))
srv := httptest.NewServer(router.New(h))
t.Cleanup(srv.Close)
return srv
}
func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (int, map[string]any) {
type testUser struct {
ID string
Username string
Password string
Token string
}
func request(t *testing.T, srv *httptest.Server, method, path, token, body string) *http.Response {
t.Helper()
req, err := http.NewRequest(method, srv.URL+path, strings.NewReader(body))
if err != nil {
@@ -36,13 +78,19 @@ func do(t *testing.T, srv *httptest.Server, method, path, userID, body string) (
if body != "" {
req.Header.Set("Content-Type", "application/json")
}
if userID != "" {
req.Header.Set("X-User-Id", userID)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
func do(t *testing.T, srv *httptest.Server, method, path, token, body string) (int, map[string]any) {
t.Helper()
resp := request(t, srv, method, path, token, body)
defer resp.Body.Close()
var out map[string]any
if err := json.NewDecoder(resp.Body).Decode(&out); err != nil {
@@ -57,21 +105,56 @@ func errorCode(body map[string]any) string {
return code
}
func createUser(t *testing.T, srv *httptest.Server, username string) string {
t.Helper()
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":"Test"}`, username))
if status != http.StatusCreated {
t.Fatalf("create user %s: status %d", username, status)
}
return body["id"].(string)
func basic(username, password string) string {
return "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))
}
func createChat(t *testing.T, srv *httptest.Server, owner string, members ...string) string {
func login(t *testing.T, srv *httptest.Server, username, password string) *http.Response {
t.Helper()
ids, _ := json.Marshal(members)
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner,
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, ids))
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/auth/sessions", nil)
if err != nil {
t.Fatal(err)
}
req.Header.Set("Authorization", basic(username, password))
resp, err := srv.Client().Do(req)
if err != nil {
t.Fatal(err)
}
return resp
}
func createUser(t *testing.T, srv *httptest.Server, label string) testUser {
t.Helper()
u := testUser{
Username: label + "_" + strings.ReplaceAll(uuid.New().String(), "-", "")[:12],
Password: "Test-password-" + label,
}
status, body := do(t, srv, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":"Test","password":%q}`, u.Username, u.Password))
if status != http.StatusCreated {
t.Fatalf("create user %s: status %d", u.Username, status)
}
u.ID = body["id"].(string)
resp := login(t, srv, u.Username, u.Password)
defer resp.Body.Close()
var session map[string]any
if err := json.NewDecoder(resp.Body).Decode(&session); err != nil || resp.StatusCode != http.StatusCreated {
t.Fatalf("login %s: status %d", u.Username, resp.StatusCode)
}
u.Token = session["token"].(string)
return u
}
func createChat(t *testing.T, srv *httptest.Server, owner testUser, members ...testUser) string {
t.Helper()
ids := make([]string, len(members))
for i, m := range members {
ids[i] = m.ID
}
raw, _ := json.Marshal(ids)
status, body := do(t, srv, http.MethodPost, "/api/v1/chats", owner.Token,
fmt.Sprintf(`{"title":"Test","member_ids":%s}`, raw))
if status != http.StatusCreated {
t.Fatalf("create chat: status %d", status)
}
@@ -80,7 +163,7 @@ func createChat(t *testing.T, srv *httptest.Server, owner string, members ...str
func TestInvalidJSON(t *testing.T) {
srv := newServer(t)
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x"}`} {
for _, body := range []string{`{"username":`, `not json`, `{"username":5,"display_name":"x","password":"long-enough-pass"}`} {
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", body)
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
t.Errorf("body %q: got %d %q, want 400 invalid_request", body, status, errorCode(resp))
@@ -101,13 +184,13 @@ func TestForeignChat(t *testing.T) {
{http.MethodPost, "/api/v1/chats/" + chat + "/messages", `{"text":"hi"}`},
}
for _, c := range cases {
status, resp := do(t, srv, c.method, c.path, eve, c.body)
status, resp := do(t, srv, c.method, c.path, eve.Token, c.body)
if status != http.StatusNotFound || errorCode(resp) != "not_found" {
t.Errorf("%s %s by outsider: got %d, want 404", c.method, c.path, status)
}
}
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve, "")
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats", eve.Token, "")
if status != http.StatusOK || len(resp["items"].([]any)) != 0 {
t.Errorf("outsider chat list: got %d %v, want 200 with no items", status, resp["items"])
}
@@ -120,7 +203,7 @@ func TestEmptyMessage(t *testing.T) {
for _, text := range []string{"", " ", "\n\t"} {
body, _ := json.Marshal(map[string]string{"text": text})
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, string(body))
status, resp := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, string(body))
if status != http.StatusBadRequest || errorCode(resp) != "invalid_request" {
t.Errorf("text %q: got %d, want 400", text, status)
}
@@ -129,8 +212,9 @@ func TestEmptyMessage(t *testing.T) {
func TestDuplicateUsername(t *testing.T) {
srv := newServer(t)
createUser(t, srv, "alice")
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "", `{"username":"alice","display_name":"Other"}`)
alice := createUser(t, srv, "alice")
status, resp := do(t, srv, http.MethodPost, "/api/v1/users", "",
fmt.Sprintf(`{"username":%q,"display_name":"Other","password":"another-password"}`, alice.Username))
if status != http.StatusConflict || errorCode(resp) != "conflict" {
t.Errorf("got %d %q, want 409 conflict", status, errorCode(resp))
}
@@ -143,7 +227,7 @@ func TestPaginationMultiplePages(t *testing.T) {
const total, limit = 7, 3
for i := range total {
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice, fmt.Sprintf(`{"text":"msg %d"}`, i))
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", alice.Token, fmt.Sprintf(`{"text":"msg %d"}`, i))
if status != http.StatusCreated {
t.Fatalf("send message %d: status %d", i, status)
}
@@ -158,7 +242,7 @@ func TestPaginationMultiplePages(t *testing.T) {
if cursor != "" {
path += "&cursor=" + cursor
}
status, resp := do(t, srv, http.MethodGet, path, alice, "")
status, resp := do(t, srv, http.MethodGet, path, alice.Token, "")
if status != http.StatusOK {
t.Fatalf("page %d: status %d", pages+1, status)
}
@@ -194,7 +278,7 @@ func TestConcurrentMessages(t *testing.T) {
srv := newServer(t)
const clients, perClient = 10, 10
users := make([]string, clients)
users := make([]testUser, clients)
for i := range users {
users[i] = createUser(t, srv, fmt.Sprintf("client_%d", i))
}
@@ -205,7 +289,7 @@ func TestConcurrentMessages(t *testing.T) {
for c, user := range users {
wg.Go(func() {
for i := range perClient {
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user,
status, _ := do(t, srv, http.MethodPost, "/api/v1/chats/"+chat+"/messages", user.Token,
fmt.Sprintf(`{"text":"client %d msg %d"}`, c, i))
if status != http.StatusCreated {
errs <- fmt.Errorf("client %d msg %d: status %d", c, i, status)
@@ -219,7 +303,7 @@ func TestConcurrentMessages(t *testing.T) {
t.Error(err)
}
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0], "")
status, resp := do(t, srv, http.MethodGet, "/api/v1/chats/"+chat+"/messages?limit=100", users[0].Token, "")
if status != http.StatusOK {
t.Fatalf("read history: status %d", status)
}
+16 -2
View File
@@ -1,11 +1,25 @@
package handler
import "net/http"
import (
"context"
"net/http"
"time"
)
const readyTimeout = time.Second
func (h *Handler) Live(w http.ResponseWriter, _ *http.Request) {
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
}
func (h *Handler) Ready(w http.ResponseWriter, _ *http.Request) {
func (h *Handler) Ready(w http.ResponseWriter, r *http.Request) {
ctx, cancel := context.WithTimeout(r.Context(), readyTimeout)
defer cancel()
for _, dep := range h.deps {
if err := dep(ctx); err != nil {
h.fail(w, r, err)
return
}
}
writeJSON(w, http.StatusOK, healthResponse{Status: "ok"})
}
+30 -9
View File
@@ -5,6 +5,7 @@ import (
"errors"
"net/http"
"runtime/debug"
"strings"
"time"
"uuid"
@@ -15,8 +16,10 @@ import (
)
const (
headerRequestID = "X-Request-Id"
headerUserID = "X-User-Id"
headerRequestID = "X-Request-Id"
headerWWWAuthenticate = "WWW-Authenticate"
bearerChallenge = `Bearer realm="messenger"`
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
)
func RequestID(next http.Handler) http.Handler {
@@ -66,26 +69,44 @@ func (h *Handler) Recoverer(next http.Handler) http.Handler {
type ctxKey struct{}
type principal struct {
user domain.User
token string
}
func (h *Handler) Authenticate(next http.Handler) http.Handler {
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
id, ok := parseUUID(r.Header.Get(headerUserID))
if !ok {
token, ok := authCredentials(r, "Bearer")
if !ok || token == "" {
h.fail(w, r, domain.ErrUnauthorized)
return
}
user, err := h.users.Authenticate(r.Context(), id)
user, err := h.auth.Authenticate(r.Context(), token)
if err != nil {
h.fail(w, r, err)
return
}
next.ServeHTTP(w, r.WithContext(context.WithValue(r.Context(), ctxKey{}, user)))
ctx := context.WithValue(r.Context(), ctxKey{}, principal{user: user, token: token})
next.ServeHTTP(w, r.WithContext(ctx))
})
}
func actor(r *http.Request) domain.User {
u, ok := r.Context().Value(ctxKey{}).(domain.User)
func authCredentials(r *http.Request, scheme string) (string, bool) {
gotScheme, credentials, ok := strings.Cut(r.Header.Get("Authorization"), " ")
if !ok || !strings.EqualFold(gotScheme, scheme) {
return "", false
}
return credentials, true
}
func current(r *http.Request) principal {
p, ok := r.Context().Value(ctxKey{}).(principal)
if !ok {
panic(errors.New("handler: actor requested on unauthenticated route"))
}
return u
return p
}
func actor(r *http.Request) domain.User {
return current(r).user
}
+3 -3
View File
@@ -8,11 +8,11 @@ func (h *Handler) RegisterUser(w http.ResponseWriter, r *http.Request) {
h.fail(w, r, err)
return
}
if req.Username == nil || req.DisplayName == nil {
h.fail(w, r, badRequest("username and display_name are required strings"))
if req.Username == nil || req.DisplayName == nil || req.Password == nil {
h.fail(w, r, badRequest("username, display_name and password are required strings"))
return
}
user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName)
user, err := h.users.Register(r.Context(), *req.Username, *req.DisplayName, *req.Password)
if err != nil {
h.fail(w, r, err)
return