forked from mtusi2026/mtusi2026lab3
Lab3 baseline: HAProxy, replicated stateless API, shared PostgreSQL/Valkey, idempotent messages
This commit is contained in:
@@ -0,0 +1,236 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/auth"
|
||||
"mtusi.ru/messenger-lab3/internal/model"
|
||||
"mtusi.ru/messenger-lab3/internal/session"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
)
|
||||
|
||||
const maxBodyBytes = 1 << 20 // far above the 4000-character message limit
|
||||
|
||||
type healthResponse struct {
|
||||
Status string `json:"status"`
|
||||
}
|
||||
|
||||
// identity is the authenticated principal derived only from the Bearer
|
||||
// session. X-User-Id is not consulted anywhere in this package.
|
||||
type identity struct {
|
||||
user model.User
|
||||
token string
|
||||
}
|
||||
|
||||
// App is the HTTP layer. PostgreSQL is the source of truth for users, chats
|
||||
// and messages; Valkey is the source of truth for sessions. App adds request
|
||||
// validation, authentication and contract mapping.
|
||||
type App struct {
|
||||
store *store.Store
|
||||
sessions *session.Store
|
||||
log *slog.Logger
|
||||
ready atomic.Bool
|
||||
maxBody int64
|
||||
instanceID string
|
||||
version string
|
||||
startedAt time.Time
|
||||
dummyHash string
|
||||
|
||||
createdMessages atomic.Uint64
|
||||
replayedMessages atomic.Uint64
|
||||
conflictMessages atomic.Uint64
|
||||
}
|
||||
|
||||
// New creates the HTTP application. The dummy Argon2id hash is generated once
|
||||
// so login can spend the same work for an unknown username as for a known one.
|
||||
func New(repository *store.Store, sessions *session.Store, logger *slog.Logger, instanceID, version string) (*App, error) {
|
||||
dummy, err := auth.Hash("dummy-password-never-used-for-login")
|
||||
if err != nil {
|
||||
return nil, err
|
||||
}
|
||||
app := &App{
|
||||
store: repository,
|
||||
sessions: sessions,
|
||||
log: logger,
|
||||
maxBody: maxBodyBytes,
|
||||
instanceID: instanceID,
|
||||
version: version,
|
||||
startedAt: time.Now(),
|
||||
dummyHash: dummy,
|
||||
}
|
||||
app.ready.Store(true)
|
||||
return app, nil
|
||||
}
|
||||
|
||||
// SetReady flips readiness. The main process clears it as soon as SIGTERM is
|
||||
// received and before http.Server.Shutdown stops accepting connections.
|
||||
func (a *App) SetReady(ready bool) { a.ready.Store(ready) }
|
||||
|
||||
// Handler returns the fully instrumented handler.
|
||||
func (a *App) Handler() http.Handler {
|
||||
return a.withObservability(a)
|
||||
}
|
||||
|
||||
// ServeHTTP routes the lab3 API. Method mismatches become 404 in the contract
|
||||
// error shape because the public error enum has no method_not_allowed code.
|
||||
func (a *App) ServeHTTP(w http.ResponseWriter, r *http.Request) {
|
||||
switch r.URL.Path {
|
||||
case "/health/live":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
case "/health/ready":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.readiness(w, r)
|
||||
case "/api/v1/users":
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createUser(w, r)
|
||||
case "/api/v1/auth/sessions":
|
||||
if r.Method != http.MethodPost {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.createSession(w, r)
|
||||
case "/api/v1/auth/sessions/current":
|
||||
if r.Method != http.MethodDelete {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.withAuth(a.logout).ServeHTTP(w, r)
|
||||
case "/api/v1/users/me":
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.withAuth(a.currentUser).ServeHTTP(w, r)
|
||||
case "/api/v1/chats":
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
a.withAuth(a.listChats).ServeHTTP(w, r)
|
||||
case http.MethodPost:
|
||||
a.withAuth(a.createChat).ServeHTTP(w, r)
|
||||
default:
|
||||
a.notFound(w, r)
|
||||
}
|
||||
default:
|
||||
if rest, ok := trimPathPrefix(r.URL.Path, "/api/v1/chats/"); ok {
|
||||
// Authentication runs before resource resolution: an anonymous
|
||||
// request must not learn whether a chat id exists.
|
||||
a.withAuth(func(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.chatRoutes(w, r, rest, actor)
|
||||
}).ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
}
|
||||
|
||||
func (a *App) chatRoutes(w http.ResponseWriter, r *http.Request, rest string, actor identity) {
|
||||
parts := splitPath(rest)
|
||||
if len(parts) == 1 {
|
||||
if r.Method != http.MethodGet {
|
||||
a.notFound(w, r)
|
||||
return
|
||||
}
|
||||
a.getChat(w, r, parts[0], actor)
|
||||
return
|
||||
}
|
||||
if len(parts) == 2 && parts[1] == "messages" {
|
||||
switch r.Method {
|
||||
case http.MethodGet:
|
||||
a.listMessages(w, r, parts[0], actor)
|
||||
case http.MethodPost:
|
||||
a.createMessage(w, r, parts[0], actor)
|
||||
default:
|
||||
a.notFound(w, r)
|
||||
}
|
||||
return
|
||||
}
|
||||
a.notFound(w, r)
|
||||
}
|
||||
|
||||
// withAuth resolves the Bearer session before the wrapped handler runs.
|
||||
func (a *App) withAuth(next func(http.ResponseWriter, *http.Request, identity)) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
actor, problem := a.authenticate(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
next(w, r, actor)
|
||||
}
|
||||
}
|
||||
|
||||
// readiness reports whether the mandatory synchronous path can be served.
|
||||
// Both PostgreSQL and Valkey are critical: without PostgreSQL the API cannot
|
||||
// answer, and without Valkey it cannot authenticate a single protected call.
|
||||
func (a *App) readiness(w http.ResponseWriter, r *http.Request) {
|
||||
if !a.ready.Load() {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
dbCtx, dbCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
||||
dbErr := a.store.Ping(dbCtx)
|
||||
dbCancel()
|
||||
if dbErr != nil {
|
||||
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "postgres", "error", dbErr)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
cacheCtx, cacheCancel := context.WithTimeout(r.Context(), 900*time.Millisecond)
|
||||
cacheErr := a.sessions.Ping(cacheCtx)
|
||||
cacheCancel()
|
||||
if cacheErr != nil {
|
||||
a.log.Warn("readiness probe failed", "request_id", requestIDFromContext(r.Context()), "dependency", "valkey", "error", cacheErr)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, healthResponse{Status: "ok"})
|
||||
}
|
||||
|
||||
// writeJSON encodes a success response. X-Request-Id is set by middleware
|
||||
// before the handler runs, so even a marshal-time 500 keeps the header.
|
||||
func (a *App) writeJSON(w http.ResponseWriter, r *http.Request, status int, value any) {
|
||||
data, err := json.Marshal(value)
|
||||
if err != nil {
|
||||
a.log.Error("response encoding failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(status)
|
||||
if _, err := w.Write(data); err != nil {
|
||||
a.log.Debug("response write failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
}
|
||||
}
|
||||
|
||||
func trimPathPrefix(value, prefix string) (string, bool) {
|
||||
if !strings.HasPrefix(value, prefix) || len(value) == len(prefix) {
|
||||
return "", false
|
||||
}
|
||||
return value[len(prefix):], true
|
||||
}
|
||||
|
||||
func splitPath(value string) []string {
|
||||
parts := strings.Split(value, "/")
|
||||
for _, part := range parts {
|
||||
if part == "" {
|
||||
return nil
|
||||
}
|
||||
}
|
||||
return parts
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/cursor"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
"mtusi.ru/messenger-lab3/internal/uuid"
|
||||
)
|
||||
|
||||
type createChatRequest struct {
|
||||
Title *string `json:"title"`
|
||||
MemberIDs []string `json:"member_ids"`
|
||||
}
|
||||
|
||||
func (a *App) createChat(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
var request createChatRequest
|
||||
if problem := a.decodeJSON(r, &request, "title", "member_ids"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Title == nil {
|
||||
a.writeError(w, r, invalidRequest("title is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateTitle(*request.Title); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if len(request.MemberIDs) < 1 || len(request.MemberIDs) > 100 {
|
||||
a.writeError(w, r, invalidRequest("member_ids must contain 1 to 100 members"))
|
||||
return
|
||||
}
|
||||
|
||||
members := make([]string, 0, len(request.MemberIDs))
|
||||
seen := make(map[string]struct{}, len(request.MemberIDs))
|
||||
callerIncluded := false
|
||||
for _, rawID := range request.MemberIDs {
|
||||
id, ok := uuid.Normalize(rawID)
|
||||
if !ok {
|
||||
a.writeError(w, r, invalidRequest("every member_ids entry must be a UUID"))
|
||||
return
|
||||
}
|
||||
if _, duplicate := seen[id]; duplicate {
|
||||
a.writeError(w, r, invalidRequest("member_ids must not contain duplicates"))
|
||||
return
|
||||
}
|
||||
seen[id] = struct{}{}
|
||||
members = append(members, id)
|
||||
if id == actor.user.ID {
|
||||
callerIncluded = true
|
||||
}
|
||||
}
|
||||
if !callerIncluded {
|
||||
a.writeError(w, r, invalidRequest("caller must be present in member_ids"))
|
||||
return
|
||||
}
|
||||
|
||||
chat, err := a.store.CreateChat(r.Context(), *request.Title, members, actor.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUnknownMember):
|
||||
a.writeError(w, r, invalidRequest("every member_ids entry must reference an existing user"))
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, chat)
|
||||
}
|
||||
|
||||
func (a *App) listChats(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
limit, rawCursor, problem := a.pageParams(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
var position *cursor.Cursor
|
||||
if rawCursor != "" {
|
||||
decoded, err := cursor.Decode(rawCursor, cursor.ScopeChats, "")
|
||||
if err != nil {
|
||||
a.writeError(w, r, invalidRequest("cursor is invalid for this request"))
|
||||
return
|
||||
}
|
||||
position = &decoded
|
||||
}
|
||||
|
||||
page, err := a.store.Chats(r.Context(), actor.user.ID, position, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("list chats failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
|
||||
func (a *App) getChat(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
chat, err := a.store.ChatForUser(r.Context(), chatID, actor.user.ID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("get chat failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, chat)
|
||||
}
|
||||
|
||||
// normalizePathUUID validates a path identifier before any database access.
|
||||
func normalizePathUUID(raw, field string) (string, *apiError) {
|
||||
id, ok := uuid.Normalize(raw)
|
||||
if !ok {
|
||||
return "", invalidRequest(field + " must be a UUID")
|
||||
}
|
||||
return id, nil
|
||||
}
|
||||
@@ -0,0 +1,176 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"context"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
"time"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/uuid"
|
||||
)
|
||||
|
||||
// apiError is a contract-shaped error: HTTP status, machine-readable code, a
|
||||
// safe human-readable message and an optional authentication challenge. The
|
||||
// request id is filled from the request context at write time.
|
||||
type apiError struct {
|
||||
status int
|
||||
code string
|
||||
message string
|
||||
challenge string
|
||||
}
|
||||
|
||||
func (e *apiError) Error() string { return e.code + ": " + e.message }
|
||||
|
||||
const (
|
||||
basicChallenge = `Basic realm="messenger", charset="UTF-8"`
|
||||
bearerChallenge = `Bearer realm="messenger"`
|
||||
)
|
||||
|
||||
var (
|
||||
statusInvalidRequest = &apiError{status: http.StatusBadRequest, code: "invalid_request", message: "request validation failed"}
|
||||
statusNotFound = &apiError{status: http.StatusNotFound, code: "not_found", message: "object not found"}
|
||||
statusConflict = &apiError{status: http.StatusConflict, code: "conflict", message: "object already exists"}
|
||||
statusPayloadTooLarge = &apiError{status: http.StatusRequestEntityTooLarge, code: "payload_too_large", message: "request body is too large"}
|
||||
statusUnsupportedMediaType = &apiError{status: http.StatusUnsupportedMediaType, code: "unsupported_media_type", message: "Content-Type must be application/json"}
|
||||
statusUnavailable = &apiError{status: http.StatusServiceUnavailable, code: "unavailable", message: "a required dependency is unavailable"}
|
||||
statusInternal = &apiError{status: http.StatusInternalServerError, code: "internal_error", message: "internal server error"}
|
||||
)
|
||||
|
||||
func invalidRequest(message string) *apiError {
|
||||
return &apiError{status: http.StatusBadRequest, code: "invalid_request", message: message}
|
||||
}
|
||||
|
||||
func unauthorizedBasic() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "invalid username or password", challenge: basicChallenge}
|
||||
}
|
||||
|
||||
func unauthorizedBearer() *apiError {
|
||||
return &apiError{status: http.StatusUnauthorized, code: "unauthorized", message: "a valid bearer session is required", challenge: bearerChallenge}
|
||||
}
|
||||
|
||||
type errorEnvelope struct {
|
||||
Error errorBody `json:"error"`
|
||||
}
|
||||
|
||||
type errorBody struct {
|
||||
Code string `json:"code"`
|
||||
Message string `json:"message"`
|
||||
RequestID string `json:"request_id"`
|
||||
}
|
||||
|
||||
// writeError writes a JSON error whose request_id matches X-Request-Id. The
|
||||
// message never contains SQL, stack traces, credentials or object existence
|
||||
// details for foreign resources.
|
||||
func (a *App) writeError(w http.ResponseWriter, r *http.Request, problem *apiError) {
|
||||
requestID := requestIDFromContext(r.Context())
|
||||
if requestID == "" {
|
||||
requestID = w.Header().Get("X-Request-Id")
|
||||
}
|
||||
if requestID == "" {
|
||||
requestID = uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
}
|
||||
if problem.challenge != "" {
|
||||
w.Header().Set("WWW-Authenticate", problem.challenge)
|
||||
}
|
||||
a.writeJSON(w, r, problem.status, errorEnvelope{Error: errorBody{
|
||||
Code: problem.code,
|
||||
Message: problem.message,
|
||||
RequestID: requestID,
|
||||
}})
|
||||
}
|
||||
|
||||
func (a *App) notFound(w http.ResponseWriter, r *http.Request) {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
}
|
||||
|
||||
type requestIDContextKey struct{}
|
||||
|
||||
func requestIDFromContext(ctx context.Context) string {
|
||||
value, _ := ctx.Value(requestIDContextKey{}).(string)
|
||||
return value
|
||||
}
|
||||
|
||||
// statusWriter records the status code and byte count for logs and for the
|
||||
// panic path, so a partially written response is not written twice.
|
||||
type statusWriter struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int
|
||||
wrote bool
|
||||
}
|
||||
|
||||
func (w *statusWriter) WriteHeader(code int) {
|
||||
if w.wrote {
|
||||
return
|
||||
}
|
||||
w.wrote = true
|
||||
w.status = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (w *statusWriter) Write(data []byte) (int, error) {
|
||||
if !w.wrote {
|
||||
w.WriteHeader(http.StatusOK)
|
||||
}
|
||||
written, err := w.ResponseWriter.Write(data)
|
||||
w.bytes += written
|
||||
return written, err
|
||||
}
|
||||
|
||||
func (a *App) withObservability(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
requestID := uuid.NewRandom(16)
|
||||
w.Header().Set("X-Request-Id", requestID)
|
||||
// Stable for the life of the process and unique per container. lab3
|
||||
// uses the container hostname: it is the actual process identity, so
|
||||
// stop-one can map a response to exactly one container. lab7 will
|
||||
// replace it with an opaque alias.
|
||||
w.Header().Set("X-Instance-Id", a.instanceID)
|
||||
// Extra, non-contract header used only to observe an image replacement
|
||||
// during the rolling-update experiment. The mandatory contract does
|
||||
// not define or require it.
|
||||
w.Header().Set("X-App-Version", a.version)
|
||||
r = r.WithContext(context.WithValue(r.Context(), requestIDContextKey{}, requestID))
|
||||
writer := &statusWriter{ResponseWriter: w, status: http.StatusOK}
|
||||
|
||||
defer func() {
|
||||
if recovered := recover(); recovered != nil {
|
||||
a.log.Error("panic while handling request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"panic", recovered,
|
||||
)
|
||||
if !writer.wrote {
|
||||
a.writeError(writer, r, statusInternal)
|
||||
}
|
||||
}
|
||||
level := slog.LevelInfo
|
||||
if r.URL.Path == "/health/live" || r.URL.Path == "/health/ready" {
|
||||
level = slog.LevelDebug
|
||||
}
|
||||
a.log.Log(r.Context(), level, "http request",
|
||||
"request_id", requestID,
|
||||
"instance_id", a.instanceID,
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
"status", writer.status,
|
||||
"duration_ms", float64(time.Since(start).Microseconds())/1000.0,
|
||||
"bytes", writer.bytes,
|
||||
)
|
||||
}()
|
||||
|
||||
next.ServeHTTP(writer, r)
|
||||
})
|
||||
}
|
||||
|
||||
// atomicBool keeps the readiness flag readable from the signal goroutine
|
||||
// without importing sync/atomic into every handler file.
|
||||
type atomicBool struct{ value atomic.Bool }
|
||||
|
||||
func (b *atomicBool) Store(value bool) { b.value.Store(value) }
|
||||
func (b *atomicBool) Load() bool { return b.value.Load() }
|
||||
@@ -0,0 +1,150 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/cursor"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
)
|
||||
|
||||
type createMessageRequest struct {
|
||||
Text *string `json:"text"`
|
||||
}
|
||||
|
||||
func (a *App) createMessage(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// The key is validated before the body, but after authentication and path
|
||||
// validation: a malformed/missing key is always 400, while an outsider
|
||||
// still cannot learn anything by replaying someone else's key.
|
||||
idempotencyKey, problem := idempotencyKey(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// Resource access is checked before the body is decoded so a foreign chat
|
||||
// always looks like a missing chat, independent of the submitted payload.
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
var request createMessageRequest
|
||||
if problem := a.decodeJSON(r, &request, "text"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Text == nil {
|
||||
a.writeError(w, r, invalidRequest("text is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateMessageText(*request.Text); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
|
||||
// The canonical body for lab3 is {"text": ...}. Hash the decoded text, not
|
||||
// the raw bytes: insignificant JSON whitespace or escapes must replay the
|
||||
// same key, while any different text must conflict. attachment_ids is not
|
||||
// part of the lab3 schema; lab4 will extend this canonical form.
|
||||
hash := sha256.Sum256([]byte(*request.Text))
|
||||
message, replayed, err := a.store.CreateMessageIdempotent(
|
||||
r.Context(), chatID, actor.user.ID, http.MethodPost, messagePath(chatID), idempotencyKey, hash[:], *request.Text,
|
||||
)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrIdempotencyConflict):
|
||||
a.conflictMessages.Add(1)
|
||||
a.writeError(w, r, statusConflict)
|
||||
return
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create message failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if replayed {
|
||||
a.replayedMessages.Add(1)
|
||||
} else {
|
||||
a.createdMessages.Add(1)
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, message)
|
||||
}
|
||||
|
||||
func messagePath(chatID string) string {
|
||||
return "/api/v1/chats/" + chatID + "/messages"
|
||||
}
|
||||
|
||||
func (a *App) listMessages(w http.ResponseWriter, r *http.Request, rawChatID string, actor identity) {
|
||||
chatID, problem := normalizePathUUID(rawChatID, "chat_id")
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
// A foreign/nonexistent chat is always 404, even if the query itself is
|
||||
// malformed; this avoids making object existence observable.
|
||||
member, err := a.store.IsChatMember(r.Context(), chatID, actor.user.ID)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("membership check failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !member {
|
||||
a.writeError(w, r, statusNotFound)
|
||||
return
|
||||
}
|
||||
|
||||
limit, rawCursor, problem := a.pageParams(r)
|
||||
if problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
var position *cursor.Cursor
|
||||
if rawCursor != "" {
|
||||
decoded, err := cursor.Decode(rawCursor, cursor.ScopeMessages, chatID)
|
||||
if err != nil {
|
||||
a.writeError(w, r, invalidRequest("cursor is invalid for this chat"))
|
||||
return
|
||||
}
|
||||
position = &decoded
|
||||
}
|
||||
|
||||
page, err := a.store.Messages(r.Context(), chatID, position, limit)
|
||||
if err != nil {
|
||||
if errors.Is(err, store.ErrUnavailable) {
|
||||
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.log.Error("list messages failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusOK, page)
|
||||
}
|
||||
@@ -0,0 +1,91 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"runtime"
|
||||
"time"
|
||||
)
|
||||
|
||||
// InternalStats is the operator-only JSON document served on the loopback
|
||||
// metrics listener inside each API container. It is deliberately not part of
|
||||
// the public contract and is never routed through the load balancer; the
|
||||
// experiment scripts read it with `docker exec` to attribute saturation to
|
||||
// the connection pool versus PostgreSQL/CPU.
|
||||
type InternalStats struct {
|
||||
InstanceID string `json:"instance_id"`
|
||||
Version string `json:"version"`
|
||||
UptimeSeconds float64 `json:"uptime_seconds"`
|
||||
Pool poolStats `json:"pool"`
|
||||
Messages messageCounters `json:"messages"`
|
||||
Runtime runtimeStats `json:"runtime"`
|
||||
CollectedAt string `json:"collected_at"`
|
||||
}
|
||||
|
||||
type poolStats struct {
|
||||
MaxConns int32 `json:"max_conns"`
|
||||
TotalConns int32 `json:"total_conns"`
|
||||
AcquiredConns int32 `json:"acquired_conns"`
|
||||
IdleConns int32 `json:"idle_conns"`
|
||||
EmptyAcquireCount int64 `json:"empty_acquire_count"`
|
||||
CanceledAcquireCount int64 `json:"canceled_acquire_count"`
|
||||
AcquireCount int64 `json:"acquire_count"`
|
||||
AcquireDurationMillis int64 `json:"acquire_duration_ms_total"`
|
||||
NewConnsCount int64 `json:"new_conns_count"`
|
||||
MaxLifetimeDestroyCount int64 `json:"max_lifetime_destroy_count"`
|
||||
MaxIdleDestroyCount int64 `json:"max_idle_destroy_count"`
|
||||
}
|
||||
|
||||
type messageCounters struct {
|
||||
Created uint64 `json:"created"`
|
||||
Replayed uint64 `json:"replayed"`
|
||||
Conflicts uint64 `json:"conflicts"`
|
||||
}
|
||||
|
||||
type runtimeStats struct {
|
||||
Goroutines int `json:"goroutines"`
|
||||
HeapAlloc uint64 `json:"heap_alloc_bytes"`
|
||||
HeapSys uint64 `json:"heap_sys_bytes"`
|
||||
TotalAlloc uint64 `json:"total_alloc_bytes"`
|
||||
}
|
||||
|
||||
// InternalStatsHandler serves one snapshot. It is mounted only on the
|
||||
// 127.0.0.1 listener started by cmd/messenger.
|
||||
func (a *App) InternalStatsHandler(w http.ResponseWriter, _ *http.Request) {
|
||||
pool := a.store.PoolStats()
|
||||
var memory runtime.MemStats
|
||||
runtime.ReadMemStats(&memory)
|
||||
stats := InternalStats{
|
||||
InstanceID: a.instanceID,
|
||||
Version: a.version,
|
||||
UptimeSeconds: time.Since(a.startedAt).Seconds(),
|
||||
Pool: poolStats{
|
||||
MaxConns: pool.MaxConns,
|
||||
TotalConns: pool.TotalConns,
|
||||
AcquiredConns: pool.AcquiredConns,
|
||||
IdleConns: pool.IdleConns,
|
||||
EmptyAcquireCount: pool.EmptyAcquireCount,
|
||||
CanceledAcquireCount: pool.CanceledAcquireCount,
|
||||
AcquireCount: pool.AcquireCount,
|
||||
AcquireDurationMillis: pool.AcquireDurationMillis,
|
||||
NewConnsCount: pool.NewConnsCount,
|
||||
MaxLifetimeDestroyCount: pool.MaxLifetimeDestroyCount,
|
||||
MaxIdleDestroyCount: pool.MaxIdleDestroyCount,
|
||||
},
|
||||
Messages: messageCounters{
|
||||
Created: a.createdMessages.Load(),
|
||||
Replayed: a.replayedMessages.Load(),
|
||||
Conflicts: a.conflictMessages.Load(),
|
||||
},
|
||||
Runtime: runtimeStats{
|
||||
Goroutines: runtime.NumGoroutine(),
|
||||
HeapAlloc: memory.HeapAlloc,
|
||||
HeapSys: memory.HeapSys,
|
||||
TotalAlloc: memory.TotalAlloc,
|
||||
},
|
||||
CollectedAt: time.Now().UTC().Format(time.RFC3339Nano),
|
||||
}
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
_ = json.NewEncoder(w).Encode(stats)
|
||||
}
|
||||
@@ -0,0 +1,157 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/auth"
|
||||
"mtusi.ru/messenger-lab3/internal/model"
|
||||
"mtusi.ru/messenger-lab3/internal/session"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
)
|
||||
|
||||
// createSession is the only endpoint that accepts Basic credentials. It never
|
||||
// accepts a JSON body and never reveals whether the username exists.
|
||||
func (a *App) createSession(w http.ResponseWriter, r *http.Request) {
|
||||
username, password, err := auth.ParseBasic(r.Header.Get("Authorization"))
|
||||
if err != nil {
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
// Reject values that could never have been registered before touching the
|
||||
// database (invalid UTF-8 would otherwise become a 500 from PostgreSQL).
|
||||
if !usernameAllowed(username) || !validLoginPassword(password) {
|
||||
_, _ = auth.Verify(password, a.dummyHash)
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
|
||||
user, passwordHash, err := a.store.UserByUsername(r.Context(), username)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
// Spend the same KDF work for an unknown username so response timing
|
||||
// does not disclose account existence.
|
||||
_, _ = auth.Verify(password, a.dummyHash)
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("login database unavailable", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("login lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
match, err := auth.Verify(password, passwordHash)
|
||||
if err != nil {
|
||||
// A corrupt stored hash is an internal data problem, not a wrong
|
||||
// password; do not silently lock the account out with a 401 log line.
|
||||
a.log.Error("stored password hash is invalid", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
if !match {
|
||||
a.writeError(w, r, unauthorizedBasic())
|
||||
return
|
||||
}
|
||||
|
||||
token, expiresAt, err := a.sessions.Create(r.Context(), user.ID)
|
||||
if err != nil {
|
||||
a.log.Error("session creation failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, session.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, model.Session{
|
||||
Token: token,
|
||||
TokenType: "Bearer",
|
||||
ExpiresAt: model.Time{Time: expiresAt},
|
||||
User: user,
|
||||
})
|
||||
}
|
||||
|
||||
// authenticate accepts only "Authorization: Bearer <opaque token>". A Basic
|
||||
// header on a business endpoint, a missing header and an X-User-Id header all
|
||||
// produce the same 401 challenge.
|
||||
func (a *App) authenticate(r *http.Request) (identity, *apiError) {
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok || !auth.ValidTokenShape(token) {
|
||||
return identity{}, unauthorizedBearer()
|
||||
}
|
||||
|
||||
userID, err := a.sessions.Get(r.Context(), token)
|
||||
switch {
|
||||
case errors.Is(err, session.ErrInvalid):
|
||||
return identity{}, unauthorizedBearer()
|
||||
case errors.Is(err, session.ErrUnavailable):
|
||||
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusUnavailable
|
||||
case err != nil:
|
||||
a.log.Error("session lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusInternal
|
||||
}
|
||||
|
||||
user, err := a.store.UserByID(r.Context(), userID)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrNotFound):
|
||||
// A session pointing at a missing user is not usable. Deleting it is
|
||||
// best effort; the response is the normal 401 either way.
|
||||
_ = a.sessions.Delete(r.Context(), token)
|
||||
return identity{}, unauthorizedBearer()
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusUnavailable
|
||||
case err != nil:
|
||||
a.log.Error("user lookup failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
return identity{}, statusInternal
|
||||
}
|
||||
return identity{user: user, token: token}, nil
|
||||
}
|
||||
|
||||
// logout revokes the current server-side session. The response has no body.
|
||||
func (a *App) logout(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
if err := a.sessions.Delete(r.Context(), actor.token); err != nil {
|
||||
a.log.Error("logout failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
if errors.Is(err, session.ErrUnavailable) {
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
}
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
}
|
||||
|
||||
func bearerToken(header string) (string, bool) {
|
||||
trimmed := strings.TrimSpace(header)
|
||||
space := strings.IndexByte(trimmed, ' ')
|
||||
if space <= 0 {
|
||||
return "", false
|
||||
}
|
||||
if !strings.EqualFold(trimmed[:space], "Bearer") {
|
||||
return "", false
|
||||
}
|
||||
token := trimmed[space+1:]
|
||||
if token == "" || strings.ContainsAny(token, " \t") {
|
||||
return "", false
|
||||
}
|
||||
return token, true
|
||||
}
|
||||
|
||||
// validLoginPassword mirrors the registration policy. A login with an
|
||||
// out-of-range password cannot match any stored hash and must still look like
|
||||
// an ordinary 401.
|
||||
func validLoginPassword(password string) bool {
|
||||
if !utf8.ValidString(password) || isBlank(password) {
|
||||
return false
|
||||
}
|
||||
count := utf8.RuneCountInString(password)
|
||||
return count >= 12 && count <= 128
|
||||
}
|
||||
@@ -0,0 +1,74 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"net/http"
|
||||
|
||||
"mtusi.ru/messenger-lab3/internal/auth"
|
||||
"mtusi.ru/messenger-lab3/internal/store"
|
||||
)
|
||||
|
||||
type createUserRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
func (a *App) createUser(w http.ResponseWriter, r *http.Request) {
|
||||
var request createUserRequest
|
||||
if problem := a.decodeJSON(r, &request, "username", "display_name", "password"); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if request.Username == nil {
|
||||
a.writeError(w, r, invalidRequest("username is required"))
|
||||
return
|
||||
}
|
||||
if request.DisplayName == nil {
|
||||
a.writeError(w, r, invalidRequest("display_name is required"))
|
||||
return
|
||||
}
|
||||
if request.Password == nil {
|
||||
a.writeError(w, r, invalidRequest("password is required"))
|
||||
return
|
||||
}
|
||||
if problem := validateUsername(*request.Username); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := validateDisplayName(*request.DisplayName); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
if problem := validatePassword(*request.Password); problem != nil {
|
||||
a.writeError(w, r, problem)
|
||||
return
|
||||
}
|
||||
|
||||
passwordHash, err := auth.Hash(*request.Password)
|
||||
if err != nil {
|
||||
a.log.Error("password hashing failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
|
||||
user, err := a.store.CreateUser(r.Context(), *request.Username, *request.DisplayName, passwordHash)
|
||||
switch {
|
||||
case errors.Is(err, store.ErrUsernameTaken):
|
||||
a.writeError(w, r, statusConflict)
|
||||
return
|
||||
case errors.Is(err, store.ErrUnavailable):
|
||||
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusUnavailable)
|
||||
return
|
||||
case err != nil:
|
||||
a.log.Error("create user failed", "request_id", requestIDFromContext(r.Context()), "error", err)
|
||||
a.writeError(w, r, statusInternal)
|
||||
return
|
||||
}
|
||||
a.writeJSON(w, r, http.StatusCreated, user)
|
||||
}
|
||||
|
||||
func (a *App) currentUser(w http.ResponseWriter, r *http.Request, actor identity) {
|
||||
a.writeJSON(w, r, http.StatusOK, actor.user)
|
||||
}
|
||||
@@ -0,0 +1,236 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"io"
|
||||
"mime"
|
||||
"net/http"
|
||||
"net/url"
|
||||
"strconv"
|
||||
"strings"
|
||||
"unicode/utf8"
|
||||
)
|
||||
|
||||
// decodeJSON enforces the contract's JSON rules: application/json, strict
|
||||
// UTF-8, exactly one object with exactly the documented top-level keys, no
|
||||
// unknown/duplicate fields and a bounded body size.
|
||||
//
|
||||
// encoding/json matches struct fields case-insensitively even with
|
||||
// DisallowUnknownFields, so the exact key set is checked separately on the
|
||||
// token stream. That also rejects Unicode case-folding aliases and duplicates.
|
||||
func (a *App) decodeJSON(r *http.Request, destination any, allowedKeys ...string) *apiError {
|
||||
if raw := r.Header.Get("Content-Type"); raw != "" {
|
||||
mediaType, _, err := mime.ParseMediaType(raw)
|
||||
if err != nil || mediaType != "application/json" {
|
||||
return statusUnsupportedMediaType
|
||||
}
|
||||
}
|
||||
|
||||
body, err := io.ReadAll(io.LimitReader(r.Body, a.maxBody+1))
|
||||
if err != nil {
|
||||
return invalidRequest("could not read request body")
|
||||
}
|
||||
if int64(len(body)) > a.maxBody {
|
||||
return statusPayloadTooLarge
|
||||
}
|
||||
if len(bytes.TrimSpace(body)) == 0 {
|
||||
return invalidRequest("request body must not be empty")
|
||||
}
|
||||
if !utf8.Valid(body) {
|
||||
return invalidRequest("request body must be valid UTF-8")
|
||||
}
|
||||
if problem := validateTopLevelKeys(body, allowedKeys); problem != nil {
|
||||
return problem
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
decoder.DisallowUnknownFields()
|
||||
if err := decoder.Decode(destination); err != nil {
|
||||
return invalidRequest("request body does not match the documented schema")
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return invalidRequest("request body must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTopLevelKeys(body []byte, allowedKeys []string) *apiError {
|
||||
allowed := make(map[string]struct{}, len(allowedKeys))
|
||||
for _, key := range allowedKeys {
|
||||
allowed[key] = struct{}{}
|
||||
}
|
||||
|
||||
decoder := json.NewDecoder(bytes.NewReader(body))
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
opening, ok := token.(json.Delim)
|
||||
if !ok || opening != '{' {
|
||||
return invalidRequest("request body must be a JSON object")
|
||||
}
|
||||
|
||||
seen := make(map[string]struct{}, len(allowedKeys))
|
||||
for decoder.More() {
|
||||
token, err := decoder.Token()
|
||||
if err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
key, ok := token.(string)
|
||||
if !ok {
|
||||
return invalidRequest("request body must contain string field names")
|
||||
}
|
||||
if _, duplicate := seen[key]; duplicate {
|
||||
return invalidRequest("request body must not contain duplicate fields")
|
||||
}
|
||||
seen[key] = struct{}{}
|
||||
if _, ok := allowed[key]; !ok {
|
||||
return invalidRequest("request body contains an unknown field")
|
||||
}
|
||||
var value json.RawMessage
|
||||
if err := decoder.Decode(&value); err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
}
|
||||
if _, err := decoder.Token(); err != nil {
|
||||
return invalidRequest("request body must be valid JSON")
|
||||
}
|
||||
var extra any
|
||||
if err := decoder.Decode(&extra); !errors.Is(err, io.EOF) {
|
||||
return invalidRequest("request body must contain exactly one JSON value")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// pageParams parses limit/cursor. Cursor decoding happens after membership is
|
||||
// verified so a foreign chat cannot be probed with a malformed cursor.
|
||||
func (a *App) pageParams(r *http.Request) (int, string, *apiError) {
|
||||
query, err := url.ParseQuery(r.URL.RawQuery)
|
||||
if err != nil {
|
||||
return 0, "", invalidRequest("query string is not valid")
|
||||
}
|
||||
|
||||
limit := 50
|
||||
if values, present := query["limit"]; present {
|
||||
if len(values) != 1 {
|
||||
return 0, "", invalidRequest("limit must be specified once")
|
||||
}
|
||||
parsed, err := strconv.Atoi(values[0])
|
||||
if err != nil || parsed < 1 || parsed > 100 {
|
||||
return 0, "", invalidRequest("limit must be an integer between 1 and 100")
|
||||
}
|
||||
limit = parsed
|
||||
}
|
||||
|
||||
cursor := ""
|
||||
if values, present := query["cursor"]; present {
|
||||
if len(values) != 1 || values[0] == "" {
|
||||
return 0, "", invalidRequest("cursor must be a non-empty string")
|
||||
}
|
||||
cursor = values[0]
|
||||
}
|
||||
return limit, cursor, nil
|
||||
}
|
||||
|
||||
func validateUsername(value string) *apiError {
|
||||
if !usernameAllowed(value) {
|
||||
return invalidRequest("username must match [a-z0-9_]{3,32}")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateDisplayName(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("display_name must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
|
||||
return invalidRequest("display_name must contain 1 to 100 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateTitle(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("title must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 100 {
|
||||
return invalidRequest("title must contain 1 to 100 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func validateMessageText(value string) *apiError {
|
||||
if isBlank(value) {
|
||||
return invalidRequest("text must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 1 || count > 4000 {
|
||||
return invalidRequest("text must contain 1 to 4000 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
// validatePassword implements the registration rule: 12 to 128 Unicode code
|
||||
// points, not only whitespace. The exact bytes are handed to Argon2id, so
|
||||
// Unicode passwords are neither truncated nor normalized by the server.
|
||||
func validatePassword(value string) *apiError {
|
||||
if !utf8.ValidString(value) {
|
||||
return invalidRequest("password must be valid UTF-8")
|
||||
}
|
||||
if isBlank(value) {
|
||||
return invalidRequest("password must not be blank")
|
||||
}
|
||||
if count := utf8.RuneCountInString(value); count < 12 || count > 128 {
|
||||
return invalidRequest("password must contain 12 to 128 Unicode code points")
|
||||
}
|
||||
return nil
|
||||
}
|
||||
|
||||
func isBlank(value string) bool {
|
||||
return strings.TrimSpace(value) == ""
|
||||
}
|
||||
|
||||
// usernameAllowed is a byte-wise equivalent of the contract pattern
|
||||
// ^[a-z0-9_]{3,32}$; non-ASCII bytes can never match.
|
||||
func usernameAllowed(value string) bool {
|
||||
if len(value) < 3 || len(value) > 32 {
|
||||
return false
|
||||
}
|
||||
for i := 0; i < len(value); i++ {
|
||||
c := value[i]
|
||||
if (c >= 'a' && c <= 'z') || (c >= '0' && c <= '9') || c == '_' {
|
||||
continue
|
||||
}
|
||||
return false
|
||||
}
|
||||
return true
|
||||
}
|
||||
|
||||
// idempotencyKey enforces the contract's header rule exactly:
|
||||
// ASCII [A-Za-z0-9._:-]{1,128}, present exactly once. No trimming: whitespace
|
||||
// is outside the permitted alphabet, so a value with surrounding spaces is
|
||||
// rejected rather than silently normalised into a different scope.
|
||||
func idempotencyKey(r *http.Request) (string, *apiError) {
|
||||
values := r.Header.Values("Idempotency-Key")
|
||||
if len(values) != 1 {
|
||||
return "", invalidRequest("Idempotency-Key header is required exactly once")
|
||||
}
|
||||
key := values[0]
|
||||
if len(key) < 1 || len(key) > 128 {
|
||||
return "", invalidRequest("Idempotency-Key must contain 1 to 128 ASCII characters")
|
||||
}
|
||||
for i := 0; i < len(key); i++ {
|
||||
c := key[i]
|
||||
switch {
|
||||
case c >= 'A' && c <= 'Z':
|
||||
case c >= 'a' && c <= 'z':
|
||||
case c >= '0' && c <= '9':
|
||||
case c == '.' || c == '_' || c == ':' || c == '-':
|
||||
default:
|
||||
return "", invalidRequest("Idempotency-Key may contain only A-Z a-z 0-9 . _ : -")
|
||||
}
|
||||
}
|
||||
return key, nil
|
||||
}
|
||||
@@ -0,0 +1,203 @@
|
||||
package api
|
||||
|
||||
import (
|
||||
"bytes"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
type sampleRequest struct {
|
||||
Username *string `json:"username"`
|
||||
DisplayName *string `json:"display_name"`
|
||||
Password *string `json:"password"`
|
||||
}
|
||||
|
||||
func decodeTestApp() *App { return &App{maxBody: maxBodyBytes} }
|
||||
|
||||
func TestDecodeJSONAcceptsDocumentedObject(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
body := `{"username":"alice","display_name":"Алиса","password":"long-enough-secret"}`
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json; charset=utf-8")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem != nil {
|
||||
t.Fatalf("decodeJSON rejected a valid body: %v", problem)
|
||||
}
|
||||
if destination.Username == nil || *destination.Username != "alice" {
|
||||
t.Fatalf("decoded value = %+v", destination)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsContractViolations(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
cases := []struct {
|
||||
name string
|
||||
body string
|
||||
contentType string
|
||||
status int
|
||||
}{
|
||||
{"empty", "", "application/json", http.StatusBadRequest},
|
||||
{"whitespace only", " \n", "application/json", http.StatusBadRequest},
|
||||
{"malformed", `{"username":`, "application/json", http.StatusBadRequest},
|
||||
{"array instead of object", `[]`, "application/json", http.StatusBadRequest},
|
||||
{"string instead of object", `"x"`, "application/json", http.StatusBadRequest},
|
||||
{"unknown field", `{"username":"a","display_name":"b","password":"c","extra":1}`, "application/json", http.StatusBadRequest},
|
||||
{"duplicate field", `{"username":"a","username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
||||
{"uppercase alias", `{"Username":"a","display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
||||
{"alias beside correct key", `{"username":"a","Username":"b","display_name":"c","password":"d"}`, "application/json", http.StatusBadRequest},
|
||||
{"wrong type", `{"username":1,"display_name":"b","password":"c"}`, "application/json", http.StatusBadRequest},
|
||||
{"two values", `{"username":"a","display_name":"b","password":"c"}{}`, "application/json", http.StatusBadRequest},
|
||||
{"wrong content type", `{"username":"a","display_name":"b","password":"c"}`, "text/plain", http.StatusUnsupportedMediaType},
|
||||
{"malformed content type", `{"username":"a","display_name":"b","password":"c"}`, "application/json; charset", http.StatusUnsupportedMediaType},
|
||||
}
|
||||
for _, tc := range cases {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(tc.body))
|
||||
request.Header.Set("Content-Type", tc.contentType)
|
||||
var destination sampleRequest
|
||||
problem := app.decodeJSON(request, &destination, "username", "display_name", "password")
|
||||
if problem == nil {
|
||||
t.Fatal("decodeJSON accepted an invalid body")
|
||||
}
|
||||
if problem.status != tc.status {
|
||||
t.Fatalf("status = %d, want %d", problem.status, tc.status)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsInvalidUTF8(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
body := append([]byte(`{"username":"`), 0xff, 0xfe)
|
||||
body = append(body, []byte(`","display_name":"b","password":"c"}`)...)
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", bytes.NewReader(body))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username", "display_name", "password"); problem == nil || problem.status != http.StatusBadRequest {
|
||||
t.Fatalf("invalid UTF-8 was not rejected with 400: %v", problem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestDecodeJSONRejectsOversizedBody(t *testing.T) {
|
||||
app := decodeTestApp()
|
||||
app.maxBody = 16
|
||||
request := httptest.NewRequest(http.MethodPost, "/api/v1/users", strings.NewReader(`{"username":"`+strings.Repeat("x", 64)+`"}`))
|
||||
request.Header.Set("Content-Type", "application/json")
|
||||
var destination sampleRequest
|
||||
if problem := app.decodeJSON(request, &destination, "username"); problem == nil || problem.status != http.StatusRequestEntityTooLarge {
|
||||
t.Fatalf("oversized body = %v, want 413", problem)
|
||||
}
|
||||
}
|
||||
|
||||
func TestUsernameValidation(t *testing.T) {
|
||||
valid := []string{"abc", "a_b9", strings.Repeat("a", 32)}
|
||||
for _, value := range valid {
|
||||
if problem := validateUsername(value); problem != nil {
|
||||
t.Fatalf("validateUsername(%q) = %v", value, problem)
|
||||
}
|
||||
}
|
||||
invalid := []string{"", "ab", strings.Repeat("a", 33), "Alice", "a-b", "a b", "aбв", "abc\n"}
|
||||
for _, value := range invalid {
|
||||
if problem := validateUsername(value); problem == nil {
|
||||
t.Fatalf("validateUsername accepted %q", value)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestLengthValidationCountsCodePoints(t *testing.T) {
|
||||
if problem := validateDisplayName(strings.Repeat("😀", 100)); problem != nil {
|
||||
t.Fatalf("100 code points rejected: %v", problem)
|
||||
}
|
||||
if problem := validateDisplayName(strings.Repeat("😀", 101)); problem == nil {
|
||||
t.Fatal("101 code points accepted")
|
||||
}
|
||||
if problem := validateDisplayName(" "); problem == nil {
|
||||
t.Fatal("blank display_name accepted")
|
||||
}
|
||||
|
||||
if problem := validateMessageText(strings.Repeat("я", 4000)); problem != nil {
|
||||
t.Fatalf("4000 code points rejected: %v", problem)
|
||||
}
|
||||
if problem := validateMessageText(strings.Repeat("я", 4001)); problem == nil {
|
||||
t.Fatal("4001 code points accepted")
|
||||
}
|
||||
if problem := validateMessageText(" \t\n"); problem == nil {
|
||||
t.Fatal("blank message accepted")
|
||||
}
|
||||
|
||||
if problem := validatePassword(strings.Repeat("p", 12)); problem != nil {
|
||||
t.Fatalf("12-character password rejected: %v", problem)
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 11)); problem == nil {
|
||||
t.Fatal("11-character password accepted")
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 128)); problem != nil {
|
||||
t.Fatalf("128-character password rejected: %v", problem)
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat("p", 129)); problem == nil {
|
||||
t.Fatal("129-character password accepted")
|
||||
}
|
||||
if problem := validatePassword(strings.Repeat(" ", 12)); problem == nil {
|
||||
t.Fatal("whitespace password accepted")
|
||||
}
|
||||
}
|
||||
|
||||
func TestPageParams(t *testing.T) {
|
||||
valid := map[string][2]any{
|
||||
"": {50, ""},
|
||||
"?limit=1": {1, ""},
|
||||
"?limit=100": {100, ""},
|
||||
"?limit=7&cursor=x": {7, "x"},
|
||||
}
|
||||
for query, want := range valid {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
||||
limit, cursor, problem := decodeTestApp().pageParams(request)
|
||||
if problem != nil {
|
||||
t.Fatalf("pageParams(%q) = %v", query, problem)
|
||||
}
|
||||
if limit != want[0].(int) || cursor != want[1].(string) {
|
||||
t.Fatalf("pageParams(%q) = %d,%q", query, limit, cursor)
|
||||
}
|
||||
}
|
||||
invalid := []string{"?limit=0", "?limit=101", "?limit=abc", "?limit=", "?limit=1&limit=2", "?cursor=", "?cursor=a&cursor=b", "?limit=1;cursor=x"}
|
||||
for _, query := range invalid {
|
||||
request := httptest.NewRequest(http.MethodGet, "/api/v1/chats"+query, nil)
|
||||
if _, _, problem := decodeTestApp().pageParams(request); problem == nil {
|
||||
t.Fatalf("pageParams accepted %q", query)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestBearerTokenParsing(t *testing.T) {
|
||||
token := strings.Repeat("a", 43)
|
||||
cases := map[string]string{
|
||||
"Bearer " + token: token,
|
||||
"bearer " + token: token,
|
||||
"BEARER " + token: token,
|
||||
}
|
||||
for header, want := range cases {
|
||||
got, ok := bearerToken(header)
|
||||
if !ok || got != want {
|
||||
t.Fatalf("bearerToken(%q) = %q,%v", header, got, ok)
|
||||
}
|
||||
}
|
||||
for _, header := range []string{"", "Bearer", "Bearer ", "Basic abc", "Bearer a b", "Token " + token} {
|
||||
if _, ok := bearerToken(header); ok {
|
||||
t.Fatalf("bearerToken accepted %q", header)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestErrorEnvelopeShape(t *testing.T) {
|
||||
envelope := errorEnvelope{Error: errorBody{Code: "invalid_request", Message: "x", RequestID: "id"}}
|
||||
data, err := json.Marshal(envelope)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(data) != `{"error":{"code":"invalid_request","message":"x","request_id":"id"}}` {
|
||||
t.Fatalf("unexpected error JSON: %s", data)
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user