Добавить сессии в Valkey и вход через Basic с Bearer-токеном

This commit is contained in:
2026-10-06 15:08:39 +03:00
parent 3c1b63ed98
commit 9890482747
23 changed files with 1047 additions and 274 deletions
+16 -3
View File
@@ -1,4 +1,4 @@
// Command server starts the messenger API over PostgreSQL.
// Command server starts the messenger API over PostgreSQL and Valkey.
package main
import (
@@ -13,6 +13,7 @@ import (
"messenger/internal/app"
"messenger/internal/platform/config"
"messenger/internal/platform/postgres"
"messenger/internal/platform/valkey"
"messenger/internal/server"
)
@@ -44,13 +45,25 @@ func run(ctx context.Context, log *slog.Logger, cfg config.Config) error {
if err := postgres.Migrate(ctx, pool); err != nil {
return err
}
sessions, err := valkey.NewClient(ctx, cfg.SessionStoreURL)
if err != nil {
return err
}
defer sessions.Close()
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})
log.Info("starting", "env", cfg.Env, "addr", cfg.Addr(),
"shutdown_timeout", cfg.ShutdownTimeout.String(), "session_ttl", cfg.SessionTTL.String())
a := app.New(app.Deps{
Log: log,
DB: pool,
Sessions: sessions,
SessionTTL: cfg.SessionTTL,
MaxBodyBytes: cfg.MaxBodyBytes,
})
return server.Run(ctx, log, ln, a.Engine, a.Health, cfg.ShutdownTimeout)
}
+9 -1
View File
@@ -5,11 +5,14 @@ package app
import (
"log/slog"
"time"
"github.com/gin-gonic/gin"
"github.com/jackc/pgx/v5/pgxpool"
"github.com/redis/go-redis/v9"
"messenger/internal/auth"
authstore "messenger/internal/auth/store"
"messenger/internal/chat"
chatstore "messenger/internal/chat/store"
"messenger/internal/health"
@@ -28,6 +31,8 @@ type App struct {
type Deps struct {
Log *slog.Logger
DB *pgxpool.Pool
Sessions *redis.Client
SessionTTL time.Duration
MaxBodyBytes int64
}
@@ -39,8 +44,11 @@ func New(d Deps) *App {
probes := health.New()
probes.Register(engine)
sessions := auth.NewService(users, authstore.NewSessions(d.Sessions), d.SessionTTL)
public := engine.Group("/api/v1")
protected := public.Group("", auth.RequireUser(users))
protected := public.Group("", auth.RequireSession(sessions))
auth.NewHandler(sessions).Register(public, protected)
user.NewHandler(users).Register(public, protected)
chat.NewHandler(chats).Register(protected)
+146 -80
View File
@@ -3,6 +3,7 @@ package app_test
import (
"bytes"
"context"
"encoding/base64"
"encoding/json"
"fmt"
"io"
@@ -15,6 +16,7 @@ import (
"strings"
"sync"
"testing"
"time"
"messenger/internal/app"
"messenger/internal/chat"
@@ -23,16 +25,25 @@ import (
"messenger/internal/user"
)
var db *testenv.DB
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
db, err = testenv.StartPostgres(context.Background())
if err != nil {
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
db.Close()
os.Exit(code)
}
@@ -51,6 +62,7 @@ type errorBody struct {
type response struct {
status int
requestID string
challenge string
raw []byte
}
@@ -60,25 +72,53 @@ 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(app.Deps{Log: log, DB: db.Pool, MaxBodyBytes: 64 * 1024})}
// account is a registered user with a live session.
type account struct {
user.Response
token string
}
// do sends one request. A string body is sent verbatim, anything else is
// JSON-encoded; both get a JSON content type. Every response is checked for
// X-Request-Id, and error bodies for the contract envelope.
func (ts *tester) do(method, path, actor string, body any, headers map[string]string) response {
// sessionBody mirrors the contract Session schema.
type sessionBody struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User user.Response `json:"user"`
}
func newTester(t *testing.T) *tester {
t.Helper()
return newTesterWithTTL(t, time.Hour)
}
// newTesterWithTTL assembles the application over empty stores.
func newTesterWithTTL(t *testing.T, ttl time.Duration) *tester {
t.Helper()
db.Reset(t)
kv.Reset(t)
log := slog.New(slog.NewTextHandler(io.Discard, nil))
return &tester{t: t, a: app.New(app.Deps{
Log: log,
DB: db.Pool,
Sessions: kv.Client,
SessionTTL: ttl,
MaxBodyBytes: 64 * 1024,
})}
}
// do sends one request, authenticated with the bearer token when it is set.
// A string body is sent verbatim, anything else is JSON-encoded; both get a
// JSON content type. Every response is checked for X-Request-Id, error
// bodies for the contract envelope, and every 401 for the challenge of the
// scheme the route expects.
func (ts *tester) do(method, path, token string, body any, headers map[string]string) response {
ts.t.Helper()
req := httptest.NewRequest(method, path, encode(ts.t, body))
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if actor != "" {
req.Header.Set("X-User-Id", actor)
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
for k, v := range headers {
req.Header.Set(k, v)
@@ -86,7 +126,12 @@ func (ts *tester) do(method, path, actor string, body any, headers map[string]st
rec := httptest.NewRecorder()
ts.a.Engine.ServeHTTP(rec, req)
res := response{status: rec.Code, requestID: rec.Header().Get("X-Request-Id"), raw: rec.Body.Bytes()}
res := response{
status: rec.Code,
requestID: rec.Header().Get("X-Request-Id"),
challenge: rec.Header().Get("WWW-Authenticate"),
raw: rec.Body.Bytes(),
}
if res.requestID == "" {
ts.t.Fatalf("%s %s: missing X-Request-Id", method, path)
}
@@ -99,6 +144,15 @@ func (ts *tester) do(method, path, actor string, body any, headers map[string]st
ts.t.Fatalf("%s %s: bad error envelope: %s", method, path, res.raw)
}
}
if res.status == http.StatusUnauthorized {
scheme := "Bearer "
if path == "/api/v1/auth/sessions" {
scheme = "Basic "
}
if !strings.HasPrefix(res.challenge, scheme) {
ts.t.Fatalf("%s %s: 401 challenge = %q, want scheme %q", method, path, res.challenge, scheme)
}
}
return res
}
@@ -146,38 +200,52 @@ func decode[T any](t *testing.T, res response) T {
return out
}
func (ts *tester) user(username, display string) user.Response {
// user registers a user and logs it in.
func (ts *tester) user(username, display string) account {
ts.t.Helper()
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)
registered := decode[user.Response](ts.t, res)
return account{Response: registered, token: ts.login(username, testPassword).Token}
}
func (ts *tester) chat(actor, title string, members ...string) chat.ChatResponse {
func basic(username, password string) map[string]string {
raw := base64.StdEncoding.EncodeToString([]byte(username + ":" + password))
return map[string]string{"Authorization": "Basic " + raw}
}
func (ts *tester) login(username, password string) sessionBody {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats", actor, map[string]any{"title": title, "member_ids": members}, nil)
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic(username, password))
ts.expect(res, http.StatusCreated, "")
return decode[sessionBody](ts.t, res)
}
func (ts *tester) chat(token, title string, members ...string) chat.ChatResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats", token, map[string]any{"title": title, "member_ids": members}, nil)
ts.expect(res, http.StatusCreated, "")
return decode[chat.ChatResponse](ts.t, res)
}
func (ts *tester) message(actor, chatID, text string) chat.MessageResponse {
func (ts *tester) message(token, chatID, text string) chat.MessageResponse {
ts.t.Helper()
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", actor, map[string]string{"text": text}, nil)
res := ts.do(http.MethodPost, "/api/v1/chats/"+chatID+"/messages", token, map[string]string{"text": text}, nil)
ts.expect(res, http.StatusCreated, "")
return decode[chat.MessageResponse](ts.t, res)
}
func (ts *tester) chats(actor, query string) pagination.PageResponse[chat.ChatResponse] {
func (ts *tester) chats(token, query string) pagination.PageResponse[chat.ChatResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats"+query, actor, nil, nil)
res := ts.do(http.MethodGet, "/api/v1/chats"+query, token, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.ChatResponse]](ts.t, res)
}
func (ts *tester) history(actor, chatID, query string) pagination.PageResponse[chat.MessageResponse] {
func (ts *tester) history(token, chatID, query string) pagination.PageResponse[chat.MessageResponse] {
ts.t.Helper()
res := ts.do(http.MethodGet, "/api/v1/chats/"+chatID+"/messages"+query, actor, nil, nil)
res := ts.do(http.MethodGet, "/api/v1/chats/"+chatID+"/messages"+query, token, nil, nil)
ts.expect(res, http.StatusOK, "")
return decode[pagination.PageResponse[chat.MessageResponse]](ts.t, res)
}
@@ -223,24 +291,21 @@ func TestRegisterUserShapeAndConflicts(t *testing.T) {
ts.expect(post(map[string]any{"username": 5, "display_name": "x"}), http.StatusBadRequest, "invalid_request")
}
func TestCurrentUserRequiresIdentity(t *testing.T) {
func TestCurrentUserIsTheTokenOwner(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
me := func(actor string) response { return ts.do(http.MethodGet, "/api/v1/users/me", actor, nil, nil) }
ts.expect(me(""), http.StatusUnauthorized, "unauthorized")
ts.expect(me("garbage"), http.StatusUnauthorized, "unauthorized")
ts.expect(me("11111111-1111-4111-8111-111111111111"), http.StatusUnauthorized, "unauthorized")
res := me(alice.ID)
ts.user("bob", "Боб")
res := ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got != alice {
t.Fatalf("me = %+v, want %+v", got, alice)
if got := decode[user.Response](t, res); got != alice.Response {
t.Fatalf("me = %+v, want %+v", got, alice.Response)
}
}
func TestChatCreationRules(t *testing.T) {
ts := newTester(t)
alice, bob := ts.user("alice", "A"), ts.user("bob", "B")
created := ts.chat(alice.ID, "Проект по ВНП", alice.ID, bob.ID)
created := ts.chat(alice.token, "Проект по ВНП", alice.ID, bob.ID)
if created.Title != "Проект по ВНП" || len(created.MemberIDs) != 2 || created.MemberIDs[0] != alice.ID || created.MemberIDs[1] != bob.ID {
t.Fatalf("chat = %+v", created)
}
@@ -257,7 +322,7 @@ func TestChatCreationRules(t *testing.T) {
"extra field": map[string]any{"title": "t", "member_ids": []string{alice.ID}, "owner": alice.ID},
}
for name, body := range invalid {
res := ts.do(http.MethodPost, "/api/v1/chats", alice.ID, body, nil)
res := ts.do(http.MethodPost, "/api/v1/chats", alice.token, body, nil)
if res.status != http.StatusBadRequest {
t.Errorf("%s: status = %d, want 400; body %s", name, res.status, res.raw)
}
@@ -268,24 +333,24 @@ func TestChatCreationRules(t *testing.T) {
func TestChatVisibilityAndListing(t *testing.T) {
ts := newTester(t)
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
created := ts.chat(alice.ID, "Контрактный тест", alice.ID, bob.ID)
created := ts.chat(alice.token, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + created.ID
res := ts.do(http.MethodGet, path, bob.ID, nil, nil)
res := ts.do(http.MethodGet, path, bob.token, nil, nil)
ts.expect(res, http.StatusOK, "")
if got := decode[chat.ChatResponse](t, res); got.ID != created.ID || len(got.MemberIDs) != 2 {
t.Fatalf("GET chat = %+v", got)
}
ts.expect(ts.do(http.MethodGet, path, eve.ID, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/33333333-3333-4333-8333-333333333333", alice.ID, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/not-a-uuid", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, path, eve.token, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/33333333-3333-4333-8333-333333333333", alice.token, nil, nil), http.StatusNotFound, "not_found")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/not-a-uuid", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, path, "", nil, nil), http.StatusUnauthorized, "unauthorized")
listed := ts.chats(bob.ID, "?limit=100")
listed := ts.chats(bob.token, "?limit=100")
if len(listed.Items) != 1 || listed.Items[0].ID != created.ID || listed.NextCursor != nil {
t.Fatalf("bob list = %+v", listed)
}
hidden := ts.do(http.MethodGet, "/api/v1/chats?limit=100", eve.ID, nil, nil)
hidden := ts.do(http.MethodGet, "/api/v1/chats?limit=100", eve.token, nil, nil)
ts.expect(hidden, http.StatusOK, "")
if !strings.Contains(string(hidden.raw), `"items":[]`) || !strings.Contains(string(hidden.raw), `"next_cursor":null`) {
t.Fatalf("empty list must serialize items as [] and next_cursor as null: %s", hidden.raw)
@@ -297,12 +362,12 @@ func TestChatListPagination(t *testing.T) {
alice := ts.user("alice", "A")
var expected []string
for i := 0; i < 5; i++ {
expected = append(expected, ts.chat(alice.ID, fmt.Sprintf("chat %d", i), alice.ID).ID)
expected = append(expected, ts.chat(alice.token, fmt.Sprintf("chat %d", i), alice.ID).ID)
}
var walked []string
var cursor *string
for pages := 0; pages < 10; pages++ {
page := ts.chats(alice.ID, cursorQuery(2, cursor))
page := ts.chats(alice.token, cursorQuery(2, cursor))
for _, c := range page.Items {
walked = append(walked, c.ID)
}
@@ -316,20 +381,20 @@ func TestChatListPagination(t *testing.T) {
}
bob := ts.user("bob", "B")
foreign := ts.chats(alice.ID, "?limit=1").NextCursor
ts.expect(ts.do(http.MethodGet, "/api/v1/chats"+cursorQuery(50, foreign), bob.ID, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?cursor=", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?limit=abc", alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
foreign := ts.chats(alice.token, "?limit=1").NextCursor
ts.expect(ts.do(http.MethodGet, "/api/v1/chats"+cursorQuery(50, foreign), bob.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?cursor=", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
ts.expect(ts.do(http.MethodGet, "/api/v1/chats?limit=abc", alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessagesEndToEnd(t *testing.T) {
ts := newTester(t)
alice, bob, eve := ts.user("alice", "A"), ts.user("bob", "B"), ts.user("eve", "E")
room := ts.chat(alice.ID, "Контрактный тест", alice.ID, bob.ID)
room := ts.chat(alice.token, "Контрактный тест", alice.ID, bob.ID)
path := "/api/v1/chats/" + room.ID + "/messages"
first := ts.message(alice.ID, room.ID, "Привет, мир 👋")
second := ts.message(bob.ID, room.ID, "Сообщение Боба")
first := ts.message(alice.token, room.ID, "Привет, мир 👋")
second := ts.message(bob.token, room.ID, "Сообщение Боба")
if first.SenderID != alice.ID || second.SenderID != bob.ID {
t.Fatalf("sender must come from X-User-Id: %+v %+v", first, second)
}
@@ -337,48 +402,48 @@ func TestMessagesEndToEnd(t *testing.T) {
t.Fatalf("message = %+v", first)
}
page1 := ts.history(bob.ID, room.ID, "?limit=1")
page1 := ts.history(bob.token, room.ID, "?limit=1")
if len(page1.Items) != 1 || page1.NextCursor == nil || page1.Items[0] != first {
t.Fatalf("page1 = %+v", page1)
}
page2 := ts.history(alice.ID, room.ID, cursorQuery(1, page1.NextCursor))
page2 := ts.history(alice.token, room.ID, cursorQuery(1, page1.NextCursor))
if len(page2.Items) != 1 || page2.NextCursor != nil || page2.Items[0] != second {
t.Fatalf("page2 = %+v", page2)
}
post := func(actor string, body any) response { return ts.do(http.MethodPost, path, actor, body, nil) }
ts.expect(post(alice.ID, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, map[string]string{"text": "x", "sender_id": bob.ID}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.ID, `{"text":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(eve.ID, map[string]string{"text": "чужое"}), http.StatusNotFound, "not_found")
ts.expect(post(eve.ID, map[string]string{"text": ""}), http.StatusNotFound, "not_found")
ts.expect(post(alice.token, map[string]string{"text": ""}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": " "}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": strings.Repeat("я", 4001)}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, map[string]string{"text": "x", "sender_id": bob.ID}), http.StatusBadRequest, "invalid_request")
ts.expect(post(alice.token, `{"text":`), http.StatusBadRequest, "invalid_request")
ts.expect(post(eve.token, map[string]string{"text": "чужое"}), http.StatusNotFound, "not_found")
ts.expect(post(eve.token, map[string]string{"text": ""}), http.StatusNotFound, "not_found")
ts.expect(post("", map[string]string{"text": "x"}), http.StatusUnauthorized, "unauthorized")
ts.expect(post(alice.ID, map[string]string{"text": strings.Repeat("я", 4000)}), http.StatusCreated, "")
ts.expect(post(alice.token, map[string]string{"text": strings.Repeat("я", 4000)}), http.StatusCreated, "")
get := func(actor, query string) response { return ts.do(http.MethodGet, path+query, actor, nil, nil) }
ts.expect(get(eve.ID, ""), http.StatusNotFound, "not_found")
ts.expect(get(alice.ID, "?limit=0"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.ID, "?limit=101"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.ID, "?cursor=garbage"), http.StatusBadRequest, "invalid_request")
ts.expect(get(eve.token, ""), http.StatusNotFound, "not_found")
ts.expect(get(alice.token, "?limit=0"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.token, "?limit=101"), http.StatusBadRequest, "invalid_request")
ts.expect(get(alice.token, "?cursor=garbage"), http.StatusBadRequest, "invalid_request")
other := ts.chat(alice.ID, "другой", alice.ID)
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+other.ID+"/messages"+cursorQuery(50, page1.NextCursor), alice.ID, nil, nil), http.StatusBadRequest, "invalid_request")
other := ts.chat(alice.token, "другой", alice.ID)
ts.expect(ts.do(http.MethodGet, "/api/v1/chats/"+other.ID+"/messages"+cursorQuery(50, page1.NextCursor), alice.token, nil, nil), http.StatusBadRequest, "invalid_request")
}
func TestMessageHistoryWalkAcrossPages(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
room := ts.chat(alice.ID, "t", alice.ID)
room := ts.chat(alice.token, "t", alice.ID)
var expected []string
for i := 0; i < 23; i++ {
expected = append(expected, ts.message(alice.ID, room.ID, fmt.Sprintf("m%d", i)).ID)
expected = append(expected, ts.message(alice.token, room.ID, fmt.Sprintf("m%d", i)).ID)
}
var walked []string
var cursor *string
for {
page := ts.history(alice.ID, room.ID, cursorQuery(5, cursor))
page := ts.history(alice.token, room.ID, cursorQuery(5, cursor))
for _, m := range page.Items {
walked = append(walked, m.ID)
}
@@ -395,28 +460,29 @@ func TestMessageHistoryWalkAcrossPages(t *testing.T) {
func TestConcurrentSendsProduceExactlyUniqueMessages(t *testing.T) {
ts := newTester(t)
const clients, perClient = 10, 10
clientsList := make([]account, 0, clients)
members := make([]string, 0, clients)
for i := 0; i < clients; i++ {
members = append(members, ts.user(fmt.Sprintf("client_%d", i), "C").ID)
c := ts.user(fmt.Sprintf("client_%d", i), "C")
clientsList = append(clientsList, c)
members = append(members, c.ID)
}
room := ts.chat(members[0], "нагрузка", members...)
room := ts.chat(clientsList[0].token, "нагрузка", members...)
var wg sync.WaitGroup
for n, actor := range members {
wg.Add(1)
go func(n int, actor string) {
defer wg.Done()
for n, c := range clientsList {
wg.Go(func() {
for i := 0; i < perClient; i++ {
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", actor, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, nil)
res := ts.do(http.MethodPost, "/api/v1/chats/"+room.ID+"/messages", c.token, map[string]string{"text": fmt.Sprintf("c%d-m%d", n, i)}, nil)
if res.status != http.StatusCreated {
t.Errorf("client %d: status %d body %s", n, res.status, res.raw)
}
}
}(n, actor)
})
}
wg.Wait()
page := ts.history(members[0], room.ID, "?limit=100")
page := ts.history(clientsList[0].token, room.ID, "?limit=100")
if len(page.Items) != clients*perClient || page.NextCursor != nil {
t.Fatalf("got %d messages, next=%v; want %d and null", len(page.Items), page.NextCursor, clients*perClient)
}
+160
View File
@@ -0,0 +1,160 @@
package app_test
import (
"encoding/base64"
"encoding/json"
"net/http"
"strings"
"testing"
"time"
"messenger/internal/user"
)
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
func TestLoginReturnsBearerSession(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "Алиса")
before := time.Now()
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic("alice", testPassword))
ts.expect(res, http.StatusCreated, "")
s := decode[sessionBody](t, res)
if s.TokenType != "Bearer" || len(s.Token) != 43 || s.Token == alice.token {
t.Fatalf("session = %+v; want a fresh 43-character Bearer token", s)
}
if s.User != alice.Response {
t.Fatalf("user = %+v, want %+v", s.User, alice.Response)
}
expires, err := time.Parse(time.RFC3339, s.ExpiresAt)
if err != nil || !strings.HasSuffix(s.ExpiresAt, "Z") {
t.Fatalf("expires_at = %q: %v", s.ExpiresAt, err)
}
if ttl := expires.Sub(before); ttl < 59*time.Minute || ttl > 61*time.Minute {
t.Fatalf("expires_at is %v after login, want the 1h TTL", ttl)
}
if strings.Contains(string(res.raw), "password") || strings.Contains(string(res.raw), "argon2") {
t.Fatalf("session response leaks password data: %s", res.raw)
}
}
func TestLoginFailuresAreUniformBasicChallenges(t *testing.T) {
ts := newTester(t)
ts.user("alice", "Алиса")
encoded := func(s string) string { return base64.StdEncoding.EncodeToString([]byte(s)) }
cases := map[string]map[string]string{
"wrong password": basic("alice", testPassword+"!"),
"unknown user": basic("mallory", testPassword),
"no header": nil,
"bearer scheme": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"not base64": {"Authorization": "Basic !!!"},
"no colon": {"Authorization": "Basic " + encoded("alice")},
}
messages := map[string]string{}
for name, headers := range cases {
res := ts.do(http.MethodPost, "/api/v1/auth/sessions", "", nil, headers)
ts.expect(res, http.StatusUnauthorized, "unauthorized")
if res.challenge != basicChallenge {
t.Errorf("%s: WWW-Authenticate = %q, want %q", name, res.challenge, basicChallenge)
}
var eb errorBody
_ = json.Unmarshal(res.raw, &eb)
messages[name] = eb.Error.Message
}
if messages["wrong password"] != messages["unknown user"] {
t.Fatalf("wrong password and unknown user must look the same: %q vs %q", messages["wrong password"], messages["unknown user"])
}
}
// The password is UTF-8 and may contain colons; only the first colon of the
// Basic credentials separates the username (contracts/README.md).
func TestLoginAcceptsColonAndUnicodePasswords(t *testing.T) {
ts := newTester(t)
const password = "пароль:с:двоеточием 👋"
body := map[string]string{"username": "alice", "display_name": "Алиса", "password": password}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, nil), http.StatusCreated, "")
s := ts.login("alice", password)
if s.User.Username != "alice" {
t.Fatalf("logged in as %+v", s.User)
}
}
func TestProtectedRoutesAcceptOnlyBearer(t *testing.T) {
ts := newTester(t)
alice, eve := ts.user("alice", "A"), ts.user("eve", "E")
me := func(headers map[string]string) response {
return ts.do(http.MethodGet, "/api/v1/users/me", "", nil, headers)
}
rejected := map[string]map[string]string{
"no header": nil,
"basic with valid credentials": basic("alice", testPassword),
"x-user-id alone": {"X-User-Id": alice.ID},
"unknown token": {"Authorization": "Bearer " + strings.Repeat("A", 43)},
"empty token": {"Authorization": "Bearer "},
"scheme only": {"Authorization": "Bearer"},
"other scheme": {"Authorization": "Token " + alice.token},
"two tokens": {"Authorization": "Bearer " + alice.token + " " + eve.token},
}
for name, headers := range rejected {
res := me(headers)
ts.expect(res, http.StatusUnauthorized, "unauthorized")
if res.challenge != bearerChallenge {
t.Errorf("%s: WWW-Authenticate = %q, want %q", name, res.challenge, bearerChallenge)
}
}
accepted := map[string]map[string]string{
"lowercase scheme": {"Authorization": "bearer " + alice.token},
"several spaces": {"Authorization": "Bearer " + alice.token},
"x-user-id is ignored": {"Authorization": "Bearer " + alice.token, "X-User-Id": eve.ID},
}
for name, headers := range accepted {
res := me(headers)
ts.expect(res, http.StatusOK, "")
if got := decode[user.Response](t, res); got.ID != alice.ID {
t.Errorf("%s: caller = %s, want alice", name, got.ID)
}
}
}
func TestLogoutRevokesOnlyTheCurrentToken(t *testing.T) {
ts := newTester(t)
alice := ts.user("alice", "A")
other := ts.login("alice", testPassword)
res := ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil)
ts.expect(res, http.StatusNoContent, "")
if len(res.raw) != 0 {
t.Fatalf("204 must have no body, got %q", res.raw)
}
for _, again := range []response{
ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil),
ts.do(http.MethodDelete, "/api/v1/auth/sessions/current", alice.token, nil, nil),
} {
ts.expect(again, http.StatusUnauthorized, "unauthorized")
if again.challenge != bearerChallenge {
t.Fatalf("revoked token: WWW-Authenticate = %q, want %q", again.challenge, bearerChallenge)
}
}
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", other.Token, nil, nil), http.StatusOK, "")
}
func TestSessionExpiresAfterTTL(t *testing.T) {
ts := newTesterWithTTL(t, time.Second)
alice := ts.user("alice", "A")
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusOK, "")
time.Sleep(1200 * time.Millisecond)
ts.expect(ts.do(http.MethodGet, "/api/v1/users/me", alice.token, nil, nil), http.StatusUnauthorized, "unauthorized")
}
func TestRegistrationIsPublicAndIgnoresAuthorization(t *testing.T) {
ts := newTester(t)
body := map[string]string{"username": "alice", "display_name": "A", "password": testPassword}
headers := map[string]string{"Authorization": "Bearer garbage"}
ts.expect(ts.do(http.MethodPost, "/api/v1/users", "", body, headers), http.StatusCreated, "")
}
-47
View File
@@ -1,47 +0,0 @@
// Package auth identifies the caller. In this lab the identity is the
// X-User-Id header naming a registered user: identification, not
// authentication, by design of the assignment.
package auth
import (
"context"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
)
type UserLookup interface {
Exists(ctx context.Context, id uuid.UUID) (bool, error)
}
// RequireUser answers 401 unless X-User-Id names a registered user, and
// records that user for the handlers behind it.
func RequireUser(users UserLookup) gin.HandlerFunc {
return func(c *gin.Context) {
raw := c.GetHeader("X-User-Id")
if raw == "" {
httpx.Error(c, apperr.Unauthorized("X-User-Id header is required"))
return
}
id, err := ident.Parse(raw)
if err != nil {
httpx.Error(c, apperr.Unauthorized("X-User-Id must be the UUID of a registered user"))
return
}
ok, err := users.Exists(c.Request.Context(), id)
if err != nil {
httpx.Error(c, err)
return
}
if !ok {
httpx.Error(c, apperr.Unauthorized("X-User-Id must be the UUID of a registered user"))
return
}
httpx.SetUserID(c, id)
c.Next()
}
}
-79
View File
@@ -1,79 +0,0 @@
package auth_test
import (
"context"
"encoding/json"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"testing"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/auth"
"messenger/internal/platform/httpx"
"messenger/internal/platform/ident"
)
type lookup map[uuid.UUID]struct{}
func (l lookup) Exists(_ context.Context, id uuid.UUID) (bool, error) {
_, ok := l[id]
return ok, nil
}
func echoActor(c *gin.Context, actor uuid.UUID) {
httpx.JSON(c, http.StatusOK, map[string]string{"id": actor.String()})
}
func newEngine(users lookup) *gin.Engine {
e := httpx.NewEngine(slog.New(slog.NewTextHandler(io.Discard, nil)), 1024)
e.GET("/me", auth.RequireUser(users), httpx.WithUser(echoActor))
return e
}
func call(e *gin.Engine, header string) (*httptest.ResponseRecorder, string) {
req := httptest.NewRequest(http.MethodGet, "/me", nil)
if header != "" {
req.Header.Set("X-User-Id", header)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
var body struct {
ID string `json:"id"`
Error struct {
Code string `json:"code"`
} `json:"error"`
}
_ = json.Unmarshal(rec.Body.Bytes(), &body)
if body.ID != "" {
return rec, body.ID
}
return rec, body.Error.Code
}
func TestKnownUserReachesHandlerWithItsID(t *testing.T) {
alice := ident.New()
rec, got := call(newEngine(lookup{alice: {}}), alice.String())
if rec.Code != http.StatusOK || got != alice.String() {
t.Fatalf("status %d, handler saw %q, want %s", rec.Code, got, alice)
}
}
func TestMiddlewareRejectsMissingMalformedAndUnknownWith401(t *testing.T) {
alice := ident.New()
e := newEngine(lookup{alice: {}})
for name, header := range map[string]string{
"missing": "",
"malformed": "not-a-uuid",
"braces": "{" + alice.String() + "}",
"unknown": ident.New().String(),
} {
rec, code := call(e, header)
if rec.Code != http.StatusUnauthorized || code != "unauthorized" {
t.Errorf("%s: status = %d code = %q, want 401 unauthorized", name, rec.Code, code)
}
}
}
+89
View File
@@ -0,0 +1,89 @@
package auth
import (
"errors"
"net/http"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
"messenger/internal/user"
)
// Challenges sent with every 401: Basic on the login endpoint, Bearer on
// every protected one.
const (
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
bearerChallenge = `Bearer realm="messenger"`
)
var errCredentialsRequired = apperr.Unauthorized("basic credentials are required")
type Handler struct {
sessions *Service
}
func NewHandler(sessions *Service) *Handler {
return &Handler{sessions: sessions}
}
// Register mounts login on the public router and logout on the router
// guarded by RequireSession.
func (h *Handler) Register(public, protected gin.IRouter) {
public.POST("/auth/sessions", h.login)
protected.DELETE("/auth/sessions/current", h.logout)
}
type sessionResponse struct {
Token string `json:"token"`
TokenType string `json:"token_type"`
ExpiresAt string `json:"expires_at"`
User user.Response `json:"user"`
}
// login accepts only the Authorization header; the body is not read.
// BasicAuth splits at the first colon, so a password may contain colons.
func (h *Handler) login(c *gin.Context) {
username, password, ok := c.Request.BasicAuth()
if !ok {
unauthorized(c, basicChallenge, errCredentialsRequired)
return
}
issued, err := h.sessions.Login(c.Request.Context(), username, password)
if err != nil {
unauthorized(c, basicChallenge, err)
return
}
httpx.JSON(c, http.StatusCreated, sessionResponse{
Token: issued.Token,
TokenType: "Bearer",
ExpiresAt: httpx.Timestamp(issued.ExpiresAt),
User: user.ToResponse(issued.User),
})
}
func (h *Handler) logout(c *gin.Context) {
token, ok := c.Get(keyToken)
if !ok {
httpx.Error(c, errors.New("logout route is missing the RequireSession middleware"))
return
}
if err := h.sessions.Logout(c.Request.Context(), token.(string)); err != nil {
httpx.Error(c, err)
return
}
// Status alone is buffered by gin; writing the header now sends the 204
// with an empty body.
c.Status(http.StatusNoContent)
c.Writer.WriteHeaderNow()
}
// unauthorized adds the challenge only to a 401: an unavailable store is a
// 503 and must not invite the client to retry its credentials.
func unauthorized(c *gin.Context, challenge string, err error) {
if apperr.KindOf(err) == apperr.KindUnauthorized {
c.Header("WWW-Authenticate", challenge)
}
httpx.Error(c, err)
}
+33
View File
@@ -0,0 +1,33 @@
package auth_test
import (
"context"
"fmt"
"os"
"testing"
"messenger/internal/testenv"
)
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
db.Close()
os.Exit(code)
}
+48
View File
@@ -0,0 +1,48 @@
package auth
import (
"strings"
"github.com/gin-gonic/gin"
"messenger/internal/platform/httpx"
)
const keyToken = "messenger.session_token"
// RequireSession admits a request only with Authorization: Bearer <token> of
// a live session and records its owner for the handlers behind it. Any other
// identification, including Basic credentials and X-User-Id, is ignored, so
// it can neither grant access nor change the caller.
func RequireSession(sessions *Service) gin.HandlerFunc {
return func(c *gin.Context) {
token, ok := bearerToken(c.GetHeader("Authorization"))
if !ok {
unauthorized(c, bearerChallenge, ErrUnauthenticated)
return
}
userID, err := sessions.Authenticate(c.Request.Context(), token)
if err != nil {
unauthorized(c, bearerChallenge, err)
return
}
httpx.SetUserID(c, userID)
c.Set(keyToken, token)
c.Next()
}
}
// bearerToken parses "Bearer <token>": the scheme is case-insensitive and
// may be followed by several spaces (RFC 7235); the token itself never
// contains whitespace.
func bearerToken(header string) (string, bool) {
scheme, rest, found := strings.Cut(header, " ")
if !found || !strings.EqualFold(scheme, "Bearer") {
return "", false
}
token := strings.TrimLeft(rest, " ")
if token == "" || strings.ContainsAny(token, " \t") {
return "", false
}
return token, true
}
+21
View File
@@ -0,0 +1,21 @@
package auth
import (
"context"
"errors"
"github.com/google/uuid"
)
// ErrSessionNotFound means the token is unknown, expired or revoked; the
// store cannot tell these apart, and the client must not either.
var ErrSessionNotFound = errors.New("session not found")
type Repository interface {
// Create stores the session until its absolute ExpiresAt.
Create(ctx context.Context, s Session) error
// UserID returns the owner of a live session or ErrSessionNotFound.
UserID(ctx context.Context, tokenHash string) (uuid.UUID, error)
// Delete revokes the session; deleting a missing one is not an error.
Delete(ctx context.Context, tokenHash string) error
}
+69
View File
@@ -0,0 +1,69 @@
package auth
import (
"context"
"errors"
"time"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/user"
)
var ErrUnauthenticated = apperr.Unauthorized("a valid bearer token is required")
// Credentials is what this module needs from the users module: the user
// whose password matches, or user.ErrInvalidCredentials.
type Credentials interface {
Authenticate(ctx context.Context, username, password string) (user.User, error)
}
// Issued is a new session as the client sees it; Token is shown only here.
type Issued struct {
Token string
ExpiresAt time.Time
User user.User
}
type Service struct {
users Credentials
sessions Repository
ttl time.Duration
}
func NewService(users Credentials, sessions Repository, ttl time.Duration) *Service {
return &Service{users: users, sessions: sessions, ttl: ttl}
}
// Login checks the credentials first, so a store outage never hands out a
// token without a stored session. The expiry is fixed here and never
// extended; it is truncated to milliseconds, the precision of both the API
// timestamps and the store.
func (s *Service) Login(ctx context.Context, username, password string) (Issued, error) {
u, err := s.users.Authenticate(ctx, username, password)
if err != nil {
return Issued{}, err
}
token := newToken()
expiresAt := time.Now().Add(s.ttl).Truncate(time.Millisecond).UTC()
if err := s.sessions.Create(ctx, Session{TokenHash: HashToken(token), UserID: u.ID, ExpiresAt: expiresAt}); err != nil {
return Issued{}, err
}
return Issued{Token: token, ExpiresAt: expiresAt, User: u}, nil
}
// Authenticate returns the owner of the token's live session. A store
// failure is returned as is, never as ErrUnauthenticated: an outage must not
// look like a bad token to the client.
func (s *Service) Authenticate(ctx context.Context, token string) (uuid.UUID, error) {
id, err := s.sessions.UserID(ctx, HashToken(token))
if errors.Is(err, ErrSessionNotFound) {
return uuid.Nil, ErrUnauthenticated
}
return id, err
}
func (s *Service) Logout(ctx context.Context, token string) error {
return s.sessions.Delete(ctx, HashToken(token))
}
+145
View File
@@ -0,0 +1,145 @@
package auth_test
import (
"context"
"encoding/base64"
"errors"
"strings"
"testing"
"time"
"messenger/internal/auth"
authstore "messenger/internal/auth/store"
"messenger/internal/platform/apperr"
"messenger/internal/user"
userstore "messenger/internal/user/store"
)
const pw = "correct-horse-battery"
type fixture struct {
ctx context.Context
svc *auth.Service
alice user.User
}
// newFixture wires the real users service and session store over empty
// databases and registers alice.
func newFixture(t *testing.T, ttl time.Duration) fixture {
t.Helper()
db.Reset(t)
kv.Reset(t)
ctx := context.Background()
users := user.NewService(userstore.NewUsers(db.Pool))
alice, err := users.Register(ctx, "alice", "Алиса", pw)
if err != nil {
t.Fatal(err)
}
return fixture{ctx: ctx, svc: auth.NewService(users, authstore.NewSessions(kv.Client), ttl), alice: alice}
}
func TestLoginIssuesOpaqueTokenBackedByStoredSession(t *testing.T) {
f := newFixture(t, time.Hour)
before := time.Now()
issued, err := f.svc.Login(f.ctx, "alice", pw)
after := time.Now()
if err != nil {
t.Fatalf("Login: %v", err)
}
raw, err := base64.RawURLEncoding.DecodeString(issued.Token)
if err != nil || len(raw) != 32 {
t.Fatalf("token %q must be 32 random bytes in base64url, got %d bytes, %v", issued.Token, len(raw), err)
}
if strings.Contains(issued.Token, f.alice.ID.String()) || strings.Contains(issued.Token, "alice") {
t.Fatal("token must not carry the identity")
}
if issued.User != f.alice {
t.Fatalf("User = %+v, want alice", issued.User)
}
if issued.ExpiresAt.Before(before.Add(time.Hour).Add(-time.Millisecond)) || issued.ExpiresAt.After(after.Add(time.Hour)) {
t.Fatalf("ExpiresAt = %v, want login time + 1h", issued.ExpiresAt)
}
key := "session:" + auth.HashToken(issued.Token)
owner, err := kv.Client.Get(f.ctx, key).Result()
if err != nil || owner != f.alice.ID.String() {
t.Fatalf("stored owner = %q, %v; want alice", owner, err)
}
expireAt, err := kv.Client.PExpireTime(f.ctx, key).Result()
if err != nil || expireAt != time.Duration(issued.ExpiresAt.UnixMilli())*time.Millisecond {
t.Fatalf("store expiry = %v, %v; want the absolute ExpiresAt %d ms", expireAt, err, issued.ExpiresAt.UnixMilli())
}
keys, err := kv.Client.Keys(f.ctx, "*").Result()
if err != nil {
t.Fatal(err)
}
for _, k := range keys {
if strings.Contains(k, issued.Token) {
t.Fatal("the raw token must never be stored")
}
}
}
func TestLoginWithBadCredentialsCreatesNoSession(t *testing.T) {
f := newFixture(t, time.Hour)
for name, in := range map[string][2]string{
"wrong password": {"alice", pw + "!"},
"unknown user": {"mallory", pw},
} {
if _, err := f.svc.Login(f.ctx, in[0], in[1]); !errors.Is(err, user.ErrInvalidCredentials) {
t.Errorf("%s: err = %v, want ErrInvalidCredentials", name, err)
}
}
if n, err := kv.Client.DBSize(f.ctx).Result(); err != nil || n != 0 {
t.Fatalf("sessions = %d, %v; want none", n, err)
}
}
func TestAuthenticateResolvesTheOwner(t *testing.T) {
f := newFixture(t, time.Hour)
first, _ := f.svc.Login(f.ctx, "alice", pw)
second, _ := f.svc.Login(f.ctx, "alice", pw)
if first.Token == second.Token {
t.Fatal("every login must get its own token")
}
for _, token := range []string{first.Token, second.Token} {
id, err := f.svc.Authenticate(f.ctx, token)
if err != nil || id != f.alice.ID {
t.Fatalf("Authenticate = %v, %v; want alice", id, err)
}
}
_, err := f.svc.Authenticate(f.ctx, "unknown-token")
if !errors.Is(err, auth.ErrUnauthenticated) || apperr.KindOf(err) != apperr.KindUnauthorized {
t.Fatalf("unknown token: err = %v, want ErrUnauthenticated", err)
}
}
func TestLogoutRevokesOnlyThatSession(t *testing.T) {
f := newFixture(t, time.Hour)
first, _ := f.svc.Login(f.ctx, "alice", pw)
second, _ := f.svc.Login(f.ctx, "alice", pw)
if err := f.svc.Logout(f.ctx, first.Token); err != nil {
t.Fatalf("Logout: %v", err)
}
if _, err := f.svc.Authenticate(f.ctx, first.Token); !errors.Is(err, auth.ErrUnauthenticated) {
t.Fatalf("revoked token: err = %v, want ErrUnauthenticated", err)
}
if id, err := f.svc.Authenticate(f.ctx, second.Token); err != nil || id != f.alice.ID {
t.Fatalf("other session: %v, %v; want still valid", id, err)
}
}
func TestSessionExpiresAfterTTL(t *testing.T) {
f := newFixture(t, time.Second)
issued, err := f.svc.Login(f.ctx, "alice", pw)
if err != nil {
t.Fatal(err)
}
if _, err := f.svc.Authenticate(f.ctx, issued.Token); err != nil {
t.Fatalf("fresh session: %v", err)
}
time.Sleep(time.Until(issued.ExpiresAt) + 100*time.Millisecond)
if _, err := f.svc.Authenticate(f.ctx, issued.Token); !errors.Is(err, auth.ErrUnauthenticated) {
t.Fatalf("expired session: err = %v, want ErrUnauthenticated", err)
}
}
+39
View File
@@ -0,0 +1,39 @@
// Package auth authenticates callers.
//
// A login with Basic credentials creates a server-side session and returns an
// opaque bearer token; every protected request presents the token, and logout
// deletes the session, which revokes the token at once. The store keeps only
// the SHA-256 of a token: a token is a random 256-bit value, so a fast digest
// cannot be reversed by guessing, and a leaked store yields no usable tokens.
// Passwords need the opposite treatment (a slow KDF), see platform/password.
package auth
import (
"crypto/rand"
"crypto/sha256"
"encoding/base64"
"encoding/hex"
"time"
"github.com/google/uuid"
)
type Session struct {
TokenHash string
UserID uuid.UUID
ExpiresAt time.Time
}
// newToken returns 32 random bytes in base64url: 43 characters, 256 bits.
func newToken() string {
raw := make([]byte, 32)
// Since Go 1.24 crypto/rand.Read never returns an error.
_, _ = rand.Read(raw)
return base64.RawURLEncoding.EncodeToString(raw)
}
// HashToken is the key under which a token's session is stored.
func HashToken(token string) string {
sum := sha256.Sum256([]byte(token))
return hex.EncodeToString(sum[:])
}
+64
View File
@@ -0,0 +1,64 @@
// Package store holds the session store implementations.
package store
import (
"context"
"errors"
"fmt"
"github.com/google/uuid"
"github.com/redis/go-redis/v9"
"messenger/internal/auth"
"messenger/internal/platform/apperr"
)
const keyPrefix = "session:"
// Sessions keeps one key per session, session:<sha256 of token>, holding the
// owner's id. Valkey expires the key itself, so no cleanup job is needed.
type Sessions struct {
client *redis.Client
}
var _ auth.Repository = (*Sessions)(nil)
func NewSessions(client *redis.Client) *Sessions {
return &Sessions{client: client}
}
// Create sets an absolute expiry (PXAT): a restart of the store replays it
// from the append-only file and does not extend the session.
func (r *Sessions) Create(ctx context.Context, s auth.Session) error {
err := r.client.Do(ctx, "SET", keyPrefix+s.TokenHash, s.UserID.String(), "PXAT", s.ExpiresAt.UnixMilli()).Err()
if err != nil {
return unavailable(err)
}
return nil
}
func (r *Sessions) UserID(ctx context.Context, tokenHash string) (uuid.UUID, error) {
raw, err := r.client.Get(ctx, keyPrefix+tokenHash).Result()
if errors.Is(err, redis.Nil) {
return uuid.Nil, auth.ErrSessionNotFound
}
if err != nil {
return uuid.Nil, unavailable(err)
}
id, err := uuid.Parse(raw)
if err != nil {
return uuid.Nil, fmt.Errorf("session holds a malformed user id: %w", err)
}
return id, nil
}
func (r *Sessions) Delete(ctx context.Context, tokenHash string) error {
if err := r.client.Del(ctx, keyPrefix+tokenHash).Err(); err != nil {
return unavailable(err)
}
return nil
}
func unavailable(err error) error {
return apperr.Wrap(apperr.KindUnavailable, "session store unavailable", err)
}
+13
View File
@@ -23,6 +23,8 @@ type Config struct {
ShutdownTimeout time.Duration
MaxBodyBytes int64
DatabaseURL string
SessionStoreURL string
SessionTTL time.Duration
}
// Lookup reads one variable, reporting whether it was set; os.LookupEnv
@@ -37,6 +39,7 @@ func Load(lookup Lookup) (Config, error) {
LogLevel: slog.LevelInfo,
ShutdownTimeout: 8 * time.Second,
MaxBodyBytes: 64 * 1024,
SessionTTL: time.Hour,
}
if v, ok := lookup("APP_HOST"); ok {
if strings.TrimSpace(v) == "" {
@@ -75,10 +78,20 @@ func Load(lookup Lookup) (Config, error) {
}
cfg.MaxBodyBytes = n
}
if v, ok := lookup("SESSION_TTL_SECONDS"); ok {
n, err := strconv.ParseUint(v, 10, 32)
if err != nil || n == 0 {
return Config{}, fmt.Errorf("SESSION_TTL_SECONDS must be a positive whole number of seconds, got %q", v)
}
cfg.SessionTTL = time.Duration(n) * time.Second
}
var err error
if cfg.DatabaseURL, err = secret(lookup, "DATABASE_URL_FILE"); err != nil {
return Config{}, err
}
if cfg.SessionStoreURL, err = secret(lookup, "SESSION_STORE_URL_FILE"); err != nil {
return Config{}, err
}
return cfg, nil
}
+36 -18
View File
@@ -27,12 +27,18 @@ func secretFile(t *testing.T, content string) string {
return path
}
const databaseURL = "postgres://app:s3cret@db:5432/messenger"
const (
databaseURL = "postgres://app:s3cret@db:5432/messenger"
sessionStoreURL = "redis://:s3cret@valkey:6379/0"
)
// 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")}
values := map[string]string{
"DATABASE_URL_FILE": secretFile(t, databaseURL+"\n"),
"SESSION_STORE_URL_FILE": secretFile(t, sessionStoreURL+"\r\n"),
}
for k, v := range extra {
values[k] = v
}
@@ -53,26 +59,33 @@ 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)
if cfg.DatabaseURL != databaseURL || cfg.SessionStoreURL != sessionStoreURL {
t.Fatalf("urls = %q, %q; want the file contents without line endings", cfg.DatabaseURL, cfg.SessionStoreURL)
}
if cfg.SessionTTL != time.Hour {
t.Fatalf("SessionTTL = %v, want 1h", cfg.SessionTTL)
}
}
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
for _, key := range []string{"DATABASE_URL_FILE", "SESSION_STORE_URL_FILE"} {
cases := map[string]func(map[string]string){
"unset": func(v map[string]string) { delete(v, key) },
"empty path": func(v map[string]string) { v[key] = "" },
"no file": func(v map[string]string) { v[key] = filepath.Join(t.TempDir(), "missing") },
"blank file": func(v map[string]string) { v[key] = secretFile(t, " \r\n") },
}
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)
for name, breakIt := range cases {
values := required(t, nil)
breakIt(values)
_, err := config.Load(env(values))
if err == nil {
t.Errorf("%s %s: want error", key, name)
continue
}
if !strings.Contains(err.Error(), key) || strings.Contains(err.Error(), "s3cret") {
t.Errorf("%s %s: error must name the variable and hide the secret: %v", key, name, err)
}
}
}
}
@@ -85,6 +98,7 @@ func TestOverrides(t *testing.T) {
"APP_LOG_LEVEL": "debug",
"APP_SHUTDOWN_TIMEOUT": "3s",
"APP_MAX_BODY_BYTES": "1024",
"SESSION_TTL_SECONDS": "300",
})))
if err != nil {
t.Fatalf("Load error: %v", err)
@@ -92,7 +106,7 @@ func TestOverrides(t *testing.T) {
if cfg.Addr() != "127.0.0.1:9090" || cfg.Env != "dev" || cfg.LogLevel != slog.LevelDebug {
t.Fatalf("cfg = %+v", cfg)
}
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 {
if cfg.ShutdownTimeout != 3*time.Second || cfg.MaxBodyBytes != 1024 || cfg.SessionTTL != 5*time.Minute {
t.Fatalf("cfg = %+v", cfg)
}
}
@@ -108,6 +122,10 @@ func TestInvalidValuesAreReported(t *testing.T) {
"body zero": {"APP_MAX_BODY_BYTES": "0"},
"body text": {"APP_MAX_BODY_BYTES": "big"},
"empty host": {"APP_HOST": ""},
"ttl zero": {"SESSION_TTL_SECONDS": "0"},
"ttl negative": {"SESSION_TTL_SECONDS": "-5"},
"ttl text": {"SESSION_TTL_SECONDS": "hour"},
"ttl fraction": {"SESSION_TTL_SECONDS": "1.5"},
}
for name, values := range cases {
if _, err := config.Load(env(required(t, values))); err == nil {
+44
View File
@@ -0,0 +1,44 @@
// Package valkey connects to the Valkey session store.
//
// Timeouts are constants: every authenticated request reads a session, so
// they bound how long a request can wait when the store is slow. Retries are
// disabled for the same reason: a request that cannot reach the store fails
// fast with 503 instead of waiting through a backoff.
package valkey
import (
"context"
"errors"
"fmt"
"time"
"github.com/redis/go-redis/v9"
)
const (
dialTimeout = 2 * time.Second
ioTimeout = time.Second
poolSize = 10
noRetries = -1
)
// NewClient connects to url (redis:// scheme) and pings the server. Errors
// never include the URL, which carries the password.
func NewClient(ctx context.Context, url string) (*redis.Client, error) {
opts, err := redis.ParseURL(url)
if err != nil {
return nil, errors.New("session store url is invalid")
}
opts.DialTimeout = dialTimeout
opts.ReadTimeout = ioTimeout
opts.WriteTimeout = ioTimeout
opts.PoolSize = poolSize
opts.MaxRetries = noRetries
client := redis.NewClient(opts)
if err := client.Ping(ctx).Err(); err != nil {
_ = client.Close()
return nil, fmt.Errorf("ping session store at %s: %w", opts.Addr, err)
}
return client, nil
}
+51
View File
@@ -0,0 +1,51 @@
package valkey_test
import (
"context"
"strings"
"testing"
"time"
"messenger/internal/platform/valkey"
"messenger/internal/testenv"
)
func TestNewClientPingsAndBoundsWaiting(t *testing.T) {
ctx := context.Background()
kv, err := testenv.StartValkey(ctx)
if err != nil {
t.Fatal(err)
}
defer kv.Close()
client, err := valkey.NewClient(ctx, kv.URL)
if err != nil {
t.Fatalf("NewClient: %v", err)
}
defer client.Close()
opts := client.Options()
if opts.DialTimeout != 2*time.Second || opts.ReadTimeout != time.Second || opts.WriteTimeout != time.Second {
t.Fatalf("timeouts = %v/%v/%v, want 2s/1s/1s", opts.DialTimeout, opts.ReadTimeout, opts.WriteTimeout)
}
// go-redis stores the requested -1 ("no retries") as 0 after init; its
// default would be 3.
if opts.PoolSize != 10 || opts.MaxRetries != 0 {
t.Fatalf("PoolSize = %d, MaxRetries = %d; want 10 and 0 (fail fast)", opts.PoolSize, opts.MaxRetries)
}
}
func TestNewClientErrorsNeverEchoTheURL(t *testing.T) {
ctx := context.Background()
for name, url := range map[string]string{
"malformed": "redis://:s3cret@host:port/x",
"unreachable": "redis://:s3cret@127.0.0.1:1/0",
} {
_, err := valkey.NewClient(ctx, url)
if err == nil {
t.Fatalf("%s: want error", name)
}
if strings.Contains(err.Error(), "s3cret") {
t.Fatalf("%s: error leaks the password: %v", name, err)
}
}
}
-10
View File
@@ -68,16 +68,6 @@ func (s *Service) GetByID(ctx context.Context, id uuid.UUID) (User, error) {
return s.repo.GetByID(ctx, id)
}
// Exists serves the identification middleware; it is the single-id form of
// ExistingIDs so existence is answered by one code path.
func (s *Service) Exists(ctx context.Context, id uuid.UUID) (bool, error) {
found, err := s.ExistingIDs(ctx, []uuid.UUID{id})
if err != nil {
return false, err
}
return len(found) == 1, nil
}
// 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 {
-6
View File
@@ -44,9 +44,6 @@ func TestRegisterStoresUserWithPasswordHash(t *testing.T) {
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 TestRegisterRejectsInvalidInputAndStoresNothing(t *testing.T) {
@@ -129,9 +126,6 @@ func TestGetByIDUnknownIsNotFound(t *testing.T) {
if !errors.Is(err, user.ErrNotFound) || apperr.KindOf(err) != apperr.KindNotFound {
t.Fatalf("err = %v, want ErrNotFound with KindNotFound", err)
}
if ok, err := svc.Exists(context.Background(), ident.New()); err != nil || ok {
t.Fatalf("Exists = %v, %v; want false, nil", ok, err)
}
}
func TestExistingIDsReturnsOnlyRegistered(t *testing.T) {
+23 -7
View File
@@ -20,7 +20,7 @@ func newClient(baseURL string) *client {
return &client{base: baseURL, http: &http.Client{Timeout: 10 * time.Second}}
}
func (c *client) post(path, actor string, body, out any) error {
func (c *client) post(path, token string, body, out any) error {
raw, err := json.Marshal(body)
if err != nil {
return err
@@ -30,12 +30,28 @@ func (c *client) post(path, actor string, body, out any) error {
return err
}
req.Header.Set("Content-Type", "application/json")
return c.do(req, actor, http.StatusCreated, out)
return c.do(req, token, http.StatusCreated, out)
}
// login opens a session with Basic credentials and returns its bearer token.
func (c *client) login(username, password string) (string, error) {
req, err := http.NewRequest(http.MethodPost, c.base+"/api/v1/auth/sessions", nil)
if err != nil {
return "", err
}
req.SetBasicAuth(username, password)
var session struct {
Token string `json:"token"`
}
if err := c.do(req, "", http.StatusCreated, &session); err != nil {
return "", err
}
return session.Token, nil
}
// get requests the largest page the contract allows, continuing from cursor
// when it is set.
func (c *client) get(path, actor, cursor string, out any) error {
func (c *client) get(path, token, cursor string, out any) error {
query := url.Values{"limit": {"100"}}
if cursor != "" {
query.Set("cursor", cursor)
@@ -44,12 +60,12 @@ func (c *client) get(path, actor, cursor string, out any) error {
if err != nil {
return err
}
return c.do(req, actor, http.StatusOK, out)
return c.do(req, token, http.StatusOK, out)
}
func (c *client) do(req *http.Request, actor string, want int, out any) error {
if actor != "" {
req.Header.Set("X-User-Id", actor)
func (c *client) do(req *http.Request, token string, want int, out any) error {
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
resp, err := c.http.Do(req)
if err != nil {
+26 -19
View File
@@ -89,22 +89,22 @@ func run(baseURL string, clients, perClient int) (Report, error) {
api := newClient(baseURL)
runID := uuid.NewString()[:8]
members, err := registerClients(api, runID, clients)
members, tokens, err := registerClients(api, runID, clients)
if err != nil {
return report, err
}
room, err := createChat(api, runID, members)
room, err := createChat(api, runID, members, tokens[0])
if err != nil {
return report, err
}
started := time.Now()
created, failed := sendConcurrently(baseURL, room.ID, members, perClient)
created, failed := sendConcurrently(baseURL, room.ID, tokens, perClient)
report.ElapsedSeconds = time.Since(started).Seconds()
report.Created = len(created)
report.Failed = failed
listed, pages, err := readHistory(api, room.ID, members[0])
listed, pages, err := readHistory(api, room.ID, tokens[0])
if err != nil {
return report, err
}
@@ -124,27 +124,34 @@ func run(baseURL string, clients, perClient int) (Report, error) {
// 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)
// registerClients registers and logs in n clients, returning their ids and
// bearer tokens in the same order.
func registerClients(api *client, runID string, n int) (ids, tokens []string, err error) {
for i := range n {
var created user.Response
username := fmt.Sprintf("load_%s_%d", runID, i)
body := map[string]string{
"username": fmt.Sprintf("load_%s_%d", runID, i),
"username": username,
"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)
return nil, nil, fmt.Errorf("register client %d: %w", i, err)
}
token, err := api.login(username, clientPassword)
if err != nil {
return nil, nil, fmt.Errorf("log in client %d: %w", i, err)
}
ids = append(ids, created.ID)
tokens = append(tokens, token)
}
return ids, nil
return ids, tokens, nil
}
func createChat(api *client, runID string, members []string) (chat.ChatResponse, error) {
func createChat(api *client, runID string, members []string, creatorToken string) (chat.ChatResponse, error) {
var created chat.ChatResponse
body := map[string]any{"title": "Concurrency check " + runID, "member_ids": members}
if err := api.post("/api/v1/chats", members[0], body, &created); err != nil {
if err := api.post("/api/v1/chats", creatorToken, body, &created); err != nil {
return chat.ChatResponse{}, fmt.Errorf("create chat: %w", err)
}
return created, nil
@@ -152,23 +159,23 @@ func createChat(api *client, runID string, members []string) (chat.ChatResponse,
// sendConcurrently gives every member its own HTTP client and releases them
// together, so the server sees genuinely parallel writes to one chat.
func sendConcurrently(baseURL, chatID string, members []string, perClient int) (map[string]struct{}, int) {
func sendConcurrently(baseURL, chatID string, tokens []string, perClient int) (map[string]struct{}, int) {
var mu sync.Mutex
created := make(map[string]struct{}, len(members)*perClient)
created := make(map[string]struct{}, len(tokens)*perClient)
failed := 0
var wg sync.WaitGroup
start := make(chan struct{})
for i, actor := range members {
for i, token := range tokens {
wg.Add(1)
go func(n int, actor string) {
go func(n int, token string) {
defer wg.Done()
own := newClient(baseURL)
<-start
for m := range perClient {
var msg chat.MessageResponse
body := map[string]string{"text": fmt.Sprintf("client %d message %d", n, m)}
err := own.post("/api/v1/chats/"+chatID+"/messages", actor, body, &msg)
err := own.post("/api/v1/chats/"+chatID+"/messages", token, body, &msg)
mu.Lock()
if err != nil {
failed++
@@ -177,20 +184,20 @@ func sendConcurrently(baseURL, chatID string, members []string, perClient int) (
}
mu.Unlock()
}
}(i, actor)
}(i, token)
}
close(start)
wg.Wait()
return created, failed
}
func readHistory(api *client, chatID, actor string) ([]string, int, error) {
func readHistory(api *client, chatID, token string) ([]string, int, error) {
var ids []string
pages := 0
cursor := ""
for {
var page pagination.PageResponse[chat.MessageResponse]
if err := api.get("/api/v1/chats/"+chatID+"/messages", actor, cursor, &page); err != nil {
if err := api.get("/api/v1/chats/"+chatID+"/messages", token, cursor, &page); err != nil {
return nil, pages, fmt.Errorf("read history: %w", err)
}
pages++
+15 -4
View File
@@ -8,28 +8,39 @@ import (
"net/http/httptest"
"os"
"testing"
"time"
"messenger/internal/app"
"messenger/internal/testenv"
)
var db *testenv.DB
var (
db *testenv.DB
kv *testenv.KV
)
func TestMain(m *testing.M) {
ctx := context.Background()
var err error
db, err = testenv.StartPostgres(context.Background())
if err != nil {
if db, err = testenv.StartPostgres(ctx); err != nil {
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
if kv, err = testenv.StartValkey(ctx); err != nil {
db.Close()
fmt.Fprintln(os.Stderr, err)
os.Exit(1)
}
code := m.Run()
kv.Close()
db.Close()
os.Exit(code)
}
func TestRunAgainstLiveServer(t *testing.T) {
log := slog.New(slog.NewTextHandler(io.Discard, nil))
srv := httptest.NewServer(app.New(app.Deps{Log: log, DB: db.Pool, MaxBodyBytes: 64 * 1024}).Engine)
a := app.New(app.Deps{Log: log, DB: db.Pool, Sessions: kv.Client, SessionTTL: time.Hour, MaxBodyBytes: 64 * 1024})
srv := httptest.NewServer(a.Engine)
defer srv.Close()
report, err := run(srv.URL, 10, 10)