forked from mtusi2026/mtusi2026lab2
Подключение Postgresql и redis
This commit is contained in:
+270
-65
@@ -2,6 +2,7 @@ package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"context"
|
||||
"encoding/base64"
|
||||
"encoding/json"
|
||||
"io"
|
||||
@@ -12,21 +13,48 @@ import (
|
||||
"strings"
|
||||
"sync"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
func newServer(t *testing.T) (*httptest.Server, *API, *bytes.Buffer) {
|
||||
t.Helper()
|
||||
var logs bytes.Buffer
|
||||
st := store.New()
|
||||
application := New(st, slog.New(slog.NewJSONHandler(&logs, nil)))
|
||||
srv := httptest.NewServer(application)
|
||||
t.Cleanup(srv.Close)
|
||||
return srv, application, &logs
|
||||
const testPassword = "correct-horse-1"
|
||||
|
||||
type labServer struct {
|
||||
URL string
|
||||
tokens map[string]string
|
||||
api *API
|
||||
store store.Repository
|
||||
sess session.Store
|
||||
}
|
||||
|
||||
func do(t *testing.T, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) {
|
||||
func newServer(t *testing.T) *labServer {
|
||||
return newServerTTL(t, time.Hour)
|
||||
}
|
||||
|
||||
func newServerTTL(t *testing.T, ttl time.Duration) *labServer {
|
||||
t.Helper()
|
||||
st := store.New()
|
||||
sess := session.NewMemory()
|
||||
application := New(st, sess, password.Params{Time: 1, Memory: 8, Threads: 1}, ttl, slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
srv := httptest.NewServer(application)
|
||||
t.Cleanup(srv.Close)
|
||||
return &labServer{URL: srv.URL, tokens: map[string]string{}, api: application, store: st, sess: sess}
|
||||
}
|
||||
|
||||
func (e *labServer) bearer(user string) string {
|
||||
if user == "" {
|
||||
return ""
|
||||
}
|
||||
if tok, ok := e.tokens[user]; ok {
|
||||
return tok
|
||||
}
|
||||
return "unknown-session-token"
|
||||
}
|
||||
|
||||
func do(t *testing.T, env *labServer, method, url, user string, body any, raw []byte, contentType string) (int, http.Header, []byte) {
|
||||
t.Helper()
|
||||
var rdr io.Reader
|
||||
if raw != nil {
|
||||
@@ -48,8 +76,8 @@ func do(t *testing.T, method, url, user string, body any, raw []byte, contentTyp
|
||||
}
|
||||
req.Header.Set("Content-Type", contentType)
|
||||
}
|
||||
if user != "" {
|
||||
req.Header.Set("X-User-Id", user)
|
||||
if tok := env.bearer(user); tok != "" {
|
||||
req.Header.Set("Authorization", "Bearer "+tok)
|
||||
}
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
@@ -75,24 +103,48 @@ func do(t *testing.T, method, url, user string, body any, raw []byte, contentTyp
|
||||
return resp.StatusCode, resp.Header, data
|
||||
}
|
||||
|
||||
func createUser(t *testing.T, base, username, display string) userJSON {
|
||||
func createUser(t *testing.T, env *labServer, username, display string) userJSON {
|
||||
t.Helper()
|
||||
status, _, body := do(t, http.MethodPost, base+"/api/v1/users", "", map[string]string{
|
||||
"username": username, "display_name": display,
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", map[string]string{
|
||||
"username": username, "display_name": display, "password": testPassword,
|
||||
}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("create user %s: %d %s", username, status, body)
|
||||
}
|
||||
if bytes.Contains(body, []byte("password")) || bytes.Contains(body, []byte("argon2")) {
|
||||
t.Fatalf("user response leaked a secret: %s", body)
|
||||
}
|
||||
var u userJSON
|
||||
if err := json.Unmarshal(body, &u); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req, err := http.NewRequest(http.MethodPost, env.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.SetBasicAuth(username, testPassword)
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer resp.Body.Close()
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
if resp.StatusCode != http.StatusCreated {
|
||||
t.Fatalf("login %s: %d %s", username, resp.StatusCode, raw)
|
||||
}
|
||||
var sess struct {
|
||||
Token string `json:"token"`
|
||||
}
|
||||
if err := json.Unmarshal(raw, &sess); err != nil || len(sess.Token) < 32 {
|
||||
t.Fatalf("session: %s", raw)
|
||||
}
|
||||
env.tokens[u.ID] = sess.Token
|
||||
return u
|
||||
}
|
||||
|
||||
func createChat(t *testing.T, base, caller, title string, members ...string) chatJSON {
|
||||
func createChat(t *testing.T, env *labServer, caller, title string, members ...string) chatJSON {
|
||||
t.Helper()
|
||||
status, _, body := do(t, http.MethodPost, base+"/api/v1/chats", caller, map[string]any{
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats", caller, map[string]any{
|
||||
"title": title, "member_ids": members,
|
||||
}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
@@ -106,7 +158,7 @@ func createChat(t *testing.T, base, caller, title string, members ...string) cha
|
||||
}
|
||||
|
||||
func TestInvalidJSONExtraFieldAndTypes(t *testing.T) {
|
||||
srv, _, _ := newServer(t)
|
||||
env := newServer(t)
|
||||
cases := [][]byte{
|
||||
[]byte(`{`),
|
||||
[]byte(`{"username":"abc","display_name":"Алиса","extra":1}`),
|
||||
@@ -114,19 +166,19 @@ func TestInvalidJSONExtraFieldAndTypes(t *testing.T) {
|
||||
[]byte(`null`),
|
||||
}
|
||||
for _, raw := range cases {
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", nil, raw, "application/json")
|
||||
if status != http.StatusBadRequest || !bytes.Contains(body, []byte(`"invalid_request"`)) {
|
||||
t.Fatalf("body %s: %d %s", raw, status, body)
|
||||
}
|
||||
}
|
||||
status, _, _ := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, []byte(`{"username":"abc","display_name":"Алиса"}`), "text/plain")
|
||||
status, _, _ := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", nil, []byte(`{"username":"abc","display_name":"Алиса"}`), "text/plain")
|
||||
if status != http.StatusUnsupportedMediaType {
|
||||
t.Fatalf("content type: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) {
|
||||
srv, _, _ := newServer(t)
|
||||
env := newServer(t)
|
||||
bad := [][]byte{
|
||||
[]byte(`{"username":"bad_json","display_name":"Я"}]`),
|
||||
[]byte(`{"username":"bad_json","display_name":"Я"}}`),
|
||||
@@ -134,38 +186,38 @@ func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) {
|
||||
append([]byte(`{"username":"bad_utf","display_name":"`), 0xff, '"', '}'),
|
||||
}
|
||||
for _, raw := range bad {
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", nil, raw, "application/json")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", nil, raw, "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("user body %q: %d %s", raw, status, body)
|
||||
}
|
||||
}
|
||||
|
||||
alice := createUser(t, srv.URL, "alice", "Алиса")
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats", alice.ID, nil, []byte(`{"Title":"чат","member_ids":["`+alice.ID+`"]}`), "application/json")
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats", alice.ID, nil, []byte(`{"Title":"чат","member_ids":["`+alice.ID+`"]}`), "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("Title: %d %s", status, body)
|
||||
}
|
||||
chat := createChat(t, srv.URL, alice.ID, "чат", alice.ID)
|
||||
chat := createChat(t, env, alice.ID, "чат", alice.ID)
|
||||
|
||||
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, []byte(`{"TEXT":"hi"}`), "application/json")
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, []byte(`{"TEXT":"hi"}`), "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("TEXT: %d %s", status, body)
|
||||
}
|
||||
rawText := append([]byte(`{"text":"`), 0xff, '"', '}')
|
||||
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, rawText, "application/json")
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, nil, rawText, "application/json")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("message utf-8: %d %s", status, body)
|
||||
}
|
||||
|
||||
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "one"}, nil, "")
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "one"}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("seed: %d %s", status, body)
|
||||
}
|
||||
status, _, body = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "two"}, nil, "")
|
||||
status, _, body = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "two"}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("seed2: %d %s", status, body)
|
||||
}
|
||||
status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil, "")
|
||||
status, _, body = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1", alice.ID, nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("page: %d %s", status, body)
|
||||
}
|
||||
@@ -178,21 +230,21 @@ func TestStrictJSONNamesUTF8AndCursorTail(t *testing.T) {
|
||||
t.Fatal(err)
|
||||
}
|
||||
tampered := base64.RawURLEncoding.EncodeToString(append(decoded, []byte("garbage")...))
|
||||
status, _, body = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(tampered), alice.ID, nil, nil, "")
|
||||
status, _, body = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(tampered), alice.ID, nil, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("tampered cursor: %d %s", status, body)
|
||||
}
|
||||
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(*page.NextCursor), alice.ID, nil, nil, "")
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=1&cursor="+url.QueryEscape(*page.NextCursor), alice.ID, nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("valid cursor: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDuplicateUsername(t *testing.T) {
|
||||
srv, _, _ := newServer(t)
|
||||
createUser(t, srv.URL, "alice", "Алиса")
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/users", "", map[string]string{
|
||||
"username": "alice", "display_name": "Другая",
|
||||
env := newServer(t)
|
||||
createUser(t, env, "alice", "Алиса")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/users", "", map[string]string{
|
||||
"username": "alice", "display_name": "Другая", "password": testPassword,
|
||||
}, nil, "")
|
||||
if status != http.StatusConflict || !bytes.Contains(body, []byte(`"conflict"`)) {
|
||||
t.Fatalf("duplicate: %d %s", status, body)
|
||||
@@ -200,46 +252,46 @@ func TestDuplicateUsername(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestEmptyMessageForeignChatAndAuth(t *testing.T) {
|
||||
srv, _, _ := newServer(t)
|
||||
alice := createUser(t, srv.URL, "alice", "Алиса")
|
||||
bob := createUser(t, srv.URL, "bob", "Боб")
|
||||
eve := createUser(t, srv.URL, "eve", "Ева")
|
||||
chat := createChat(t, srv.URL, alice.ID, "Контрактный тест", alice.ID, bob.ID)
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
bob := createUser(t, env, "bob", "Боб")
|
||||
eve := createUser(t, env, "eve", "Ева")
|
||||
chat := createChat(t, env, alice.ID, "Контрактный тест", alice.ID, bob.ID)
|
||||
|
||||
status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "", nil, nil, "")
|
||||
status, _, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", "", nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("missing header: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/users/me", "11111111-1111-4111-8111-111111111111", nil, nil, "")
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", "11111111-1111-4111-8111-111111111111", nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("unknown user: %d", status)
|
||||
}
|
||||
meStatus, _, meBody := do(t, http.MethodGet, srv.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
meStatus, _, meBody := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
if meStatus != http.StatusOK || !bytes.Contains(meBody, []byte(alice.ID)) {
|
||||
t.Fatalf("me: %d %s", meStatus, meBody)
|
||||
}
|
||||
|
||||
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID, eve.ID, nil, nil, "")
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID, eve.ID, nil, nil, "")
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign chat: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", eve.ID, map[string]string{"text": "чужое"}, nil, "")
|
||||
status, _, _ = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", eve.ID, map[string]string{"text": "чужое"}, nil, "")
|
||||
if status != http.StatusNotFound {
|
||||
t.Fatalf("foreign post: %d", status)
|
||||
}
|
||||
for _, text := range []string{"", " ", "\n\t"} {
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("empty %q: %d %s", text, status, body)
|
||||
}
|
||||
}
|
||||
status, _, _ = do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "привет", "sender_id": eve.ID}, nil, "")
|
||||
status, _, _ = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": "привет", "sender_id": eve.ID}, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("sender_id must be rejected: %d", status)
|
||||
}
|
||||
|
||||
text := "Привет, мир 👋"
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]string{"text": text}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
t.Fatalf("unicode: %d %s", status, body)
|
||||
}
|
||||
@@ -256,11 +308,11 @@ func TestEmptyMessageForeignChatAndAuth(t *testing.T) {
|
||||
}
|
||||
|
||||
func TestPaginationSeveralPages(t *testing.T) {
|
||||
srv, _, _ := newServer(t)
|
||||
alice := createUser(t, srv.URL, "alice", "Алиса")
|
||||
bob := createUser(t, srv.URL, "bob", "Боб")
|
||||
chat := createChat(t, srv.URL, alice.ID, "страницы", alice.ID, bob.ID)
|
||||
other := createChat(t, srv.URL, alice.ID, "другой", alice.ID)
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
bob := createUser(t, env, "bob", "Боб")
|
||||
chat := createChat(t, env, alice.ID, "страницы", alice.ID, bob.ID)
|
||||
other := createChat(t, env, alice.ID, "другой", alice.ID)
|
||||
const n = 25
|
||||
ids := make([]string, 0, n)
|
||||
for i := 0; i < n; i++ {
|
||||
@@ -268,7 +320,7 @@ func TestPaginationSeveralPages(t *testing.T) {
|
||||
if i%2 == 1 {
|
||||
sender = bob.ID
|
||||
}
|
||||
status, _, body := do(t, http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", sender, map[string]string{
|
||||
status, _, body := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", sender, map[string]string{
|
||||
"text": "сообщение " + strings.Repeat("я", i%3) + string(rune('a'+i%26)),
|
||||
}, nil, "")
|
||||
if status != http.StatusCreated {
|
||||
@@ -288,11 +340,11 @@ func TestPaginationSeveralPages(t *testing.T) {
|
||||
if pages > 10 {
|
||||
t.Fatal("pagination did not finish")
|
||||
}
|
||||
url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10"
|
||||
url := env.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10"
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
status, _, body := do(t, http.MethodGet, url, bob.ID, nil, nil, "")
|
||||
status, _, body := do(t, env, http.MethodGet, url, bob.ID, nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("page: %d %s", status, body)
|
||||
}
|
||||
@@ -317,25 +369,25 @@ func TestPaginationSeveralPages(t *testing.T) {
|
||||
if strings.Join(got, ",") != strings.Join(ids, ",") {
|
||||
t.Fatalf("order/duplication mismatch\nwant %v\ngot %v", ids, got)
|
||||
}
|
||||
status, _, _ := do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+other.ID+"/messages?limit=10&cursor="+cursor, alice.ID, nil, nil, "")
|
||||
status, _, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+other.ID+"/messages?limit=10&cursor="+cursor, alice.ID, nil, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("foreign cursor: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, http.MethodGet, srv.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=0", alice.ID, nil, nil, "")
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/chats/"+chat.ID+"/messages?limit=0", alice.ID, nil, nil, "")
|
||||
if status != http.StatusBadRequest {
|
||||
t.Fatalf("limit 0: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestConcurrentHundredMessages(t *testing.T) {
|
||||
srv, _, _ := newServer(t)
|
||||
env := newServer(t)
|
||||
users := make([]userJSON, 10)
|
||||
ids := make([]string, 10)
|
||||
for i := 0; i < 10; i++ {
|
||||
users[i] = createUser(t, srv.URL, "u"+string(rune('a'+i))+"x", "Участник")
|
||||
users[i] = createUser(t, env, "u"+string(rune('a'+i))+"x", "Участник")
|
||||
ids[i] = users[i].ID
|
||||
}
|
||||
chat := createChat(t, srv.URL, ids[0], "гонка", ids...)
|
||||
chat := createChat(t, env, ids[0], "гонка", ids...)
|
||||
var wg sync.WaitGroup
|
||||
errCh := make(chan error, 100)
|
||||
for i := 0; i < 10; i++ {
|
||||
@@ -343,13 +395,13 @@ func TestConcurrentHundredMessages(t *testing.T) {
|
||||
go func(user string) {
|
||||
defer wg.Done()
|
||||
for j := 0; j < 10; j++ {
|
||||
req, err := http.NewRequest(http.MethodPost, srv.URL+"/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(`{"text":"n"}`))
|
||||
req, err := http.NewRequest(http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", strings.NewReader(`{"text":"n"}`))
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
return
|
||||
}
|
||||
req.Header.Set("Content-Type", "application/json")
|
||||
req.Header.Set("X-User-Id", user)
|
||||
req.Header.Set("Authorization", "Bearer "+env.tokens[user])
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
errCh <- err
|
||||
@@ -371,11 +423,11 @@ func TestConcurrentHundredMessages(t *testing.T) {
|
||||
seen := map[string]struct{}{}
|
||||
cursor := ""
|
||||
for {
|
||||
url := srv.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17"
|
||||
url := env.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17"
|
||||
if cursor != "" {
|
||||
url += "&cursor=" + cursor
|
||||
}
|
||||
status, _, body := do(t, http.MethodGet, url, ids[3], nil, nil, "")
|
||||
status, _, body := do(t, env, http.MethodGet, url, ids[3], nil, nil, "")
|
||||
if status != http.StatusOK {
|
||||
t.Fatalf("list: %d %s", status, body)
|
||||
}
|
||||
@@ -399,6 +451,159 @@ func TestConcurrentHundredMessages(t *testing.T) {
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionWrongPasswordLogoutAndIgnoredUserHeader(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
eve := createUser(t, env, "eve", "Ева")
|
||||
|
||||
req, err := http.NewRequest(http.MethodPost, env.URL+"/api/v1/auth/sessions", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
req.SetBasicAuth("alice", "wrong-password-1")
|
||||
resp, err := http.DefaultClient.Do(req)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
body, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized || !strings.HasPrefix(resp.Header.Get("WWW-Authenticate"), "Basic ") {
|
||||
t.Fatalf("wrong password: %d %s %q", resp.StatusCode, body, resp.Header.Get("WWW-Authenticate"))
|
||||
}
|
||||
|
||||
status, hdr, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", "", nil, nil, "")
|
||||
if status != http.StatusUnauthorized || !strings.HasPrefix(hdr.Get("WWW-Authenticate"), "Bearer ") {
|
||||
t.Fatalf("missing bearer: %d %q", status, hdr.Get("WWW-Authenticate"))
|
||||
}
|
||||
bare, err := http.NewRequest(http.MethodGet, env.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
bare.Header.Set("X-User-Id", alice.ID)
|
||||
resp, err = http.DefaultClient.Do(bare)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("X-User-Id alone: %d", resp.StatusCode)
|
||||
}
|
||||
over, err := http.NewRequest(http.MethodGet, env.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
over.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID])
|
||||
over.Header.Set("X-User-Id", eve.ID)
|
||||
resp, err = http.DefaultClient.Do(over)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
raw, _ := io.ReadAll(resp.Body)
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusOK || !bytes.Contains(raw, []byte(alice.ID)) || bytes.Contains(raw, []byte(eve.ID)) {
|
||||
t.Fatalf("X-User-Id overrode bearer: %d %s", resp.StatusCode, raw)
|
||||
}
|
||||
|
||||
basic, err := http.NewRequest(http.MethodGet, env.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
basic.SetBasicAuth("alice", testPassword)
|
||||
resp, err = http.DefaultClient.Do(basic)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusUnauthorized || !strings.HasPrefix(resp.Header.Get("WWW-Authenticate"), "Bearer ") {
|
||||
t.Fatalf("basic on business endpoint: %d", resp.StatusCode)
|
||||
}
|
||||
|
||||
status, _, body = do(t, env, http.MethodDelete, env.URL+"/api/v1/auth/sessions/current", alice.ID, nil, nil, "")
|
||||
if status != http.StatusNoContent || len(body) != 0 {
|
||||
t.Fatalf("logout: %d %q", status, body)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("revoked token: %d", status)
|
||||
}
|
||||
status, _, _ = do(t, env, http.MethodDelete, env.URL+"/api/v1/auth/sessions/current", alice.ID, nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("second logout: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSessionExpires(t *testing.T) {
|
||||
env := newServerTTL(t, 2*time.Second)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
time.Sleep(2100 * time.Millisecond)
|
||||
status, _, _ := do(t, env, http.MethodGet, env.URL+"/api/v1/users/me", alice.ID, nil, nil, "")
|
||||
if status != http.StatusUnauthorized {
|
||||
t.Fatalf("expired session: %d", status)
|
||||
}
|
||||
}
|
||||
|
||||
type downSessions struct{ session.Store }
|
||||
|
||||
func (downSessions) Lookup(context.Context, string) (string, time.Time, error) {
|
||||
return "", time.Time{}, session.ErrUnavailable
|
||||
}
|
||||
func (downSessions) Ping(context.Context) error { return session.ErrUnavailable }
|
||||
|
||||
type downStore struct{ store.Repository }
|
||||
|
||||
func (downStore) Ping(context.Context) error { return store.ErrUnavailable }
|
||||
func (downStore) User(context.Context, string) (store.User, error) {
|
||||
return store.User{}, store.ErrUnavailable
|
||||
}
|
||||
|
||||
func TestDependencyDownDoesNotTrustAnonymous(t *testing.T) {
|
||||
env := newServer(t)
|
||||
alice := createUser(t, env, "alice", "Алиса")
|
||||
broken := New(downStore{env.store}, downSessions{env.sess}, password.Params{Time: 1, Memory: 8, Threads: 1}, time.Hour, slog.New(slog.NewJSONHandler(io.Discard, nil)))
|
||||
srv := httptest.NewServer(broken)
|
||||
defer srv.Close()
|
||||
|
||||
live, err := http.Get(srv.URL + "/health/live")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
live.Body.Close()
|
||||
if live.StatusCode != http.StatusOK {
|
||||
t.Fatalf("live: %d", live.StatusCode)
|
||||
}
|
||||
ready, err := http.Get(srv.URL + "/health/ready")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
readyBody, _ := io.ReadAll(ready.Body)
|
||||
ready.Body.Close()
|
||||
if ready.StatusCode != http.StatusServiceUnavailable || !bytes.Contains(readyBody, []byte(`"unavailable"`)) {
|
||||
t.Fatalf("ready: %d %s", ready.StatusCode, readyBody)
|
||||
}
|
||||
|
||||
anon, err := http.Get(srv.URL + "/api/v1/users/me")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
anon.Body.Close()
|
||||
if anon.StatusCode != http.StatusUnauthorized {
|
||||
t.Fatalf("anonymous while down: %d", anon.StatusCode)
|
||||
}
|
||||
authed, err := http.NewRequest(http.MethodGet, srv.URL+"/api/v1/users/me", nil)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
authed.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID])
|
||||
resp, err := http.DefaultClient.Do(authed)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
resp.Body.Close()
|
||||
if resp.StatusCode != http.StatusServiceUnavailable {
|
||||
t.Fatalf("bearer while session store is down: %d", resp.StatusCode)
|
||||
}
|
||||
}
|
||||
|
||||
type statusErr struct {
|
||||
code int
|
||||
body []byte
|
||||
|
||||
Reference in New Issue
Block a user