Добавить сессии в 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
+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, "")
}