forked from mtusi2026/mtusi2026lab3
внес правки
This commit is contained in:
@@ -49,6 +49,9 @@ services:
|
||||
- "up"
|
||||
restart: "no"
|
||||
networks: [data]
|
||||
deploy:
|
||||
resources:
|
||||
limits: { cpus: "0.25", memory: 128M }
|
||||
|
||||
api:
|
||||
build:
|
||||
|
||||
@@ -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
@@ -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)
|
||||
}
|
||||
|
||||
@@ -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() {
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -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 {
|
||||
|
||||
@@ -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
|
||||
}
|
||||
@@ -8,6 +8,7 @@ import (
|
||||
"fmt"
|
||||
"strconv"
|
||||
"sync/atomic"
|
||||
"unicode"
|
||||
"unicode/utf8"
|
||||
|
||||
"github.com/jackc/pgx/v5"
|
||||
@@ -390,12 +391,16 @@ func validMessageText(s string) bool {
|
||||
if n == 0 || n > 4000 {
|
||||
return false
|
||||
}
|
||||
hasContent := false
|
||||
for _, r := range s {
|
||||
if r != ' ' && r != '\t' && r != '\n' && r != '\r' {
|
||||
return true
|
||||
if r == 0 {
|
||||
return false
|
||||
}
|
||||
if !unicode.IsSpace(r) {
|
||||
hasContent = true
|
||||
}
|
||||
}
|
||||
return false
|
||||
return hasContent
|
||||
}
|
||||
|
||||
var ErrSessionNotFound = errors.New("session not found or expired")
|
||||
|
||||
@@ -0,0 +1,51 @@
|
||||
import base64, json, sys, time, urllib.request, urllib.error, uuid
|
||||
|
||||
BASE = sys.argv[1] if len(sys.argv) > 1 else "http://localhost:8080"
|
||||
PWD = "correct-horse-battery-staple"
|
||||
|
||||
|
||||
def call(method, path, body=None, token=None, basic=None, key=None):
|
||||
data = json.dumps(body).encode() if body is not None else None
|
||||
r = urllib.request.Request(BASE + path, data=data, method=method)
|
||||
if data is not None: r.add_header("Content-Type", "application/json")
|
||||
if token: r.add_header("Authorization", "Bearer " + token)
|
||||
if basic: r.add_header("Authorization", "Basic " + base64.b64encode(basic.encode()).decode())
|
||||
if key: r.add_header("Idempotency-Key", key)
|
||||
try:
|
||||
with urllib.request.urlopen(r, timeout=10) as resp:
|
||||
return resp.status, json.loads(resp.read() or b"null")
|
||||
except urllib.error.HTTPError as e:
|
||||
return e.code, None
|
||||
|
||||
|
||||
name = "edge_" + uuid.uuid4().hex[:8]
|
||||
_, u = call("POST", "/api/v1/users", {"username": name, "display_name": "e", "password": PWD})
|
||||
_, s = call("POST", "/api/v1/auth/sessions", basic=f"{name}:{PWD}")
|
||||
t = s["token"]
|
||||
_, c = call("POST", "/api/v1/chats", {"title": "t", "member_ids": [u["id"]]}, token=t)
|
||||
m = f"/api/v1/chats/{c['id']}/messages"
|
||||
k = lambda: uuid.uuid4().hex
|
||||
|
||||
cases = [
|
||||
("поле Text (другой регистр)", call("POST", m, {"Text": "x"}, token=t, key=k())[0], {400}),
|
||||
("текст из NBSP/U+3000", call("POST", m, {"text": "\u00a0\u3000"}, token=t, key=k())[0], {400}),
|
||||
("текст с NUL", call("POST", m, {"text": "a\u0000b"}, token=t, key=k())[0], {400}),
|
||||
("limit= пустой", call("GET", "/api/v1/chats?limit=", token=t)[0], {400}),
|
||||
("cursor= пустой", call("GET", m + "?cursor=", token=t)[0], {400}),
|
||||
("chat_id не UUID", call("GET", "/api/v1/chats/not-a-uuid/messages", token=t)[0], {400}),
|
||||
("member_ids не UUID", call("POST", "/api/v1/chats", {"title": "t", "member_ids": [u["id"], "not-a-uuid"]}, token=t)[0], {400}),
|
||||
("название из пробелов", call("POST", "/api/v1/chats", {"title": " ", "member_ids": [u["id"]]}, token=t)[0], {400}),
|
||||
("название 101 символ", call("POST", "/api/v1/chats", {"title": "a" * 101, "member_ids": [u["id"]]}, token=t)[0], {400}),
|
||||
]
|
||||
for label, got, ok in cases:
|
||||
print("PASS" if got in ok else "FAIL", label, "->", got)
|
||||
|
||||
|
||||
def login_ms(basic):
|
||||
t0 = time.time(); call("POST", "/api/v1/auth/sessions", basic=basic)
|
||||
return (time.time() - t0) * 1000
|
||||
|
||||
ms_unknown = sorted(login_ms("nobody_" + uuid.uuid4().hex[:6] + ":" + PWD) for _ in range(5))[2]
|
||||
ms_wrong = sorted(login_ms(name + ":wrong-password-123") for _ in range(5))[2]
|
||||
print("PASS" if abs(ms_unknown - ms_wrong) < 0.5 * ms_wrong else "FAIL",
|
||||
f"тайминг входа: неизвестный {ms_unknown:.1f} мс, неверный пароль {ms_wrong:.1f} мс")
|
||||
Reference in New Issue
Block a user