From 8012ad57fea3ca08eb4d196b970548023c3d2550 Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 15:24:03 +0300 Subject: [PATCH 1/6] Fix body-skip matching for prefixes with leading slash --- assembly/locator.go | 2 +- tests/log_capture_test.go | 74 ++++++++++++++++++ tests/skip_body_logging_test.go | 128 ++++++++++++++++++++++++++++++++ 3 files changed, 203 insertions(+), 1 deletion(-) create mode 100644 tests/log_capture_test.go create mode 100644 tests/skip_body_logging_test.go diff --git a/assembly/locator.go b/assembly/locator.go index bdd8459..09b3da1 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -136,7 +136,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha middleware.Logger( l.logger, config.Logging.RequestLogEnable, enableBodyLog, - config.Logging.SkipBodyLoggingEndpointPrefixes, + skipBodyLoggingEndpointPrefixes, config.Logging.EnableForceUnescapingUnicode, ), middleware.RequestId(), diff --git a/tests/log_capture_test.go b/tests/log_capture_test.go new file mode 100644 index 0000000..73c7352 --- /dev/null +++ b/tests/log_capture_test.go @@ -0,0 +1,74 @@ +package tests + +import ( + "context" + "fmt" + "sync" + + "github.com/txix-open/isp-kit/log" + "go.uber.org/zap/zapcore" +) + +type capturedLogEntry struct { + level zapcore.Level + message string + fields map[string]any +} + +// logCapture ловит лог-записи в память. Zap-hook поля не получает, +// поэтому логгер реализован напрямую через интерфейс log.Logger. +type logCapture struct { + mu sync.Mutex + entries []capturedLogEntry +} + +func (c *logCapture) Error(_ context.Context, message any, fields ...log.Field) { + c.log(zapcore.ErrorLevel, message, fields...) +} + +func (c *logCapture) Warn(_ context.Context, message any, fields ...log.Field) { + c.log(zapcore.WarnLevel, message, fields...) +} + +func (c *logCapture) Info(_ context.Context, message any, fields ...log.Field) { + c.log(zapcore.InfoLevel, message, fields...) +} + +func (c *logCapture) Debug(_ context.Context, message any, fields ...log.Field) { + c.log(zapcore.DebugLevel, message, fields...) +} + +func (c *logCapture) log(level zapcore.Level, message any, fields ...log.Field) { + encoder := zapcore.NewMapObjectEncoder() + for _, field := range fields { + field.AddTo(encoder) + } + + c.mu.Lock() + defer c.mu.Unlock() + c.entries = append(c.entries, capturedLogEntry{ + level: level, + message: captureMessage(message), + fields: encoder.Fields, + }) +} + +func (c *logCapture) entriesWithMessage(message string) []capturedLogEntry { + c.mu.Lock() + defer c.mu.Unlock() + + found := make([]capturedLogEntry, 0, len(c.entries)) + for _, entry := range c.entries { + if entry.message == message { + found = append(found, entry) + } + } + return found +} + +func captureMessage(message any) string { + if msg, ok := message.(string); ok { + return msg + } + return fmt.Sprintf("%v", message) +} diff --git a/tests/skip_body_logging_test.go b/tests/skip_body_logging_test.go new file mode 100644 index 0000000..df834f3 --- /dev/null +++ b/tests/skip_body_logging_test.go @@ -0,0 +1,128 @@ +package tests + +import ( + "context" + "net/http" + "net/http/httptest" + "net/url" + "testing" + + "isp-gate-service/assembly" + "isp-gate-service/conf" + "isp-gate-service/entity" + "isp-gate-service/routes" + + "github.com/stretchr/testify/suite" + "github.com/txix-open/isp-kit/cluster" + "github.com/txix-open/isp-kit/grpc/client" + "github.com/txix-open/isp-kit/http/httpcli" + "github.com/txix-open/isp-kit/lb" + "github.com/txix-open/isp-kit/log" + "github.com/txix-open/isp-kit/test" + "github.com/txix-open/isp-kit/test/grpct" + "github.com/txix-open/isp-kit/test/httpt" +) + +type SkipBodyLoggingTestSuite struct { + suite.Suite +} + +// Regression: skipBodyLoggingEndpointPrefixes с ведущим '/' должны +// работать и в non-skipAuth цепочках — лог-строка пишется, тела нет. +func (s *SkipBodyLoggingTestSuite) Test_KnownEndpoint_BodySkip_StrippedPrefix() { + test, require := test.New(s.T()) + capture := &logCapture{} + + config, systemCli, adminCli := s.authDependencies(test) + + 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) + + locator := assembly.NewLocator(capture, nil, targetHosts, routes, systemCli, adminCli, nil, nil, nil) + locations := []conf.Location{{ + SkipAuth: false, + 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"). + Header("x-application-token", "token"). + Header("x-auth-admin", "mock-token"). + JsonRequestBody(request{Id: "test"}). + Do(s.T().Context()) + require.NoError(err) + require.EqualValues(http.StatusOK, resp.StatusCode()) + + // ровно одна лог-строка на запрос — без тел + require.Len(capture.entries, 1) + entries := capture.entriesWithMessage("log request") + require.Len(entries, 1) + require.NotContains(entries[0].fields, "request") + require.NotContains(entries[0].fields, "response") +} + +// nolint:ireturn +func (s *SkipBodyLoggingTestSuite) authDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) { + config := conf.Remote{ + Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15}, + Logging: conf.Logging{ + LogLevel: log.DebugLevel, + RequestLogEnable: true, + BodyLogEnable: true, + SkipBodyLoggingEndpointPrefixes: []string{"/endpoint"}, + }, + Caching: conf.Caching{AuthorizationDataInSec: 1, AuthenticationDataInSec: 1}, + } + + systemService, systemCli := grpct.NewMock(test) + systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse { + return entity.AuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AuthData: &entity.AppAuthData{ + SystemId: 1, + DomainId: 2, + ServiceId: 3, + ApplicationId: 4, + AppName: "test", + }, + } + }).Mock("system/secure/authorize", func() entity.AuthorizeResponse { + return entity.AuthorizeResponse{Authorized: true} + }) + + adminService, adminCli := grpct.NewMock(test) + adminService.Mock("admin/secure/authenticate", func(req entity.AdminAuthorizeRequest) entity.AdminAuthenticateResponse { + return entity.AdminAuthenticateResponse{ + Authenticated: true, + ErrorReason: "", + AdminId: 1, + } + }).Mock("admin/secure/authorize", func(req entity.AdminAuthorizeRequest) entity.AdminAuthorizeResponse { + return entity.AdminAuthorizeResponse{Authorized: true} + }) + + return config, systemCli, adminCli +} + +func TestSkipBodyLoggingTestSuite(t *testing.T) { + t.Parallel() + suite.Run(t, new(SkipBodyLoggingTestSuite)) +} From 48af0bb13214ddda31db761dcb5c2369c0f5bd5b Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 15:26:32 +0300 Subject: [PATCH 2/6] Add unknown location logging with path prefix suppression --- assembly/locator.go | 7 + conf/default_remote_config.json | 3 +- conf/remote.go | 1 + middleware/entrypoint.go | 23 ++- middleware/logger.go | 5 + middleware/skip_logging.go | 33 ++++ middleware/skip_logging_test.go | 46 +++++ middleware/unknown_location.go | 26 +++ tests/unknown_locations_logging_test.go | 246 ++++++++++++++++++++++++ 9 files changed, 379 insertions(+), 11 deletions(-) create mode 100644 middleware/skip_logging.go create mode 100644 middleware/skip_logging_test.go create mode 100644 middleware/unknown_location.go create mode 100644 tests/unknown_locations_logging_test.go diff --git a/assembly/locator.go b/assembly/locator.go index 09b3da1..66ed355 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -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 } diff --git a/conf/default_remote_config.json b/conf/default_remote_config.json index 7f0bd99..c5cd74e 100644 --- a/conf/default_remote_config.json +++ b/conf/default_remote_config.json @@ -4,7 +4,8 @@ "requestLogEnable": true, "bodyLogEnable": false, "skipBodyLoggingEndpointPrefixes": [], - "enableForceUnescapingUnicode": false + "enableForceUnescapingUnicode": false, + "skipLoggingPathPrefixes": [] }, "caching": { "authenticationDataInSec": 60, diff --git a/conf/remote.go b/conf/remote.go index c686dfe..8b15342 100644 --- a/conf/remote.go +++ b/conf/remote.go @@ -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 { diff --git a/middleware/entrypoint.go b/middleware/entrypoint.go index 49e39f1..8fbb182 100644 --- a/middleware/entrypoint.go +++ b/middleware/entrypoint.go @@ -14,6 +14,7 @@ type EntryPointConfig struct { WithPrefix bool ErrorOnUnknownEndpoint bool WithLendingSlash bool + SkipLogging SkipLoggingPaths } type EndpointResolver interface { @@ -33,16 +34,18 @@ func Entrypoint( endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg) if err != nil { - lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg) - logger.Warn( - req.Context(), - "call unknown method", - log.String("pathPrefix", cfg.PathPrefix), - log.String("httpMethod", req.Method), - log.String("originalPath", req.URL.Path), - log.String("lookupPath", lookupPath), - log.String("enpoint", endpoint), - ) + if !cfg.SkipLogging.ShouldSkip(req.URL.Path) { + lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg) + logger.Warn( + req.Context(), + "call unknown method", + log.String("pathPrefix", cfg.PathPrefix), + log.String("httpMethod", req.Method), + log.String("originalPath", req.URL.Path), + log.String("lookupPath", lookupPath), + log.String("enpoint", endpoint), + ) + } http.Error(writer, err.Error(), http.StatusNotImplemented) return diff --git a/middleware/logger.go b/middleware/logger.go index 88de9c6..bb97517 100644 --- a/middleware/logger.go +++ b/middleware/logger.go @@ -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 { diff --git a/middleware/skip_logging.go b/middleware/skip_logging.go new file mode 100644 index 0000000..65e0b5f --- /dev/null +++ b/middleware/skip_logging.go @@ -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 +} diff --git a/middleware/skip_logging_test.go b/middleware/skip_logging_test.go new file mode 100644 index 0000000..a7ae940 --- /dev/null +++ b/middleware/skip_logging_test.go @@ -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)) + } +} diff --git a/middleware/unknown_location.go b/middleware/unknown_location.go new file mode 100644 index 0000000..ac8a020 --- /dev/null +++ b/middleware/unknown_location.go @@ -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) + }) +} diff --git a/tests/unknown_locations_logging_test.go b/tests/unknown_locations_logging_test.go new file mode 100644 index 0000000..329f67f --- /dev/null +++ b/tests/unknown_locations_logging_test.go @@ -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)) +} From 1776a6a8e3d111ab42ea9e90a61c9159e3fc7abd Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 16:06:11 +0300 Subject: [PATCH 3/6] Gate unknown location logging on requestLogEnable --- assembly/locator.go | 2 +- middleware/unknown_location.go | 5 ++-- tests/unknown_locations_logging_test.go | 35 ++++++++++++++++++++++--- 3 files changed, 36 insertions(+), 6 deletions(-) diff --git a/assembly/locator.go b/assembly/locator.go index 66ed355..f21890c 100644 --- a/assembly/locator.go +++ b/assembly/locator.go @@ -189,7 +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) + mux.NotFoundHandler = middleware.UnknownLocation(l.logger, config.Logging.RequestLogEnable, skipLogging) return mux, nil } diff --git a/middleware/unknown_location.go b/middleware/unknown_location.go index ac8a020..4c714b4 100644 --- a/middleware/unknown_location.go +++ b/middleware/unknown_location.go @@ -7,9 +7,10 @@ import ( ) // UnknownLocation — catch-all для запросов, не попавших ни в один location. -func UnknownLocation(logger log.Logger, skipLogging SkipLoggingPaths) http.Handler { +// Warn пишется при включённом логировании запросов (как у log request). +func UnknownLocation(logger log.Logger, enableRequestLogging bool, skipLogging SkipLoggingPaths) http.Handler { return http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { - if !skipLogging.ShouldSkip(r.URL.Path) { + if enableRequestLogging && !skipLogging.ShouldSkip(r.URL.Path) { logger.Warn(r.Context(), "request to unknown location", log.String("httpMethod", r.Method), log.String("path", r.URL.Path), diff --git a/tests/unknown_locations_logging_test.go b/tests/unknown_locations_logging_test.go index 329f67f..2f62e1c 100644 --- a/tests/unknown_locations_logging_test.go +++ b/tests/unknown_locations_logging_test.go @@ -29,7 +29,10 @@ func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_LogsWarn() { 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) + handler, err := locator.Handler(conf.Remote{ + Http: conf.Http{MaxRequestBodySizeInMb: 1}, + Logging: conf.Logging{RequestLogEnable: true}, + }, nil) require.NoError(err) srv := httptest.NewServer(handler) @@ -58,8 +61,11 @@ func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_SuppressionSkipsWarn capture := &logCapture{} config := conf.Remote{ - Http: conf.Http{MaxRequestBodySizeInMb: 1}, - Logging: conf.Logging{SkipLoggingPathPrefixes: []string{"/unknown"}}, + Http: conf.Http{MaxRequestBodySizeInMb: 1}, + Logging: conf.Logging{ + RequestLogEnable: true, + SkipLoggingPathPrefixes: []string{"/unknown"}, + }, } locator := assembly.NewLocator(capture, nil, nil, routes.NewRoutes(test.Logger()), nil, nil, nil, nil, nil) handler, err := locator.Handler(config, nil) @@ -76,6 +82,29 @@ func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_SuppressionSkipsWarn require.Empty(capture.entries) } +// Warn о незнакомой location привязан к requestLogEnable как обычный лог запросов: +// при выключенном флаге запрос не логируется, но ответ 404 — без изменений. +func (s *UnknownLocationsLoggingTestSuite) Test_UnknownPath_RequestLoggingDisabled_NoWarn() { + 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)) + + require.Empty(capture.entries) +} + func (s *UnknownLocationsLoggingTestSuite) Test_UnknownEndpoint_LogsWarn() { test, require := test.New(s.T()) capture := &logCapture{} From a7427d73dea7e2207c5fc563d0458000757601ae Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 17:02:48 +0300 Subject: [PATCH 4/6] Bump version to 5.11.6 --- .version | 2 +- CHANGELOG.md | 4 ++++ 2 files changed, 5 insertions(+), 1 deletion(-) diff --git a/.version b/.version index 515dbad..dba7103 100644 --- a/.version +++ b/.version @@ -1 +1 @@ -5.11.5 \ No newline at end of file +5.11.6 \ No newline at end of file diff --git a/CHANGELOG.md b/CHANGELOG.md index 3c13340..bddb44c 100644 --- a/CHANGELOG.md +++ b/CHANGELOG.md @@ -1,3 +1,7 @@ +### v5.11.6 +* Логирование запросов на незнакомые locations — `warn` `request to unknown location` при включённом `logging.requestLogEnable` +* Добавлена настройка `logging.skipLoggingPathPrefixes` — полное отключение логирования запросов для путей с префиксом из списка (лог запросов, `warn` об неизвестном эндпоинте, лог незнакомых locations) +* Исправлено `logging.skipBodyLoggingEndpointPrefixes`: значения с ведущим `/` теперь работают и для локаций без `SkipAuth` ### v5.11.5 * Обновлена версия go до версии 1.27 * Обновлены правила для linter From 6bf8c4e6e3aff6fa1a83150b9f32a483f574296b Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 17:07:15 +0300 Subject: [PATCH 5/6] Update dependencies --- go.mod | 15 ++++++++------- go.sum | 30 ++++++++++++++++-------------- 2 files changed, 24 insertions(+), 21 deletions(-) diff --git a/go.mod b/go.mod index e6fd431..f3b83aa 100644 --- a/go.mod +++ b/go.mod @@ -1,19 +1,20 @@ module isp-gate-service -go 1.27.0 +go 1.27 require ( github.com/google/uuid v1.6.0 github.com/gorilla/mux v1.8.1 github.com/gorilla/websocket v1.5.3 github.com/julienschmidt/httprouter v1.3.0 - github.com/redis/go-redis/v9 v9.24.0 + github.com/redis/go-redis/v9 v9.18.0 github.com/stretchr/testify v1.12.1 github.com/tomakado/websocketproxy v0.1.0 github.com/txix-open/etp/v3 v3.2.0 github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/jsonschema v1.3.0 - google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2 + go.uber.org/zap v1.28.0 + google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f google.golang.org/grpc v1.85.0 ) @@ -24,6 +25,7 @@ require ( github.com/cenkalti/backoff/v5 v5.0.3 // indirect github.com/cespare/xxhash/v2 v2.3.0 // indirect github.com/coder/websocket v1.8.15 // indirect + github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f // indirect github.com/gabriel-vasile/mimetype v1.4.16 // indirect github.com/getsentry/sentry-go v0.50.0 // indirect github.com/go-faker/faker/v4 v4.12.0 // indirect @@ -33,7 +35,7 @@ require ( github.com/go-playground/universal-translator v0.18.2 // indirect github.com/grpc-ecosystem/grpc-gateway/v2 v2.34.0 // indirect github.com/json-iterator/go v1.1.12 // indirect - github.com/klauspost/compress v1.20.5 // indirect + github.com/klauspost/compress v1.20.4 // indirect github.com/leodido/go-urn v1.5.0 // indirect github.com/mailru/easyjson v0.9.2 // indirect github.com/mitchellh/mapstructure v1.5.0 // indirect @@ -52,7 +54,7 @@ require ( github.com/xeipuuv/gojsonpointer v0.0.0-20190905194746-02993c407bfb // indirect github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 // indirect github.com/xeipuuv/gojsonschema v1.2.0 // indirect - go.opentelemetry.io/auto/sdk v1.2.2 // indirect + go.opentelemetry.io/auto/sdk v1.2.1 // indirect go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 // indirect go.opentelemetry.io/otel v1.47.0 // indirect go.opentelemetry.io/otel/exporters/otlp/otlptrace v1.47.0 // indirect @@ -64,13 +66,12 @@ require ( go.opentelemetry.io/proto/otlp v1.11.1 // indirect go.uber.org/atomic v1.12.0 // indirect go.uber.org/multierr v1.11.0 // indirect - go.uber.org/zap v1.28.0 // indirect go.yaml.in/yaml/v3 v3.0.6 // indirect golang.org/x/crypto v0.59.0 // indirect golang.org/x/net v0.63.0 // indirect golang.org/x/sys v0.50.0 // indirect golang.org/x/text v0.44.0 // indirect - google.golang.org/genproto/googleapis/api v0.0.0-20261123191846-1e707ab9fbc2 // indirect + google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f // indirect google.golang.org/protobuf v1.36.12 // indirect gopkg.in/natefinch/lumberjack.v2 v2.2.1 // indirect gopkg.in/yaml.v3 v3.0.1 // indirect diff --git a/go.sum b/go.sum index 1fa200b..5c47d4a 100644 --- a/go.sum +++ b/go.sum @@ -18,6 +18,8 @@ github.com/coder/websocket v1.8.15 h1:6B2JPeOGlpff2Uz6vOEH1Vzpi0iUz20A+lPVhPHtNU github.com/coder/websocket v1.8.15/go.mod h1:NX3SzP+inril6yawo5CQXx8+fk145lPDC6pumgx0mVg= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f h1:lO4WD4F/rVNCu3HqELle0jiPLLBs70cWOduZpkS1E78= +github.com/dgryski/go-rendezvous v0.0.0-20200823014737-9f7001d12a5f/go.mod h1:cuUVRXasLTGF7a8hSLbxyZXjz+1KgoB3wDUb6vlszIc= github.com/felixge/httpsnoop v1.1.0 h1:3YtUj32ZZkqZtt3sZZsClsymw/QDuVfpNhoA31zeORc= github.com/felixge/httpsnoop v1.1.0/go.mod h1:Zqxgdd+1Rkcz8euOqdr7lqgCRJztwr5hp9vDSi5UZCE= github.com/gabriel-vasile/mimetype v1.4.16 h1:5izNFuvA37st1dDRAcA7TtmngBmRgiIPDmTtiEvjx1E= @@ -56,10 +58,10 @@ github.com/json-iterator/go v1.1.12 h1:PV8peI4a0ysnczrg+LtxykD8LfKY9ML6u2jnxaEnr github.com/json-iterator/go v1.1.12/go.mod h1:e30LSqwooZae/UwlEbR2852Gd8hjQvJoHmT4TnhNGBo= github.com/julienschmidt/httprouter v1.3.0 h1:U0609e9tgbseu3rBINet9P48AI/D3oJs4dN7jwJOQ1U= github.com/julienschmidt/httprouter v1.3.0/go.mod h1:JR6WtHb+2LUe8TCKY3cZOxFyyO8IZAc4RVcycCCAKdM= -github.com/klauspost/compress v1.20.5 h1:rJj5VjH4xQxbnLphg6eqUcDxRFCw1jpMdDY9qXlrwSs= -github.com/klauspost/compress v1.20.5/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= -github.com/klauspost/cpuid/v2 v2.4.0 h1:S6Hrbc7+ywsr0r+RLapfGBHfyefhCTwEh3A0tV913Dw= -github.com/klauspost/cpuid/v2 v2.4.0/go.mod h1:19jmZ9mjzoF//ddRSUsv0zfBTJWh3QJh9FNxZTMrGxU= +github.com/klauspost/compress v1.20.4 h1:dD0v/bvxtjCBqQu6sx1TNWkalEY5lNTIe+HY9w8TeNI= +github.com/klauspost/compress v1.20.4/go.mod h1:LUdAzn7YLVvxLpc7y3V1m40wESHTgc1422pwwBSKYuI= +github.com/klauspost/cpuid/v2 v2.0.9 h1:lgaqFMSdTdQYdZ04uHyN2d/eKdOMyi2YLSvlQIBFYa4= +github.com/klauspost/cpuid/v2 v2.0.9/go.mod h1:FInQzS24/EEf25PyTYn52gqo7WaD8xa0213Md/qVLRg= github.com/kr/pretty v0.3.1 h1:flRD4NNwYAUpkphVc1HcthR4KEIFJ65n8Mw5qdRn3LE= github.com/kr/pretty v0.3.1/go.mod h1:hoEshYVHaxMs3cyo3Yncou5ZscifuDolrwPKZanG3xk= github.com/kr/text v0.2.0 h1:5Nx0Ya0ZqY2ygV366QzturHI13Jq95ApcVaJBhpS+AY= @@ -96,8 +98,8 @@ github.com/prometheus/procfs v0.23.0 h1:ad+S6FTkzwaMgacKLM5h6bNKExS+DMH0YiUwXItH github.com/prometheus/procfs v0.23.0/go.mod h1:3AVXO0FqLafyYFU/V/IQRZlC8Rgqz8Dm/x6pKLK+RIk= github.com/rabbitmq/amqp091-go v1.17.0 h1:6KmTqrnJq93cGIE3Q3UnXgsqw6NtLu8MNfFoIbfBAIQ= github.com/rabbitmq/amqp091-go v1.17.0/go.mod h1:Hy4jKW5kQART1u+JkDTF9YYOQUHXqMuhrgxOEeS7G4o= -github.com/redis/go-redis/v9 v9.24.0 h1:X1AnQHWaSfMeggDQm7UFad1YwJmoZxVm5XkaP0kr6nQ= -github.com/redis/go-redis/v9 v9.24.0/go.mod h1:ted97kpLnB4S2KJkTkw+7GzRjgkFnU909IIrksu+ut4= +github.com/redis/go-redis/v9 v9.18.0 h1:pMkxYPkEbMPwRdenAzUNyFNrDgHx9U+DrBabWNfSRQs= +github.com/redis/go-redis/v9 v9.18.0/go.mod h1:k3ufPphLU5YXwNTUcCRXGxUoF1fqxnhFQmscfkCoDA0= github.com/rogpeppe/go-internal v1.14.1 h1:UQB4HGPB6osV0SQTLymcB4TgvyWu6ZyliaW0tI/otEQ= github.com/rogpeppe/go-internal v1.14.1/go.mod h1:MaRKkUm5W0goXpeCfT7UZI6fk/L7L7so1lCWt35ZSgc= github.com/stretchr/objx v0.1.0/go.mod h1:HFkY916IF+rwdDfMAkV7OtwuqBVzrE8GR6GFx+wExME= @@ -136,10 +138,10 @@ github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415 h1:EzJWgHo github.com/xeipuuv/gojsonreference v0.0.0-20180127040603-bd5ef7bd5415/go.mod h1:GwrjFmJcFw6At/Gs6z4yjiIwzuJ1/+UwLxMQDVQXShQ= github.com/xeipuuv/gojsonschema v1.2.0 h1:LhYJRs+L4fBtjZUfuSZIKGeVu0QRy8e5Xi7D17UxZ74= github.com/xeipuuv/gojsonschema v1.2.0/go.mod h1:anYRn/JVcOK2ZgGU+IjEV4nwlhoK5sQluxsYJ78Id3Y= -github.com/zeebo/xxh3 v1.1.0 h1:s7DLGDK45Dyfg7++yxI0khrfwq9661w9EN78eP/UZVs= -github.com/zeebo/xxh3 v1.1.0/go.mod h1:IisAie1LELR4xhVinxWS5+zf1lA4p0MW4T+w+W07F5s= -go.opentelemetry.io/auto/sdk v1.2.2 h1:ErNn7NW2t1F9CFBLb9iyPMyLRbcEd07l5m/StCe9AEE= -go.opentelemetry.io/auto/sdk v1.2.2/go.mod h1:Ca3X8ec6gdTYjAirla//dnp05ECtQPfN4Ut74OJLVsQ= +github.com/zeebo/xxh3 v1.0.2 h1:xZmwmqxHZA8AI603jOQ0tMqmBr9lPeFwGg6d+xy9DC0= +github.com/zeebo/xxh3 v1.0.2/go.mod h1:5NWz9Sef7zIDm2JHfFlcQvNekmcEl9ekUZQQKCYaDcA= +go.opentelemetry.io/auto/sdk v1.2.1 h1:jXsnJ4Lmnqd11kwkBV2LgLoFMZKizbCi5fNZ/ipaZ64= +go.opentelemetry.io/auto/sdk v1.2.1/go.mod h1:KRTj+aOaElaLi+wW1kO/DZRXwkF4C5xPbEe3ZiIhN7Y= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0 h1:jva1c3z2ZFEQ5sTvnLG2tBALNehO+QvdXKQii6eKRoo= go.opentelemetry.io/contrib/instrumentation/net/http/httptrace/otelhttptrace v0.72.0/go.mod h1:3pjFS5EnOVfjvYO6/NMdtJFHFQR+8uiGtrZ965nZP4w= go.opentelemetry.io/contrib/instrumentation/net/http/otelhttp v0.72.0 h1:LxwW/9ctSCv+QkE/cLR7M91ZIkXNMqJtEMi1vCw9U8s= @@ -186,10 +188,10 @@ golang.org/x/text v0.44.0 h1:YItdp/mQNGnsmrgpcdA5yQ3bnRxCfo/Tj/iByGW9GGo= golang.org/x/text v0.44.0/go.mod h1:S4FR1waQ9LbjQTls97SyRjDaUUVkaM+cXwwuG/G+MwY= gonum.org/v1/gonum v0.17.0 h1:VbpOemQlsSMrYmn7T2OUvQ4dqxQXU+ouZFQsZOx50z4= gonum.org/v1/gonum v0.17.0/go.mod h1:El3tOrEuMpv2UdMrbNlKEh9vd86bmQ6vqIcDwxEOc1E= -google.golang.org/genproto/googleapis/api v0.0.0-20261123191846-1e707ab9fbc2 h1:TVEW5ciB4lPlyo3RBDd2JTlUY0vAzMkPlU/qAzC+rqU= -google.golang.org/genproto/googleapis/api v0.0.0-20261123191846-1e707ab9fbc2/go.mod h1:3q/FqMoaJXT/mbOLAkZaCXuOEpmvBNwYXqdJKeN0gD0= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2 h1:FCWn4wv5of/ooWpbWDIeOXqI3+h2MGnV7SvvcJ8f+bQ= -google.golang.org/genproto/googleapis/rpc v0.0.0-20261123191846-1e707ab9fbc2/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= +google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f h1:7CbYDSDM5xqpq8v2tNm+Q057COf1lvA0gorVk+304tY= +google.golang.org/genproto/googleapis/api v0.0.0-20261118221215-c8830f628b3f/go.mod h1:CPxXEEQ1S9iJmInAF/8MNc8tKWnya8I8Kni9Zh2hV0M= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f h1:aDW6Vb2T1K0xbAgW+ED8iz39WlgjjX/OKiNh6tXv/+g= +google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f/go.mod h1:OaIUM3+LpYcK2GXM4FTmhWoIq371Owdr+Cc7/BsYHHc= google.golang.org/grpc v1.85.0 h1:BPBCfuVRQ1qvBhKDOq9uvQllMvO59rKsYhXpp7Dd8vw= google.golang.org/grpc v1.85.0/go.mod h1:0rQrOD58yjal/0EaVbGBANindixsCZNQPDV3VKtaKuQ= google.golang.org/protobuf v1.36.12 h1:pJOKDDOyeXErUroCihFAd5LQuwXBSpVnKGrj5o/fwxc= From f891fd52b11b62c3fd8d0f8ef05115ac6f372535 Mon Sep 17 00:00:00 2001 From: gr-dv Date: Wed, 25 Nov 2026 17:45:28 +0300 Subject: [PATCH 6/6] fix lint --- .golangci.yml | 12 ++++++++++-- httperrors/errors.go | 7 +------ middleware/logger.go | 8 ++------ middleware/metrics_middleware.go | 6 ++---- middleware/middleware.go | 8 +++++--- proxy/grpc.go | 2 -- proxy/http.go | 1 - proxy/ws.go | 1 - tests/acceptance_test.go | 17 +++++++++-------- 9 files changed, 29 insertions(+), 33 deletions(-) diff --git a/.golangci.yml b/.golangci.yml index 575b423..3537ffc 100644 --- a/.golangci.yml +++ b/.golangci.yml @@ -15,6 +15,7 @@ linters: - nolintlint # Goland все равно форматирует с отступом - perfsprint # мнимая производительность в угоду читаемости - tagalign # не всегда имеет смысл + - testpackage - varnamelen # очень индивидуально (db) - wsl # расставление пробелов очень индивидуально - wsl_v5 # расставление пробелов очень индивидуально @@ -66,8 +67,15 @@ linters: - prealloc path: ".*_test\\.go$" - linters: - - goconst - path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы + - wrapcheck + path: middleware #отсутствует необходимость оборачивать ошибки + - linters: + - gochecknoglobals + - mnd + path: proxy + - linters: + - wrapcheck + path: httperrors #отсутствует необходимость оборачивать ошибки paths: - third_party$ - builtin$ diff --git a/httperrors/errors.go b/httperrors/errors.go index 3e00ac2..ee00178 100644 --- a/httperrors/errors.go +++ b/httperrors/errors.go @@ -3,7 +3,6 @@ package httperrors import ( "net/http" - "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/json" ) @@ -34,11 +33,7 @@ func (e *HttpError) WriteError(w http.ResponseWriter) error { "errorMessage": e.userMessage, "details": e.details, } - err := json.NewEncoder(w).Encode(data) - if err != nil { - return errors.WithMessage(err, "json encode error") - } - return nil + return json.NewEncoder(w).Encode(data) } func (e *HttpError) WithDetails(details ...any) { diff --git a/middleware/logger.go b/middleware/logger.go index bb97517..c3b71eb 100644 --- a/middleware/logger.go +++ b/middleware/logger.go @@ -35,11 +35,7 @@ func (w *writerWrapper) Hijack() (net.Conn, *bufio.ReadWriter, error) { if !ok { return nil, nil, errors.New("writerWrapper: upstream writer doesn't implement Hijack") } - conn, rw, err := upstream.Hijack() - if err != nil { - return nil, nil, errors.WithMessage(err, "hijack error") - } - return conn, rw, nil + return upstream.Hijack() } func (w *writerWrapper) StatusCode() int { @@ -145,7 +141,7 @@ func Logger( // nolint:gocognit,funlen logger.Debug(ctx.Context(), "log request", fields...) } - return errors.WithMessage(err, "logger middleware error") + return err }) } } diff --git a/middleware/metrics_middleware.go b/middleware/metrics_middleware.go index 8c2cf34..87273fb 100644 --- a/middleware/metrics_middleware.go +++ b/middleware/metrics_middleware.go @@ -1,11 +1,9 @@ package middleware import ( + "isp-gate-service/request" "time" - "isp-gate-service/request" - - "github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/metrics/http_metrics" ) @@ -22,7 +20,7 @@ func Metrics(storage *http_metrics.ServerStorage) Middleware { start := time.Now() err := next.Handle(ctx) if err != nil { - return errors.WithMessage(err, "metrics middleware error") + return err } storage.ObserveDuration(r.Method, pathSchema, time.Since(start)) diff --git a/middleware/middleware.go b/middleware/middleware.go index 635ca6e..2b3ff69 100644 --- a/middleware/middleware.go +++ b/middleware/middleware.go @@ -1,6 +1,8 @@ package middleware import ( + "slices" + "isp-gate-service/request" ) @@ -16,10 +18,10 @@ func (f HandlerFunc) Handle(ctx *request.Context) error { type Middleware func(next Handler) Handler -// nolint:ireturn, modernize +//nolint:ireturn // Chain по определению возвращает Handler-интерфейс func Chain(root Handler, middlewares ...Middleware) Handler { - for i := len(middlewares) - 1; i >= 0; i-- { - root = middlewares[i](root) + for _, m := range slices.Backward(middlewares) { + root = m(root) } return root } diff --git a/proxy/grpc.go b/proxy/grpc.go index 06698b7..e521070 100644 --- a/proxy/grpc.go +++ b/proxy/grpc.go @@ -33,7 +33,6 @@ func init() { } var ( - // nolint: gochecknoglobals codeMap = map[int]codes.Code{ http.StatusOK: codes.OK, http.StatusRequestTimeout: codes.Canceled, @@ -49,7 +48,6 @@ var ( http.StatusInternalServerError: codes.Internal, http.StatusServiceUnavailable: codes.Unavailable, } - // nolint: gochecknoglobals inverseCodeMap = map[codes.Code]int{} ) diff --git a/proxy/http.go b/proxy/http.go index 39383eb..113e80c 100644 --- a/proxy/http.go +++ b/proxy/http.go @@ -21,7 +21,6 @@ import ( ) var ( - // nolint: gochecknoglobals, mnd httpTransport = &http.Transport{ Proxy: http.ProxyFromEnvironment, DialContext: defaultTransportDialContext(&net.Dialer{ diff --git a/proxy/ws.go b/proxy/ws.go index e4cd149..061ed51 100644 --- a/proxy/ws.go +++ b/proxy/ws.go @@ -46,7 +46,6 @@ func (ws Ws) Handle(ctx *request.Context) error { proxy.Director = func(incoming *http.Request, out http.Header) { setHttpHeaders(ctx, out, ws.skipAuth) } - // nolint: mnd proxy.Upgrader = &websocket.Upgrader{ HandshakeTimeout: 5 * time.Second, ReadBufferSize: 1024, diff --git a/tests/acceptance_test.go b/tests/acceptance_test.go index a28c4d0..c122a36 100644 --- a/tests/acceptance_test.go +++ b/tests/acceptance_test.go @@ -1,4 +1,5 @@ -package tests_test +// nolint:canonicalheader +package tests import ( "context" @@ -238,7 +239,7 @@ type wsEventHandlerMock struct { func (s wsEventHandlerMock) Handle(_ context.Context, conn *etp.Conn, event msg.Event) []byte { headers := conn.HttpRequest().Header - ctx := requestid.ToContext(context.Background(), headers.Get("x-request-id")) // nolint: canonicalheader + ctx := requestid.ToContext(context.Background(), headers.Get("x-request-id")) assertHeaders(s.require, s.requestId, ctx, headers) require.EqualValues(s.t, "data", event.Data) return []byte("world") @@ -630,13 +631,13 @@ func TestHappyPathTestSuite(t *testing.T) { } func assertHeaders(require *require.Assertions, requestId string, ctx context.Context, headers http.Header) { - systemId, err := strconv.Atoi(headers.Get("x-system-identity")) // nolint: canonicalheader + systemId, err := strconv.Atoi(headers.Get("x-system-identity")) require.NoError(err) - domainId, err := strconv.Atoi(headers.Get("x-domain-identity")) // nolint: canonicalheader + domainId, err := strconv.Atoi(headers.Get("x-domain-identity")) require.NoError(err) - serviceId, err := strconv.Atoi(headers.Get("x-service-identity")) // nolint: canonicalheader + serviceId, err := strconv.Atoi(headers.Get("x-service-identity")) require.NoError(err) - applicationId, err := strconv.Atoi(headers.Get("x-application-identity")) // nolint: canonicalheader + applicationId, err := strconv.Atoi(headers.Get("x-application-identity")) require.NoError(err) require.EqualValues(requestId, requestid.FromContext(ctx)) require.EqualValues(1, systemId) @@ -644,9 +645,9 @@ func assertHeaders(require *require.Assertions, requestId string, ctx context.Co require.EqualValues(3, serviceId) require.EqualValues(4, applicationId) expectedAppName := base64.StdEncoding.EncodeToString([]byte("test")) - require.EqualValues(expectedAppName, headers.Get("x-application-name")) // nolint: canonicalheader + require.EqualValues(expectedAppName, headers.Get("x-application-name")) - adminId, err := strconv.Atoi(headers.Get("x-admin-id")) // nolint: canonicalheader + adminId, err := strconv.Atoi(headers.Get("x-admin-id")) require.NoError(err) require.EqualValues(1, adminId) }