Compare commits

..
6 Commits
26 changed files with 101 additions and 718 deletions

No files matched your search

+3 -1
View File
@@ -15,7 +15,6 @@ linters:
- nolintlint # Goland все равно форматирует с отступом - nolintlint # Goland все равно форматирует с отступом
- perfsprint # мнимая производительность в угоду читаемости - perfsprint # мнимая производительность в угоду читаемости
- tagalign # не всегда имеет смысл - tagalign # не всегда имеет смысл
- testpackage
- varnamelen # очень индивидуально (db) - varnamelen # очень индивидуально (db)
- wsl # расставление пробелов очень индивидуально - wsl # расставление пробелов очень индивидуально
- wsl_v5 # расставление пробелов очень индивидуально - wsl_v5 # расставление пробелов очень индивидуально
@@ -76,6 +75,9 @@ linters:
- linters: - linters:
- wrapcheck - wrapcheck
path: httperrors #отсутствует необходимость оборачивать ошибки path: httperrors #отсутствует необходимость оборачивать ошибки
- linters:
- goconst
path: "tests/" # компонентные тесты: фикстуры и моки не выносим в константы
paths: paths:
- third_party$ - third_party$
- builtin$ - builtin$
+1 -1
View File
@@ -1 +1 @@
5.11.6 5.12.0
+2 -8
View File
@@ -1,11 +1,5 @@
### v5.11.6 ### v5.12.0
* Логирование запросов на незнакомые locations — `warn` `request to unknown location` при включённом `logging.requestLogEnable` * взаимодействие с `isp-admin-service` переведено с gRPC на HTTP
* Добавлена настройка `logging.skipLoggingPathPrefixes` — полное отключение логирования запросов для путей с префиксом из списка (лог запросов, `warn` об неизвестном эндпоинте, лог незнакомых locations)
* Исправлено `logging.skipBodyLoggingEndpointPrefixes`: значения с ведущим `/` теперь работают и для локаций без `SkipAuth`
### v5.11.5
* Обновлена версия go до версии 1.27
* Обновлены правила для linter
* Обновлены зависимости
### v5.11.4 ### v5.11.4
* добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service` * добавлена возможность через переменную окружения `adminServiceName` переопределить название сервиса `msp-admin-service`
### v5.11.3 ### v5.11.3
+4 -6
View File
@@ -14,6 +14,7 @@ import (
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/grpc/client"
"github.com/txix-open/isp-kit/http" "github.com/txix-open/isp-kit/http"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/lb" "github.com/txix-open/isp-kit/lb"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
) )
@@ -30,7 +31,7 @@ type Assembly struct {
logger *log.Adapter logger *log.Adapter
routes *routes.Routes routes *routes.Routes
systemCli *client.Client systemCli *client.Client
adminCli *client.Client adminCli *httpclix.ClientBalancer
lockerCli *client.Client lockerCli *client.Client
routerLb *lb.RoundRobin routerLb *lb.RoundRobin
@@ -72,10 +73,7 @@ func New(boot *bootstrap.Bootstrap) (*Assembly, error) {
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "create system cli") return nil, errors.WithMessage(err, "create system cli")
} }
adminCli, err := client.Default() adminCli := httpclix.DefaultWithBalancer(nil)
if err != nil {
return nil, errors.WithMessage(err, "create admin cli")
}
lockerCli, err := client.Default() lockerCli, err := client.Default()
if err != nil { if err != nil {
return nil, errors.WithMessage(err, "create isp-lock-service client") return nil, errors.WithMessage(err, "create isp-lock-service client")
@@ -173,7 +171,7 @@ func (a *Assembly) Closers() []app.Closer {
for _, cliCloser := range a.grpcClientByModuleName { for _, cliCloser := range a.grpcClientByModuleName {
closers = append(closers, cliCloser) closers = append(closers, cliCloser)
} }
closers = append(closers, a.systemCli, a.adminCli, a.lockerCli) closers = append(closers, a.systemCli, a.lockerCli)
return closers return closers
} }
+4 -10
View File
@@ -5,6 +5,7 @@ import (
"strings" "strings"
"time" "time"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/metrics" "github.com/txix-open/isp-kit/metrics"
"github.com/txix-open/isp-kit/metrics/http_metrics" "github.com/txix-open/isp-kit/metrics/http_metrics"
@@ -29,7 +30,7 @@ type Locator struct {
httpHostManagerByModuleName map[string]*lb.RoundRobin httpHostManagerByModuleName map[string]*lb.RoundRobin
routes *routes.Routes routes *routes.Routes
systemCli *client.Client systemCli *client.Client
adminCli *client.Client adminCli *httpclix.ClientBalancer
lockerCli *client.Client lockerCli *client.Client
routerLb *lb.RoundRobin routerLb *lb.RoundRobin
usersAuthCache *cache.Cache usersAuthCache *cache.Cache
@@ -41,7 +42,7 @@ func NewLocator(
httpHostManagerByModuleName map[string]*lb.RoundRobin, httpHostManagerByModuleName map[string]*lb.RoundRobin,
routes *routes.Routes, routes *routes.Routes,
systemCli *client.Client, systemCli *client.Client,
adminCli *client.Client, adminCli *httpclix.ClientBalancer,
lockerCli *client.Client, lockerCli *client.Client,
routerLb *lb.RoundRobin, routerLb *lb.RoundRobin,
usersAuthCache *cache.Cache, usersAuthCache *cache.Cache,
@@ -96,8 +97,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
skipBodyLoggingEndpointPrefixes = append(skipBodyLoggingEndpointPrefixes, strings.TrimPrefix(prefix, "/")) skipBodyLoggingEndpointPrefixes = append(skipBodyLoggingEndpointPrefixes, strings.TrimPrefix(prefix, "/"))
} }
skipLogging := middleware.NewSkipLoggingPaths(config.Logging.SkipLoggingPathPrefixes)
mux := mux2.NewRouter() mux := mux2.NewRouter()
for _, location := range locations { for _, location := range locations {
var proxyFunc middleware.Handler var proxyFunc middleware.Handler
@@ -138,8 +137,7 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
middleware.Logger( middleware.Logger(
l.logger, config.Logging.RequestLogEnable, l.logger, config.Logging.RequestLogEnable,
enableBodyLog, enableBodyLog,
skipLogging, config.Logging.SkipBodyLoggingEndpointPrefixes,
skipBodyLoggingEndpointPrefixes,
config.Logging.EnableForceUnescapingUnicode, config.Logging.EnableForceUnescapingUnicode,
), ),
middleware.RequestId(), middleware.RequestId(),
@@ -163,7 +161,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
proxyFunc, proxyFunc,
middleware.Logger(l.logger, config.Logging.RequestLogEnable, middleware.Logger(l.logger, config.Logging.RequestLogEnable,
enableBodyLog, enableBodyLog,
skipLogging,
skipBodyLoggingEndpointPrefixes, skipBodyLoggingEndpointPrefixes,
config.Logging.EnableForceUnescapingUnicode, config.Logging.EnableForceUnescapingUnicode,
), ),
@@ -181,7 +178,6 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
PathPrefix: location.PathPrefix, PathPrefix: location.PathPrefix,
ErrorOnUnknownEndpoint: errorOnUnknownEndpoint, ErrorOnUnknownEndpoint: errorOnUnknownEndpoint,
WithLendingSlash: location.Protocol != conf.GrpcProtocol, WithLendingSlash: location.Protocol != conf.GrpcProtocol,
SkipLogging: skipLogging,
}, },
l.routes, l.routes,
l.logger, l.logger,
@@ -189,7 +185,5 @@ func (l Locator) Handler(config conf.Remote, locations []conf.Location) (http.Ha
mux.PathPrefix(location.PathPrefix).Handler(entrypoint) mux.PathPrefix(location.PathPrefix).Handler(entrypoint)
} }
mux.NotFoundHandler = middleware.UnknownLocation(l.logger, config.Logging.RequestLogEnable, skipLogging)
return mux, nil return mux, nil
} }
+1 -2
View File
@@ -4,8 +4,7 @@
"requestLogEnable": true, "requestLogEnable": true,
"bodyLogEnable": false, "bodyLogEnable": false,
"skipBodyLoggingEndpointPrefixes": [], "skipBodyLoggingEndpointPrefixes": [],
"enableForceUnescapingUnicode": false, "enableForceUnescapingUnicode": false
"skipLoggingPathPrefixes": []
}, },
"caching": { "caching": {
"authenticationDataInSec": 60, "authenticationDataInSec": 60,
-1
View File
@@ -49,7 +49,6 @@ type Logging struct {
BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"` BodyLogEnable bool `schema:"Включить логирование тел запросов и ответов,должно быть включено логирование запросов"`
SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"` SkipBodyLoggingEndpointPrefixes []string `schema:"Выключить логирование тел запросов и ответов для путей имеющих префикс из списка,'/' в начале игнорируется"`
EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"` EnableForceUnescapingUnicode bool `schema:"Включить перевод тел запроса из unicode в utf-8, должно быть включено логирование тел запросов и ответов"`
SkipLoggingPathPrefixes []string `schema:"Полностью не логировать запросы к путям с префиксом из списка (сырой path, query не учитывается, '/' в начале игнорируется). Применяется к логу запросов, предупреждению о неизвестном эндпоинте и логу незнакомых locations"`
} }
type Caching struct { type Caching struct {
-3
View File
@@ -8,9 +8,6 @@ type AuthenticateAppResponse struct {
type AppAuthData struct { type AppAuthData struct {
AppName string AppName string
SystemId int
DomainId int
ServiceId int
ApplicationId int ApplicationId int
} }
-3
View File
@@ -2,8 +2,5 @@ package entity
type AppAuthData struct { type AppAuthData struct {
AppName string AppName string
SystemId int
DomainId int
ServiceId int
ApplicationId int ApplicationId int
} }
+1 -1
View File
@@ -13,7 +13,6 @@ require (
github.com/txix-open/etp/v3 v3.2.0 github.com/txix-open/etp/v3 v3.2.0
github.com/txix-open/isp-kit v1.76.0 github.com/txix-open/isp-kit v1.76.0
github.com/txix-open/jsonschema v1.3.0 github.com/txix-open/jsonschema v1.3.0
go.uber.org/zap v1.28.0
google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f google.golang.org/genproto/googleapis/rpc v0.0.0-20261118221215-c8830f628b3f
google.golang.org/grpc v1.85.0 google.golang.org/grpc v1.85.0
) )
@@ -66,6 +65,7 @@ require (
go.opentelemetry.io/proto/otlp v1.11.1 // indirect go.opentelemetry.io/proto/otlp v1.11.1 // indirect
go.uber.org/atomic v1.12.0 // indirect go.uber.org/atomic v1.12.0 // indirect
go.uber.org/multierr v1.11.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 go.yaml.in/yaml/v3 v3.0.6 // indirect
golang.org/x/crypto v0.59.0 // indirect golang.org/x/crypto v0.59.0 // indirect
golang.org/x/net v0.63.0 // indirect golang.org/x/net v0.63.0 // indirect
+10 -13
View File
@@ -14,7 +14,6 @@ type EntryPointConfig struct {
WithPrefix bool WithPrefix bool
ErrorOnUnknownEndpoint bool ErrorOnUnknownEndpoint bool
WithLendingSlash bool WithLendingSlash bool
SkipLogging SkipLoggingPaths
} }
type EndpointResolver interface { type EndpointResolver interface {
@@ -34,18 +33,16 @@ func Entrypoint(
endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg) endpoint, err := entryPointResolver.ResolveEndpoint(req.Method, req.URL.Path, cfg)
if err != nil { if err != nil {
if !cfg.SkipLogging.ShouldSkip(req.URL.Path) { lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg)
lookupPath, endpoint := entryPointResolver.GetPaths(req.URL.Path, cfg) logger.Warn(
logger.Warn( req.Context(),
req.Context(), "call unknown method",
"call unknown method", log.String("pathPrefix", cfg.PathPrefix),
log.String("pathPrefix", cfg.PathPrefix), log.String("httpMethod", req.Method),
log.String("httpMethod", req.Method), log.String("originalPath", req.URL.Path),
log.String("originalPath", req.URL.Path), log.String("lookupPath", lookupPath),
log.String("lookupPath", lookupPath), log.String("enpoint", endpoint),
log.String("enpoint", endpoint), )
)
}
http.Error(writer, err.Error(), http.StatusNotImplemented) http.Error(writer, err.Error(), http.StatusNotImplemented)
return return
-5
View File
@@ -54,7 +54,6 @@ func Logger( // nolint:gocognit,funlen
logger log.Logger, logger log.Logger,
enableRequestLogging bool, enableRequestLogging bool,
enableBodyLogging bool, enableBodyLogging bool,
skipLogging SkipLoggingPaths,
skipBodyLoggingEndpointPrefixes []string, skipBodyLoggingEndpointPrefixes []string,
enableForceUnescapingUnicode bool, enableForceUnescapingUnicode bool,
) Middleware { ) Middleware {
@@ -66,10 +65,6 @@ func Logger( // nolint:gocognit,funlen
r := ctx.Request() r := ctx.Request()
if skipLogging.ShouldSkip(r.URL.Path) {
return next.Handle(ctx)
}
endpoint := ctx.EndpointMeta().NormalizedEndpoint endpoint := ctx.EndpointMeta().NormalizedEndpoint
logBodyFromCurrenRequest := enableBodyLogging logBodyFromCurrenRequest := enableBodyLogging
if logBodyFromCurrenRequest { if logBodyFromCurrenRequest {
+3 -3
View File
@@ -18,10 +18,10 @@ func (f HandlerFunc) Handle(ctx *request.Context) error {
type Middleware func(next Handler) Handler type Middleware func(next Handler) Handler
//nolint:ireturn // Chain по определению возвращает Handler-интерфейс // nolint:ireturn
func Chain(root Handler, middlewares ...Middleware) Handler { func Chain(root Handler, middlewares ...Middleware) Handler {
for _, m := range slices.Backward(middlewares) { for _, middleware := range slices.Backward(middlewares) {
root = m(root) root = middleware(root)
} }
return root return root
} }
-33
View File
@@ -1,33 +0,0 @@
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
}
-46
View File
@@ -1,46 +0,0 @@
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))
}
}
-27
View File
@@ -1,27 +0,0 @@
package middleware
import (
"net/http"
"github.com/txix-open/isp-kit/log"
)
// UnknownLocation — catch-all для запросов, не попавших ни в один location.
// 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 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),
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)
})
}
-3
View File
@@ -164,9 +164,6 @@ func (p Grpc) writeMetadata(ctx *request.Context) metadata.MD {
appAuthData, err := ctx.GetAuthData() appAuthData, err := ctx.GetAuthData()
if err == nil { if err == nil {
md[grpc.SystemIdHeader] = []string{strconv.Itoa(appAuthData.SystemId)}
md[grpc.DomainIdHeader] = []string{strconv.Itoa(appAuthData.DomainId)}
md[grpc.ServiceIdHeader] = []string{strconv.Itoa(appAuthData.ServiceId)}
md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(appAuthData.ApplicationId)} md[grpc.ApplicationIdHeader] = []string{strconv.Itoa(appAuthData.ApplicationId)}
encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName)) encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName))
md[grpc.ApplicationNameHeader] = []string{encodedAppName} md[grpc.ApplicationNameHeader] = []string{encodedAppName}
-3
View File
@@ -110,9 +110,6 @@ func setHttpHeaders(ctx *request.Context, header http.Header, skipAuth bool) {
appAuthData, err := ctx.GetAuthData() appAuthData, err := ctx.GetAuthData()
if err == nil { if err == nil {
header.Set(grpc.SystemIdHeader, strconv.Itoa(appAuthData.SystemId))
header.Set(grpc.DomainIdHeader, strconv.Itoa(appAuthData.DomainId))
header.Set(grpc.ServiceIdHeader, strconv.Itoa(appAuthData.ServiceId))
header.Set(grpc.ApplicationIdHeader, strconv.Itoa(appAuthData.ApplicationId)) header.Set(grpc.ApplicationIdHeader, strconv.Itoa(appAuthData.ApplicationId))
encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName)) encodedAppName := base64.StdEncoding.EncodeToString([]byte(appAuthData.AppName))
header.Set(grpc.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader header.Set(grpc.ApplicationNameHeader, encodedAppName) //nolint:canonicalheader
+2 -3
View File
@@ -6,12 +6,11 @@ import (
"net/url" "net/url"
"time" "time"
"isp-gate-service/httperrors"
"isp-gate-service/request"
"github.com/gorilla/websocket" "github.com/gorilla/websocket"
"github.com/tomakado/websocketproxy" "github.com/tomakado/websocketproxy"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"isp-gate-service/httperrors"
"isp-gate-service/request"
) )
type Ws struct { type Ws struct {
+16 -9
View File
@@ -7,7 +7,8 @@ import (
"isp-gate-service/entity" "isp-gate-service/entity"
"github.com/txix-open/isp-kit/errors" "github.com/txix-open/isp-kit/errors"
"github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/metrics/http_metrics"
) )
const ( const (
@@ -16,33 +17,39 @@ const (
) )
type Admin struct { type Admin struct {
cli *client.Client cli *httpclix.ClientBalancer
} }
func NewAdmin(cli *client.Client) Admin { func NewAdmin(cli *httpclix.ClientBalancer) Admin {
return Admin{cli: cli} return Admin{cli: cli}
} }
func (r Admin) Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error) { func (r Admin) Authenticate(ctx context.Context, token string) (*entity.AdminAuthenticateResponse, error) {
ctx = http_metrics.ClientEndpointToContext(ctx, adminAuthenticate)
resp := entity.AdminAuthenticateResponse{} resp := entity.AdminAuthenticateResponse{}
err := r.cli.Invoke(adminAuthenticate). err := r.cli.Post(adminAuthenticate).
JsonRequestBody(entity.AuthenticateRequest{Token: token}). JsonRequestBody(entity.AuthenticateRequest{Token: token}).
JsonResponseBody(&resp). JsonResponseBody(&resp).
Do(ctx) StatusCodeToError().
DoWithoutResponse(ctx)
if err != nil { if err != nil {
return nil, errors.WithMessagef(err, "grpc client invoke %s", adminAuthenticate) return nil, errors.WithMessagef(err, "http client invoke %s", adminAuthenticate)
} }
return &resp, nil return &resp, nil
} }
func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) { func (r Admin) Authorize(ctx context.Context, adminId int, permission string) (bool, error) {
ctx = http_metrics.ClientEndpointToContext(ctx, adminAuthorize)
resp := entity.AdminAuthorizeResponse{} resp := entity.AdminAuthorizeResponse{}
err := r.cli.Invoke(adminAuthorize). err := r.cli.Post(adminAuthorize).
JsonRequestBody(entity.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}). JsonRequestBody(entity.AdminAuthorizeRequest{AdminId: adminId, Permission: permission}).
JsonResponseBody(&resp). JsonResponseBody(&resp).
Do(ctx) StatusCodeToError().
DoWithoutResponse(ctx)
if err != nil { if err != nil {
return false, errors.WithMessagef(err, "grpc client invoke: %s", adminAuthorize) return false, errors.WithMessagef(err, "http client invoke %s", adminAuthorize)
} }
return resp.Authorized, nil return resp.Authorized, nil
} }
-3
View File
@@ -74,9 +74,6 @@ func (Authentication) convertAuthData(authData *entity.AppAuthData) *domain.AppA
return &domain.AppAuthData{ return &domain.AppAuthData{
AppName: authData.AppName, AppName: authData.AppName,
SystemId: authData.SystemId,
DomainId: authData.DomainId,
ServiceId: authData.ServiceId,
ApplicationId: authData.ApplicationId, ApplicationId: authData.ApplicationId,
} }
} }
+24 -36
View File
@@ -1,5 +1,5 @@
// nolint:canonicalheader // nolint:canonicalheader
package tests package tests_test
import ( import (
"context" "context"
@@ -24,6 +24,7 @@ import (
"github.com/txix-open/isp-kit/http/endpoint" "github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog" "github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/httpcli" "github.com/txix-open/isp-kit/http/httpcli"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/http/router" "github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/test/fake" "github.com/txix-open/isp-kit/test/fake"
@@ -59,18 +60,9 @@ func (s *HappyPathTestSuite) TestGrpcProxy() {
requestId := requestid.Next() requestId := requestid.Next()
targetService, targetCli := grpct.NewMock(test) targetService, targetCli := grpct.NewMock(test)
targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response { targetService.Mock("endpoint", func(ctx context.Context, authData grpc.AuthData, req request) response {
systemId, err := authData.SystemId()
require.NoError(err)
domainId, err := authData.DomainId()
require.NoError(err)
serviceId, err := authData.ServiceId()
require.NoError(err)
applicationId, err := authData.ApplicationId() applicationId, err := authData.ApplicationId()
require.NoError(err) require.NoError(err)
require.EqualValues(requestId, requestid.FromContext(ctx)) require.EqualValues(requestId, requestid.FromContext(ctx))
require.EqualValues(1, systemId)
require.EqualValues(2, domainId)
require.EqualValues(3, serviceId)
require.EqualValues(4, applicationId) require.EqualValues(4, applicationId)
adminId, err := grpc.StringFromMd("x-admin-id", metadata.MD(authData)) adminId, err := grpc.StringFromMd("x-admin-id", metadata.MD(authData))
@@ -580,7 +572,7 @@ func (s *HappyPathTestSuite) TestUserAuthorization_SkipAppAuth() { // nolint:fun
} }
// nolint:ireturn // nolint:ireturn
func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *client.Client) { func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *client.Client, *httpclix.ClientBalancer) {
config := conf.Remote{ config := conf.Remote{
Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15}, Http: conf.Http{MaxRequestBodySizeInMb: 1, ProxyTimeoutInSec: 15},
Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true, Logging: conf.Logging{LogLevel: log.DebugLevel, RequestLogEnable: true, BodyLogEnable: true,
@@ -597,9 +589,6 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
Authenticated: true, Authenticated: true,
ErrorReason: "", ErrorReason: "",
AuthData: &entity.AppAuthData{ AuthData: &entity.AppAuthData{
SystemId: 1,
DomainId: 2,
ServiceId: 3,
ApplicationId: 4, ApplicationId: 4,
AppName: "test", AppName: "test",
}, },
@@ -608,19 +597,27 @@ func (s *HappyPathTestSuite) commonDependencies(test *test.Test) (conf.Remote, *
return entity.AuthorizeResponse{Authorized: true} return entity.AuthorizeResponse{Authorized: true}
}) })
adminService, adminCli := grpct.NewMock(test) adminMux := router.New()
adminService.Mock("admin/secure/authenticate", func(req entity.AdminAuthorizeRequest) entity.AdminAuthenticateResponse { defaultWrapper := endpoint.DefaultWrapper(test.Logger(), httplog.Noop())
return entity.AdminAuthenticateResponse{ adminMux.POST("/admin/secure/authenticate",
Authenticated: true, defaultWrapper.Endpoint(func(req entity.AuthenticateRequest) entity.AdminAuthenticateResponse {
ErrorReason: "", return entity.AdminAuthenticateResponse{
AdminId: 1, Authenticated: true,
} ErrorReason: "",
}).Mock("admin/secure/authorize", func(req entity.AdminAuthorizeRequest) entity.AdminAuthorizeResponse { AdminId: 1,
if req.Permission == "ok_permission" { }
return entity.AdminAuthorizeResponse{Authorized: true} }))
} adminMux.POST("/admin/secure/authorize",
return entity.AdminAuthorizeResponse{Authorized: false} defaultWrapper.Endpoint(func(req entity.AdminAuthorizeRequest) entity.AdminAuthorizeResponse {
}) if req.Permission == "ok_permission" {
return entity.AdminAuthorizeResponse{Authorized: true}
}
return entity.AdminAuthorizeResponse{Authorized: false}
}))
adminMock := httptest.NewServer(adminMux)
adminUrl, err := url.Parse(adminMock.URL)
require.New(s.T()).NoError(err)
adminCli := httpclix.NewClientBalancer([]string{adminUrl.Host})
return config, systemCli, adminCli return config, systemCli, adminCli
} }
@@ -631,18 +628,9 @@ func TestHappyPathTestSuite(t *testing.T) {
} }
func assertHeaders(require *require.Assertions, requestId string, ctx context.Context, headers http.Header) { func assertHeaders(require *require.Assertions, requestId string, ctx context.Context, headers http.Header) {
systemId, err := strconv.Atoi(headers.Get("x-system-identity"))
require.NoError(err)
domainId, err := strconv.Atoi(headers.Get("x-domain-identity"))
require.NoError(err)
serviceId, err := strconv.Atoi(headers.Get("x-service-identity"))
require.NoError(err)
applicationId, err := strconv.Atoi(headers.Get("x-application-identity")) applicationId, err := strconv.Atoi(headers.Get("x-application-identity"))
require.NoError(err) require.NoError(err)
require.EqualValues(requestId, requestid.FromContext(ctx)) require.EqualValues(requestId, requestid.FromContext(ctx))
require.EqualValues(1, systemId)
require.EqualValues(2, domainId)
require.EqualValues(3, serviceId)
require.EqualValues(4, applicationId) require.EqualValues(4, applicationId)
expectedAppName := base64.StdEncoding.EncodeToString([]byte("test")) expectedAppName := base64.StdEncoding.EncodeToString([]byte("test"))
require.EqualValues(expectedAppName, headers.Get("x-application-name")) require.EqualValues(expectedAppName, headers.Get("x-application-name"))
+30 -21
View File
@@ -4,10 +4,11 @@ import (
"context" "context"
"net" "net"
"net/http" "net/http"
"net/http/httptest"
"net/url"
"isp-gate-service/assembly" "isp-gate-service/assembly"
"isp-gate-service/conf" "isp-gate-service/conf"
"isp-gate-service/domain"
"isp-gate-service/entity" "isp-gate-service/entity"
"isp-gate-service/routes" "isp-gate-service/routes"
@@ -17,6 +18,10 @@ import (
"github.com/txix-open/isp-kit/grpc/client" "github.com/txix-open/isp-kit/grpc/client"
endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint" endpoint2 "github.com/txix-open/isp-kit/grpc/endpoint"
"github.com/txix-open/isp-kit/grpc/isp" "github.com/txix-open/isp-kit/grpc/isp"
"github.com/txix-open/isp-kit/http/endpoint"
"github.com/txix-open/isp-kit/http/endpoint/httplog"
"github.com/txix-open/isp-kit/http/httpclix"
"github.com/txix-open/isp-kit/http/router"
"github.com/txix-open/isp-kit/log" "github.com/txix-open/isp-kit/log"
) )
@@ -55,15 +60,12 @@ func main() {
Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 5000}}, Throttling: []conf.Throttling{{ApplicationId: 1, RequestsPerSeconds: 5000}},
} }
systemService, systemCli, _ := NewMock(logger) systemService, systemCli := NewMock(logger)
systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse { systemService.Mock("system/secure/authenticate", func() entity.AuthenticateResponse {
return entity.AuthenticateResponse{ return entity.AuthenticateResponse{
Authenticated: true, Authenticated: true,
ErrorReason: "", ErrorReason: "",
AuthData: &entity.AppAuthData{ AuthData: &entity.AppAuthData{
SystemId: 1,
DomainId: 1,
ServiceId: 1,
ApplicationId: 1, ApplicationId: 1,
}, },
} }
@@ -71,16 +73,9 @@ func main() {
return entity.AuthorizeResponse{Authorized: true} return entity.AuthorizeResponse{Authorized: true}
}) })
adminService, _, adminCli := NewMock(logger) adminCli := NewAdminMock(logger)
adminService.Mock("admin/secure/authenticate", func() domain.AdminAuthenticateResponse {
return domain.AdminAuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AdminId: 1,
}
})
targetService, targetCli, _ := NewMock(logger) targetService, targetCli := NewMock(logger)
targetService.Mock("endpoint", func(req request) response { targetService.Mock("endpoint", func(req request) response {
return response{Id: req.Id} return response{Id: req.Id}
}) })
@@ -102,19 +97,33 @@ func main() {
srv.ListenAndServe() srv.ListenAndServe()
} }
func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client, *client.Client) { func NewAdminMock(logger log.Logger) *httpclix.ClientBalancer {
mux := router.New()
wrapper := endpoint.DefaultWrapper(logger, httplog.Noop())
mux.POST("/admin/secure/authenticate",
wrapper.Endpoint(func() entity.AdminAuthenticateResponse {
return entity.AdminAuthenticateResponse{
Authenticated: true,
ErrorReason: "",
AdminId: 1,
}
}))
mock := httptest.NewServer(mux)
u, _ := url.Parse(mock.URL)
return httpclix.NewClientBalancer([]string{u.Host})
}
func TestServer(service isp.BackendServiceServer) (*grpc.Server, *client.Client) {
listener, _ := net.Listen("tcp", "127.0.0.1:") // nolint:noctx listener, _ := net.Listen("tcp", "127.0.0.1:") // nolint:noctx
srv := grpc.NewServer() srv := grpc.NewServer()
sysCli, _ := client.Default() sysCli, _ := client.Default()
adminCli, _ := client.Default()
srv.Upgrade(service) srv.Upgrade(service)
go func() { go func() {
_ = srv.Serve(listener) _ = srv.Serve(listener)
}() }()
sysCli.Upgrade([]string{listener.Addr().String()}) sysCli.Upgrade([]string{listener.Addr().String()})
adminCli.Upgrade([]string{listener.Addr().String()}) return srv, sysCli
return srv, sysCli, adminCli
} }
type MockServer struct { type MockServer struct {
@@ -123,13 +132,13 @@ type MockServer struct {
mockEndpoints map[string]any mockEndpoints map[string]any
} }
func NewMock(logger log.Logger) (*MockServer, *client.Client, *client.Client) { func NewMock(logger log.Logger) (*MockServer, *client.Client) {
srv, syscli, admincli := TestServer(grpc.NewMux()) srv, syscli := TestServer(grpc.NewMux())
return &MockServer{ return &MockServer{
srv: srv, srv: srv,
logger: logger, logger: logger,
mockEndpoints: make(map[string]any), mockEndpoints: make(map[string]any),
}, syscli, admincli }, syscli
} }
func (m *MockServer) Mock(endpoint string, handler any) *MockServer { func (m *MockServer) Mock(endpoint string, handler any) *MockServer {
-74
View File
@@ -1,74 +0,0 @@
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)
}
-128
View File
@@ -1,128 +0,0 @@
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))
}
-275
View File
@@ -1,275 +0,0 @@
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},
Logging: conf.Logging{RequestLogEnable: true},
}, 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{
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)
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)
}
// 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{}
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))
}