Перенести решение лабораторной 1 как основу для лабораторной 2

This commit is contained in:
2026-10-06 11:54:05 +03:00
parent 65003b6119
commit 5c3f2bfad0
54 changed files with 4472 additions and 0 deletions
+70
View File
@@ -0,0 +1,70 @@
package httpx
import (
"bytes"
"encoding/json"
"errors"
"fmt"
"io"
"mime"
"net/http"
"strings"
"unicode/utf8"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
// DecodeJSON reads exactly one JSON object into dst and enforces what gin's
// binding does not: the media type must be application/json (415), invalid
// UTF-8, unknown fields, wrong types, malformed syntax and trailing data are
// 400, an oversized body is 413, and messages never expose Go type names.
func DecodeJSON(c *gin.Context, dst any) error {
mediaType, _, err := mime.ParseMediaType(c.GetHeader("Content-Type"))
if err != nil || mediaType != "application/json" {
return apperr.UnsupportedMedia("Content-Type must be application/json")
}
// The body is already capped by the bodyLimit middleware, so reading it
// whole is bounded.
body, err := io.ReadAll(c.Request.Body)
if err != nil {
return decodeError(err)
}
// encoding/json silently replaces invalid UTF-8 with U+FFFD; the contract
// and RFC 8259 require UTF-8, so such a body is rejected, not repaired.
if !utf8.Valid(body) {
return apperr.Invalid("request body must be valid UTF-8")
}
dec := json.NewDecoder(bytes.NewReader(body))
dec.DisallowUnknownFields()
if err := dec.Decode(dst); err != nil {
return decodeError(err)
}
if err := dec.Decode(&struct{}{}); !errors.Is(err, io.EOF) {
return apperr.Invalid("unexpected data after JSON body")
}
return nil
}
func decodeError(err error) error {
if tooLarge, ok := errors.AsType[*http.MaxBytesError](err); ok {
return apperr.Wrap(apperr.KindPayloadTooLarge, fmt.Sprintf("request body must be at most %d bytes", tooLarge.Limit), err)
}
if errors.Is(err, io.EOF) {
return apperr.Wrap(apperr.KindInvalid, "request body is required", err)
}
if wrongType, ok := errors.AsType[*json.UnmarshalTypeError](err); ok {
if wrongType.Field == "" {
return apperr.Wrap(apperr.KindInvalid, "request body must be a JSON object", err)
}
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("field %q has wrong type", wrongType.Field), err)
}
// encoding/json reports unknown fields as a plain error without a type.
const unknownPrefix = "json: unknown field "
if msg := err.Error(); strings.HasPrefix(msg, unknownPrefix) {
field := strings.Trim(strings.TrimPrefix(msg, unknownPrefix), `"`)
return apperr.Wrap(apperr.KindInvalid, fmt.Sprintf("unknown field %q", field), err)
}
return apperr.Wrap(apperr.KindInvalid, "malformed JSON body", err)
}
+49
View File
@@ -0,0 +1,49 @@
// Package httpx is the transport layer over gin: request ids, access
// logging, panic recovery, body limits, strict JSON decoding and the single
// error format of the API contract. gin is used for routing and the
// middleware chain; everything here exists because the contract demands a
// specific behaviour that gin's own helpers do not provide.
package httpx
import (
"log/slog"
"net/http"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
const (
keyRequestID = "messenger.request_id"
keyLogger = "messenger.logger"
)
// NewEngine builds an engine whose every response, including routing
// failures and panics, carries X-Request-Id and the contract error body.
func NewEngine(log *slog.Logger, maxBodyBytes int64) *gin.Engine {
gin.SetMode(gin.ReleaseMode)
e := gin.New()
// Redirects would answer with text/plain and without a request id.
e.RedirectTrailingSlash = false
e.RedirectFixedPath = false
e.HandleMethodNotAllowed = true
e.Use(requestID(log), accessLog(), recovery(), bodyLimit(maxBodyBytes))
e.NoRoute(func(c *gin.Context) { Error(c, apperr.NotFound("route not found")) })
e.NoMethod(func(c *gin.Context) { Fail(c, http.StatusMethodNotAllowed, "invalid_request", "method not allowed") })
return e
}
func RequestID(c *gin.Context) string {
return c.GetString(keyRequestID)
}
func logger(c *gin.Context) *slog.Logger {
if l, ok := c.Get(keyLogger); ok {
if log, ok := l.(*slog.Logger); ok {
return log
}
}
return slog.Default()
}
+309
View File
@@ -0,0 +1,309 @@
package httpx_test
import (
"bytes"
"encoding/json"
"errors"
"io"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"github.com/gin-gonic/gin"
"github.com/google/uuid"
"messenger/internal/platform/apperr"
"messenger/internal/platform/httpx"
)
type errorBody struct {
Error struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
} `json:"error"`
}
type payload struct {
Text string `json:"text"`
Count int `json:"count"`
}
func newEngine(t *testing.T, logs *bytes.Buffer) *gin.Engine {
t.Helper()
return newEngineAt(t, logs, slog.LevelDebug)
}
func newEngineAt(t *testing.T, logs *bytes.Buffer, level slog.Level) *gin.Engine {
t.Helper()
if logs == nil {
logs = &bytes.Buffer{}
}
log := slog.New(slog.NewJSONHandler(logs, &slog.HandlerOptions{Level: level}))
e := httpx.NewEngine(log, 64)
e.GET("/ok", func(c *gin.Context) { httpx.JSON(c, http.StatusOK, gin.H{"text": "<a&b>"}) })
e.GET("/panic", func(c *gin.Context) { panic("secret detail") })
e.GET("/fail", func(c *gin.Context) { httpx.Error(c, errors.New("db password leaked")) })
e.GET("/notfound", func(c *gin.Context) { httpx.Error(c, apperr.NotFound("chat not found")) })
e.GET("/who", func(c *gin.Context) {
httpx.SetUserID(c, uuid.MustParse("11111111-1111-4111-8111-111111111111"))
id, ok := httpx.UserID(c)
httpx.JSON(c, http.StatusOK, gin.H{"id": id.String(), "ok": ok})
})
e.POST("/decode", func(c *gin.Context) {
var p payload
if err := httpx.DecodeJSON(c, &p); err != nil {
httpx.Error(c, err)
return
}
httpx.JSON(c, http.StatusOK, p)
})
return e
}
func do(t *testing.T, e *gin.Engine, method, path string, body string, headers map[string]string) (*httptest.ResponseRecorder, errorBody) {
t.Helper()
var reader io.Reader
if body != "" {
reader = strings.NewReader(body)
}
req := httptest.NewRequest(method, path, reader)
for k, v := range headers {
req.Header.Set(k, v)
}
rec := httptest.NewRecorder()
e.ServeHTTP(rec, req)
var eb errorBody
if rec.Code >= 400 {
if err := json.Unmarshal(rec.Body.Bytes(), &eb); err != nil {
t.Fatalf("%s %s: error body is not JSON: %v: %s", method, path, err, rec.Body.String())
}
}
return rec, eb
}
func assertError(t *testing.T, rec *httptest.ResponseRecorder, eb errorBody, status int, code string) {
t.Helper()
if rec.Code != status {
t.Fatalf("status = %d, want %d (body %s)", rec.Code, status, rec.Body.String())
}
if ct := rec.Header().Get("Content-Type"); !strings.HasPrefix(ct, "application/json") {
t.Fatalf("Content-Type = %q", ct)
}
rid := rec.Header().Get("X-Request-Id")
if rid == "" {
t.Fatal("missing X-Request-Id header")
}
if eb.Error.RequestID != rid {
t.Fatalf("body request_id %q != header %q", eb.Error.RequestID, rid)
}
if eb.Error.Code != code || eb.Error.Message == "" {
t.Fatalf("error = %+v, want code %q with a message", eb.Error, code)
}
}
func TestUnknownRouteIsJSON404(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/nope", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
}
func TestTrailingSlashIsNotRedirected(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/ok/", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
}
func TestWrongMethodIsJSON405WithAllow(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodDelete, "/ok", "", nil)
assertError(t, rec, eb, http.StatusMethodNotAllowed, "invalid_request")
if !strings.Contains(rec.Header().Get("Allow"), "GET") {
t.Fatalf("Allow = %q, want GET", rec.Header().Get("Allow"))
}
}
func TestPanicBecomesJSON500WithoutDetails(t *testing.T) {
logs := &bytes.Buffer{}
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/panic", "", nil)
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
if strings.Contains(rec.Body.String(), "secret detail") {
t.Fatal("panic value leaked to the client")
}
if !strings.Contains(logs.String(), "secret detail") {
t.Fatal("panic must be logged for operators")
}
}
func TestForeignErrorBecomesJSON500WithoutDetails(t *testing.T) {
logs := &bytes.Buffer{}
rec, eb := do(t, newEngine(t, logs), http.MethodGet, "/fail", "", nil)
assertError(t, rec, eb, http.StatusInternalServerError, "internal_error")
if strings.Contains(rec.Body.String(), "password") {
t.Fatal("internal error text leaked to the client")
}
if !strings.Contains(logs.String(), "db password leaked") {
t.Fatal("cause must be logged for operators")
}
}
func TestApplicationErrorMapping(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodGet, "/notfound", "", nil)
assertError(t, rec, eb, http.StatusNotFound, "not_found")
if eb.Error.Message != "chat not found" {
t.Fatalf("message = %q", eb.Error.Message)
}
}
func TestSuccessResponseHeadersAndEscaping(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", nil)
if rec.Code != http.StatusOK {
t.Fatalf("status = %d", rec.Code)
}
if ct := rec.Header().Get("Content-Type"); ct != "application/json; charset=utf-8" {
t.Fatalf("Content-Type = %q", ct)
}
if rec.Header().Get("X-Request-Id") == "" {
t.Fatal("missing X-Request-Id on success")
}
if !strings.Contains(rec.Body.String(), `"<a&b>"`) {
t.Fatalf("HTML escaping must be off, body %s", rec.Body.String())
}
}
func TestRequestIDIsGeneratedNotEchoed(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodGet, "/ok", "", map[string]string{"X-Request-Id": "client-chosen"})
if got := rec.Header().Get("X-Request-Id"); got == "" || got == "client-chosen" {
t.Fatalf("X-Request-Id = %q, want a server generated value", got)
}
}
func TestDecodeJSONHappyPath(t *testing.T) {
rec, _ := do(t, newEngine(t, nil), http.MethodPost, "/decode", `{"text":"Привет","count":2}`, map[string]string{"Content-Type": "application/json; charset=utf-8"})
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"Привет"`) {
t.Fatalf("status %d body %s", rec.Code, rec.Body.String())
}
}
func TestDecodeJSONFailures(t *testing.T) {
jsonCT := map[string]string{"Content-Type": "application/json"}
cases := []struct {
name string
body string
headers map[string]string
status int
code string
contain string
}{
{"no content type", `{"text":"x"}`, nil, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
{"wrong content type", `{"text":"x"}`, map[string]string{"Content-Type": "text/plain"}, http.StatusUnsupportedMediaType, "unsupported_media_type", ""},
{"empty body", "", jsonCT, http.StatusBadRequest, "invalid_request", "body"},
{"malformed", `{"text":`, jsonCT, http.StatusBadRequest, "invalid_request", "malformed"},
{"invalid utf-8", "{\"text\":\"bad \xff byte\"}", jsonCT, http.StatusBadRequest, "invalid_request", "UTF-8"},
{"unknown field", `{"text":"x","extra":1}`, jsonCT, http.StatusBadRequest, "invalid_request", "extra"},
{"wrong type", `{"text":123}`, jsonCT, http.StatusBadRequest, "invalid_request", "text"},
{"trailing data", `{"text":"x"} {"text":"y"}`, jsonCT, http.StatusBadRequest, "invalid_request", "after"},
{"array instead of object", `[1,2]`, jsonCT, http.StatusBadRequest, "invalid_request", ""},
{"too large", `{"text":"` + strings.Repeat("x", 100) + `"}`, jsonCT, http.StatusRequestEntityTooLarge, "payload_too_large", ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
rec, eb := do(t, newEngine(t, nil), http.MethodPost, "/decode", tc.body, tc.headers)
assertError(t, rec, eb, tc.status, tc.code)
if tc.contain != "" && !strings.Contains(eb.Error.Message, tc.contain) {
t.Fatalf("message %q must mention %q", eb.Error.Message, tc.contain)
}
if strings.Contains(eb.Error.Message, "httpx_test") || strings.Contains(eb.Error.Message, "payload") {
t.Fatalf("message must not leak Go type names: %q", eb.Error.Message)
}
})
}
}
func TestAccessLogHasRequestFieldsButNoBody(t *testing.T) {
logs := &bytes.Buffer{}
e := newEngine(t, logs)
rec, _ := do(t, e, http.MethodPost, "/decode", `{"text":"confidential"}`, map[string]string{"Content-Type": "application/json"})
var entry map[string]any
line := lastLine(logs.String())
if err := json.Unmarshal([]byte(line), &entry); err != nil {
t.Fatalf("log line is not JSON: %v: %s", err, line)
}
for _, key := range []string{"request_id", "method", "path", "status", "duration_ms"} {
if _, ok := entry[key]; !ok {
t.Errorf("log entry missing %q: %s", key, line)
}
}
if entry["request_id"] != rec.Header().Get("X-Request-Id") {
t.Errorf("log request_id %v != header %q", entry["request_id"], rec.Header().Get("X-Request-Id"))
}
if strings.Contains(logs.String(), "confidential") {
t.Fatal("request body must never be logged")
}
}
func TestAccessLogLevelFollowsStatus(t *testing.T) {
logs := &bytes.Buffer{}
e := newEngineAt(t, logs, slog.LevelInfo)
do(t, e, http.MethodGet, "/ok", "", nil)
if strings.Contains(logs.String(), `"msg":"request"`) {
t.Fatalf("successful requests must be logged at debug level only, got %s", logs.String())
}
do(t, e, http.MethodGet, "/notfound", "", nil)
if entry := logEntry(t, logs); entry["level"] != "INFO" || entry["status"] != float64(404) {
t.Fatalf("client error must be logged at info level with its status, got %v", entry)
}
do(t, e, http.MethodGet, "/fail", "", nil)
if entry := logEntry(t, logs); entry["level"] != "ERROR" || entry["status"] != float64(500) {
t.Fatalf("server error must be logged at error level with its status, got %v", entry)
}
verbose := &bytes.Buffer{}
do(t, newEngineAt(t, verbose, slog.LevelDebug), http.MethodGet, "/ok", "", nil)
if entry := logEntry(t, verbose); entry["level"] != "DEBUG" || entry["status"] != float64(200) {
t.Fatalf("at debug level successful requests must be logged, got %v", entry)
}
}
func TestUserIDRoundTripAndAccessLogAttribution(t *testing.T) {
logs := &bytes.Buffer{}
rec, _ := do(t, newEngine(t, logs), http.MethodGet, "/who", "", nil)
if rec.Code != http.StatusOK || !strings.Contains(rec.Body.String(), `"ok":true`) {
t.Fatalf("UserID must return what SetUserID stored: %d %s", rec.Code, rec.Body.String())
}
if entry := logEntry(t, logs); entry["user_id"] != "11111111-1111-4111-8111-111111111111" {
t.Fatalf("access log must attribute the request to the user, got %v", entry)
}
anonymous := &bytes.Buffer{}
do(t, newEngine(t, anonymous), http.MethodGet, "/ok", "", nil)
if _, present := logEntry(t, anonymous)["user_id"]; present {
t.Fatal("anonymous requests must not carry user_id")
}
}
func logEntry(t *testing.T, logs *bytes.Buffer) map[string]any {
t.Helper()
var entry map[string]any
line := lastLine(logs.String())
if err := json.Unmarshal([]byte(line), &entry); err != nil {
t.Fatalf("log line is not JSON: %v: %s", err, line)
}
return entry
}
func TestTimestampFormat(t *testing.T) {
ts := time.Date(2026, 9, 1, 12, 0, 0, 0, time.FixedZone("MSK", 3*3600))
if got := httpx.Timestamp(ts); got != "2026-09-01T09:00:00.000Z" {
t.Fatalf("Timestamp = %q", got)
}
ts = time.Date(2026, 9, 1, 12, 0, 0, 7_000_000, time.UTC)
if got := httpx.Timestamp(ts); got != "2026-09-01T12:00:00.007Z" {
t.Fatalf("Timestamp = %q", got)
}
}
func lastLine(s string) string {
lines := strings.Split(strings.TrimSpace(s), "\n")
return lines[len(lines)-1]
}
+25
View File
@@ -0,0 +1,25 @@
package httpx
import (
"github.com/gin-gonic/gin"
"github.com/google/uuid"
)
const keyUserID = "messenger.user_id"
// SetUserID records the identified caller for the handlers behind the
// identification middleware and for the access log. It lives here rather
// than in the auth package because the access log needs it and auth already
// depends on this package.
func SetUserID(c *gin.Context, id uuid.UUID) {
c.Set(keyUserID, id)
}
func UserID(c *gin.Context) (uuid.UUID, bool) {
v, ok := c.Get(keyUserID)
if !ok {
return uuid.Nil, false
}
id, ok := v.(uuid.UUID)
return id, ok
}
+105
View File
@@ -0,0 +1,105 @@
package httpx
import (
"crypto/rand"
"encoding/hex"
"fmt"
"log/slog"
"net/http"
"runtime/debug"
"time"
"github.com/gin-gonic/gin"
)
// requestID assigns a fresh identifier to every request.
//
// An incoming X-Request-Id is deliberately not reused. This service is
// client-facing: there is no trusted upstream that could have minted the
// value, so honouring it would let any caller pick an arbitrary string that
// ends up in logs (log injection, unbounded length) or collides with another
// request and corrupts log correlation. Reusing the header is the right
// choice only when the caller is a trusted proxy or a sibling service that
// propagates one id across a chain of calls.
func requestID(log *slog.Logger) gin.HandlerFunc {
return func(c *gin.Context) {
var raw [16]byte
if _, err := rand.Read(raw[:]); err != nil {
panic("httpx: random source unavailable: " + err.Error())
}
id := hex.EncodeToString(raw[:])
c.Set(keyRequestID, id)
c.Set(keyLogger, log)
c.Writer.Header().Set("X-Request-Id", id)
c.Next()
}
}
// accessLog writes one line per request at a level that follows the
// outcome (2xx debug, 4xx info, 5xx error), so the ordinary log level decides
// how much traffic is recorded. Headers, query strings and bodies are never
// recorded. time.Since uses the monotonic clock, so wall clock adjustments
// cannot distort the duration.
func accessLog() gin.HandlerFunc {
return func(c *gin.Context) {
start := time.Now()
c.Next()
status := c.Writer.Status()
level := slog.LevelDebug
switch {
case status >= http.StatusInternalServerError:
level = slog.LevelError
case status >= http.StatusBadRequest:
level = slog.LevelInfo
}
log := logger(c)
ctx := c.Request.Context()
if !log.Enabled(ctx, level) {
return
}
attrs := []any{
"request_id", RequestID(c),
"method", c.Request.Method,
"path", c.Request.URL.Path,
"status", status,
"duration_ms", float64(time.Since(start).Microseconds()) / 1000,
"bytes", c.Writer.Size(),
}
if id, ok := UserID(c); ok {
attrs = append(attrs, "user_id", id.String())
}
log.Log(ctx, level, "request", attrs...)
}
}
// recovery turns a panic into a contract 500; the stack goes to the log only.
func recovery() gin.HandlerFunc {
return func(c *gin.Context) {
defer func() {
if r := recover(); r != nil {
logger(c).Error("panic recovered",
"request_id", RequestID(c),
"panic", fmt.Sprint(r),
"stack", string(debug.Stack()),
)
if !c.Writer.Written() {
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
}
c.Abort()
}
}()
c.Next()
}
}
// bodyLimit caps request bodies; exceeding it surfaces from the JSON
// decoder as *http.MaxBytesError.
func bodyLimit(maxBytes int64) gin.HandlerFunc {
return func(c *gin.Context) {
if c.Request.Body != nil {
c.Request.Body = http.MaxBytesReader(c.Writer, c.Request.Body, maxBytes)
}
c.Next()
}
}
+71
View File
@@ -0,0 +1,71 @@
package httpx
import (
"net/http"
"time"
"github.com/gin-gonic/gin"
"messenger/internal/platform/apperr"
)
type errorEnvelope struct {
Error errorDetail `json:"error"`
}
type errorDetail struct {
Code string `json:"code"`
Message string `json:"message"`
RequestID string `json:"request_id"`
}
type statusCode struct {
status int
code string
}
var kinds = map[apperr.Kind]statusCode{
apperr.KindInvalid: {http.StatusBadRequest, "invalid_request"},
apperr.KindUnauthorized: {http.StatusUnauthorized, "unauthorized"},
apperr.KindNotFound: {http.StatusNotFound, "not_found"},
apperr.KindConflict: {http.StatusConflict, "conflict"},
apperr.KindPayloadTooLarge: {http.StatusRequestEntityTooLarge, "payload_too_large"},
apperr.KindUnsupportedMedia: {http.StatusUnsupportedMediaType, "unsupported_media_type"},
apperr.KindUnavailable: {http.StatusServiceUnavailable, "unavailable"},
}
// JSON is the single place that fixes the response media type; PureJSON
// keeps non-ASCII and HTML characters verbatim.
func JSON(c *gin.Context, status int, body any) {
c.PureJSON(status, body)
}
// Fail writes the contract error body and stops the handler chain.
func Fail(c *gin.Context, status int, code, message string) {
JSON(c, status, errorEnvelope{Error: errorDetail{
Code: code,
Message: message,
RequestID: RequestID(c),
}})
c.Abort()
}
// Error maps an application error to its status. Anything that is not an
// application error is logged with its text and reported as an opaque 500,
// so internal details never reach the client.
func Error(c *gin.Context, err error) {
mapped, known := kinds[apperr.KindOf(err)]
if !known {
logger(c).Error("request failed", "request_id", RequestID(c), "error", err.Error())
Fail(c, http.StatusInternalServerError, "internal_error", "internal error")
return
}
Fail(c, mapped.status, mapped.code, err.Error())
}
// Timestamp renders RFC 3339 UTC with a fixed millisecond width: Python 3.9
// (the oldest version the public tests support) only parses 3 or 6 fractional
// digits, and RFC3339Nano would trim trailing zeros to a variable width.
func Timestamp(t time.Time) string {
return t.UTC().Format("2006-01-02T15:04:05.000Z")
}