forked from mtusi2026/mtusi2026lab4
S3-вложения и сверка Postgresql с MinIO
This commit is contained in:
@@ -0,0 +1,277 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/blob"
|
||||
"messenger/internal/imagecheck"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
type attachmentJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
OwnerID string `json:"owner_id"`
|
||||
Filename string `json:"filename"`
|
||||
ContentType string `json:"content_type"`
|
||||
SizeBytes int64 `json:"size_bytes"`
|
||||
SHA256 string `json:"sha256"`
|
||||
Status string `json:"status"`
|
||||
Variants []struct{} `json:"variants"`
|
||||
ErrorCode *string `json:"error_code"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
UpdatedAt string `json:"updated_at"`
|
||||
}
|
||||
|
||||
func (a *API) routeAttachment(w http.ResponseWriter, r *http.Request, rest string) {
|
||||
if _, ok := a.authenticate(w, r); !ok {
|
||||
return
|
||||
}
|
||||
rest = strings.Trim(rest, "/")
|
||||
if rest == "" || strings.Count(rest, "/") > 1 {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
id, content, hasContent := strings.Cut(rest, "/")
|
||||
if hasContent && content != "content" {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
if _, ok := canonicalUUID(id); !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return
|
||||
}
|
||||
if r.Method != http.MethodGet {
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
return
|
||||
}
|
||||
if hasContent {
|
||||
a.downloadAttachment(w, r, id)
|
||||
return
|
||||
}
|
||||
a.getAttachment(w, r, id)
|
||||
}
|
||||
|
||||
func (a *API) uploadAttachment(w http.ResponseWriter, r *http.Request, rawChatID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
chatID, ok := a.chatID(w, r, rawChatID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), chatID, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
filename := r.URL.Query().Get("filename")
|
||||
if !validFilename(filename) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректное имя файла", 0)
|
||||
return
|
||||
}
|
||||
media := ""
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
media = strings.ToLower(strings.TrimSpace(strings.Split(ct, ";")[0]))
|
||||
}
|
||||
if media != "image/png" && media != "image/jpeg" {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен PNG или JPEG", 0)
|
||||
return
|
||||
}
|
||||
// Не отвечаем до чтения: иначе клиент ещё шлёт тело и видит обрыв вместо 413.
|
||||
// Читаем не больше лимита плюс один байт. Лишний байт - отказ, без записи в bucket.
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxUpload+1))
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Загрузка прервана", 0)
|
||||
return
|
||||
}
|
||||
if int64(len(body)) > a.maxUpload {
|
||||
a.fail(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "Файл больше 10 МиБ", 0)
|
||||
return
|
||||
}
|
||||
if len(body) == 0 {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Пустое изображение", 0)
|
||||
return
|
||||
}
|
||||
width, height, err := imagecheck.Inspect(media, body, a.maxPixels)
|
||||
if err != nil {
|
||||
if errors.Is(err, imagecheck.ErrPixels) {
|
||||
a.fail(w, r, http.StatusRequestEntityTooLarge, "payload_too_large", "Слишком много пикселей", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Файл не является PNG или JPEG", 0)
|
||||
return
|
||||
}
|
||||
sum := sha256.Sum256(body)
|
||||
key, err := newObjectKey()
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
if err := a.blobs.Put(r.Context(), key, media, body); err != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
row, err := a.store.InsertAttachment(r.Context(), store.Attachment{
|
||||
ChatID: chatID,
|
||||
OwnerID: user.ID,
|
||||
Filename: filename,
|
||||
ContentType: media,
|
||||
SizeBytes: int64(len(body)),
|
||||
SHA256: hex.EncodeToString(sum[:]),
|
||||
ObjectKey: key,
|
||||
Width: width,
|
||||
Height: height,
|
||||
})
|
||||
if err != nil {
|
||||
// PUT уже прошёл, COMMIT нет: сразу убираем объект. Если удаление не удалось,
|
||||
// ключ останется сиротой до сверки и не попадёт в ответ 201.
|
||||
if delErr := a.blobs.Delete(r.Context(), key); delErr != nil {
|
||||
a.log.Error("orphan object", "request_id", requestIDFrom(r))
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asAttachment(row))
|
||||
}
|
||||
|
||||
func (a *API) getAttachment(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
row, ok := a.visibleAttachment(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asAttachment(row))
|
||||
}
|
||||
|
||||
func (a *API) downloadAttachment(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
row, ok := a.visibleAttachment(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
variant := "original"
|
||||
if r.URL.Query().Has("variant") {
|
||||
variant = r.URL.Query().Get("variant")
|
||||
}
|
||||
switch variant {
|
||||
case "original":
|
||||
case "thumbnail", "crop", "optimized":
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
default:
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный вариант", 0)
|
||||
return
|
||||
}
|
||||
if a.blobs == nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
rc, err := a.blobs.Get(r.Context(), row.ObjectKey)
|
||||
if err != nil {
|
||||
if errors.Is(err, blob.ErrNotFound) {
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
defer rc.Close()
|
||||
w.Header().Set("Content-Type", row.ContentType)
|
||||
w.Header().Set("Content-Length", strconv.FormatInt(row.SizeBytes, 10))
|
||||
w.WriteHeader(http.StatusOK)
|
||||
if _, err := io.Copy(w, rc); err != nil {
|
||||
a.log.Error("download", "request_id", requestIDFrom(r))
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) visibleAttachment(w http.ResponseWriter, r *http.Request, rawID string) (store.Attachment, bool) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return store.Attachment{}, false
|
||||
}
|
||||
id, ok := canonicalUUID(rawID)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return store.Attachment{}, false
|
||||
}
|
||||
row, err := a.store.AttachmentVisible(r.Context(), id, user.ID)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return store.Attachment{}, false
|
||||
}
|
||||
return row, true
|
||||
}
|
||||
|
||||
func (a *API) attachmentIDList(w http.ResponseWriter, r *http.Request, raw []string) ([]string, bool) {
|
||||
if len(raw) > 10 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Слишком много вложений", 0)
|
||||
return nil, false
|
||||
}
|
||||
seen := make(map[string]struct{}, len(raw))
|
||||
out := make([]string, 0, len(raw))
|
||||
for _, item := range raw {
|
||||
id, ok := canonicalUUID(item)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор вложения", 0)
|
||||
return nil, false
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Повторяющееся вложение", 0)
|
||||
return nil, false
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
out = append(out, id)
|
||||
}
|
||||
return out, true
|
||||
}
|
||||
|
||||
func asAttachment(row store.Attachment) attachmentJSON {
|
||||
return attachmentJSON{
|
||||
ID: row.ID,
|
||||
ChatID: row.ChatID,
|
||||
OwnerID: row.OwnerID,
|
||||
Filename: row.Filename,
|
||||
ContentType: row.ContentType,
|
||||
SizeBytes: row.SizeBytes,
|
||||
SHA256: row.SHA256,
|
||||
Status: row.Status,
|
||||
Variants: []struct{}{},
|
||||
ErrorCode: nil,
|
||||
CreatedAt: formatTime(row.CreatedAt),
|
||||
UpdatedAt: formatTime(row.UpdatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func validFilename(name string) bool {
|
||||
if !utf8.ValidString(name) {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(name)
|
||||
if n < 1 || n > 255 {
|
||||
return false
|
||||
}
|
||||
for _, r := range name {
|
||||
if r < 0x20 || r == 0x7f || r == '/' || r == '\\' {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func newObjectKey() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return "o/" + hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
@@ -0,0 +1,182 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"errors"
|
||||
"io"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
func (a *API) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
if !emptyBody(r) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "У входа не должно быть тела", 0)
|
||||
return
|
||||
}
|
||||
username, plain, ok := parseBasic(r)
|
||||
if !ok || !usernameRe.MatchString(username) || !validPassword(plain) {
|
||||
a.unauthorized(w, r, basicChallenge)
|
||||
return
|
||||
}
|
||||
user, hash, err := a.store.UserByUsername(r.Context(), username)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
password.Verify(plain, a.dummyHash)
|
||||
a.unauthorized(w, r, basicChallenge)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
if !password.Verify(plain, hash) {
|
||||
a.unauthorized(w, r, basicChallenge)
|
||||
return
|
||||
}
|
||||
token, err := newToken()
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
expires := time.Now().UTC().Add(a.sessionTTL).Truncate(time.Microsecond)
|
||||
if err := a.sessions.Create(r.Context(), token, user.ID, expires); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, map[string]any{
|
||||
"token": token,
|
||||
"token_type": "Bearer",
|
||||
"expires_at": formatTime(expires),
|
||||
"user": asUser(user),
|
||||
})
|
||||
}
|
||||
|
||||
func (a *API) revokeSession(w http.ResponseWriter, r *http.Request) {
|
||||
token, ok := a.bearerToken(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, _, err := a.sessions.Lookup(r.Context(), token); err != nil {
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return
|
||||
}
|
||||
a.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
if err := a.sessions.Revoke(r.Context(), token); err != nil {
|
||||
if errors.Is(err, session.ErrNotFound) {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return
|
||||
}
|
||||
a.writeStoreErr(w, r, err)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func (a *API) authenticate(w http.ResponseWriter, r *http.Request) (store.User, bool) {
|
||||
token, ok := a.bearerToken(w, r)
|
||||
if !ok {
|
||||
return store.User{}, false
|
||||
}
|
||||
userID, expires, err := a.sessions.Lookup(r.Context(), token)
|
||||
if errors.Is(err, session.ErrNotFound) || (err == nil && !time.Now().Before(expires)) {
|
||||
if err == nil {
|
||||
_ = a.sessions.Revoke(r.Context(), token)
|
||||
}
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return store.User{}, false
|
||||
}
|
||||
if err != nil {
|
||||
a.writeStoreErr(w, r, err)
|
||||
return store.User{}, false
|
||||
}
|
||||
user, err := a.store.User(r.Context(), userID)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return store.User{}, false
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return store.User{}, false
|
||||
}
|
||||
return user, true
|
||||
}
|
||||
|
||||
func (a *API) bearerToken(w http.ResponseWriter, r *http.Request) (string, bool) {
|
||||
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
|
||||
if !ok || !strings.EqualFold(scheme, "Bearer") || param == "" || len(param) > 512 || strings.Contains(param, " ") {
|
||||
a.unauthorized(w, r, bearerChallenge)
|
||||
return "", false
|
||||
}
|
||||
return param, true
|
||||
}
|
||||
|
||||
func (a *API) unauthorized(w http.ResponseWriter, r *http.Request, challenge string) {
|
||||
w.Header().Set("WWW-Authenticate", challenge)
|
||||
a.fail(w, r, http.StatusUnauthorized, "unauthorized", "Нет действительной идентификации", 0)
|
||||
}
|
||||
|
||||
func parseBasic(r *http.Request) (string, string, bool) {
|
||||
scheme, param, ok := splitAuth(r.Header.Get("Authorization"))
|
||||
if !ok || !strings.EqualFold(scheme, "Basic") || param == "" {
|
||||
return "", "", false
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(param)
|
||||
if err != nil {
|
||||
raw, err = base64.RawStdEncoding.DecodeString(param)
|
||||
if err != nil {
|
||||
return "", "", false
|
||||
}
|
||||
}
|
||||
if !utf8.Valid(raw) {
|
||||
return "", "", false
|
||||
}
|
||||
username, plain, ok := strings.Cut(string(raw), ":")
|
||||
if !ok || username == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return username, plain, true
|
||||
}
|
||||
|
||||
func splitAuth(header string) (string, string, bool) {
|
||||
scheme, param, ok := strings.Cut(strings.TrimSpace(header), " ")
|
||||
if !ok {
|
||||
return "", "", false
|
||||
}
|
||||
param = strings.TrimSpace(param)
|
||||
if scheme == "" || param == "" {
|
||||
return "", "", false
|
||||
}
|
||||
return scheme, param, true
|
||||
}
|
||||
|
||||
func emptyBody(r *http.Request) bool {
|
||||
if r.Body == nil || r.ContentLength == 0 {
|
||||
return true
|
||||
}
|
||||
buf := make([]byte, 1)
|
||||
n, err := r.Body.Read(buf)
|
||||
if n > 0 {
|
||||
return false
|
||||
}
|
||||
return err == io.EOF || err == nil
|
||||
}
|
||||
|
||||
func newToken() (string, error) {
|
||||
var b [32]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return "", err
|
||||
}
|
||||
return hex.EncodeToString(b[:]), nil
|
||||
}
|
||||
@@ -0,0 +1,365 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
func (a *API) live(w http.ResponseWriter, _ *http.Request) {
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) ready(w http.ResponseWriter, r *http.Request) {
|
||||
if a.shutting.Load() {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
||||
return
|
||||
}
|
||||
ctx, cancel := context.WithTimeout(r.Context(), 800*time.Millisecond)
|
||||
defer cancel()
|
||||
if err := a.store.Ping(ctx); err != nil || a.sessions.Ping(ctx) != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
if a.blobs != nil {
|
||||
if err := a.blobs.Ping(ctx); err != nil {
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
return
|
||||
}
|
||||
}
|
||||
writeJSON(w, http.StatusOK, map[string]string{"status": "ok"})
|
||||
}
|
||||
|
||||
func (a *API) route(w http.ResponseWriter, r *http.Request) {
|
||||
path := r.URL.Path
|
||||
switch {
|
||||
case path == "/api/v1/users" && r.Method == http.MethodPost:
|
||||
a.createUser(w, r)
|
||||
case path == "/api/v1/users/me" && r.Method == http.MethodGet:
|
||||
a.currentUser(w, r)
|
||||
case path == "/api/v1/auth/sessions" && r.Method == http.MethodPost:
|
||||
a.createSession(w, r)
|
||||
case path == "/api/v1/auth/sessions/current" && r.Method == http.MethodDelete:
|
||||
a.revokeSession(w, r)
|
||||
case path == "/api/v1/chats" && r.Method == http.MethodPost:
|
||||
a.createChat(w, r)
|
||||
case path == "/api/v1/chats" && r.Method == http.MethodGet:
|
||||
a.listChats(w, r)
|
||||
default:
|
||||
if strings.HasPrefix(path, "/api/v1/attachments/") {
|
||||
a.routeAttachment(w, r, strings.TrimPrefix(path, "/api/v1/attachments/"))
|
||||
return
|
||||
}
|
||||
chatID, kind, ok := splitChatPath(path)
|
||||
if !ok {
|
||||
if knownWrongMethod(path) {
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
return
|
||||
}
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
return
|
||||
}
|
||||
switch kind {
|
||||
case "":
|
||||
if r.Method == http.MethodGet {
|
||||
a.getChat(w, r, chatID)
|
||||
return
|
||||
}
|
||||
case "messages":
|
||||
switch r.Method {
|
||||
case http.MethodPost:
|
||||
a.createMessage(w, r, chatID)
|
||||
return
|
||||
case http.MethodGet:
|
||||
a.listMessages(w, r, chatID)
|
||||
return
|
||||
}
|
||||
case "attachments":
|
||||
if r.Method == http.MethodPost {
|
||||
a.uploadAttachment(w, r, chatID)
|
||||
return
|
||||
}
|
||||
}
|
||||
a.fail(w, r, http.StatusMethodNotAllowed, "invalid_request", "Метод не поддерживается", 0)
|
||||
}
|
||||
}
|
||||
|
||||
func knownWrongMethod(path string) bool {
|
||||
switch path {
|
||||
case "/api/v1/users", "/api/v1/users/me", "/api/v1/chats",
|
||||
"/api/v1/auth/sessions", "/api/v1/auth/sessions/current":
|
||||
return true
|
||||
default:
|
||||
return false
|
||||
}
|
||||
}
|
||||
|
||||
func (a *API) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var body struct {
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
Password string `json:"password"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !usernameRe.MatchString(body.Username) || !validText(body.DisplayName, 1, 100) || !validPassword(body.Password) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля пользователя", 0)
|
||||
return
|
||||
}
|
||||
hash, err := a.hasher.Hash(body.Password)
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
return
|
||||
}
|
||||
user, err := a.store.CreateUser(r.Context(), body.Username, body.DisplayName, hash)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asUser(user))
|
||||
}
|
||||
|
||||
func (a *API) currentUser(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asUser(user))
|
||||
}
|
||||
|
||||
func (a *API) createChat(w http.ResponseWriter, r *http.Request) {
|
||||
caller, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
if !validText(body.Title, 1, 100) || len(body.MemberIDs) < 1 || len(body.MemberIDs) > 100 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные поля чата", 0)
|
||||
return
|
||||
}
|
||||
ids := make([]string, len(body.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(body.MemberIDs))
|
||||
callerIn := false
|
||||
for i, raw := range body.MemberIDs {
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if _, dup := seen[id]; dup {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
_, err := a.store.User(r.Context(), id)
|
||||
if errors.Is(err, store.ErrNotFound) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
if id == caller.ID {
|
||||
callerIn = true
|
||||
}
|
||||
ids[i] = id
|
||||
}
|
||||
if !callerIn {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
chat, err := a.store.CreateChat(r.Context(), body.Title, ids, caller.ID)
|
||||
if errors.Is(err, store.ErrInvalid) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный список участников", 0)
|
||||
return
|
||||
}
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) listChats(w http.ResponseWriter, r *http.Request) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
limit, cur, ok := a.pageQuery(w, r, "chats:"+user.ID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, hasMore, err := a.store.ListChats(r.Context(), user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]chatJSON, 0, len(items))
|
||||
for _, c := range items {
|
||||
out = append(out, asChat(c))
|
||||
}
|
||||
var next *string
|
||||
if hasMore && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := encodeCursor(cursorPayload{Scope: "chats:" + user.ID, ID: last.ID, At: formatTime(last.CreatedAt)})
|
||||
next = &encoded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, chatPage{Items: out, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *API) getChat(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatFor(r.Context(), id, user.ID)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusOK, asChat(chat))
|
||||
}
|
||||
|
||||
func (a *API) createMessage(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
idemKey := r.Header.Get("Idempotency-Key")
|
||||
if !idemKeyRe.MatchString(idemKey) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Нужен заголовок Idempotency-Key", 0)
|
||||
return
|
||||
}
|
||||
var body struct {
|
||||
Text string `json:"text"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
if !a.readJSON(w, r, &body) {
|
||||
return
|
||||
}
|
||||
ids, ok := a.attachmentIDList(w, r, body.AttachmentIDs)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if !validMessageText(body.Text, len(ids)) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный текст сообщения", 0)
|
||||
return
|
||||
}
|
||||
// Отпечаток — разобранные поля, не сырые байты: порядок ключей JSON и отсутствующий attachment_ids равны пустому списку.
|
||||
msg, err := a.store.AddMessage(r.Context(), id, user.ID, body.Text, ids, idemKey, messageFingerprint(body.Text, ids))
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
writeJSON(w, http.StatusCreated, asMessage(msg))
|
||||
}
|
||||
|
||||
func (a *API) listMessages(w http.ResponseWriter, r *http.Request, rawID string) {
|
||||
user, ok := a.authenticate(w, r)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
id, ok := a.chatID(w, r, rawID)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
if _, err := a.store.ChatFor(r.Context(), id, user.ID); a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
limit, cur, ok := a.pageQuery(w, r, "msg:"+id)
|
||||
if !ok {
|
||||
return
|
||||
}
|
||||
items, hasMore, err := a.store.ListMessages(r.Context(), id, user.ID, cur, limit)
|
||||
if a.writeStoreErr(w, r, err) {
|
||||
return
|
||||
}
|
||||
out := make([]messageJSON, 0, len(items))
|
||||
for _, m := range items {
|
||||
out = append(out, asMessage(m))
|
||||
}
|
||||
var next *string
|
||||
if hasMore && len(items) > 0 {
|
||||
last := items[len(items)-1]
|
||||
encoded := encodeCursor(cursorPayload{Scope: "msg:" + id, ID: last.ID, At: formatTime(last.CreatedAt)})
|
||||
next = &encoded
|
||||
}
|
||||
writeJSON(w, http.StatusOK, messagePage{Items: out, NextCursor: next})
|
||||
}
|
||||
|
||||
func (a *API) chatID(w http.ResponseWriter, r *http.Request, raw string) (string, bool) {
|
||||
id, ok := canonicalUUID(raw)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный идентификатор", 0)
|
||||
return "", false
|
||||
}
|
||||
return id, true
|
||||
}
|
||||
|
||||
func (a *API) writeStoreErr(w http.ResponseWriter, r *http.Request, err error) bool {
|
||||
if err == nil {
|
||||
return false
|
||||
}
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnavailable), errors.Is(err, session.ErrUnavailable):
|
||||
a.fail(w, r, http.StatusServiceUnavailable, "unavailable", "Сервис временно недоступен", 1)
|
||||
case errors.Is(err, store.ErrIdempotencyMismatch):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Этот ключ уже использован для другого сообщения", 0)
|
||||
case errors.Is(err, store.ErrConflict):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Имя пользователя уже занято", 0)
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.fail(w, r, http.StatusNotFound, "not_found", "Объект не найден", 0)
|
||||
case errors.Is(err, store.ErrNotReady):
|
||||
a.fail(w, r, http.StatusConflict, "conflict", "Вложение нельзя прикрепить", 0)
|
||||
case errors.Is(err, store.ErrInvalid):
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректные данные", 0)
|
||||
case errors.Is(err, store.ErrBadCursor):
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
default:
|
||||
a.log.Error("store", "request_id", requestIDFrom(r))
|
||||
a.fail(w, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func splitChatPath(path string) (id, kind string, ok bool) {
|
||||
const prefix = "/api/v1/chats/"
|
||||
if !strings.HasPrefix(path, prefix) {
|
||||
return "", "", false
|
||||
}
|
||||
rest := strings.TrimPrefix(path, prefix)
|
||||
if rest == "" {
|
||||
return "", "", false
|
||||
}
|
||||
for _, suffix := range []string{"/messages", "/attachments"} {
|
||||
if strings.HasSuffix(rest, suffix) {
|
||||
id = strings.TrimSuffix(rest, suffix)
|
||||
if id == "" || strings.Contains(id, "/") {
|
||||
return "", "", false
|
||||
}
|
||||
return id, strings.TrimPrefix(suffix, "/"), true
|
||||
}
|
||||
}
|
||||
if strings.Contains(rest, "/") {
|
||||
return "", "", false
|
||||
}
|
||||
return rest, "", true
|
||||
}
|
||||
@@ -0,0 +1,338 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"crypto/rand"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"reflect"
|
||||
"regexp"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
"unicode/utf8"
|
||||
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
var usernameRe = regexp.MustCompile(`^[a-z0-9_]{3,32}$`)
|
||||
var uuidRe = regexp.MustCompile(`(?i)^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$`)
|
||||
var limitRe = regexp.MustCompile(`^[0-9]{1,3}$`)
|
||||
var requestIDRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,64}$`)
|
||||
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorObject `json:"error"`
|
||||
}
|
||||
|
||||
type errorObject struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
type userJSON struct {
|
||||
ID string `json:"id"`
|
||||
Username string `json:"username"`
|
||||
DisplayName string `json:"display_name"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type chatJSON struct {
|
||||
ID string `json:"id"`
|
||||
Title string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
}
|
||||
|
||||
type messageJSON struct {
|
||||
ID string `json:"id"`
|
||||
ChatID string `json:"chat_id"`
|
||||
SenderID string `json:"sender_id"`
|
||||
Text string `json:"text"`
|
||||
CreatedAt string `json:"created_at"`
|
||||
AttachmentIDs []string `json:"attachment_ids"`
|
||||
}
|
||||
|
||||
type chatPage struct {
|
||||
Items []chatJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type messagePage struct {
|
||||
Items []messageJSON `json:"items"`
|
||||
NextCursor *string `json:"next_cursor"`
|
||||
}
|
||||
|
||||
type cursorPayload struct {
|
||||
Scope string `json:"scope"`
|
||||
ID string `json:"id"`
|
||||
At string `json:"at"`
|
||||
}
|
||||
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (s *statusWriter) WriteHeader(code int) {
|
||||
if s.wrote {
|
||||
return
|
||||
}
|
||||
s.status = code
|
||||
s.wrote = true
|
||||
s.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (s *statusWriter) Write(b []byte) (int, error) {
|
||||
if !s.wrote {
|
||||
s.WriteHeader(http.StatusOK)
|
||||
}
|
||||
return s.ResponseWriter.Write(b)
|
||||
}
|
||||
|
||||
func (a *API) fail(w http.ResponseWriter, r *http.Request, status int, code, message string, retryAfter int) {
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", strconv.Itoa(retryAfter))
|
||||
}
|
||||
writeJSON(w, status, errorEnvelope{Error: errorObject{
|
||||
Code: code,
|
||||
Message: message,
|
||||
RequestID: requestIDFrom(r),
|
||||
}})
|
||||
}
|
||||
|
||||
func writeJSON(w http.ResponseWriter, status int, v any) {
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.WriteHeader(status)
|
||||
enc := json.NewEncoder(w)
|
||||
enc.SetEscapeHTML(false)
|
||||
_ = enc.Encode(v)
|
||||
}
|
||||
|
||||
func (a *API) readJSON(w http.ResponseWriter, r *http.Request, dst any) bool {
|
||||
media := ""
|
||||
if ct := r.Header.Get("Content-Type"); ct != "" {
|
||||
media = strings.TrimSpace(strings.Split(ct, ";")[0])
|
||||
}
|
||||
if !strings.EqualFold(media, "application/json") {
|
||||
a.fail(w, r, http.StatusUnsupportedMediaType, "unsupported_media_type", "Нужен Content-Type application/json", 0)
|
||||
return false
|
||||
}
|
||||
body, err := io.ReadAll(r.Body)
|
||||
if err != nil || !utf8.Valid(body) || !decodeExactJSON(body, dst) {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный JSON", 0)
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// decodeExactJSON принимает один JSON-объект: точные имена полей, без хвоста и без замены битого UTF-8.
|
||||
func decodeExactJSON(body []byte, dst any) bool {
|
||||
dec := json.NewDecoder(bytes.NewReader(body))
|
||||
var fields map[string]json.RawMessage
|
||||
if err := dec.Decode(&fields); err != nil || fields == nil {
|
||||
return false
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := dec.Decode(&trailing); err != io.EOF {
|
||||
return false
|
||||
}
|
||||
allowed, ok := jsonFieldNames(dst)
|
||||
if !ok {
|
||||
return false
|
||||
}
|
||||
for name := range fields {
|
||||
if _, ok := allowed[name]; !ok {
|
||||
return false
|
||||
}
|
||||
}
|
||||
return json.Unmarshal(body, dst) == nil
|
||||
}
|
||||
|
||||
func jsonFieldNames(dst any) (map[string]struct{}, bool) {
|
||||
t := reflect.TypeOf(dst)
|
||||
if t == nil || t.Kind() != reflect.Pointer {
|
||||
return nil, false
|
||||
}
|
||||
t = t.Elem()
|
||||
if t.Kind() != reflect.Struct {
|
||||
return nil, false
|
||||
}
|
||||
names := make(map[string]struct{}, t.NumField())
|
||||
for i := 0; i < t.NumField(); i++ {
|
||||
name, _, _ := strings.Cut(t.Field(i).Tag.Get("json"), ",")
|
||||
if name == "" || name == "-" {
|
||||
return nil, false
|
||||
}
|
||||
names[name] = struct{}{}
|
||||
}
|
||||
return names, true
|
||||
}
|
||||
|
||||
func validPassword(s string) bool {
|
||||
if !utf8.ValidString(s) {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= 12 && n <= 128 && strings.TrimSpace(s) != ""
|
||||
}
|
||||
|
||||
func (a *API) pageQuery(w http.ResponseWriter, r *http.Request, scope string) (int, *store.Cursor, bool) {
|
||||
q := r.URL.Query()
|
||||
limit := 50
|
||||
if q.Has("limit") {
|
||||
raw := q.Get("limit")
|
||||
n, err := strconv.Atoi(raw)
|
||||
if err != nil || !limitRe.MatchString(raw) || n < 1 || n > 100 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный limit", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
limit = n
|
||||
}
|
||||
if !q.Has("cursor") {
|
||||
return limit, nil, true
|
||||
}
|
||||
raw := q.Get("cursor")
|
||||
if raw == "" || len(raw) > 512 {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
payload, err := decodeCursor(raw)
|
||||
if err != nil || payload.Scope != scope || payload.ID == "" || payload.At == "" {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
at, err := time.Parse("2006-01-02T15:04:05.000000Z", payload.At)
|
||||
if err != nil {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
id, ok := canonicalUUID(payload.ID)
|
||||
if !ok {
|
||||
a.fail(w, r, http.StatusBadRequest, "invalid_request", "Некорректный cursor", 0)
|
||||
return 0, nil, false
|
||||
}
|
||||
return limit, &store.Cursor{ID: id, At: at}, true
|
||||
}
|
||||
|
||||
func asUser(u store.User) userJSON {
|
||||
return userJSON{
|
||||
ID: u.ID,
|
||||
Username: u.Username,
|
||||
DisplayName: u.DisplayName,
|
||||
CreatedAt: formatTime(u.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func asChat(c store.Chat) chatJSON {
|
||||
ids := c.MemberIDs
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
return chatJSON{
|
||||
ID: c.ID,
|
||||
Title: c.Title,
|
||||
MemberIDs: ids,
|
||||
CreatedAt: formatTime(c.CreatedAt),
|
||||
}
|
||||
}
|
||||
|
||||
func asMessage(m store.Message) messageJSON {
|
||||
ids := m.AttachmentIDs
|
||||
if ids == nil {
|
||||
ids = []string{}
|
||||
}
|
||||
return messageJSON{
|
||||
ID: m.ID,
|
||||
ChatID: m.ChatID,
|
||||
SenderID: m.SenderID,
|
||||
Text: m.Text,
|
||||
CreatedAt: formatTime(m.CreatedAt),
|
||||
AttachmentIDs: ids,
|
||||
}
|
||||
}
|
||||
|
||||
func messageFingerprint(text string, ids []string) string {
|
||||
if len(ids) == 0 {
|
||||
return text + "\n"
|
||||
}
|
||||
return text + "\n" + strings.Join(ids, ",")
|
||||
}
|
||||
|
||||
func validMessageText(text string, attachments int) bool {
|
||||
if utf8.RuneCountInString(text) > 4000 {
|
||||
return false
|
||||
}
|
||||
if strings.TrimSpace(text) == "" {
|
||||
return text == "" && attachments > 0
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
func formatTime(t time.Time) string {
|
||||
return t.UTC().Format("2006-01-02T15:04:05.000000Z")
|
||||
}
|
||||
|
||||
func canonicalUUID(s string) (string, bool) {
|
||||
if !uuidRe.MatchString(s) {
|
||||
return "", false
|
||||
}
|
||||
return strings.ToLower(s), true
|
||||
}
|
||||
|
||||
func validText(s string, min, max int) bool {
|
||||
if strings.TrimSpace(s) == "" {
|
||||
return false
|
||||
}
|
||||
n := utf8.RuneCountInString(s)
|
||||
return n >= min && n <= max
|
||||
}
|
||||
|
||||
func requestID(r *http.Request) string {
|
||||
incoming := strings.TrimSpace(r.Header.Get("X-Request-Id"))
|
||||
if requestIDRe.MatchString(incoming) {
|
||||
return incoming
|
||||
}
|
||||
var b [16]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
return strconv.FormatInt(time.Now().UnixNano(), 36)
|
||||
}
|
||||
return hex.EncodeToString(b[:])
|
||||
}
|
||||
|
||||
func encodeCursor(p cursorPayload) string {
|
||||
raw, err := json.Marshal(p)
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
return base64.RawURLEncoding.EncodeToString(raw)
|
||||
}
|
||||
|
||||
func decodeCursor(s string) (cursorPayload, error) {
|
||||
b, err := base64.RawURLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
b, err = base64.URLEncoding.DecodeString(s)
|
||||
if err != nil {
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
}
|
||||
dec := json.NewDecoder(bytes.NewReader(b))
|
||||
dec.DisallowUnknownFields()
|
||||
var p cursorPayload
|
||||
if err := dec.Decode(&p); err != nil {
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
var trailing json.RawMessage
|
||||
if err := dec.Decode(&trailing); err != io.EOF {
|
||||
if err == nil {
|
||||
err = io.ErrUnexpectedEOF
|
||||
}
|
||||
return cursorPayload{}, err
|
||||
}
|
||||
return p, nil
|
||||
}
|
||||
@@ -0,0 +1,130 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"messenger/internal/blob"
|
||||
"messenger/internal/password"
|
||||
"messenger/internal/session"
|
||||
"messenger/internal/store"
|
||||
)
|
||||
|
||||
type ctxKey struct{}
|
||||
|
||||
type API struct {
|
||||
store store.Repository
|
||||
sessions session.Store
|
||||
hasher password.Params
|
||||
dummyHash string
|
||||
sessionTTL time.Duration
|
||||
instanceID string
|
||||
log *slog.Logger
|
||||
shutting atomic.Bool
|
||||
blobs blob.Store
|
||||
maxUpload int64
|
||||
maxPixels int
|
||||
}
|
||||
|
||||
// New связывает HTTP с хранилищем и сессиями.
|
||||
// dummyHash нужен, чтобы несуществующий username тратил столько же KDF, сколько существующий.
|
||||
func New(st store.Repository, sessions session.Store, hasher password.Params, sessionTTL time.Duration, instanceID string, log *slog.Logger) *API {
|
||||
if log == nil {
|
||||
log = slog.Default()
|
||||
}
|
||||
if sessionTTL <= 0 {
|
||||
sessionTTL = time.Hour
|
||||
}
|
||||
if instanceID == "" {
|
||||
instanceID = "api"
|
||||
}
|
||||
dummy, err := hasher.Hash("dummy-password-not-a-login")
|
||||
if err != nil {
|
||||
// Параметры KDF проверяются на старте. Пустая строка заставит Verify сразу вернуть false.
|
||||
dummy = ""
|
||||
}
|
||||
return &API{
|
||||
store: st,
|
||||
sessions: sessions,
|
||||
hasher: hasher,
|
||||
dummyHash: dummy,
|
||||
sessionTTL: sessionTTL,
|
||||
instanceID: instanceID,
|
||||
log: log,
|
||||
}
|
||||
}
|
||||
|
||||
// EnableAttachments подключает приватный bucket и жёсткие лимиты загрузки.
|
||||
// maxUpload не может превысить 10 МиБ контракта.
|
||||
func (a *API) EnableAttachments(objects blob.Store, maxUpload int64, maxPixels int) {
|
||||
const contractMax = 10 * 1024 * 1024
|
||||
if maxUpload <= 0 || maxUpload > contractMax {
|
||||
maxUpload = contractMax
|
||||
}
|
||||
if maxPixels <= 0 || maxPixels > 40_000_000 {
|
||||
maxPixels = 40_000_000
|
||||
}
|
||||
a.blobs = objects
|
||||
a.maxUpload = maxUpload
|
||||
a.maxPixels = maxPixels
|
||||
}
|
||||
|
||||
// BeginShutdown переводит /health/ready в 503 и говорит новым бизнес-запросам
|
||||
// отказать до закрытия слушателя. Уже принятые обработчики дорабатывают.
|
||||
func (a *API) BeginShutdown() {
|
||||
a.shutting.Store(true)
|
||||
a.log.Info("shutdown started")
|
||||
}
|
||||
|
||||
// Точка входа
|
||||
func (a *API) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
sw := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
start := time.Now()
|
||||
id := requestID(r)
|
||||
sw.Header().Set("X-Request-Id", id)
|
||||
sw.Header().Set("X-Instance-Id", a.instanceID)
|
||||
r = r.WithContext(context.WithValue(r.Context(), ctxKey{}, id))
|
||||
|
||||
defer func() {
|
||||
if p := recover(); p != nil {
|
||||
a.log.Error("panic", "request_id", id)
|
||||
if !sw.wrote {
|
||||
a.fail(sw, r, http.StatusInternalServerError, "internal_error", "Внутренняя ошибка", 0)
|
||||
}
|
||||
}
|
||||
a.log.Info("request",
|
||||
"request_id", id,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", sw.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
"bytes_in", r.ContentLength,
|
||||
)
|
||||
}()
|
||||
|
||||
switch {
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/health/live":
|
||||
a.live(sw, r)
|
||||
return
|
||||
case r.Method == http.MethodGet && r.URL.Path == "/health/ready":
|
||||
a.ready(sw, r)
|
||||
return
|
||||
}
|
||||
|
||||
if a.shutting.Load() {
|
||||
a.fail(sw, r, http.StatusServiceUnavailable, "unavailable", "Сервер останавливается", 1)
|
||||
return
|
||||
}
|
||||
a.route(sw, r)
|
||||
}
|
||||
|
||||
func requestIDFrom(r *http.Request) string {
|
||||
id, _ := r.Context().Value(ctxKey{}).(string)
|
||||
if id == "" {
|
||||
return "unknown"
|
||||
}
|
||||
return id
|
||||
}
|
||||
@@ -0,0 +1,842 @@
|
||||
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)
|
||||
}
|
||||
Reference in New Issue
Block a user