package main import ( "context" "crypto/sha256" "sync/atomic" "errors" "log" "net/http" "runtime/debug" "sort" "strings" "time" "unicode/utf8" ) type API struct { store *Store hasher *Hasher ttlSecs int reqLimit time.Duration // instanceID — стабильный на всё время жизни процесса псевдоним реплики (X-Instance-Id). instanceID string // draining выставляется по SIGTERM: /health/ready отвечает 503, новые запросы уходят на другие реплики. draining atomic.Bool } // ---- аутентификация ---- // actor: «кто вы». Только действующая Bearer-сессия из PostgreSQL; ответ на любой сбой одинаков. func (a *API) actor(r *http.Request) (User, string, *apiError) { token, ok := bearerToken(r) if !ok { return User{}, "", unauthorized(bearerChallenge, "Требуется Authorization: Bearer ") } user, err := a.store.sessionUser(r.Context(), hashToken(token)) if errors.Is(err, errNotFound) { return User{}, "", unauthorized(bearerChallenge, "Недействительная сессия") } if err != nil { return User{}, "", dbFail(err) } return user, token, nil } func (a *API) createSession(r *http.Request) (int, any, *apiError) { denied := unauthorized(basicChallenge, "Неверные учётные данные") username, password, ok := parseBasic(r) if !ok { return 0, nil, denied } user, hash, err := a.store.userWithHash(r.Context(), username) found := err == nil if err != nil && !errors.Is(err, errNotFound) { return 0, nil, dbFail(err) } if !found { hash = a.hasher.dummy } match, herr := a.hasher.verify(r.Context(), password, hash) if herr != nil && !errors.Is(herr, context.Canceled) && !errors.Is(herr, context.DeadlineExceeded) { match = false // повреждённый хеш = отказ, не 500 } else if herr != nil { return 0, nil, unavailable() } if !found || !match { return 0, nil, denied } token, tokenHash := newToken() expires, err := a.store.createSession(r.Context(), tokenHash, user.ID, a.ttlSecs) if err != nil { return 0, nil, dbFail(err) } return http.StatusCreated, map[string]any{ "token": token, "token_type": "Bearer", "expires_at": formatTime(expires), "user": user, }, nil } func (a *API) revokeSession(r *http.Request) (int, any, *apiError) { _, token, err := a.actor(r) if err != nil { return 0, nil, err } if rerr := a.store.revokeSession(r.Context(), hashToken(token)); rerr != nil { return 0, nil, dbFail(rerr) } return http.StatusNoContent, nil, nil } // ---- пользователи ---- func (a *API) createUser(r *http.Request) (int, any, *apiError) { body, err := readJSON(r) if err != nil { return 0, nil, err } if err := exactFields(body, "username", "display_name", "password"); err != nil { return 0, nil, err } username, ok := body["username"].(string) if !ok || !usernamePattern.MatchString(username) { return 0, nil, invalid("Некорректный username") } displayName, err := requiredString(body["display_name"], 100, "display_name") if err != nil { return 0, nil, err } password, ok := body["password"].(string) if n := utf8.RuneCountInString(password); !ok || !utf8.ValidString(password) || n < 12 || n > 128 { return 0, nil, invalid("Некорректный password") } hash, herr := a.hasher.hash(r.Context(), password) if herr != nil { return 0, nil, unavailable() } user, serr := a.store.createUser(r.Context(), User{ID: newUUID(), Username: username, DisplayName: displayName}, hash) if errors.Is(serr, errConflict) { return 0, nil, fail(http.StatusConflict, "conflict", "Username уже занят") } if serr != nil { return 0, nil, dbFail(serr) } return http.StatusCreated, user, nil } func (a *API) currentUser(r *http.Request) (int, any, *apiError) { user, _, err := a.actor(r) if err != nil { return 0, nil, err } return http.StatusOK, user, nil } // ---- чаты ---- func (a *API) createChat(r *http.Request) (int, any, *apiError) { actor, _, err := a.actor(r) if err != nil { return 0, nil, err } body, err := readJSON(r) if err != nil { return 0, nil, err } if err := exactFields(body, "title", "member_ids"); err != nil { return 0, nil, err } title, err := requiredString(body["title"], 100, "title") if err != nil { return 0, nil, err } rawMembers, ok := body["member_ids"].([]any) if !ok || len(rawMembers) < 1 || len(rawMembers) > 100 { return 0, nil, invalid("Некорректные участники") } members, seen := make([]string, 0, len(rawMembers)), map[string]bool{} for _, raw := range rawMembers { member, typeOK := raw.(string) id, idOK := validUUID(member) if !typeOK || !idOK || seen[id] { return 0, nil, invalid("Некорректные участники") } seen[id] = true members = append(members, id) } if !seen[actor.ID] { return 0, nil, invalid("Создатель должен быть участником") } sort.Strings(members) // детерминированный порядок: одинаковый в POST и GET chat, serr := a.store.createChat(r.Context(), Chat{ID: newUUID(), Title: title, MemberIDs: members}, actor.ID) if errors.Is(serr, errInvalidMembers) { return 0, nil, invalid("Некорректные участники") } if serr != nil { return 0, nil, dbFail(serr) } return http.StatusCreated, chat, nil } func (a *API) listChats(r *http.Request) (int, any, *apiError) { actor, _, err := a.actor(r) if err != nil { return 0, nil, err } limit, rawCursor, err := parsePage(r) if err != nil { return 0, nil, err } var after *time.Time var afterID string if rawCursor != "" { t, id, cerr := decodeCursor(rawCursor, "chats", actor.ID) if cerr != nil { return 0, nil, cerr } after, afterID = &t, id } items, next, serr := a.store.listChats(r.Context(), actor.ID, limit, after, afterID) if serr != nil { return 0, nil, dbFail(serr) } return http.StatusOK, pageBody(items, next), nil } func pageBody(items any, next string) map[string]any { var cursor any if next != "" { cursor = next } return map[string]any{"items": items, "next_cursor": cursor} } // chatAccess: сначала аутентификация (вызывается до этого), затем доступ к конкретному чату. // Чужой и несуществующий чат неразличимы: оба дают 404. func (a *API) chatAccess(r *http.Request, actorID, rawID string) (string, *apiError) { id, ok := validUUID(rawID) if !ok { return "", invalid("Некорректный идентификатор") } member, err := a.store.isMember(r.Context(), actorID, id) if err != nil { return "", dbFail(err) } if !member { return "", notFound() } return id, nil } func (a *API) getChat(r *http.Request, rawID string) (int, any, *apiError) { actor, _, err := a.actor(r) if err != nil { return 0, nil, err } id, ok := validUUID(rawID) if !ok { return 0, nil, invalid("Некорректный идентификатор") } chat, serr := a.store.getChat(r.Context(), actor.ID, id) if errors.Is(serr, errNotFound) { return 0, nil, notFound() } if serr != nil { return 0, nil, dbFail(serr) } return http.StatusOK, chat, nil } // ---- сообщения ---- func (a *API) createMessage(r *http.Request, rawID string) (int, any, *apiError) { actor, _, err := a.actor(r) if err != nil { return 0, nil, err } chatID, err := a.chatAccess(r, actor.ID, rawID) if err != nil { return 0, nil, err } keys := r.Header.Values("Idempotency-Key") if len(keys) != 1 || !idempotencyKeyPattern.MatchString(keys[0]) { return 0, nil, invalid("Требуется корректный заголовок Idempotency-Key") } key := keys[0] body, err := readJSON(r) if err != nil { return 0, nil, err } // sender_id в теле не принимается: лишнее поле — 400. Отправитель берётся только из сессии. if err := exactFields(body, "text"); err != nil { return 0, nil, err } text, err := requiredString(body["text"], 4000, "text") if err != nil { return 0, nil, err } sum := sha256.Sum256([]byte(text)) // канонический вид тела: единственное поле text path := "/api/v1/chats/" + chatID + "/messages" message, _, serr := a.store.createMessageIdempotent(r.Context(), Message{ID: newUUID(), ChatID: chatID, SenderID: actor.ID, Text: text}, key, path, sum[:]) if errors.Is(serr, errConflict) { return 0, nil, fail(http.StatusConflict, "conflict", "Idempotency-Key уже использован с другим сообщением") } if serr != nil { return 0, nil, dbFail(serr) } return http.StatusCreated, message, nil } func (a *API) listMessages(r *http.Request, rawID string) (int, any, *apiError) { actor, _, err := a.actor(r) if err != nil { return 0, nil, err } chatID, err := a.chatAccess(r, actor.ID, rawID) if err != nil { return 0, nil, err } limit, rawCursor, err := parsePage(r) if err != nil { return 0, nil, err } var after *time.Time var afterID string if rawCursor != "" { t, id, cerr := decodeCursor(rawCursor, "messages", chatID) if cerr != nil { return 0, nil, cerr } after, afterID = &t, id } items, next, serr := a.store.listMessages(r.Context(), chatID, limit, after, afterID) if serr != nil { return 0, nil, dbFail(serr) } return http.StatusOK, pageBody(items, next), nil } // ---- health ---- func (a *API) ready(r *http.Request) (int, any, *apiError) { if a.draining.Load() { return 0, nil, unavailable() } ctx, cancel := context.WithTimeout(r.Context(), 2*time.Second) defer cancel() if err := a.store.ready(ctx); err != nil { log.Printf("readiness: dependency check failed") return 0, nil, unavailable() } return http.StatusOK, map[string]string{"status": "ok"}, nil } // ---- маршрутизация ---- func (a *API) dispatch(r *http.Request) (int, any, *apiError) { path := r.URL.Path switch { case r.Method == http.MethodGet && path == "/health/live": return http.StatusOK, map[string]string{"status": "ok"}, nil case r.Method == http.MethodGet && path == "/health/ready": return a.ready(r) case r.Method == http.MethodPost && path == "/api/v1/users": return a.createUser(r) case r.Method == http.MethodGet && path == "/api/v1/users/me": return a.currentUser(r) case r.Method == http.MethodPost && path == "/api/v1/auth/sessions": return a.createSession(r) // единственное место, где принимается Basic case r.Method == http.MethodDelete && path == "/api/v1/auth/sessions/current": return a.revokeSession(r) case r.Method == http.MethodPost && path == "/api/v1/chats": return a.createChat(r) case r.Method == http.MethodGet && path == "/api/v1/chats": return a.listChats(r) } parts := strings.Split(strings.Trim(path, "/"), "/") if len(parts) == 4 && strings.Join(parts[:3], "/") == "api/v1/chats" && r.Method == http.MethodGet { return a.getChat(r, parts[3]) } if len(parts) == 5 && strings.Join(parts[:3], "/") == "api/v1/chats" && parts[4] == "messages" { if r.Method == http.MethodPost { return a.createMessage(r, parts[3]) } if r.Method == http.MethodGet { return a.listMessages(r, parts[3]) } } return 0, nil, notFound() } type statusWriter struct { http.ResponseWriter status int } func (w *statusWriter) WriteHeader(code int) { w.status = code; w.ResponseWriter.WriteHeader(code) } func (a *API) ServeHTTP(rw http.ResponseWriter, r *http.Request) { id := newUUID() rw.Header().Set("X-Instance-Id", a.instanceID) w := &statusWriter{ResponseWriter: rw, status: 200} started := time.Now() ctx, cancel := context.WithTimeout(r.Context(), a.reqLimit) defer cancel() r = r.WithContext(ctx) defer func() { if rec := recover(); rec != nil { log.Printf("panic request_id=%s: %v\n%s", id, rec, debug.Stack()) writeError(w, id, fail(http.StatusInternalServerError, "internal_error", "Внутренняя ошибка")) } // В лог не попадают заголовки, query-строка, тела запросов и токены. log.Printf("%s %s -> %d request_id=%s %s", r.Method, r.URL.Path, w.status, id, time.Since(started).Round(time.Millisecond)) }() status, body, err := a.dispatch(r) if err != nil { writeError(w, id, err) return } if status == http.StatusNoContent { w.Header().Set("X-Request-Id", id) w.WriteHeader(status) return } writeJSON(w, id, status, body) }