forked from mtusi2026/mtusi2026lab5
на оценку 5
This commit is contained in:
@@ -0,0 +1,113 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"errors"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"mtusi2026lab5/internal/domain"
|
||||
"mtusi2026lab5/internal/transport/http/response"
|
||||
)
|
||||
|
||||
const bearerChallenge = `Bearer realm="messenger"`
|
||||
|
||||
const (
|
||||
UserContextKey contextKey = "current_user"
|
||||
sessionTokenHashKey contextKey = "session_token_hash"
|
||||
)
|
||||
|
||||
type SessionAuthenticator interface {
|
||||
Authenticate(
|
||||
ctx context.Context,
|
||||
token string,
|
||||
) (domain.User, []byte, error)
|
||||
}
|
||||
|
||||
func RequireAuth(
|
||||
authenticator SessionAuthenticator,
|
||||
next http.HandlerFunc,
|
||||
) http.HandlerFunc {
|
||||
return func(w http.ResponseWriter, r *http.Request) {
|
||||
requestID := GetRequestID(r.Context())
|
||||
|
||||
token, ok := bearerToken(r.Header.Get("Authorization"))
|
||||
if !ok {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
|
||||
user, tokenHash, err := authenticator.Authenticate(
|
||||
r.Context(),
|
||||
token,
|
||||
)
|
||||
if errors.Is(err, domain.ErrNotFound) {
|
||||
writeBearerUnauthorized(w, requestID)
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is temporarily unavailable",
|
||||
requestID,
|
||||
)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := context.WithValue(
|
||||
r.Context(),
|
||||
UserContextKey,
|
||||
user,
|
||||
)
|
||||
ctx = context.WithValue(
|
||||
ctx,
|
||||
sessionTokenHashKey,
|
||||
tokenHash,
|
||||
)
|
||||
|
||||
next(w, r.WithContext(ctx))
|
||||
}
|
||||
}
|
||||
|
||||
func GetCurrentUser(ctx context.Context) domain.User {
|
||||
user, _ := ctx.Value(UserContextKey).(domain.User)
|
||||
return user
|
||||
}
|
||||
|
||||
func GetCurrentSessionTokenHash(ctx context.Context) []byte {
|
||||
tokenHash, _ := ctx.Value(sessionTokenHashKey).([]byte)
|
||||
|
||||
result := make([]byte, len(tokenHash))
|
||||
copy(result, tokenHash)
|
||||
|
||||
return result
|
||||
}
|
||||
|
||||
func bearerToken(authorization string) (string, bool) {
|
||||
parts := strings.Fields(authorization)
|
||||
|
||||
if len(parts) != 2 ||
|
||||
!strings.EqualFold(parts[0], "Bearer") ||
|
||||
parts[1] == "" {
|
||||
return "", false
|
||||
}
|
||||
|
||||
return parts[1], true
|
||||
}
|
||||
|
||||
func writeBearerUnauthorized(
|
||||
w http.ResponseWriter,
|
||||
requestID string,
|
||||
) {
|
||||
w.Header().Set("WWW-Authenticate", bearerChallenge)
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusUnauthorized,
|
||||
response.CodeUnauthorized,
|
||||
"invalid or expired bearer token",
|
||||
requestID,
|
||||
)
|
||||
}
|
||||
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"sync/atomic"
|
||||
|
||||
"mtusi2026lab5/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// AvailabilityGate lets a process reject new work before its HTTP listener is
|
||||
// closed. Existing requests are still drained by http.Server.Shutdown.
|
||||
type AvailabilityGate struct {
|
||||
accepting atomic.Bool
|
||||
}
|
||||
|
||||
func NewAvailabilityGate() *AvailabilityGate {
|
||||
gate := &AvailabilityGate{}
|
||||
gate.accepting.Store(true)
|
||||
|
||||
return gate
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) BeginDrain() {
|
||||
g.accepting.Store(false)
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) IsAccepting() bool {
|
||||
return g.accepting.Load()
|
||||
}
|
||||
|
||||
func (g *AvailabilityGate) Middleware(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
// Liveness deliberately stays available while the process drains. The
|
||||
// readiness endpoint and all business traffic receive 503 immediately.
|
||||
if g.IsAccepting() || r.URL.Path == "/health/live" {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusServiceUnavailable,
|
||||
response.CodeUnavailable,
|
||||
"service is draining",
|
||||
GetRequestID(r.Context()),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,38 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestAvailabilityGateRejectsNewWorkWhileKeepingLiveness(t *testing.T) {
|
||||
gate := NewAvailabilityGate()
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := RequestID(gate.Middleware(next))
|
||||
|
||||
before := httptest.NewRecorder()
|
||||
handler.ServeHTTP(before, httptest.NewRequest(http.MethodGet, "/api/v1/users/me", nil))
|
||||
if before.Code != http.StatusNoContent {
|
||||
t.Fatalf("before drain status = %d, want %d", before.Code, http.StatusNoContent)
|
||||
}
|
||||
|
||||
gate.BeginDrain()
|
||||
|
||||
draining := httptest.NewRecorder()
|
||||
handler.ServeHTTP(draining, httptest.NewRequest(http.MethodGet, "/health/ready", nil))
|
||||
if draining.Code != http.StatusServiceUnavailable {
|
||||
t.Fatalf("ready while draining status = %d, want %d", draining.Code, http.StatusServiceUnavailable)
|
||||
}
|
||||
if draining.Header().Get("X-Request-Id") == "" {
|
||||
t.Fatal("draining response is missing X-Request-Id")
|
||||
}
|
||||
|
||||
live := httptest.NewRecorder()
|
||||
handler.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/health/live", nil))
|
||||
if live.Code != http.StatusNoContent {
|
||||
t.Fatalf("live while draining status = %d, want %d", live.Code, http.StatusNoContent)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,15 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
const InstanceIDHeader = "X-Instance-Id"
|
||||
|
||||
// InstanceID identifies the process that actually produced the response.
|
||||
// It must wrap recovery and routing so even errors, health checks and 404/405
|
||||
// responses carry the same stable process identifier.
|
||||
func InstanceID(instanceID string, next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set(InstanceIDHeader, instanceID)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,50 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestInstanceIDOnSuccessfulAndNotFoundResponses(t *testing.T) {
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /ok", func(w http.ResponseWriter, _ *http.Request) {
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
handler := InstanceID("api-01", mux)
|
||||
|
||||
for _, test := range []struct {
|
||||
path string
|
||||
wantStatus int
|
||||
}{
|
||||
{path: "/ok", wantStatus: http.StatusNoContent},
|
||||
{path: "/missing", wantStatus: http.StatusNotFound},
|
||||
} {
|
||||
recorder := httptest.NewRecorder()
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, test.path, nil))
|
||||
|
||||
if recorder.Code != test.wantStatus {
|
||||
t.Fatalf("%s: got status %d, want %d", test.path, recorder.Code, test.wantStatus)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-01" {
|
||||
t.Fatalf("%s: got instance ID %q, want api-01", test.path, got)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
func TestInstanceIDSurvivesRecoveredPanic(t *testing.T) {
|
||||
panicking := http.HandlerFunc(func(http.ResponseWriter, *http.Request) {
|
||||
panic("test panic")
|
||||
})
|
||||
handler := InstanceID("api-panic", Recovery(panicking))
|
||||
recorder := httptest.NewRecorder()
|
||||
|
||||
handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/panic", nil))
|
||||
|
||||
if recorder.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("got status %d, want 500", recorder.Code)
|
||||
}
|
||||
if got := recorder.Header().Get(InstanceIDHeader); got != "api-panic" {
|
||||
t.Fatalf("got instance ID %q, want api-panic", got)
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,44 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// responseWriterInterceptor перехватывает статус-код ответа для логов
|
||||
type responseWriterInterceptor struct {
|
||||
http.ResponseWriter
|
||||
statusCode int
|
||||
}
|
||||
|
||||
func (w *responseWriterInterceptor) WriteHeader(code int) {
|
||||
w.statusCode = code
|
||||
w.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func Logger(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
|
||||
interceptor := &responseWriterInterceptor{
|
||||
ResponseWriter: w,
|
||||
statusCode: http.StatusOK, // дефолтный статус если WriteHeader не вызывался
|
||||
}
|
||||
|
||||
next.ServeHTTP(interceptor, r)
|
||||
|
||||
reqID := GetRequestID(r.Context())
|
||||
duration := time.Since(start)
|
||||
|
||||
// метаданные без r.Body
|
||||
log.Printf(
|
||||
"[HTTP] %s %s | status: %d | duration: %v | request_id: %s",
|
||||
r.Method,
|
||||
r.URL.Path,
|
||||
interceptor.statusCode,
|
||||
duration,
|
||||
reqID,
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,28 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"mtusi2026lab5/internal/transport/http/response"
|
||||
)
|
||||
|
||||
// Recovery перехватывает панику и возвращает клиенту валидный JSON 500
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if err := recover(); err != nil {
|
||||
reqID := GetRequestID(r.Context())
|
||||
//из контракта: не раскрывать stack trace и внутренности
|
||||
response.WriteError(
|
||||
w,
|
||||
http.StatusInternalServerError,
|
||||
response.CodeInternalError,
|
||||
"internal server error",
|
||||
reqID,
|
||||
)
|
||||
}
|
||||
}()
|
||||
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,35 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
|
||||
"github.com/google/uuid"
|
||||
)
|
||||
|
||||
type contextKey string
|
||||
|
||||
const RequestIDKey contextKey = "request_id"
|
||||
|
||||
// RequestID извлекает или генерирует X-Request-Id и кладет его в контекст и заголовок ответа
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
reqID := r.Header.Get("X-Request-Id")
|
||||
if reqID == "" {
|
||||
reqID = uuid.NewString()
|
||||
}
|
||||
|
||||
w.Header().Set("X-Request-Id", reqID)
|
||||
|
||||
ctx := context.WithValue(r.Context(), RequestIDKey, reqID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
// GetRequestID достает ID запроса из контекста
|
||||
func GetRequestID(ctx context.Context) string {
|
||||
if val, ok := ctx.Value(RequestIDKey).(string); ok {
|
||||
return val
|
||||
}
|
||||
return uuid.NewString()
|
||||
}
|
||||
Reference in New Issue
Block a user