forked from mtusi2026/mtusi2026lab7
lab7: безопасность, mTLS, OpenBao и PKI lifecycle
This commit is contained in:
@@ -10,6 +10,7 @@ import (
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/transport/rest/internal/oas"
|
||||
)
|
||||
|
||||
@@ -70,7 +71,7 @@ func statusForDomainError(err error) int {
|
||||
errors.Is(err, domain.ErrUnknownMember),
|
||||
errors.Is(err, domain.ErrInvalidCursor):
|
||||
return http.StatusBadRequest
|
||||
case errors.Is(err, domain.ErrRateLimited):
|
||||
case errors.Is(err, domain.ErrRateLimited), errors.Is(err, password.ErrBusy):
|
||||
return http.StatusTooManyRequests
|
||||
case errors.Is(err, domain.ErrTooLarge):
|
||||
return http.StatusRequestEntityTooLarge
|
||||
@@ -120,6 +121,9 @@ func writeError(ctx context.Context, log *slog.Logger, w http.ResponseWriter, r
|
||||
|
||||
w.Header().Set("Content-Type", "application/json; charset=utf-8")
|
||||
w.Header().Set(requestIDHeader, requestID)
|
||||
if status == http.StatusTooManyRequests && w.Header().Get("Retry-After") == "" {
|
||||
w.Header().Set("Retry-After", "1")
|
||||
}
|
||||
if status == http.StatusUnauthorized {
|
||||
challenge := `Bearer realm="messenger"`
|
||||
if r.URL.Path == "/api/v1/auth/sessions" {
|
||||
|
||||
@@ -0,0 +1,125 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"log/slog"
|
||||
"net"
|
||||
"net/http"
|
||||
"net/netip"
|
||||
"strconv"
|
||||
"strings"
|
||||
"time"
|
||||
|
||||
"mtusi-messenger/internal/domain"
|
||||
"mtusi-messenger/internal/platform/ratelimit"
|
||||
)
|
||||
|
||||
type LoginLimits struct {
|
||||
Account ratelimit.Limit
|
||||
Source ratelimit.Limit
|
||||
Global ratelimit.Limit
|
||||
}
|
||||
|
||||
func DefaultLoginLimits() LoginLimits {
|
||||
return LoginLimits{
|
||||
Account: ratelimit.Limit{Count: 8, Window: time.Minute},
|
||||
Source: ratelimit.Limit{Count: 120, Window: time.Minute},
|
||||
Global: ratelimit.Limit{Count: 16, Window: time.Second},
|
||||
}
|
||||
}
|
||||
|
||||
// WithLoginLimits must wrap the router so admission precedes generated Basic
|
||||
// authentication. Registration shares the source and global derivation budgets.
|
||||
func WithLoginLimits(
|
||||
next http.Handler, limiter ratelimit.Limiter, limits LoginLimits, log *slog.Logger,
|
||||
) http.Handler {
|
||||
id := InstanceID()
|
||||
return requestIDMiddleware(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
isLogin := r.Method == http.MethodPost && r.URL.Path == "/api/v1/auth/sessions"
|
||||
isRegister := r.Method == http.MethodPost && r.URL.Path == "/api/v1/users"
|
||||
if !isLogin && !isRegister {
|
||||
next.ServeHTTP(w, r)
|
||||
return
|
||||
}
|
||||
w.Header().Set(instanceIDHeader, id)
|
||||
if limiter == nil {
|
||||
logRejected(r.Context(), log, r, http.StatusServiceUnavailable, domain.ErrUnavailable)
|
||||
writeError(r.Context(), log, w, r, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
reservations := make([]ratelimit.Limit, 0, 3)
|
||||
source, global := limits.Source, limits.Global
|
||||
source.Key = loginLimitKey("source", loginSourceIP(r))
|
||||
global.Key = loginLimitKey("global", "login-register")
|
||||
reservations = append(reservations, source, global)
|
||||
if isLogin {
|
||||
username, _, _ := r.BasicAuth()
|
||||
account := limits.Account
|
||||
account.Key = loginLimitKey("account", username)
|
||||
reservations = append(reservations, account)
|
||||
}
|
||||
retryAfter, err := limiter.Reserve(r.Context(), reservations)
|
||||
if err != nil {
|
||||
logRejected(r.Context(), log, r, http.StatusServiceUnavailable, domain.ErrUnavailable)
|
||||
writeError(r.Context(), log, w, r, http.StatusServiceUnavailable)
|
||||
return
|
||||
}
|
||||
if retryAfter > 0 {
|
||||
w.Header().Set("Retry-After", retryAfterSeconds(retryAfter))
|
||||
logRejected(r.Context(), log, r, http.StatusTooManyRequests, domain.ErrRateLimited)
|
||||
writeError(r.Context(), log, w, r, http.StatusTooManyRequests)
|
||||
return
|
||||
}
|
||||
next.ServeHTTP(w, r)
|
||||
}))
|
||||
}
|
||||
|
||||
func loginLimitKey(scope, value string) string {
|
||||
digest := sha256.Sum256([]byte(scope + "\x00" + value))
|
||||
return hex.EncodeToString(digest[:])
|
||||
}
|
||||
|
||||
func loginSourceIP(r *http.Request) string {
|
||||
if authenticatedLB(r) {
|
||||
values := r.Header.Values("X-Forwarded-For")
|
||||
if len(values) == 1 {
|
||||
if ip, err := netip.ParseAddr(strings.TrimSpace(values[0])); err == nil {
|
||||
return ip.Unmap().String()
|
||||
}
|
||||
}
|
||||
}
|
||||
host, _, err := net.SplitHostPort(r.RemoteAddr)
|
||||
if err != nil {
|
||||
host = r.RemoteAddr
|
||||
}
|
||||
if ip, err := netip.ParseAddr(host); err == nil {
|
||||
return ip.Unmap().String()
|
||||
}
|
||||
return "unknown"
|
||||
}
|
||||
|
||||
func authenticatedLB(r *http.Request) bool {
|
||||
if r.TLS == nil {
|
||||
return false
|
||||
}
|
||||
for _, chain := range r.TLS.VerifiedChains {
|
||||
if len(chain) == 0 {
|
||||
continue
|
||||
}
|
||||
for _, uri := range chain[0].URIs {
|
||||
if uri.String() == "spiffe://mtusi/lb" {
|
||||
return true
|
||||
}
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
|
||||
func retryAfterSeconds(duration time.Duration) string {
|
||||
seconds := duration / time.Second
|
||||
if duration%time.Second != 0 {
|
||||
seconds++
|
||||
}
|
||||
return strconv.FormatInt(max(1, int64(seconds)), 10)
|
||||
}
|
||||
@@ -0,0 +1,137 @@
|
||||
package rest
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/tls"
|
||||
"crypto/x509"
|
||||
"errors"
|
||||
"fmt"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
"time"
|
||||
|
||||
"github.com/ogen-go/ogen/ogenerrors"
|
||||
"github.com/stretchr/testify/require"
|
||||
|
||||
"mtusi-messenger/internal/platform/password"
|
||||
"mtusi-messenger/internal/platform/ratelimit"
|
||||
)
|
||||
|
||||
type limiterFunc func(context.Context, []ratelimit.Limit) (time.Duration, error)
|
||||
|
||||
func (f limiterFunc) Reserve(ctx context.Context, limits []ratelimit.Limit) (time.Duration, error) {
|
||||
return f(ctx, limits)
|
||||
}
|
||||
|
||||
func TestLoginLimitsReserveBeforeAuthenticationAndFailClosed(t *testing.T) {
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
retry time.Duration
|
||||
err error
|
||||
status int
|
||||
wantRetry string
|
||||
}{
|
||||
{name: "accepted", status: http.StatusNoContent},
|
||||
{name: "limited", retry: 1500 * time.Millisecond, status: http.StatusTooManyRequests, wantRetry: "2"},
|
||||
{name: "dependency failure", err: errors.New("sensitive dependency failure"), status: http.StatusServiceUnavailable},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Setenv(instanceIDEnv, "admission-replica")
|
||||
reserved, authenticated, authenticatedBeforeReservation := false, false, false
|
||||
limiter := limiterFunc(func(_ context.Context, _ []ratelimit.Limit) (time.Duration, error) {
|
||||
require.False(t, authenticated)
|
||||
reserved = true
|
||||
return test.retry, test.err
|
||||
})
|
||||
next := http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
|
||||
authenticatedBeforeReservation = !reserved
|
||||
authenticated = true
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.SetBasicAuth("private-account", "private-password")
|
||||
request.Header.Set(requestIDHeader, "invalid\r\nrequest-id")
|
||||
recorder := httptest.NewRecorder()
|
||||
WithLoginLimits(next, limiter, DefaultLoginLimits(), nil).ServeHTTP(recorder, request)
|
||||
require.True(t, reserved)
|
||||
require.Equal(t, test.status, recorder.Code)
|
||||
require.Equal(t, test.wantRetry, recorder.Header().Get("Retry-After"))
|
||||
require.Equal(t, test.status == http.StatusNoContent, authenticated)
|
||||
require.False(t, authenticatedBeforeReservation)
|
||||
require.True(t, requestIDPattern.MatchString(recorder.Header().Get(requestIDHeader)))
|
||||
require.Equal(t, "admission-replica", recorder.Header().Get(instanceIDHeader))
|
||||
require.NotContains(t, recorder.Body.String(), "sensitive")
|
||||
require.NotContains(t, recorder.Body.String(), "private")
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginSourceIPRejectsForwardedSpoofing(t *testing.T) {
|
||||
lbURI, err := url.Parse("spiffe://mtusi/lb")
|
||||
require.NoError(t, err)
|
||||
rogueURI, err := url.Parse("spiffe://mtusi/rogue")
|
||||
require.NoError(t, err)
|
||||
lb := &x509.Certificate{URIs: []*url.URL{lbURI}}
|
||||
rogue := &x509.Certificate{URIs: []*url.URL{rogueURI}}
|
||||
for _, test := range []struct {
|
||||
name string
|
||||
tls *tls.ConnectionState
|
||||
header string
|
||||
want string
|
||||
}{
|
||||
{name: "plaintext spoof", header: "198.51.100.1", want: "192.0.2.1"},
|
||||
{
|
||||
name: "unverified lb", tls: &tls.ConnectionState{PeerCertificates: []*x509.Certificate{lb}},
|
||||
header: "198.51.100.1", want: "192.0.2.1",
|
||||
},
|
||||
{
|
||||
name: "verified rogue", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{rogue}}},
|
||||
header: "198.51.100.1", want: "192.0.2.1",
|
||||
},
|
||||
{
|
||||
name: "authenticated lb", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{lb}}},
|
||||
header: "198.51.100.1", want: "198.51.100.1",
|
||||
},
|
||||
{
|
||||
name: "forwarded chain rejected", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{lb}}},
|
||||
header: "198.51.100.1, 203.0.113.2", want: "192.0.2.1",
|
||||
},
|
||||
{
|
||||
name: "malformed forwarded rejected", tls: &tls.ConnectionState{VerifiedChains: [][]*x509.Certificate{{lb}}},
|
||||
header: "not-an-ip", want: "192.0.2.1",
|
||||
},
|
||||
} {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
request.RemoteAddr, request.TLS = "192.0.2.1:1234", test.tls
|
||||
request.Header.Set("X-Forwarded-For", test.header)
|
||||
require.Equal(t, test.want, loginSourceIP(request))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestBusyDerivationProduces429Not401(t *testing.T) {
|
||||
for _, err := range []error{
|
||||
fmt.Errorf("hash password: %w", password.ErrBusy),
|
||||
&ogenerrors.SecurityError{Security: "BasicAuth", Err: fmt.Errorf("verify password: %w", password.ErrBusy)},
|
||||
} {
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/auth/sessions", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
newErrorHandler(nil)(request.Context(), recorder, request, err)
|
||||
require.Equal(t, http.StatusTooManyRequests, recorder.Code)
|
||||
require.Equal(t, "1", recorder.Header().Get("Retry-After"))
|
||||
require.Empty(t, recorder.Header().Get("WWW-Authenticate"))
|
||||
}
|
||||
}
|
||||
|
||||
func TestLoginLimitsDoNotAdmitWhenLimiterMissing(t *testing.T) {
|
||||
called := false
|
||||
next := http.HandlerFunc(func(http.ResponseWriter, *http.Request) { called = true })
|
||||
request := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/api/v1/users", nil)
|
||||
recorder := httptest.NewRecorder()
|
||||
WithLoginLimits(next, nil, DefaultLoginLimits(), nil).ServeHTTP(recorder, request)
|
||||
require.Equal(t, http.StatusServiceUnavailable, recorder.Code)
|
||||
require.False(t, called)
|
||||
}
|
||||
Reference in New Issue
Block a user