forked from mtusi2026/mtusi2026lab7
lab7: TLS/mTLS по trust matrix, OpenBao (cert auth, KV, policies), роли БД, Argon2id+rehash, лимит входа, hardening, secprobe и тесты
This commit is contained in:
@@ -0,0 +1,48 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"errors"
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"strings"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// Auth проверяет Authorization: Bearer <token> через AuthService.
|
||||
func Auth(auth *service.AuthService) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
header := r.Header.Get("Authorization")
|
||||
if !strings.HasPrefix(header, "Bearer ") {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
token := strings.TrimPrefix(header, "Bearer ")
|
||||
if token == "" {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
|
||||
u, err := auth.ValidateSession(r.Context(), token)
|
||||
if err != nil {
|
||||
if errors.Is(err, service.ErrUnauthorized) {
|
||||
writeUnauthorized(w, r)
|
||||
return
|
||||
}
|
||||
slog.Error("auth: unexpected", "err", err)
|
||||
httputil.WriteError(w, r, nil)
|
||||
return
|
||||
}
|
||||
|
||||
ctx := httputil.ContextWithUserID(r.Context(), u.ID)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func writeUnauthorized(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("WWW-Authenticate", `Bearer realm="messenger"`)
|
||||
httputil.WriteError(w, r, service.ErrUnauthorized)
|
||||
}
|
||||
@@ -0,0 +1,14 @@
|
||||
package middleware
|
||||
|
||||
import "net/http"
|
||||
|
||||
// InstanceID добавляет X-Instance-Id ко всем ответам API, включая ошибки и health.
|
||||
// Значение задаётся один раз при старте процесса и не меняется до его завершения.
|
||||
func InstanceID(id string) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("X-Instance-Id", id)
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,37 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"time"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// Logging — структурный лог запроса (event=http.request) в контексте server span:
|
||||
// trace_id/span_id добавляются обработчиком slog. Вместо сырого пути пишется
|
||||
// шаблон маршрута, тело и заголовки (Authorization) не логируются.
|
||||
func Logging(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
rec, ok := w.(*statusRecorder)
|
||||
if !ok {
|
||||
rec = &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
}
|
||||
next.ServeHTTP(rec, r)
|
||||
level := slog.LevelInfo
|
||||
if rec.status >= 500 {
|
||||
level = slog.LevelError
|
||||
} else if rec.status >= 400 {
|
||||
level = slog.LevelWarn
|
||||
}
|
||||
slog.Log(r.Context(), level, "http request",
|
||||
"event", "http.request",
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"route", route(r),
|
||||
"status", rec.status,
|
||||
"duration_ms", time.Since(start).Milliseconds(),
|
||||
)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,117 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/base64"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"github.com/redis/go-redis/v9"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/service"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// LoginLimiter — общий для всех реплик лимит попыток входа (Redis, фиксированное
|
||||
// окно): отдельно по username и по IP клиента. Превышение — 429 + Retry-After до
|
||||
// конца окна; Argon2id при этом не вычисляется (дорогой hash не становится
|
||||
// усилителем DoS). Ключи Redis — SHA-256 username/IP, не сами значения.
|
||||
//
|
||||
// IP берётся из последнего значения X-Forwarded-For, которое добавляет HAProxy:
|
||||
// API принимает соединения только от LB (mTLS с identity lb), поэтому заголовок
|
||||
// нельзя подделать в обход балансировщика.
|
||||
type LoginLimiter struct {
|
||||
rdb *redis.Client
|
||||
perUser int64
|
||||
perIP int64
|
||||
window time.Duration
|
||||
}
|
||||
|
||||
func NewLoginLimiter(rdb *redis.Client, perUser, perIP int, window time.Duration) *LoginLimiter {
|
||||
return &LoginLimiter{rdb: rdb, perUser: int64(perUser), perIP: int64(perIP), window: window}
|
||||
}
|
||||
|
||||
func clientIP(r *http.Request) string {
|
||||
if xff := r.Header.Get("X-Forwarded-For"); xff != "" {
|
||||
parts := strings.Split(xff, ",")
|
||||
return strings.TrimSpace(parts[len(parts)-1])
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
return r.RemoteAddr
|
||||
}
|
||||
return host
|
||||
}
|
||||
|
||||
func basicUser(r *http.Request) string {
|
||||
h := r.Header.Get("Authorization")
|
||||
if len(h) < 6 || !strings.EqualFold(h[:6], "basic ") {
|
||||
return ""
|
||||
}
|
||||
raw, err := base64.StdEncoding.DecodeString(strings.TrimSpace(h[6:]))
|
||||
if err != nil {
|
||||
return ""
|
||||
}
|
||||
u, _, _ := strings.Cut(string(raw), ":")
|
||||
return u
|
||||
}
|
||||
|
||||
func hkey(prefix, v string) string {
|
||||
sum := sha256.Sum256([]byte(v))
|
||||
return prefix + hex.EncodeToString(sum[:12])
|
||||
}
|
||||
|
||||
// hit увеличивает счётчик окна и возвращает (значение, оставшийся TTL).
|
||||
func (l *LoginLimiter) hit(r *http.Request, key string) (int64, time.Duration, error) {
|
||||
ctx := r.Context()
|
||||
pipe := l.rdb.TxPipeline()
|
||||
incr := pipe.Incr(ctx, key)
|
||||
pipe.ExpireNX(ctx, key, l.window)
|
||||
ttl := pipe.TTL(ctx, key)
|
||||
if _, err := pipe.Exec(ctx); err != nil {
|
||||
return 0, 0, err
|
||||
}
|
||||
return incr.Val(), ttl.Val(), nil
|
||||
}
|
||||
|
||||
func (l *LoginLimiter) Wrap(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
checks := []struct {
|
||||
key string
|
||||
limit int64
|
||||
kind string
|
||||
}{{hkey("rl:login:ip:", clientIP(r)), l.perIP, "ip"}}
|
||||
if u := basicUser(r); u != "" {
|
||||
checks = append(checks, struct {
|
||||
key string
|
||||
limit int64
|
||||
kind string
|
||||
}{hkey("rl:login:user:", strings.ToLower(u)), l.perUser, "user"})
|
||||
}
|
||||
for _, c := range checks {
|
||||
n, ttl, err := l.hit(r, c.key)
|
||||
if err != nil {
|
||||
// Без общего счётчика вход не разрешаем (fail closed): 503, не обход лимита.
|
||||
slog.WarnContext(r.Context(), "login rate limiter unavailable", "event", "auth.ratelimit_error", "err", err)
|
||||
httputil.WriteError(w, r, service.ErrUnavailable)
|
||||
return
|
||||
}
|
||||
if n > c.limit {
|
||||
secs := int(ttl.Seconds() + 0.999)
|
||||
if secs < 1 {
|
||||
secs = 1
|
||||
}
|
||||
w.Header().Set("Retry-After", strconv.Itoa(secs))
|
||||
slog.WarnContext(r.Context(), "login rate limited", "event", "auth.rate_limited", "by", c.kind, "retry_after_s", secs)
|
||||
httputil.WriteError(w, r, service.ErrRateLimited)
|
||||
return
|
||||
}
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,25 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func Recovery(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
defer func() {
|
||||
if rec := recover(); rec != nil {
|
||||
slog.Error("panic in handler",
|
||||
"panic", rec,
|
||||
"request_id", httputil.RequestIDFrom(r.Context()),
|
||||
"method", r.Method,
|
||||
"path", r.URL.Path,
|
||||
)
|
||||
httputil.WriteError(w, r, nil)
|
||||
}
|
||||
}()
|
||||
next.ServeHTTP(w, r)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,29 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"crypto/rand"
|
||||
"fmt"
|
||||
"net/http"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
func RequestID(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
id := r.Header.Get("X-Request-Id")
|
||||
if id == "" {
|
||||
id = newRequestID()
|
||||
}
|
||||
w.Header().Set("X-Request-Id", id)
|
||||
ctx := httputil.ContextWithRequestID(r.Context(), id)
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
|
||||
func newRequestID() string {
|
||||
var b [12]byte
|
||||
if _, err := rand.Read(b[:]); err != nil {
|
||||
panic(fmt.Sprintf("crypto/rand failed: %v", err))
|
||||
}
|
||||
return fmt.Sprintf("%x", b[:])
|
||||
}
|
||||
@@ -0,0 +1,107 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"fmt"
|
||||
"net/http"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/attribute"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/metric"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
"go.opentelemetry.io/otel/trace"
|
||||
|
||||
"github.com/charawein/mtusi2026lab7/internal/telemetry"
|
||||
"github.com/charawein/mtusi2026lab7/internal/transport/httputil"
|
||||
)
|
||||
|
||||
// statusRecorder запоминает код ответа и число байт тела.
|
||||
type statusRecorder struct {
|
||||
http.ResponseWriter
|
||||
status int
|
||||
bytes int64
|
||||
}
|
||||
|
||||
func (r *statusRecorder) WriteHeader(code int) {
|
||||
r.status = code
|
||||
r.ResponseWriter.WriteHeader(code)
|
||||
}
|
||||
|
||||
func (r *statusRecorder) Write(b []byte) (int, error) {
|
||||
n, err := r.ResponseWriter.Write(b)
|
||||
r.bytes += int64(n)
|
||||
return n, err
|
||||
}
|
||||
|
||||
// Unwrap даёт http.ResponseController доступ к исходному writer.
|
||||
func (r *statusRecorder) Unwrap() http.ResponseWriter { return r.ResponseWriter }
|
||||
|
||||
// route — шаблон маршрута ServeMux без метода ("/api/v1/chats/{chat_id}/messages").
|
||||
// ServeMux записывает его в r.Pattern того же *Request, поэтому читается после
|
||||
// next.ServeHTTP. Неизвестный путь не попадает в метки как сырой URL.
|
||||
func route(r *http.Request) string {
|
||||
p := r.Pattern
|
||||
if p == "" {
|
||||
return "unmatched"
|
||||
}
|
||||
if i := strings.IndexByte(p, ' '); i >= 0 {
|
||||
p = p[i+1:]
|
||||
}
|
||||
return p
|
||||
}
|
||||
|
||||
func statusClass(code int) string { return fmt.Sprintf("%dxx", code/100) }
|
||||
|
||||
// Telemetry — server span на запрос и метрика http.server.request.duration
|
||||
// (histogram, секунды; её _count — счётчик запросов). Метки: метод, шаблон
|
||||
// маршрута, код и класс ответа — без user/chat/message ID и сырого URL.
|
||||
func Telemetry(next http.Handler) http.Handler {
|
||||
tracer := telemetry.Tracer()
|
||||
meter := telemetry.Meter()
|
||||
duration, _ := meter.Float64Histogram("http.server.request.duration",
|
||||
metric.WithUnit("s"), metric.WithDescription("Duration of HTTP server requests"))
|
||||
inflight, _ := meter.Int64UpDownCounter("http.server.active_requests",
|
||||
metric.WithUnit("{request}"), metric.WithDescription("In-flight HTTP requests"))
|
||||
prop := otel.GetTextMapPropagator()
|
||||
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
start := time.Now()
|
||||
ctx := prop.Extract(r.Context(), propagation.HeaderCarrier(r.Header))
|
||||
if strings.HasPrefix(r.URL.Path, "/health/") {
|
||||
// Проверки LB раз в секунду: метрики пишем, трассы нет (ParentBased).
|
||||
ctx = telemetry.Unsampled(r.Context())
|
||||
}
|
||||
ctx, span := tracer.Start(ctx, r.Method, trace.WithSpanKind(trace.SpanKindServer),
|
||||
trace.WithAttributes(
|
||||
attribute.String("http.request.method", r.Method),
|
||||
attribute.String("request_id", httputil.RequestIDFrom(r.Context())),
|
||||
))
|
||||
defer span.End()
|
||||
methodAttr := attribute.String("http.request.method", r.Method)
|
||||
inflight.Add(ctx, 1, metric.WithAttributes(methodAttr))
|
||||
defer inflight.Add(ctx, -1, metric.WithAttributes(methodAttr))
|
||||
|
||||
rec := &statusRecorder{ResponseWriter: w, status: http.StatusOK}
|
||||
r2 := r.WithContext(ctx)
|
||||
next.ServeHTTP(rec, r2)
|
||||
|
||||
rt := route(r2)
|
||||
span.SetName(r.Method + " " + rt)
|
||||
span.SetAttributes(
|
||||
attribute.String("http.route", rt),
|
||||
attribute.Int("http.response.status_code", rec.status),
|
||||
)
|
||||
if rec.status >= 500 {
|
||||
span.SetStatus(codes.Error, http.StatusText(rec.status))
|
||||
}
|
||||
duration.Record(ctx, time.Since(start).Seconds(), metric.WithAttributes(
|
||||
methodAttr,
|
||||
attribute.String("http.route", rt),
|
||||
attribute.Int("http.response.status_code", rec.status),
|
||||
attribute.String("http.response.status_class", statusClass(rec.status)),
|
||||
))
|
||||
r.Pattern = r2.Pattern // для внешних middleware (логирование)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,84 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"go.opentelemetry.io/otel"
|
||||
"go.opentelemetry.io/otel/codes"
|
||||
"go.opentelemetry.io/otel/propagation"
|
||||
sdkmetric "go.opentelemetry.io/otel/sdk/metric"
|
||||
"go.opentelemetry.io/otel/sdk/metric/metricdata"
|
||||
sdktrace "go.opentelemetry.io/otel/sdk/trace"
|
||||
"go.opentelemetry.io/otel/sdk/trace/tracetest"
|
||||
)
|
||||
|
||||
// Метки метрики и имя span — шаблон маршрута, а не сырой путь с UUID;
|
||||
// 5xx помечает span ошибкой; /health/* не создаёт трасс; входящий traceparent
|
||||
// продолжается.
|
||||
func TestTelemetryRouteTemplateAndStatus(t *testing.T) {
|
||||
exp := tracetest.NewInMemoryExporter()
|
||||
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSyncer(exp)))
|
||||
reader := sdkmetric.NewManualReader()
|
||||
otel.SetMeterProvider(sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)))
|
||||
otel.SetTextMapPropagator(propagation.TraceContext{})
|
||||
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("POST /api/v1/chats/{chat_id}/messages", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusServiceUnavailable)
|
||||
})
|
||||
mux.HandleFunc("GET /health/ready", func(w http.ResponseWriter, r *http.Request) {})
|
||||
h := Telemetry(Logging(mux))
|
||||
|
||||
const chat = "0b5ad0a8-6b44-4d34-9a43-2b4d1f1a7c11"
|
||||
req := httptest.NewRequest("POST", "/api/v1/chats/"+chat+"/messages", nil)
|
||||
req.Header.Set("traceparent", "00-4bf92f3577b34da6a3ce929d0e0e4736-00f067aa0ba902b7-01")
|
||||
h.ServeHTTP(httptest.NewRecorder(), req)
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/health/ready", nil))
|
||||
h.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/nope/"+chat, nil))
|
||||
|
||||
spans := exp.GetSpans()
|
||||
if len(spans) != 2 {
|
||||
t.Fatalf("want 2 spans (health is not traced), got %d", len(spans))
|
||||
}
|
||||
s := spans[0]
|
||||
if s.Name != "POST /api/v1/chats/{chat_id}/messages" || s.Status.Code != codes.Error {
|
||||
t.Fatalf("span %q status %v", s.Name, s.Status)
|
||||
}
|
||||
if s.SpanContext.TraceID().String() != "4bf92f3577b34da6a3ce929d0e0e4736" || s.Parent.SpanID().String() != "00f067aa0ba902b7" {
|
||||
t.Fatalf("incoming traceparent not continued: %s parent %s", s.SpanContext.TraceID(), s.Parent.SpanID())
|
||||
}
|
||||
if spans[1].Name != "GET unmatched" {
|
||||
t.Fatalf("unknown path must be 'unmatched', got %q", spans[1].Name)
|
||||
}
|
||||
|
||||
var rm metricdata.ResourceMetrics
|
||||
if err := reader.Collect(context.Background(), &rm); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
routes := map[string]bool{}
|
||||
for _, sm := range rm.ScopeMetrics {
|
||||
for _, m := range sm.Metrics {
|
||||
if m.Name != "http.server.request.duration" {
|
||||
continue
|
||||
}
|
||||
for _, dp := range m.Data.(metricdata.Histogram[float64]).DataPoints {
|
||||
for _, kv := range dp.Attributes.ToSlice() {
|
||||
if strings.Contains(kv.Value.Emit(), chat) {
|
||||
t.Fatalf("raw id in metric attribute %s", kv.Key)
|
||||
}
|
||||
}
|
||||
r, _ := dp.Attributes.Value("http.route")
|
||||
routes[r.AsString()] = true
|
||||
}
|
||||
}
|
||||
}
|
||||
for _, want := range []string{"/api/v1/chats/{chat_id}/messages", "/health/ready", "unmatched"} {
|
||||
if !routes[want] {
|
||||
t.Fatalf("route %q not recorded: %v", want, routes)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,18 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"time"
|
||||
)
|
||||
|
||||
// Timeout ограничивает время выполнения запроса.
|
||||
func Timeout(d time.Duration) func(http.Handler) http.Handler {
|
||||
return func(next http.Handler) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
ctx, cancel := context.WithTimeout(r.Context(), d)
|
||||
defer cancel()
|
||||
next.ServeHTTP(w, r.WithContext(ctx))
|
||||
})
|
||||
}
|
||||
}
|
||||
Reference in New Issue
Block a user