Add unknown location logging with path prefix suppression
This commit is contained in:
1 parent
8012ad57fe
commit
48af0bb132
9 files changed
+369
-1
No files matched your search
@@ -96,6 +96,8 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
skipBodyLoggingEndpointPrefixes = append(skipBodyLoggingEndpointPrefixes, strings.TrimPrefix(prefix, "/"))
|
||||
}
|
||||
|
||||
skipLogging := middleware.NewSkipLoggingPaths(config.Logging.SkipLoggingPathPrefixes)
|
||||
|
||||
mux := mux2.NewRouter()
|
||||
for _, location := range locations {
|
||||
var proxyFunc middleware.Handler
|
||||
@@ -136,6 +138,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
middleware.Logger(
|
||||
l.logger, config.Logging.RequestLogEnable,
|
||||
enableBodyLog,
|
||||
skipLogging,
|
||||
skipBodyLoggingEndpointPrefixes,
|
||||
config.Logging.EnableForceUnescapingUnicode,
|
||||
),
|
||||
@@ -160,6 +163,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
proxyFunc,
|
||||
middleware.Logger(l.logger, config.Logging.RequestLogEnable,
|
||||
enableBodyLog,
|
||||
skipLogging,
|
||||
skipBodyLoggingEndpointPrefixes,
|
||||
config.Logging.EnableForceUnescapingUnicode,
|
||||
),
|
||||
@@ -177,6 +181,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
PathPrefix: location.PathPrefix,
|
||||
ErrorOnUnknownEndpoint: errorOnUnknownEndpoint,
|
||||
WithLendingSlash: location.Protocol != conf.GrpcProtocol,
|
||||
SkipLogging: skipLogging,
|
||||
},
|
||||
l.routes,
|
||||
l.logger,
|
||||
@@ -184,5 +189,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
|
||||
mux.PathPrefix(location.PathPrefix).Handler(entrypoint)
|
||||
}
|
||||
|
||||
mux.NotFoundHandler = middleware.UnknownLocation(l.logger, skipLogging)
|
||||
|
||||
return mux, nil
|
||||
}
|
||||
@@ -4,7 +4,8 @@
|
||||
"requestLogEnable": true,
|
||||
"bodyLogEnable": false,
|
||||
"skipBodyLoggingEndpointPrefixes": [],
|
||||
"enableForceUnescapingUnicode": false
|
||||
"enableForceUnescapingUnicode": false,
|
||||
"skipLoggingPathPrefixes": []
|
||||
},
|
||||
"caching": {
|
||||
"authenticationDataInSec": 60,
|
||||
|
||||
@@ -49,6 +49,7 @@ type Logging struct {
|
||||
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
|
||||
SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"`
|
||||
EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"`
|
||||
SkipLoggingPathPrefixes []string `schema:"Полностью не логировать запросы к путям с префиксом из списка (сырой path, query не учитывается, '/' в начале игнорируется). Применяется к логу запросов, предупреждению о неизвестном эндпоинте и логу незнакомых locations"`
|
||||
}
|
||||
|
||||
type Caching struct {
|
||||
|
||||
@@ -14,6 +14,7 @@ type EntryPointConfig struct {
|
||||
WithPrefix bool
|
||||
ErrorOnUnknownEndpoint bool
|
||||
WithLendingSlash bool
|
||||
SkipLogging SkipLoggingPaths
|
||||
}
|
||||
|
||||
type EndpointResolver interface {
|
||||
@@ -33,6 +34,7 @@ func Entrypoint(
|
||||
|
||||
endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg)
|
||||
if err != nil {
|
||||
if !cfg.SkipLogging.ShouldSkip(req.URL.Path) {
|
||||
lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg)
|
||||
logger.Warn(
|
||||
req.Context(),
|
||||
@@ -43,6 +45,7 @@ func Entrypoint(
|
||||
log.String("lookupPath", lookupPath),
|
||||
log.String("enpoint", endpoint),
|
||||
)
|
||||
}
|
||||
|
||||
http.Error(writer, err.Error(), http.StatusNotImplemented)
|
||||
return
|
||||
|
||||
@@ -58,6 +58,7 @@ func Logger( // nolint:gocognit,funlen
|
||||
logger log.Logger,
|
||||
enableRequestLogging bool,
|
||||
enableBodyLogging bool,
|
||||
skipLogging SkipLoggingPaths,
|
||||
skipBodyLoggingEndpointPrefixes []string,
|
||||
enableForceUnescapingUnicode bool,
|
||||
) Middleware {
|
||||
@@ -69,6 +70,10 @@ func Logger( // nolint:gocognit,funlen
|
||||
|
||||
r := ctx.Request()
|
||||
|
||||
if skipLogging.ShouldSkip(r.URL.Path) {
|
||||
return next.Handle(ctx)
|
||||
}
|
||||
|
||||
endpoint := ctx.EndpointMeta().NormalizedEndpoint
|
||||
logBodyFromCurrenRequest := enableBodyLogging
|
||||
if logBodyFromCurrenRequest {
|
||||
|
||||
@@ -0,0 +1,33 @@
|
||||
package middleware
|
||||
|
||||
import "strings"
|
||||
|
||||
// SkipLoggingPaths — префиксы сырого request path, для которых
|
||||
// полностью отключено логирование (строка лога, не только тела).
|
||||
type SkipLoggingPaths struct {
|
||||
prefixes []string
|
||||
}
|
||||
|
||||
// NewSkipLoggingPaths нормализует значения конфы: обрезает ведущий '/',
|
||||
// отбрасывает пустые.
|
||||
func NewSkipLoggingPaths(rawPrefixes []string) SkipLoggingPaths {
|
||||
prefixes := make([]string, 0, len(rawPrefixes))
|
||||
for _, p := range rawPrefixes {
|
||||
p = strings.TrimPrefix(p, "/")
|
||||
if p != "" {
|
||||
prefixes = append(prefixes, p)
|
||||
}
|
||||
}
|
||||
return SkipLoggingPaths{prefixes: prefixes}
|
||||
}
|
||||
|
||||
// ShouldSkip — case-sensitive prefix-match. path — сырой r.URL.Path.
|
||||
func (s SkipLoggingPaths) ShouldSkip(path string) bool {
|
||||
path = strings.TrimPrefix(path, "/")
|
||||
for _, p := range s.prefixes {
|
||||
if strings.HasPrefix(path, p) {
|
||||
return true
|
||||
}
|
||||
}
|
||||
return false
|
||||
}
|
||||
@@ -0,0 +1,46 @@
|
||||
package middleware_test
|
||||
|
||||
import (
|
||||
"testing"
|
||||
|
||||
"isp-gate-service/middleware"
|
||||
|
||||
"github.com/stretchr/testify/require"
|
||||
)
|
||||
|
||||
func TestSkipLoggingPaths_ShouldSkip(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
tests := []struct {
|
||||
name string
|
||||
prefixes []string
|
||||
path string
|
||||
wantSkip bool
|
||||
}{
|
||||
{name: "prefix without leading slash", prefixes: []string{"health"}, path: "/health", wantSkip: true},
|
||||
{name: "prefix with leading slash is equivalent", prefixes: []string{"/health"}, path: "/health", wantSkip: true},
|
||||
{name: "no match", prefixes: []string{"health"}, path: "/other", wantSkip: false},
|
||||
{name: "empty value is discarded", prefixes: []string{""}, path: "/health", wantSkip: false},
|
||||
{name: "root slash value is discarded", prefixes: []string{"/"}, path: "/health", wantSkip: false},
|
||||
{name: "case sensitive", prefixes: []string{"Health"}, path: "/health/x", wantSkip: false},
|
||||
{name: "plain prefix matches longer name", prefixes: []string{"health"}, path: "/healthz", wantSkip: true},
|
||||
{name: "plain prefix matches nested path", prefixes: []string{"health"}, path: "/health/x", wantSkip: true},
|
||||
}
|
||||
|
||||
for _, test := range tests {
|
||||
t.Run(test.name, func(t *testing.T) {
|
||||
t.Parallel()
|
||||
matcher := middleware.NewSkipLoggingPaths(test.prefixes)
|
||||
require.Equal(t, test.wantSkip, matcher.ShouldSkip(test.path))
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestSkipLoggingPaths_ShouldSkip_EmptyList(t *testing.T) {
|
||||
t.Parallel()
|
||||
|
||||
matcher := middleware.NewSkipLoggingPaths(nil)
|
||||
for _, path := range []string{"/", "/health", "/health/x", "/unknown"} {
|
||||
require.False(t, matcher.ShouldSkip(path))
|
||||
}
|
||||
}
|
||||
@@ -0,0 +1,26 @@
|
||||
package middleware
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
|
||||
"github.com/txix-open/isp-kit/log"
|
||||
)
|
||||
|
||||
// UnknownLocation — catch-all для запросов, не попавших ни в один location.
|
||||
func UnknownLocation(logger log.Logger, skipLogging SkipLoggingPaths) http.Handler {
|
||||
return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if !skipLogging.ShouldSkip(r.URL.Path) {
|
||||
logger.Warn(r.Context(), "request to unknown location",
|
||||
log.String("httpMethod", r.Method),
|
||||
log.String("path", r.URL.Path),
|
||||
log.String("remoteAddr", r.RemoteAddr),
|
||||
log.String("xForwardedFor", r.Header.Get("X-Forwarded-For")),
|
||||
log.String("userAgent", r.Header.Get("User-Agent")),
|
||||
log.Int("statusCode", http.StatusNotFound),
|
||||
)
|
||||
}
|
||||
|
||||
// Ответ идентичен текущему дефолтному NotFoundHandler gorilla/mux
|
||||
http.Error(w, "404 page not found", http.StatusNotFound)
|
||||
})
|
||||
}
|
||||
@@ -0,0 +1,246 @@
|
||||
package tests
|
||||
|
||||
import (
|
||||
"context"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"isp-gate-service/assembly"
|
||||
"isp-gate-service/conf"
|
||||
"isp-gate-service/routes"
|
||||
|
||||
"github.com/stretchr/testify/suite"
|
||||
"github.com/txix-open/isp-kit/cluster"
|
||||
"github.com/txix-open/isp-kit/http/httpcli"
|
||||
"github.com/txix-open/isp-kit/lb"
|
||||
"github.com/txix-open/isp-kit/test"
|
||||
"github.com/txix-open/isp-kit/test/httpt"
|
||||
"go.uber.org/zap/zapcore"
|
||||
)
|
||||
|
||||
type UnknownLocationsLoggingTestSuite struct {
|
||||
suite.Suite
|
||||
}
|
||||
|
||||
func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_LogsWarn() {
|
||||
test, require := test.New(s.T())
|
||||
capture := &logCapture{}
|
||||
|
||||
locator := assembly.NewLocator(capture, nil, nil, routes.NewRoutes(test.Logger()), nil, nil, nil, nil, nil)
|
||||
handler, err := locator.Handler(conf.Remote{Http: conf.Http{MaxRequestBodySizeInMb: 1}}, nil)
|
||||
require.NoError(err)
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := httpcli.New().Get(srv.URL + "/unknown/path").Do(s.T().Context())
|
||||
require.NoError(err)
|
||||
require.EqualValues(http.StatusNotFound, resp.StatusCode())
|
||||
body, err := resp.BodyCopy()
|
||||
require.NoError(err)
|
||||
require.EqualValues("404 page not found\n", string(body))
|
||||
|
||||
// ровно одна лог-строка на запрос, и это warn о незнакомой location
|
||||
require.Len(capture.entries, 1)
|
||||
entries := capture.entriesWithMessage("request to unknown location")
|
||||
require.Len(entries, 1)
|
||||
require.EqualValues(zapcore.WarnLevel, entries[0].level)
|
||||
require.EqualValues(http.MethodGet, entries[0].fields["httpMethod"])
|
||||
require.EqualValues("/unknown/path", entries[0].fields["path"])
|
||||
require.EqualValues(http.StatusNotFound, entries[0].fields["statusCode"])
|
||||
require.NotEmpty(entries[0].fields["remoteAddr"])
|
||||
}
|
||||
|
||||
func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_SuppressionSkipsWarn() {
|
||||
test, require := test.New(s.T())
|
||||
capture := &logCapture{}
|
||||
|
||||
config := conf.Remote{
|
||||
Http: conf.Http{MaxRequestBodySizeInMb: 1},
|
||||
Logging: conf.Logging{SkipLoggingPathPrefixes: []string{"/unknown"}},
|
||||
}
|
||||
locator := assembly.NewLocator(capture, nil, nil, routes.NewRoutes(test.Logger()), nil, nil, nil, nil, nil)
|
||||
handler, err := locator.Handler(config, nil)
|
||||
require.NoError(err)
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := httpcli.New().Get(srv.URL + "/unknown/path").Do(s.T().Context())
|
||||
require.NoError(err)
|
||||
require.EqualValues(http.StatusNotFound, resp.StatusCode())
|
||||
|
||||
// запрос полностью не логируется
|
||||
require.Empty(capture.entries)
|
||||
}
|
||||
|
||||
func (s *UnknownLocationsLoggingTestSuite) Test_UnknownEndpoint_LogsWarn() {
|
||||
test, require := test.New(s.T())
|
||||
capture := &logCapture{}
|
||||
|
||||
routes := routes.NewRoutes(test.Logger())
|
||||
err := routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||
Endpoints: []cluster.EndpointDescriptor{{Path: "endpoint"}},
|
||||
}})
|
||||
require.NoError(err)
|
||||
|
||||
config := conf.Remote{Http: conf.Http{MaxRequestBodySizeInMb: 1}}
|
||||
locator := assembly.NewLocator(capture, nil, nil, routes, nil, nil, nil, nil, nil)
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: false,
|
||||
PathPrefix: "/api",
|
||||
Protocol: "grpc",
|
||||
TargetModule: "target",
|
||||
}}
|
||||
handler, err := locator.Handler(config, locations)
|
||||
require.NoError(err)
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := httpcli.New().Post(srv.URL + "/api/nope").Do(s.T().Context())
|
||||
require.NoError(err)
|
||||
require.EqualValues(http.StatusNotImplemented, resp.StatusCode())
|
||||
|
||||
// ровно одна лог-строка на запрос — warn о неизвестном эндпоинте
|
||||
require.Len(capture.entries, 1)
|
||||
entries := capture.entriesWithMessage("call unknown method")
|
||||
require.Len(entries, 1)
|
||||
require.EqualValues(zapcore.WarnLevel, entries[0].level)
|
||||
}
|
||||
|
||||
func (s *UnknownLocationsLoggingTestSuite) Test_UnknownEndpoint_SuppressionSkipsWarn() {
|
||||
test, require := test.New(s.T())
|
||||
capture := &logCapture{}
|
||||
|
||||
routes := routes.NewRoutes(test.Logger())
|
||||
err := routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||
Endpoints: []cluster.EndpointDescriptor{{Path: "endpoint"}},
|
||||
}})
|
||||
require.NoError(err)
|
||||
|
||||
config := conf.Remote{
|
||||
Http: conf.Http{MaxRequestBodySizeInMb: 1},
|
||||
Logging: conf.Logging{SkipLoggingPathPrefixes: []string{"/api/nope"}},
|
||||
}
|
||||
locator := assembly.NewLocator(capture, nil, nil, routes, nil, nil, nil, nil, nil)
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: false,
|
||||
PathPrefix: "/api",
|
||||
Protocol: "grpc",
|
||||
TargetModule: "target",
|
||||
}}
|
||||
handler, err := locator.Handler(config, locations)
|
||||
require.NoError(err)
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := httpcli.New().Post(srv.URL + "/api/nope").Do(s.T().Context())
|
||||
require.NoError(err)
|
||||
require.EqualValues(http.StatusNotImplemented, resp.StatusCode())
|
||||
|
||||
require.Empty(capture.entries)
|
||||
}
|
||||
|
||||
func (s *UnknownLocationsLoggingTestSuite) Test_KnownEndpoint_LogsRequest() {
|
||||
test, require := test.New(s.T())
|
||||
capture := &logCapture{}
|
||||
|
||||
targetService := httpt.NewMock(test)
|
||||
targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response {
|
||||
return response{Id: req.Id}
|
||||
})
|
||||
targetUrl, err := url.Parse(targetService.BaseURL())
|
||||
require.NoError(err)
|
||||
targetHosts := map[string]*lb.RoundRobin{"target": lb.NewRoundRobin([]string{targetUrl.Host})}
|
||||
|
||||
routes := routes.NewRoutes(test.Logger())
|
||||
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||
Endpoints: []cluster.EndpointDescriptor{{Path: "/endpoint"}},
|
||||
}})
|
||||
require.NoError(err)
|
||||
|
||||
config := conf.Remote{
|
||||
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
|
||||
Logging: conf.Logging{RequestLogEnable: true},
|
||||
}
|
||||
locator := assembly.NewLocator(capture, nil, targetHosts, routes, nil, nil, nil, nil, nil)
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: true,
|
||||
PathPrefix: "/api",
|
||||
Protocol: "http",
|
||||
TargetModule: "target",
|
||||
}}
|
||||
handler, err := locator.Handler(config, locations)
|
||||
require.NoError(err)
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := httpcli.New().Post(srv.URL + "/api/endpoint").
|
||||
JsonRequestBody(request{Id: "test"}).
|
||||
Do(s.T().Context())
|
||||
require.NoError(err)
|
||||
require.EqualValues(http.StatusOK, resp.StatusCode())
|
||||
|
||||
// ровно одна лог-строка на запрос — log request
|
||||
require.Len(capture.entries, 1)
|
||||
entries := capture.entriesWithMessage("log request")
|
||||
require.Len(entries, 1)
|
||||
require.EqualValues("/api/endpoint", entries[0].fields["path"])
|
||||
}
|
||||
|
||||
func (s *UnknownLocationsLoggingTestSuite) Test_KnownEndpoint_SuppressionSkipsRequestLog() {
|
||||
test, require := test.New(s.T())
|
||||
capture := &logCapture{}
|
||||
|
||||
targetService := httpt.NewMock(test)
|
||||
targetService.POST("/endpoint", func(ctx context.Context, httpReq *http.Request, req request) response {
|
||||
return response{Id: req.Id}
|
||||
})
|
||||
targetUrl, err := url.Parse(targetService.BaseURL())
|
||||
require.NoError(err)
|
||||
targetHosts := map[string]*lb.RoundRobin{"target": lb.NewRoundRobin([]string{targetUrl.Host})}
|
||||
|
||||
routes := routes.NewRoutes(test.Logger())
|
||||
err = routes.ReceiveRoutes(s.T().Context(), cluster.RoutingConfig{{
|
||||
Endpoints: []cluster.EndpointDescriptor{{Path: "/endpoint"}},
|
||||
}})
|
||||
require.NoError(err)
|
||||
|
||||
config := conf.Remote{
|
||||
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
|
||||
Logging: conf.Logging{
|
||||
RequestLogEnable: true,
|
||||
SkipLoggingPathPrefixes: []string{"/api/endpoint"},
|
||||
},
|
||||
}
|
||||
locator := assembly.NewLocator(capture, nil, targetHosts, routes, nil, nil, nil, nil, nil)
|
||||
locations := []conf.Location{{
|
||||
SkipAuth: true,
|
||||
PathPrefix: "/api",
|
||||
Protocol: "http",
|
||||
TargetModule: "target",
|
||||
}}
|
||||
handler, err := locator.Handler(config, locations)
|
||||
require.NoError(err)
|
||||
|
||||
srv := httptest.NewServer(handler)
|
||||
defer srv.Close()
|
||||
|
||||
resp, err := httpcli.New().Post(srv.URL + "/api/endpoint").
|
||||
JsonRequestBody(request{Id: "test"}).
|
||||
Do(s.T().Context())
|
||||
require.NoError(err)
|
||||
require.EqualValues(http.StatusOK, resp.StatusCode())
|
||||
|
||||
require.Empty(capture.entries)
|
||||
}
|
||||
|
||||
func TestUnknownLocationsLoggingTestSuite(t *testing.T) {
|
||||
t.Parallel()
|
||||
suite.Run(t, new(UnknownLocationsLoggingTestSuite))
|
||||
}
|
||||
Reference in new issue
Block a user