package api import ( "bytes" "context" "encoding/base64" "encoding/json" "image" "image/png" "io" "log/slog" "net/http" "net/http/httptest" "net/url" "reflect" "strconv" "strings" "sync" "sync/atomic" "testing" "time" "messenger/internal/blob" "messenger/internal/password" "messenger/internal/session" "messenger/internal/store" ) const testPassword = "correct-horse-1" type labServer struct { URL string tokens map[string]string api *API store store.Repository sess session.Store } 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, "test-instance", 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" } var keySeq atomic.Uint64 func nextIdemKey() string { return "k" + strconv.FormatUint(keySeq.Add(1), 36) } func do(t *testing.T, env *labServer, method, url, user string, body any, raw []byte, contentType string, extra ...map[string]string) (int, http.Header, []byte) { t.Helper() var rdr io.Reader if raw != nil { rdr = bytes.NewReader(raw) } else if body != nil { b, err := json.Marshal(body) if err != nil { t.Fatal(err) } rdr = bytes.NewReader(b) } req, err := http.NewRequest(method, url, rdr) if err != nil { t.Fatal(err) } if body != nil || raw != nil { if contentType == "" { contentType = "application/json" } req.Header.Set("Content-Type", contentType) } if tok := env.bearer(user); tok != "" { req.Header.Set("Authorization", "Bearer "+tok) } if len(extra) > 0 { for k, v := range extra[0] { req.Header.Set(k, v) } } if method == http.MethodPost && strings.Contains(url, "/messages") && req.Header.Get("Idempotency-Key") == "" { req.Header.Set("Idempotency-Key", nextIdemKey()) } resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } defer resp.Body.Close() data, err := io.ReadAll(resp.Body) if err != nil { t.Fatal(err) } if resp.Header.Get("X-Request-Id") == "" { t.Fatalf("%s %s: missing X-Request-Id", method, url) } if resp.Header.Get("X-Instance-Id") != "test-instance" { t.Fatalf("%s %s: X-Instance-Id = %q", method, url, resp.Header.Get("X-Instance-Id")) } if resp.StatusCode >= 400 { var env errorEnvelope if err := json.Unmarshal(data, &env); err != nil { t.Fatalf("error json: %v body %s", err, data) } if env.Error.RequestID != resp.Header.Get("X-Request-Id") || env.Error.Code == "" || env.Error.Message == "" { t.Fatalf("bad error envelope: %+v", env) } } return resp.StatusCode, resp.Header, data } func createUser(t *testing.T, env *labServer, username, display string) userJSON { t.Helper() 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, env *labServer, caller, title string, members ...string) chatJSON { t.Helper() 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 { t.Fatalf("create chat: %d %s", status, body) } var c chatJSON if err := json.Unmarshal(body, &c); err != nil { t.Fatal(err) } return c } func TestInvalidJSONExtraFieldAndTypes(t *testing.T) { env := newServer(t) cases := [][]byte{ []byte(`{`), []byte(`{"username":"abc","display_name":"Алиса","extra":1}`), []byte(`{"username":1,"display_name":"Алиса"}`), []byte(`null`), } for _, raw := range cases { 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, 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) { env := newServer(t) bad := [][]byte{ []byte(`{"username":"bad_json","display_name":"Я"}]`), []byte(`{"username":"bad_json","display_name":"Я"}}`), []byte(`{"Username":"bad_case","display_name":"Я"}`), append([]byte(`{"username":"bad_utf","display_name":"`), 0xff, '"', '}'), } for _, raw := range bad { 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, 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, env, alice.ID, "чат", alice.ID) 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, 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, 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, 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, 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) } var page messagePage if err := json.Unmarshal(body, &page); err != nil || page.NextCursor == nil { t.Fatalf("cursor: %v %s", err, body) } decoded, err := base64.RawURLEncoding.DecodeString(*page.NextCursor) if err != nil { t.Fatal(err) } tampered := base64.RawURLEncoding.EncodeToString(append(decoded, []byte("garbage")...)) 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, 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) { 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) } } func TestEmptyMessageForeignChatAndAuth(t *testing.T) { 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, env, http.MethodGet, env.URL+"/api/v1/users/me", "", nil, nil, "") if status != http.StatusUnauthorized { t.Fatalf("missing header: %d", status) } 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, 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, 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, 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, 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, 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, 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) } var msg messageJSON if err := json.Unmarshal(body, &msg); err != nil { t.Fatal(err) } if msg.Text != text || msg.SenderID != alice.ID || msg.ChatID != chat.ID { t.Fatalf("message mutated: %+v", msg) } if !strings.HasSuffix(msg.CreatedAt, "Z") { t.Fatalf("timestamp: %s", msg.CreatedAt) } } func TestPaginationSeveralPages(t *testing.T) { 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++ { sender := alice.ID if i%2 == 1 { sender = bob.ID } 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 { t.Fatalf("post %d: %d %s", i, status, body) } var msg messageJSON if err := json.Unmarshal(body, &msg); err != nil { t.Fatal(err) } ids = append(ids, msg.ID) } var got []string cursor := "" pages := 0 for { pages++ if pages > 10 { t.Fatal("pagination did not finish") } url := env.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=10" if cursor != "" { url += "&cursor=" + cursor } status, _, body := do(t, env, http.MethodGet, url, bob.ID, nil, nil, "") if status != http.StatusOK { t.Fatalf("page: %d %s", status, body) } var page messagePage if err := json.Unmarshal(body, &page); err != nil { t.Fatal(err) } if len(page.Items) == 0 || len(page.Items) > 10 { t.Fatalf("page size %d", len(page.Items)) } for _, item := range page.Items { got = append(got, item.ID) } if page.NextCursor == nil { break } cursor = *page.NextCursor } if pages < 3 { t.Fatalf("expected several pages, got %d", pages) } if strings.Join(got, ",") != strings.Join(ids, ",") { t.Fatalf("order/duplication mismatch\nwant %v\ngot %v", ids, got) } 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, 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) { env := newServer(t) users := make([]userJSON, 10) ids := make([]string, 10) for i := 0; i < 10; i++ { users[i] = createUser(t, env, "u"+string(rune('a'+i))+"x", "Участник") ids[i] = users[i].ID } chat := createChat(t, env, ids[0], "гонка", ids...) var wg sync.WaitGroup errCh := make(chan error, 100) for i := 0; i < 10; i++ { wg.Add(1) go func(user string) { defer wg.Done() for j := 0; j < 10; j++ { 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("Authorization", "Bearer "+env.tokens[user]) req.Header.Set("Idempotency-Key", user+"-"+strconv.Itoa(j)) resp, err := http.DefaultClient.Do(req) if err != nil { errCh <- err return } body, _ := io.ReadAll(resp.Body) resp.Body.Close() if resp.StatusCode != http.StatusCreated { errCh <- &statusErr{resp.StatusCode, body} } } }(ids[i]) } wg.Wait() close(errCh) for err := range errCh { t.Fatal(err) } seen := map[string]struct{}{} cursor := "" for { url := env.URL + "/api/v1/chats/" + chat.ID + "/messages?limit=17" if cursor != "" { url += "&cursor=" + cursor } status, _, body := do(t, env, http.MethodGet, url, ids[3], nil, nil, "") if status != http.StatusOK { t.Fatalf("list: %d %s", status, body) } var page messagePage if err := json.Unmarshal(body, &page); err != nil { t.Fatal(err) } for _, item := range page.Items { if _, ok := seen[item.ID]; ok { t.Fatalf("duplicate %s", item.ID) } seen[item.ID] = struct{}{} } if page.NextCursor == nil { break } cursor = *page.NextCursor } if len(seen) != 100 { t.Fatalf("unique messages = %d, want 100", len(seen)) } } 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, "test-instance", 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) } } func TestIdempotencyReplayConflictAndRace(t *testing.T) { env := newServer(t) alice := createUser(t, env, "alice", "Алиса") bob := createUser(t, env, "bob", "Боб") chat := createChat(t, env, alice.ID, "ключ", alice.ID, bob.ID) path := env.URL + "/api/v1/chats/" + chat.ID + "/messages" key := "same-key-1" status, _, body := do(t, env, http.MethodPost, path, alice.ID, map[string]string{"text": "одно"}, nil, "", map[string]string{"Idempotency-Key": key}) if status != http.StatusCreated { t.Fatalf("first: %d %s", status, body) } var first messageJSON if err := json.Unmarshal(body, &first); err != nil { t.Fatal(err) } status, _, body = do(t, env, http.MethodPost, path, alice.ID, nil, []byte(`{"text":"одно"}`), "application/json", map[string]string{"Idempotency-Key": key}) if status != http.StatusCreated { t.Fatalf("replay: %d %s", status, body) } var replay messageJSON if err := json.Unmarshal(body, &replay); err != nil { t.Fatal(err) } if !reflect.DeepEqual(replay, first) { t.Fatalf("replay changed message: %+v vs %+v", replay, first) } status, _, _ = do(t, env, http.MethodPost, path, alice.ID, map[string]string{"text": "другое"}, nil, "", map[string]string{"Idempotency-Key": key}) if status != http.StatusConflict { t.Fatalf("mismatch: %d", status) } req, err := http.NewRequest(http.MethodPost, path, strings.NewReader(`{"text":"без ключа"}`)) if err != nil { t.Fatal(err) } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID]) resp, err := http.DefaultClient.Do(req) if err != nil { t.Fatal(err) } resp.Body.Close() if resp.StatusCode != http.StatusBadRequest { t.Fatalf("missing key: %d", resp.StatusCode) } status, _, body = do(t, env, http.MethodPost, path, bob.ID, map[string]string{"text": "одно"}, nil, "", map[string]string{"Idempotency-Key": key}) if status != http.StatusCreated { t.Fatalf("other user: %d %s", status, body) } var other messageJSON if err := json.Unmarshal(body, &other); err != nil { t.Fatal(err) } if other.ID == first.ID { t.Fatal("same key for another user reused the message") } raceKey := "race-key" var wg sync.WaitGroup ids := make(chan string, 16) errs := make(chan error, 16) for i := 0; i < 16; i++ { wg.Add(1) go func() { defer wg.Done() req, err := http.NewRequest(http.MethodPost, path, strings.NewReader(`{"text":"гонка"}`)) if err != nil { errs <- err return } req.Header.Set("Content-Type", "application/json") req.Header.Set("Authorization", "Bearer "+env.tokens[alice.ID]) req.Header.Set("Idempotency-Key", raceKey) resp, err := http.DefaultClient.Do(req) if err != nil { errs <- err return } defer resp.Body.Close() raw, _ := io.ReadAll(resp.Body) if resp.StatusCode != http.StatusCreated { errs <- &statusErr{resp.StatusCode, raw} return } var msg messageJSON if err := json.Unmarshal(raw, &msg); err != nil { errs <- err return } ids <- msg.ID }() } wg.Wait() close(ids) close(errs) for err := range errs { t.Fatal(err) } seen := map[string]struct{}{} for id := range ids { seen[id] = struct{}{} } if len(seen) != 1 { t.Fatalf("concurrent same key created %d messages", len(seen)) } } func pngBytes(t *testing.T, w, h int) []byte { t.Helper() img := image.NewNRGBA(image.Rect(0, 0, w, h)) var buf bytes.Buffer if err := png.Encode(&buf, img); err != nil { t.Fatal(err) } return buf.Bytes() } func TestAttachmentRoundTripAndRejections(t *testing.T) { env := newServer(t) env.api.EnableAttachments(blob.NewMemory(), 10*1024*1024, 40_000_000) 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) other := createChat(t, env, alice.ID, "другой", alice.ID) body := pngBytes(t, 4, 3) status, _, raw := do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=a/b.png", alice.ID, nil, body, "image/png") if status != http.StatusBadRequest { t.Fatalf("slash filename: %d %s", status, raw) } status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=note.png", alice.ID, nil, []byte("hello"), "image/png") if status != http.StatusUnsupportedMediaType { t.Fatalf("text as png: %d %s", status, raw) } jpegHeader := []byte{0xff, 0xd8, 0xff, 0xd9} status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=x.png", alice.ID, nil, jpegHeader, "image/png") if status != http.StatusUnsupportedMediaType { t.Fatalf("mime swap: %d %s", status, raw) } status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=pic.png", alice.ID, nil, body, "image/png") if status != http.StatusCreated { t.Fatalf("upload: %d %s", status, raw) } var att attachmentJSON if err := json.Unmarshal(raw, &att); err != nil { t.Fatal(err) } if att.Status != "ready" || att.ErrorCode != nil || att.ChatID != chat.ID || att.OwnerID != alice.ID || len(att.Variants) != 0 { t.Fatalf("metadata: %+v", att) } if bytes.Contains(raw, []byte("object_key")) || bytes.Contains(raw, []byte("\"o/")) { t.Fatalf("key leaked: %s", raw) } status, hdr, got := do(t, env, http.MethodGet, env.URL+"/api/v1/attachments/"+att.ID+"/content", bob.ID, nil, nil, "") if status != http.StatusOK || hdr.Get("Content-Type") != "image/png" || !bytes.Equal(got, body) { t.Fatalf("download: %d %s %d", status, hdr.Get("Content-Type"), len(got)) } status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/attachments/"+att.ID, eve.ID, nil, nil, "") if status != http.StatusNotFound { t.Fatalf("outsider meta: %d", status) } status, _, _ = do(t, env, http.MethodGet, env.URL+"/api/v1/attachments/"+att.ID+"/content", eve.ID, nil, nil, "") if status != http.StatusNotFound { t.Fatalf("outsider bytes: %d", status) } status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+other.ID+"/attachments?filename=other.png", alice.ID, nil, body, "image/png") if status != http.StatusCreated { t.Fatalf("other upload: %d %s", status, raw) } var foreign attachmentJSON if err := json.Unmarshal(raw, &foreign); err != nil { t.Fatal(err) } status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]any{ "text": "", "attachment_ids": []string{foreign.ID}, }, nil, "") if status != http.StatusNotFound { t.Fatalf("foreign attachment: %d %s", status, raw) } status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/messages", alice.ID, map[string]any{ "text": "", "attachment_ids": []string{att.ID}, }, nil, "") if status != http.StatusCreated { t.Fatalf("attach: %d %s", status, raw) } var msg messageJSON if err := json.Unmarshal(raw, &msg); err != nil { t.Fatal(err) } if len(msg.AttachmentIDs) != 1 || msg.AttachmentIDs[0] != att.ID || msg.Text != "" { t.Fatalf("message: %+v", msg) } env.api.EnableAttachments(blob.NewMemory(), 8, 40_000_000) status, _, raw = do(t, env, http.MethodPost, env.URL+"/api/v1/chats/"+chat.ID+"/attachments?filename=big.png", alice.ID, nil, body, "image/png") if status != http.StatusRequestEntityTooLarge { t.Fatalf("small cap: %d %s", status, raw) } } type statusErr struct { code int body []byte } func (e *statusErr) Error() string { return http.StatusText(e.code) + " " + string(e.body) }