внес правки

This commit is contained in:
2026-10-23 00:00:08 +03:00
parent 3695ab6dfa
commit 2ebebda388
9 changed files with 217 additions and 44 deletions
+15
View File
@@ -1,16 +1,26 @@
package httpapi
import (
"errors"
"net/http"
"strings"
"mtusi2026/internal/auth"
"mtusi2026/internal/config"
"mtusi2026/internal/model"
"mtusi2026/internal/store"
)
const sessionTTLEnvKey = "SESSION_TTL_SECONDS"
var dummyPasswordHash = func() string {
h, err := auth.HashPassword("timing-equalizer-password")
if err != nil {
panic(err)
}
return h
}()
func (a *api) handleCreateSession(w http.ResponseWriter, r *http.Request) {
requestID := newRequestID()
@@ -23,6 +33,11 @@ func (a *api) handleCreateSession(w http.ResponseWriter, r *http.Request) {
u, passwordHash, err := a.store.GetUserByUsername(r.Context(), username)
if err != nil {
if !errors.Is(err, store.ErrUsernameNotFound) {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
return
}
_, _ = auth.VerifyPassword(password, dummyPasswordHash)
w.Header().Set("WWW-Authenticate", `Basic realm="messenger", charset="UTF-8"`)
writeError(w, http.StatusUnauthorized, requestID, codeUnauthorized, "invalid username or password")
return
+43 -23
View File
@@ -1,20 +1,26 @@
package httpapi
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"time"
"mtusi2026/internal/idgen"
"mtusi2026/internal/model"
"mtusi2026/internal/store"
)
func parseLimit(r *http.Request) (int, bool) {
raw := r.URL.Query().Get("limit")
if raw == "" {
q := r.URL.Query()
if !q.Has("limit") {
return 50, true
}
raw := q.Get("limit")
n, err := strconv.Atoi(raw)
if err != nil || n < 1 || n > 100 {
if err != nil || n < 1 || n > 100 || raw != strconv.Itoa(n) {
return 0, false
}
return n, true
@@ -26,17 +32,27 @@ func (a *api) handleCreateChat(w http.ResponseWriter, r *http.Request, u model.U
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "malformed request body")
return
}
if !validText(req.Title, 100) || len(req.MemberIDs) == 0 {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
return
}
for i, id := range req.MemberIDs {
if !idgen.IsValidUUID(id) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
return
}
req.MemberIDs[i] = strings.ToLower(id)
}
c, err := a.store.CreateChat(r.Context(), u.ID, req.Title, req.MemberIDs)
if err != nil {
if err == store.ErrValidation {
if errors.Is(err, store.ErrValidation) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid title or member_ids")
return
}
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
return
}
writeJSON(w, http.StatusCreated, requestID, c)
}
@@ -46,11 +62,15 @@ func (a *api) handleListChats(w http.ResponseWriter, r *http.Request, u model.Us
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit")
return
}
cursorStr := r.URL.Query().Get("cursor")
cursorStr, ok := parseCursor(r)
if !ok {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
return
}
items, next, err := a.store.ListChatsForUser(r.Context(), u.ID, cursorStr, limit)
if err != nil {
if err == store.ErrValidation {
if errors.Is(err, store.ErrValidation) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
return
}
@@ -64,48 +84,48 @@ func (a *api) handleListChats(w http.ResponseWriter, r *http.Request, u model.Us
}
func (a *api) handleGetChat(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
chatID := r.PathValue("chat_id")
chatID, ok := chatIDParam(w, r, requestID)
if !ok {
return
}
if a.chatCache != nil {
c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID)
if err == nil && hit {
if c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID); err == nil && hit {
writeJSON(w, http.StatusOK, requestID, c)
return
}
}
flightKey := u.ID + ":" + chatID
result, err, _ := a.chatFlight.Do(u.ID+":"+chatID, func() (any, error) {
ctx, cancel := context.WithTimeout(context.WithoutCancel(r.Context()), 5*time.Second)
defer cancel()
result, err, _ := a.chatFlight.Do(flightKey, func() (any, error) {
if a.chatCache != nil {
c, hit, err := a.chatCache.Get(r.Context(), u.ID, chatID)
if err == nil && hit {
if c, hit, err := a.chatCache.Get(ctx, u.ID, chatID); err == nil && hit {
return c, nil
}
}
c, err := a.store.GetChat(r.Context(), chatID, u.ID)
c, err := a.store.GetChat(ctx, chatID, u.ID)
if err != nil {
return model.Chat{}, err
}
if a.chatCache != nil {
_ = a.chatCache.Set(r.Context(), u.ID, chatID, c)
_ = a.chatCache.Set(ctx, u.ID, chatID, c)
}
return c, nil
})
if err != nil {
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
if errors.Is(err, store.ErrChatNotFound) {
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
} else {
writeError(w, http.StatusServiceUnavailable, requestID, codeUnavailable, "database unavailable")
}
return
}
c, ok := result.(model.Chat)
if !ok {
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
return
}
writeJSON(w, http.StatusOK, requestID, c)
}
+35 -4
View File
@@ -1,11 +1,14 @@
package httpapi
import (
"bytes"
"crypto/rand"
"encoding/json"
"fmt"
"io"
"net/http"
"reflect"
"strings"
)
type errorCode string
@@ -44,13 +47,41 @@ func writeError(w http.ResponseWriter, status int, requestID string, code errorC
})
}
func jsonFieldNames(dst any) map[string]bool {
names := map[string]bool{}
t := reflect.TypeOf(dst)
for t.Kind() == reflect.Ptr {
t = t.Elem()
}
for i := 0; i < t.NumField(); i++ {
tag := strings.Split(t.Field(i).Tag.Get("json"), ",")[0]
if tag != "" && tag != "-" {
names[tag] = true
}
}
return names
}
func decodeJSONStrict(r *http.Request, dst any) error {
dec := json.NewDecoder(r.Body)
raw, err := io.ReadAll(io.LimitReader(r.Body, 1<<20))
if err != nil {
return err
}
if len(bytes.TrimSpace(raw)) == 0 {
return fmt.Errorf("empty body")
}
var probe map[string]json.RawMessage
if err := json.Unmarshal(raw, &probe); err != nil {
return err
}
allowed := jsonFieldNames(dst)
for k := range probe {
if !allowed[k] {
return fmt.Errorf("unknown field %q", k)
}
}
dec := json.NewDecoder(bytes.NewReader(raw))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
if err == io.EOF {
return fmt.Errorf("empty body")
}
return err
}
if dec.More() {
+16 -8
View File
@@ -12,8 +12,10 @@ import (
var idemKeyRe = regexp.MustCompile(`^[A-Za-z0-9._:-]{1,128}$`)
func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
chatID := r.PathValue("chat_id")
chatID, ok := chatIDParam(w, r, requestID)
if !ok {
return
}
key := r.Header.Get("Idempotency-Key")
if !idemKeyRe.MatchString(key) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "missing or invalid Idempotency-Key")
@@ -44,21 +46,27 @@ func (a *api) handleCreateMessage(w http.ResponseWriter, r *http.Request, u mode
}
func (a *api) handleListMessages(w http.ResponseWriter, r *http.Request, u model.User, requestID string) {
chatID := r.PathValue("chat_id")
chatID, ok := chatIDParam(w, r, requestID)
if !ok {
return
}
limit, ok := parseLimit(r)
if !ok {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid limit")
return
}
cursorStr := r.URL.Query().Get("cursor")
cursorStr, ok := parseCursor(r)
if !ok {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
return
}
items, next, err := a.store.ListMessages(r.Context(), chatID, u.ID, cursorStr, limit)
if err != nil {
switch err {
case store.ErrChatNotFound:
switch {
case errors.Is(err, store.ErrChatNotFound):
writeError(w, http.StatusNotFound, requestID, codeNotFound, "chat not found")
case store.ErrValidation:
case errors.Is(err, store.ErrValidation):
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid cursor")
default:
writeError(w, http.StatusInternalServerError, requestID, codeInternal, "internal error")
+1 -6
View File
@@ -4,7 +4,6 @@ import (
"errors"
"net/http"
"regexp"
"strings"
"unicode/utf8"
"golang.org/x/sync/singleflight"
@@ -64,11 +63,7 @@ func (a *api) authMiddleware(next func(w http.ResponseWriter, r *http.Request, u
}
func validDisplayName(s string) bool {
if strings.TrimSpace(s) == "" {
return false
}
n := utf8.RuneCountInString(s)
return n >= 1 && n <= 100
return validText(s, 100)
}
func validPassword(s string) bool {
+45
View File
@@ -0,0 +1,45 @@
package httpapi
import (
"net/http"
"strings"
"unicode"
"unicode/utf8"
"mtusi2026/internal/idgen"
)
func validText(s string, max int) bool {
n := utf8.RuneCountInString(s)
if n < 1 || n > max {
return false
}
hasContent := false
for _, r := range s {
if r == 0 {
return false
}
if !unicode.IsSpace(r) {
hasContent = true
}
}
return hasContent
}
func parseCursor(r *http.Request) (string, bool) {
q := r.URL.Query()
if !q.Has("cursor") {
return "", true
}
c := q.Get("cursor")
return c, c != ""
}
func chatIDParam(w http.ResponseWriter, r *http.Request, requestID string) (string, bool) {
id := r.PathValue("chat_id")
if !idgen.IsValidUUID(id) {
writeError(w, http.StatusBadRequest, requestID, codeInvalidRequest, "invalid chat_id")
return "", false
}
return strings.ToLower(id), true
}