Files
mtusi2026lab2/app/e2e/failures_test.go
T

377 lines
15 KiB
Go
Raw Blame History

This file contains ambiguous Unicode characters
This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.
// Package e2e — проверки уровня 4 против запущенного compose-стенда.
//
// Неверный пароль, X-User-Id/Basic вместо Bearer, logout, expiry при коротком
// SESSION_TTL_SECONDS, недоступность Valkey сессий, PostgreSQL и Valkey-кэша.
// Тест сам останавливает и запускает контейнеры (volumes не трогает) и в конце
// возвращает стенд в исходный режим. Токены и пароли не печатает.
//
// Запуск: scripts/failures-tests.sh; без E2E_BASE_URL тесты пропускаются,
// поэтому обычный go test ./... контейнеры не трогает.
package e2e
import (
"bytes"
"crypto/rand"
"encoding/base64"
"encoding/hex"
"encoding/json"
"io"
"net/http"
"os"
"os/exec"
"path/filepath"
"slices"
"strings"
"testing"
"time"
)
// root — корень репозитория: go test запускает пакет из app/e2e.
var root = filepath.Join("..", "..")
type client struct {
base string
http *http.Client
}
type response struct {
status int
header http.Header
body map[string]any
raw []byte
}
func (r response) errorCode() string {
e, _ := r.body["error"].(map[string]any)
code, _ := e["code"].(string)
return code
}
func (r response) errorMessage() string {
e, _ := r.body["error"].(map[string]any)
msg, _ := e["message"].(string)
return msg
}
func (r response) str(key string) string {
s, _ := r.body[key].(string)
return s
}
// itemIDs — id сообщений страницы истории.
func (r response) itemIDs() []string {
items, _ := r.body["items"].([]any)
ids := make([]string, 0, len(items))
for _, it := range items {
m, _ := it.(map[string]any)
id, _ := m["id"].(string)
ids = append(ids, id)
}
return ids
}
// call возвращает status 0, если соединиться не удалось (API перезапускается).
func (c *client) call(method, path, token string, body any, headers map[string]string) response {
var rd io.Reader
if body != nil {
b, _ := json.Marshal(body)
rd = bytes.NewReader(b)
}
req, _ := http.NewRequest(method, c.base+path, rd)
if body != nil {
req.Header.Set("Content-Type", "application/json")
}
if token != "" {
req.Header.Set("Authorization", "Bearer "+token)
}
for k, v := range headers {
req.Header.Set(k, v)
}
resp, err := c.http.Do(req)
if err != nil {
return response{}
}
defer resp.Body.Close()
raw, _ := io.ReadAll(resp.Body)
out := response{status: resp.StatusCode, header: resp.Header, raw: raw}
_ = json.Unmarshal(raw, &out.body)
return out
}
func basic(username, password string) map[string]string {
return map[string]string{"Authorization": "Basic " + base64.StdEncoding.EncodeToString([]byte(username+":"+password))}
}
func (c *client) login(username, password string) response {
return c.call(http.MethodPost, "/api/v1/auth/sessions", "", nil, basic(username, password))
}
// waitReady ждёт /health/ready и возвращает момент готовности.
func (c *client) waitReady(t *testing.T) time.Time {
t.Helper()
deadline := time.Now().Add(90 * time.Second)
for time.Now().Before(deadline) {
if c.call(http.MethodGet, "/health/ready", "", nil, nil).status == http.StatusOK {
return time.Now()
}
time.Sleep(500 * time.Millisecond)
}
t.Fatal("стенд не готов за 90 с")
return time.Time{}
}
// compose запускает docker compose из корня; env дополняет окружение процесса
// (compose.yaml берёт SESSION_TTL_SECONDS из окружения раньше, чем из .env).
func compose(t *testing.T, env map[string]string, args ...string) {
t.Helper()
cmd := exec.Command("docker", append([]string{"compose", "--env-file", ".env"}, args...)...)
cmd.Dir = root
cmd.Env = os.Environ()
for k, v := range env {
cmd.Env = append(cmd.Env, k+"="+v)
}
// Вывод compose не печатаем: в нём могут оказаться значения окружения.
if err := cmd.Run(); err != nil {
t.Fatalf("docker compose %s: %v", strings.Join(args, " "), err)
}
}
// waitHealthy ждёт healthcheck сервиса: после unpause он остаётся unhealthy
// до следующей успешной проверки, и compose up --wait сразу падает.
func waitHealthy(t *testing.T, service string) {
t.Helper()
deadline := time.Now().Add(30 * time.Second)
for time.Now().Before(deadline) {
cmd := exec.Command("docker", "compose", "--env-file", ".env", "ps", "--format", "{{.Health}}", service)
cmd.Dir = root
out, _ := cmd.Output()
if strings.TrimSpace(string(out)) == "healthy" {
return
}
time.Sleep(500 * time.Millisecond)
}
t.Fatalf("%s не стал healthy за 30 с", service)
}
func randHex(n int) string {
b := make([]byte, n)
_, _ = rand.Read(b)
return hex.EncodeToString(b)
}
func TestFailures(t *testing.T) {
base := os.Getenv("E2E_BASE_URL")
if base == "" {
t.Skip("E2E_BASE_URL не задан (scripts/failures-tests.sh)")
}
c := &client{base: strings.TrimRight(base, "/"), http: &http.Client{Timeout: 10 * time.Second}}
c.waitReady(t)
// Что бы ни упало, стенд возвращается в рабочий режим: все сервисы запущены,
// API с обычным TTL.
t.Cleanup(func() {
compose(t, nil, "up", "-d", "--wait")
})
name, password := "f_"+randHex(4), "pw-"+randHex(8)
u := c.call(http.MethodPost, "/api/v1/users", "", map[string]string{
"username": name, "display_name": "Отказ", "password": password,
}, nil)
if u.status != http.StatusCreated {
t.Fatalf("регистрация: status %d", u.status)
}
uid := u.str("id")
token := c.login(name, password).str("token")
chat := c.call(http.MethodPost, "/api/v1/chats", token, map[string]any{"title": "Отказы", "member_ids": []string{uid}}, nil)
if chat.status != http.StatusCreated {
t.Fatalf("создание чата: status %d", chat.status)
}
messagesPath := "/api/v1/chats/" + chat.str("id") + "/messages"
// --- аутентификация ---
t.Run("неверный пароль → 401 Basic, неотличим от неизвестного username", func(t *testing.T) {
wrong := c.login(name, password+"x")
unknown := c.login("no_such_"+randHex(3), password)
challenge := wrong.header.Get("WWW-Authenticate")
t.Logf("статусы %d/%d, challenge %q", wrong.status, unknown.status, challenge)
if wrong.status != 401 || unknown.status != 401 || !strings.HasPrefix(challenge, "Basic") {
t.Error("ожидали 401 с WWW-Authenticate: Basic для обоих случаев")
}
if wrong.errorCode() != "unauthorized" || wrong.errorCode() != unknown.errorCode() ||
wrong.errorMessage() != unknown.errorMessage() {
t.Error("ответы на неверный пароль и неизвестный username различаются")
}
})
t.Run("X-User-Id без Bearer → 401", func(t *testing.T) {
r := c.call(http.MethodGet, "/api/v1/users/me", "", nil, map[string]string{"X-User-Id": uid})
t.Logf("status %d", r.status)
if r.status != 401 || !strings.HasPrefix(r.header.Get("WWW-Authenticate"), "Bearer") {
t.Error("ожидали 401 с WWW-Authenticate: Bearer")
}
})
t.Run("Basic на бизнес-endpoint → 401", func(t *testing.T) {
r := c.call(http.MethodGet, "/api/v1/users/me", "", nil, basic(name, password))
t.Logf("status %d", r.status)
if r.status != 401 {
t.Error("ожидали 401")
}
})
t.Run("logout → 204, тот же токен → 401, повторный logout → 401, другая сессия жива", func(t *testing.T) {
tmp := c.login(name, password).str("token")
got := []int{
c.call(http.MethodDelete, "/api/v1/auth/sessions/current", tmp, nil, nil).status,
c.call(http.MethodGet, "/api/v1/users/me", tmp, nil, nil).status,
c.call(http.MethodDelete, "/api/v1/auth/sessions/current", tmp, nil, nil).status,
c.call(http.MethodGet, "/api/v1/users/me", token, nil, nil).status,
}
t.Logf("статусы %v", got)
if !slices.Equal(got, []int{204, 401, 401, 200}) {
t.Error("ожидали [204 401 401 200]")
}
})
t.Run("expiry при SESSION_TTL_SECONDS=2: 200 сразу, 401 через 3 с", func(t *testing.T) {
compose(t, map[string]string{"SESSION_TTL_SECONDS": "2"}, "up", "-d", "--wait", "api")
defer func() {
compose(t, nil, "up", "-d", "--wait", "api")
c.waitReady(t)
}()
c.waitReady(t)
s := c.login(name, password)
if s.status != http.StatusCreated {
t.Fatalf("вход: status %d", s.status)
}
expiresAt, err := time.Parse(time.RFC3339, s.str("expires_at"))
if err != nil {
t.Fatalf("expires_at: %v", err)
}
ttl := time.Until(expiresAt)
short := s.str("token")
before := c.call(http.MethodGet, "/api/v1/users/me", short, nil, nil).status
time.Sleep(3200 * time.Millisecond)
after := c.call(http.MethodGet, "/api/v1/users/me", short, nil, nil)
t.Logf("expires_at через %.1f с, статусы %d → %d", ttl.Seconds(), before, after.status)
if ttl > 2500*time.Millisecond || before != 200 || after.status != 401 ||
!strings.HasPrefix(after.header.Get("WWW-Authenticate"), "Bearer") {
t.Error("ожидали TTL ≤ 2.5 с, 200 до и 401 Bearer после истечения")
}
})
t.Run("Valkey сессий остановлен: Bearer → 503, без токена → 401, вход → 503, ready → 503", func(t *testing.T) {
compose(t, nil, "stop", "valkey")
me := c.call(http.MethodGet, "/api/v1/users/me", token, nil, nil)
anon := c.call(http.MethodGet, "/api/v1/users/me", "", nil, nil).status
login := c.login(name, password).status
ready := c.call(http.MethodGet, "/health/ready", "", nil, nil).status
t.Logf("me %d, anon %d, login %d, ready %d", me.status, anon, login, ready)
if me.status != 503 || me.errorCode() != "unavailable" || anon != 401 || login != 503 || ready != 503 {
t.Error("ожидали me 503 unavailable, anon 401, login 503, ready 503")
}
})
t.Run("Valkey сессий восстановлен: прежний токен снова действителен (AOF)", func(t *testing.T) {
t0 := time.Now()
compose(t, nil, "start", "valkey")
t1 := c.waitReady(t)
st := c.call(http.MethodGet, "/api/v1/users/me", token, nil, nil).status
t.Logf("ready через %.1f с после start, me %d", t1.Sub(t0).Seconds(), st)
if st != 200 {
t.Error("прежний токен не действителен после рестарта Valkey")
}
})
t.Run("PostgreSQL остановлен: чтение/запись → 503 без деталей, ready → 503", func(t *testing.T) {
compose(t, nil, "stop", "postgres")
list := c.call(http.MethodGet, messagesPath, token, nil, nil)
send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "при упавшей БД"}, nil)
ready := c.call(http.MethodGet, "/health/ready", "", nil, nil).status
lower := strings.ToLower(string(list.raw) + string(send.raw))
leaked := false
for _, w := range []string{"sql", "pgx", "dial", "postgres"} {
leaked = leaked || strings.Contains(lower, w)
}
t.Logf("list %d (кэш может отдать страницу), send %d, ready %d, утечка деталей: %v", list.status, send.status, ready, leaked)
if send.status != 503 || ready != 503 || (list.status != 200 && list.status != 503) || leaked {
t.Error("ожидали send 503, ready 503, list 200/503 и никаких деталей БД в ответе")
}
})
var restoredID string
t.Run("PostgreSQL восстановлен: запись 201 тем же токеном", func(t *testing.T) {
t0 := time.Now()
compose(t, nil, "start", "postgres")
t1 := c.waitReady(t)
send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "после восстановления БД"}, nil)
restoredID = send.str("id")
t.Logf("ready через %.1f с после start, send %d", t1.Sub(t0).Seconds(), send.status)
if send.status != 201 {
t.Error("ожидали 201")
}
})
var bypassID string
t.Run("Valkey-кэш остановлен: ready 200, запись 201, чтение 200 из PostgreSQL с новым сообщением", func(t *testing.T) {
compose(t, nil, "stop", "valkey-cache")
ready := c.call(http.MethodGet, "/health/ready", "", nil, nil).status
send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "при упавшем кэше"}, nil)
bypassID = send.str("id")
list := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil)
ids := list.itemIDs()
t.Logf("ready %d, send %d, list %d, сообщений %d", ready, send.status, list.status, len(ids))
if ready != 200 || send.status != 201 || list.status != 200 ||
!slices.Contains(ids, bypassID) || !slices.Contains(ids, restoredID) {
t.Error("ожидали ready 200, send 201, list 200 с обоими новыми сообщениями")
}
})
t.Run("Valkey-кэш восстановлен: история полная и одинаковая при промахе и попадании", func(t *testing.T) {
compose(t, nil, "up", "-d", "--wait", "valkey-cache")
time.Sleep(1500 * time.Millisecond) // breaker 1 с + повтор отложенной инвалидации 200 мс
miss := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil)
hit := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil)
ids := hit.itemIDs()
t.Logf("статусы %d/%d, сообщений %d", miss.status, hit.status, len(ids))
if miss.status != 200 || hit.status != 200 || !bytes.Equal(miss.raw, hit.raw) || !slices.Contains(ids, bypassID) {
t.Error("ожидали две одинаковые полные страницы с сообщением, записанным при упавшем кэше")
}
})
t.Run("инвалидация не удалась, API перезапущен: сообщение с 201 сразу видно в истории", func(t *testing.T) {
// Прогреваем страницу в кэше, затем замораживаем Valkey-кэш: данные
// (и старая версия) остаются, но DEL версии падает по таймауту.
c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil)
c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil)
compose(t, nil, "pause", "valkey-cache")
paused := true
t.Cleanup(func() {
if paused {
compose(t, nil, "unpause", "valkey-cache")
}
waitHealthy(t, "valkey-cache")
})
send := c.call(http.MethodPost, messagesPath, token, map[string]string{"text": "до рестарта API"}, nil)
if send.status != 201 {
t.Fatalf("ожидали 201, получили %d", send.status)
}
compose(t, nil, "restart", "api")
c.waitReady(t)
compose(t, nil, "unpause", "valkey-cache")
paused = false
for i := 0; i < 3; i++ {
list := c.call(http.MethodGet, messagesPath+"?limit=100", token, nil, nil)
if list.status != 200 || !slices.Contains(list.itemIDs(), send.str("id")) {
t.Fatalf("чтение %d после рестарта: status %d, подтверждённого сообщения нет в истории", i+1, list.status)
}
time.Sleep(300 * time.Millisecond)
}
})
}