308 lines
10 KiB
Go
308 lines
10 KiB
Go
package main
|
||
|
||
import (
|
||
"bytes"
|
||
"context"
|
||
"encoding/base64"
|
||
"encoding/json"
|
||
"net/http"
|
||
"net/http/httptest"
|
||
"os"
|
||
"strings"
|
||
"sync"
|
||
"testing"
|
||
"time"
|
||
)
|
||
|
||
// Тесты без БД всегда выполняются; тесты с БД — только если задан TEST_DATABASE_URL
|
||
// (пустая тестовая БД, например postgres://messenger@127.0.0.1:55432/messenger_test).
|
||
|
||
func TestCursorIsBoundToResource(t *testing.T) {
|
||
now := time.Now().UTC().Truncate(time.Microsecond)
|
||
c := encodeCursor("messages", "chat-a", now, newUUID())
|
||
if _, _, err := decodeCursor(c, "messages", "chat-a"); err != nil {
|
||
t.Fatalf("own cursor rejected: %v", err.message)
|
||
}
|
||
if _, _, err := decodeCursor(c, "messages", "chat-b"); err == nil || err.status != 400 {
|
||
t.Fatal("cursor of another chat must be rejected with 400")
|
||
}
|
||
if _, _, err := decodeCursor(c, "chats", "chat-a"); err == nil {
|
||
t.Fatal("cursor of another list kind must be rejected")
|
||
}
|
||
if _, _, err := decodeCursor("not-a-cursor", "messages", "chat-a"); err == nil {
|
||
t.Fatal("garbage cursor must be rejected")
|
||
}
|
||
}
|
||
|
||
func TestBasicParsing(t *testing.T) {
|
||
mk := func(raw string) *http.Request {
|
||
r := httptest.NewRequest("POST", "/", nil)
|
||
r.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte(raw)))
|
||
return r
|
||
}
|
||
u, p, ok := parseBasic(mk("alice:pa:ss:wörd-ü"))
|
||
if !ok || u != "alice" || p != "pa:ss:wörd-ü" {
|
||
t.Fatalf("colon in password must be kept, got %q %q %v", u, p, ok)
|
||
}
|
||
if _, _, ok := parseBasic(mk("no-colon")); ok {
|
||
t.Fatal("credentials without colon must be rejected")
|
||
}
|
||
r := httptest.NewRequest("POST", "/", nil)
|
||
r.Header.Set("Authorization", "Basic !!!not-base64")
|
||
if _, _, ok := parseBasic(r); ok {
|
||
t.Fatal("invalid base64 must be rejected")
|
||
}
|
||
b := httptest.NewRequest("GET", "/", nil)
|
||
b.Header.Set("Authorization", "Basic "+base64.StdEncoding.EncodeToString([]byte("a:b")))
|
||
if _, ok := bearerToken(b); ok {
|
||
t.Fatal("Basic must not be accepted as Bearer")
|
||
}
|
||
}
|
||
|
||
func TestTokenAndPasswordHash(t *testing.T) {
|
||
token, hash := newToken()
|
||
if len(token) != 43 || len(hash) != 32 {
|
||
t.Fatalf("token must carry 256 bits (43 base64url chars), got %d", len(token))
|
||
}
|
||
if other, _ := newToken(); other == token {
|
||
t.Fatal("tokens must be unique")
|
||
}
|
||
h := newHasher(1)
|
||
hashed, err := h.hash(context.Background(), "correct horse battery")
|
||
if err != nil || len(hashed) < 40 || hashed[:10] != "$argon2id$" {
|
||
t.Fatalf("expected a PHC argon2id hash, got %q (%v)", hashed, err)
|
||
}
|
||
if ok, _ := h.verify(context.Background(), "correct horse battery", hashed); !ok {
|
||
t.Fatal("correct password must verify")
|
||
}
|
||
if ok, _ := h.verify(context.Background(), "wrong horse battery!", hashed); ok {
|
||
t.Fatal("wrong password must not verify")
|
||
}
|
||
}
|
||
|
||
// ---- тесты с PostgreSQL ----
|
||
|
||
type env struct {
|
||
srv *httptest.Server
|
||
store *Store
|
||
url string
|
||
}
|
||
|
||
func setup(t *testing.T, ttl int) *env {
|
||
t.Helper()
|
||
url := os.Getenv("TEST_DATABASE_URL")
|
||
if url == "" {
|
||
t.Skip("TEST_DATABASE_URL is not set")
|
||
}
|
||
ctx := context.Background()
|
||
if err := runMigrations(ctx, url); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
pool, err := newPool(ctx, url, 10)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
t.Cleanup(pool.Close)
|
||
store := &Store{pool: pool}
|
||
api := &API{store: store, hasher: newHasher(4), ttlSecs: ttl, reqLimit: 8 * time.Second}
|
||
srv := httptest.NewServer(api)
|
||
t.Cleanup(srv.Close)
|
||
return &env{srv: srv, store: store, url: url}
|
||
}
|
||
|
||
func (e *env) do(t *testing.T, method, path string, body any, headers map[string]string) (int, map[string]any, http.Header) {
|
||
t.Helper()
|
||
var rd *bytes.Reader
|
||
if body != nil {
|
||
raw, _ := json.Marshal(body)
|
||
rd = bytes.NewReader(raw)
|
||
} else {
|
||
rd = bytes.NewReader(nil)
|
||
}
|
||
req, _ := http.NewRequest(method, e.srv.URL+path, rd)
|
||
if body != nil {
|
||
req.Header.Set("Content-Type", "application/json")
|
||
}
|
||
for k, v := range headers {
|
||
req.Header.Set(k, v)
|
||
}
|
||
resp, err := http.DefaultClient.Do(req)
|
||
if err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
defer resp.Body.Close()
|
||
var out map[string]any
|
||
_ = json.NewDecoder(resp.Body).Decode(&out)
|
||
return resp.StatusCode, out, resp.Header
|
||
}
|
||
|
||
func basic(user, pass string) map[string]string {
|
||
return map[string]string{"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(user+":"+pass))}
|
||
}
|
||
|
||
func bearer(token string) map[string]string {
|
||
return map[string]string{"Authorization": "Bearer " + token}
|
||
}
|
||
|
||
func (e *env) register(t *testing.T, name string) (id, pass string) {
|
||
t.Helper()
|
||
pass = "Passw0rd-" + newUUID()
|
||
status, out, _ := e.do(t, "POST", "/api/v1/users", map[string]any{"username": name, "display_name": "Тест", "password": pass}, nil)
|
||
if status != 201 {
|
||
t.Fatalf("register %s: %d %v", name, status, out)
|
||
}
|
||
if _, leaked := out["password"]; leaked {
|
||
t.Fatal("password must never be returned")
|
||
}
|
||
return out["id"].(string), pass
|
||
}
|
||
|
||
func (e *env) login(t *testing.T, name, pass string) string {
|
||
t.Helper()
|
||
status, out, _ := e.do(t, "POST", "/api/v1/auth/sessions", nil, basic(name, pass))
|
||
if status != 201 {
|
||
t.Fatalf("login: %d %v", status, out)
|
||
}
|
||
return out["token"].(string)
|
||
}
|
||
|
||
func uname() string { return "t_" + strings.ReplaceAll(newUUID(), "-", "")[:12] }
|
||
|
||
func TestRegistrationRaceYieldsOneUser(t *testing.T) {
|
||
e := setup(t, 3600)
|
||
name := uname()
|
||
const workers = 16
|
||
var wg sync.WaitGroup
|
||
codes := make(chan int, workers)
|
||
for i := 0; i < workers; i++ {
|
||
wg.Add(1)
|
||
go func() {
|
||
defer wg.Done()
|
||
status, _, _ := e.do(t, "POST", "/api/v1/users", map[string]any{"username": name, "display_name": "Гонка", "password": "Race-password-123"}, nil)
|
||
codes <- status
|
||
}()
|
||
}
|
||
wg.Wait()
|
||
close(codes)
|
||
created, conflicts := 0, 0
|
||
for c := range codes {
|
||
switch c {
|
||
case 201:
|
||
created++
|
||
case 409:
|
||
conflicts++
|
||
default:
|
||
t.Fatalf("unexpected status %d", c)
|
||
}
|
||
}
|
||
if created != 1 || conflicts != workers-1 {
|
||
t.Fatalf("expected exactly one 201 and %d×409, got %d / %d", workers-1, created, conflicts)
|
||
}
|
||
var n int
|
||
if err := e.store.pool.QueryRow(context.Background(), `SELECT count(*) FROM users WHERE username = $1`, name).Scan(&n); err != nil || n != 1 {
|
||
t.Fatalf("database must hold exactly one row, got %d (%v)", n, err)
|
||
}
|
||
}
|
||
|
||
func TestCreateChatIsAtomic(t *testing.T) {
|
||
e := setup(t, 3600)
|
||
name := uname()
|
||
id, pass := e.register(t, name)
|
||
ctx := context.Background()
|
||
var before int
|
||
_ = e.store.pool.QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&before)
|
||
|
||
// Участник-призрак: INSERT чата уже выполнен, INSERT участников падает на внешнем ключе -> откат всего.
|
||
chat := Chat{ID: newUUID(), Title: "rollback", MemberIDs: []string{id, newUUID()}}
|
||
if _, err := e.store.createChat(ctx, chat, id); err != errInvalidMembers {
|
||
t.Fatalf("expected errInvalidMembers, got %v", err)
|
||
}
|
||
var after, members int
|
||
_ = e.store.pool.QueryRow(ctx, `SELECT count(*) FROM chats`).Scan(&after)
|
||
_ = e.store.pool.QueryRow(ctx, `SELECT count(*) FROM chat_members WHERE chat_id = $1::uuid`, chat.ID).Scan(&members)
|
||
if after != before || members != 0 {
|
||
t.Fatalf("partial chat left behind: chats %d->%d, members %d", before, after, members)
|
||
}
|
||
|
||
// То же через HTTP: 400, а у пользователя по-прежнему нет чатов.
|
||
token := e.login(t, name, pass)
|
||
status, _, _ := e.do(t, "POST", "/api/v1/chats", map[string]any{"title": "x", "member_ids": []string{id, newUUID()}}, bearer(token))
|
||
if status != 400 {
|
||
t.Fatalf("unknown member must give 400, got %d", status)
|
||
}
|
||
_, list, _ := e.do(t, "GET", "/api/v1/chats", nil, bearer(token))
|
||
if items, _ := list["items"].([]any); len(items) != 0 {
|
||
t.Fatalf("failed creation must leave no chat, got %d", len(items))
|
||
}
|
||
}
|
||
|
||
func TestSessionLifecycle(t *testing.T) {
|
||
e := setup(t, 1) // TTL = 1 с
|
||
name := uname()
|
||
id, pass := e.register(t, name)
|
||
|
||
// неверный пароль и неизвестный пользователь: одинаковый 401 + Basic challenge
|
||
for _, c := range []map[string]string{basic(name, "wrong-password-xx"), basic(uname(), "whatever-password")} {
|
||
status, _, h := e.do(t, "POST", "/api/v1/auth/sessions", nil, c)
|
||
if status != 401 || h.Get("WWW-Authenticate") != basicChallenge {
|
||
t.Fatalf("bad credentials: %d %q", status, h.Get("WWW-Authenticate"))
|
||
}
|
||
}
|
||
token := e.login(t, name, pass)
|
||
|
||
status, out, _ := e.do(t, "GET", "/api/v1/users/me", nil, bearer(token))
|
||
if status != 200 || out["id"] != id {
|
||
t.Fatalf("fresh session must work: %d", status)
|
||
}
|
||
// X-User-Id не даёт доступа и не подменяет владельца; Basic на бизнес-эндпоинте — 401
|
||
if status, _, _ := e.do(t, "GET", "/api/v1/users/me", nil, map[string]string{"X-User-Id": id}); status != 401 {
|
||
t.Fatalf("X-User-Id alone must give 401, got %d", status)
|
||
}
|
||
if status, _, h := e.do(t, "GET", "/api/v1/users/me", nil, basic(name, pass)); status != 401 || h.Get("WWW-Authenticate") != bearerChallenge {
|
||
t.Fatalf("Basic on business endpoint must give 401 Bearer, got %d", status)
|
||
}
|
||
|
||
// истечение срока
|
||
time.Sleep(1300 * time.Millisecond)
|
||
if status, _, _ := e.do(t, "GET", "/api/v1/users/me", nil, bearer(token)); status != 401 {
|
||
t.Fatalf("expired session must give 401, got %d", status)
|
||
}
|
||
|
||
// logout (отдельный пользователь с длинным TTL)
|
||
long := setup(t, 3600)
|
||
n2 := uname()
|
||
_, p2 := long.register(t, n2)
|
||
t2 := long.login(t, n2, p2)
|
||
if status, _, _ := long.do(t, "DELETE", "/api/v1/auth/sessions/current", nil, bearer(t2)); status != 204 {
|
||
t.Fatalf("logout must give 204, got %d", status)
|
||
}
|
||
if status, _, _ := long.do(t, "GET", "/api/v1/users/me", nil, bearer(t2)); status != 401 {
|
||
t.Fatalf("revoked token must give 401, got %d", status)
|
||
}
|
||
if status, _, _ := long.do(t, "DELETE", "/api/v1/auth/sessions/current", nil, bearer(t2)); status != 401 {
|
||
t.Fatalf("repeated logout must give 401, got %d", status)
|
||
}
|
||
}
|
||
|
||
func TestMigrationsAreIdempotent(t *testing.T) {
|
||
e := setup(t, 3600)
|
||
name := uname()
|
||
e.register(t, name)
|
||
count := func(table string) int {
|
||
var n int
|
||
if err := e.store.pool.QueryRow(context.Background(), `SELECT count(*) FROM `+table).Scan(&n); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
return n
|
||
}
|
||
users, versions := count("users"), count("schema_migrations")
|
||
for i := 0; i < 2; i++ {
|
||
if err := runMigrations(context.Background(), e.url); err != nil {
|
||
t.Fatal(err)
|
||
}
|
||
}
|
||
if count("users") != users || count("schema_migrations") != versions {
|
||
t.Fatal("re-running migrations changed data or duplicated version records")
|
||
}
|
||
}
|